-
Notifications
You must be signed in to change notification settings - Fork 621
/
interpreter.rs
442 lines (400 loc) · 16.3 KB
/
interpreter.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// SPDX-FileCopyrightText: 2023 Greenbone AG
//
// SPDX-License-Identifier: GPL-2.0-or-later WITH x11vnc-openssl-exception
use std::{collections::HashMap, io};
use crate::nasl::syntax::{
IdentifierType, LoadError, NaslValue, Statement, StatementKind::*, SyntaxError, Token,
TokenCategory,
};
use crate::storage::StorageError;
use crate::nasl::interpreter::{
declare::{DeclareFunctionExtension, DeclareVariableExtension},
InterpretError, InterpretErrorKind,
};
use crate::nasl::utils::{Context, ContextType, Register};
/// Is used to identify the depth of the current statement
///
/// Initial call of retry_resolce sets the first element all others are only
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Position {
index: Vec<usize>,
}
impl Position {
pub fn new(index: usize) -> Self {
Self { index: vec![index] }
}
pub fn up(&mut self) {
self.index.push(0);
}
pub fn down(&mut self) -> Option<usize> {
self.index.pop()
}
pub fn current_init_statement(&self) -> Self {
Self {
index: vec![*self.index.first().unwrap_or(&0)],
}
}
fn root_index(&self) -> usize {
*self.index.first().unwrap_or(&0)
}
}
/// Contains data that is specific for a single run
///
/// Some methods start multiple runs (e.g. get_kb_item) and need to have their own specific data to
/// manipulate. To make it more convencient the data that is bound to run is summarized within this
/// struct.
pub(crate) struct RunSpecific {
pub(crate) register: Register,
pub(crate) position: Position,
pub(crate) skip_until_return: Option<(Position, NaslValue)>,
}
/// Used to interpret a Statement
pub struct Interpreter<'a> {
pub(crate) run_specific: Vec<RunSpecific>,
pub(crate) ctxconfigs: &'a Context<'a>,
pub(crate) index: usize,
}
/// Interpreter always returns a NaslValue or an InterpretError
///
/// When a result does not contain a value than NaslValue::Null must be returned.
pub type InterpretResult = Result<NaslValue, InterpretError>;
impl<'a> Interpreter<'a> {
/// Creates a new Interpreter
pub fn new(register: Register, ctxconfigs: &'a Context) -> Self {
let root_run = RunSpecific {
register,
position: Position::new(0),
skip_until_return: None,
};
Interpreter {
run_specific: vec![root_run],
ctxconfigs,
index: 0,
}
}
pub(crate) fn identifier(token: &Token) -> Result<String, InterpretError> {
match token.category() {
TokenCategory::Identifier(IdentifierType::Undefined(x)) => Ok(x.to_owned()),
cat => Err(InterpretError::wrong_category(cat)),
}
}
/// May return the next interpreter to run against that statement
///
/// When the interpreter are done a None will be returned. Afterwards it will begin at at 0
/// again. This is done to inform the caller that all interpreter interpret this statement and
/// the next Statement can be executed.
// TODO remove in favor of iterrator of run_specific
pub fn next_interpreter(&mut self) -> Option<&mut Interpreter<'a>> {
if self.run_specific.len() == 1 || self.index + 1 == self.run_specific.len() {
return None;
}
// if self.forked_interpreter.is_empty() {
// return None;
// }
tracing::trace!(amount = self.run_specific.len(), index = self.index,);
self.index += 1;
Some(self)
}
async fn execute_statements<'b>(
&self,
key: &str,
inter: &mut Interpreter<'b>,
stmt: Result<Statement, SyntaxError>,
) -> InterpretResult {
match stmt {
Ok(stmt) => inter.resolve(&stmt).await,
Err(err) => Err(InterpretError::include_syntax_error(key, err)),
}
}
/// Includes a script into to the current runtime by executing it and share the register as
/// well as DB of the current runtime.
///
// NOTE: This is currently optimized for interpreting runs, but it is very inefficient if we want to
// switch to a jitc approach or do parallelization of statements within a script. For that it
// would be necessary to include the statements within a statement list of a script prior of
// execution. In the current usage (2024-04-02) it would be overkill, but I'm writing a note as
// I think this can be easily overlooked.
async fn include(&mut self, name: &Statement) -> InterpretResult {
match self.resolve(name).await? {
NaslValue::String(key) => {
let code = self.ctxconfigs.loader().load(&key)?;
let mut inter = Interpreter::new(self.register().clone(), self.ctxconfigs);
for stmt in crate::nasl::syntax::parse(&code) {
self.execute_statements(&key, &mut inter, stmt).await?;
}
self.set_register(inter.register().clone());
Ok(NaslValue::Null)
}
_ => Err(InterpretError::unsupported(name, "string")),
}
}
/// Changes the internal position and tries to interpret a statement while retrying n times on specific error
///
/// When encountering a retrievable error:
/// - LoadError(Retry(_))
/// - StorageError(Retry(_))
/// - IOError(Interrupted(_))
///
/// then it retries the statement for a given max_attempts times.
///
/// When max_attempts is set to 0 it will it execute it once.
pub async fn retry_resolve_next(
&mut self,
stmt: &Statement,
max_attempts: usize,
) -> InterpretResult {
if let Some(last) = self.position_mut().index.last_mut() {
*last += 1;
}
self.index = 0;
self.retry_resolve(stmt, max_attempts).await
}
/// Tries to interpret a statement and retries n times on a retry error
///
/// When encountering a retrievable error:
/// - LoadError(Retry(_))
/// - StorageError(Retry(_))
/// - IOError(Interrupted(_))
///
/// then it retries the statement for a given max_attempts times.
///
/// When max_attempts is set to 0 it will it execute it once.
pub async fn retry_resolve(
&mut self,
stmt: &Statement,
max_attempts: usize,
) -> InterpretResult {
match self.resolve(stmt).await {
Ok(x) => Ok(x),
Err(e) => {
if max_attempts > 0 {
match e.kind {
InterpretErrorKind::LoadError(LoadError::Retry(_))
| InterpretErrorKind::IOError(io::ErrorKind::Interrupted)
| InterpretErrorKind::StorageError(StorageError::Retry(_)) => {
Box::pin(self.retry_resolve_next(stmt, max_attempts - 1)).await
}
_ => Err(e),
}
} else {
Err(e)
}
}
}
}
/// Interprets a Statement
pub(crate) async fn resolve(&mut self, statement: &Statement) -> InterpretResult {
self.position_mut().up();
tracing::trace!(position=?self.position(), statement=statement.to_string(), "executing");
// On a fork statement run we skip until the root index is reached. Between the root index
// of the return value and the position of the return value the interpretation is
// continued. This is done because the client just executes higher statements.
if let Some((cp, rv)) = &self.skip_until_return() {
tracing::trace!(check_position=?cp);
if self.position().root_index() < cp.root_index() {
tracing::trace!("skip execution");
self.position_mut().down();
return Ok(NaslValue::Null);
}
if cp == self.position() {
tracing::trace!(return=?rv, "skip execution and returning");
let rv = rv.clone();
self.set_skip_until_return(None);
self.position_mut().down();
return Ok(rv);
}
}
let results = {
match statement.kind() {
Include(inc) => Box::pin(self.include(inc)).await,
Array(position) => self.resolve_array(statement, position.clone()).await,
Exit(stmt) => self.resolve_exit(stmt).await,
Return(stmt) => self.resolve_return(stmt).await,
NamedParameter(..) => {
unreachable!("named parameter should not be an executable statement.")
}
For(assignment, condition, update, body) => {
Box::pin(self.for_loop(assignment, condition, update, body)).await
}
While(condition, body) => Box::pin(self.while_loop(condition, body)).await,
Repeat(body, condition) => Box::pin(self.repeat_loop(body, condition)).await,
ForEach(variable, iterable, body) => {
Box::pin(self.for_each_loop(variable, iterable, body)).await
}
FunctionDeclaration(name, args, exec) => {
self.declare_function(name, args.children(), exec)
}
Primitive => self.resolve_primitive(statement),
Variable => self.resolve_variable(statement),
Call(arguments) => {
Box::pin(self.call(statement.as_token(), arguments.children())).await
}
Declare(stmts) => self.declare_variable(statement.as_token(), stmts),
Parameter(x) => self.resolve_parameter(x).await,
Assign(cat, order, left, right) => {
Box::pin(self.assign(cat, order, left, right)).await
}
Operator(sign, stmts) => Box::pin(self.operator(sign, stmts)).await,
If(condition, if_block, _, else_block) => {
self.resolve_if(condition, if_block, else_block.clone())
.await
}
Block(blocks) => self.resolve_block(blocks).await,
NoOp => Ok(NaslValue::Null),
EoF => Ok(NaslValue::Null),
AttackCategory => self.resolve_attack_category(statement),
Continue => Ok(NaslValue::Continue),
Break => Ok(NaslValue::Break),
}
.map_err(|e| {
if e.origin.is_none() {
InterpretError::from_statement(statement, e.kind)
} else {
e
}
})
};
self.position_mut().down();
results
}
async fn resolve_array(
&mut self,
statement: &Statement,
position: Option<Box<Statement>>,
) -> Result<NaslValue, InterpretError> {
let name = Self::identifier(statement.start())?;
let val = self
.register()
.named(&name)
.unwrap_or(&ContextType::Value(NaslValue::Null));
let val = val.clone();
match (position, val) {
(None, ContextType::Value(v)) => Ok(v),
(Some(p), ContextType::Value(NaslValue::Array(x))) => {
let position = Box::pin(self.resolve(&p)).await?;
let position = i64::from(&position) as usize;
let result = x.get(position).unwrap_or(&NaslValue::Null);
Ok(result.clone())
}
(Some(p), ContextType::Value(NaslValue::Dict(x))) => {
let position = Box::pin(self.resolve(&p)).await?.to_string();
let result = x.get(&position).unwrap_or(&NaslValue::Null);
Ok(result.clone())
}
(Some(_), ContextType::Value(NaslValue::Null)) => Ok(NaslValue::Null),
(Some(p), _) => Err(InterpretError::unsupported(&p, "array")),
(None, ContextType::Function(_, _)) => {
Err(InterpretError::unsupported(statement, "variable"))
}
}
}
/// Returns used register
pub fn register(&self) -> &Register {
&self.run_specific[self.index].register
}
/// Returns used register
pub(crate) fn register_mut(&mut self) -> &mut Register {
&mut self.run_specific[self.index].register
}
pub(crate) fn position_mut(&mut self) -> &mut Position {
&mut self.run_specific[self.index].position
}
pub(crate) fn position(&self) -> &Position {
&self.run_specific[self.index].position
}
fn set_register(&mut self, val: Register) {
let rs = &mut self.run_specific[self.index];
rs.register = val;
}
pub(crate) fn set_skip_until_return(&mut self, val: Option<(Position, NaslValue)>) {
let rs = &mut self.run_specific[self.index];
rs.skip_until_return = val;
}
pub(crate) fn skip_until_return(&self) -> Option<&(Position, NaslValue)> {
self.run_specific[self.index].skip_until_return.as_ref()
}
async fn resolve_exit(&mut self, statement: &Statement) -> Result<NaslValue, InterpretError> {
let rc = Box::pin(self.resolve(statement)).await?;
match rc {
NaslValue::Number(rc) => Ok(NaslValue::Exit(rc)),
_ => Err(InterpretError::unsupported(statement, "numeric")),
}
}
async fn resolve_return(&mut self, statement: &Statement) -> Result<NaslValue, InterpretError> {
let rc = Box::pin(self.resolve(statement)).await?;
Ok(NaslValue::Return(Box::new(rc)))
}
fn resolve_primitive(&self, statement: &Statement) -> Result<NaslValue, InterpretError> {
TryFrom::try_from(statement.as_token()).map_err(|e: TokenCategory| e.into())
}
fn resolve_variable(&mut self, statement: &Statement) -> Result<NaslValue, InterpretError> {
let name: NaslValue = TryFrom::try_from(statement.as_token())?;
match self.register().named(&name.to_string()) {
Some(ContextType::Value(result)) => Ok(result.clone()),
None => Ok(NaslValue::Null),
Some(ContextType::Function(_, _)) => {
Err(InterpretError::unsupported(statement, "variable"))
}
}
}
async fn resolve_parameter(&mut self, x: &[Statement]) -> Result<NaslValue, InterpretError> {
let mut result = vec![];
for stmt in x {
let val = Box::pin(self.resolve(stmt)).await?;
result.push(val);
}
Ok(NaslValue::Array(result))
}
async fn resolve_if(
&mut self,
condition: &Statement,
if_block: &Statement,
else_block: Option<Box<Statement>>,
) -> Result<NaslValue, InterpretError> {
match Box::pin(self.resolve(condition)).await {
Ok(value) => {
if bool::from(value) {
return Box::pin(self.resolve(if_block)).await;
} else if let Some(else_block) = else_block {
return Box::pin(self.resolve(else_block.as_ref())).await;
}
Ok(NaslValue::Null)
}
Err(err) => Err(err),
}
}
async fn resolve_block(&mut self, blocks: &[Statement]) -> Result<NaslValue, InterpretError> {
self.register_mut().create_child(HashMap::default());
for stmt in blocks {
match Box::pin(self.resolve(stmt)).await {
Ok(x) => {
if matches!(
x,
NaslValue::Exit(_)
| NaslValue::Return(_)
| NaslValue::Break
| NaslValue::Continue
) {
self.register_mut().drop_last();
return Ok(x);
}
}
Err(e) => return Err(e),
}
}
self.register_mut().drop_last();
// currently blocks don't return something
Ok(NaslValue::Null)
}
fn resolve_attack_category(&self, statement: &Statement) -> Result<NaslValue, InterpretError> {
match statement.as_token().category() {
TokenCategory::Identifier(IdentifierType::ACT(cat)) => {
Ok(NaslValue::AttackCategory(*cat))
}
_ => unreachable!(
"AttackCategory must have ACT token but got {:?}, this is an bug within the lexer.",
statement.as_token()
),
}
}
}