dsct 0.2.5

LLM-friendly packet dissector CLI
Documentation
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! SQL expression parser for packet filters.
//!
//! Converts SQL WHERE-clause expressions into [`FilterExpr`] trees using
//! the `sqlparser` crate.  The `packet_number` identifier is treated as a
//! virtual column for pre-dissection packet-number filtering.
//!
//! # Examples
//!
//! ```text
//! tcp AND ipv4.src = '10.0.0.1'
//! tcp.dst_port > 1024
//! (tcp OR udp) AND NOT dns
//! packet_number BETWEEN 1 AND 100
//! ```

use sqlparser::ast::{BinaryOperator, Expr, UnaryOperator, Value};
use sqlparser::dialect::GenericDialect;
use sqlparser::parser::Parser;
use sqlparser::tokenizer::Token;

use crate::filter::{CompareOp, PacketNumberFilter, WhereClause, normalize_protocol_name};
use crate::filter_expr::FilterExpr;

/// Virtual column name for packet-number filtering.
const PACKET_NUMBER_COL: &str = "packet_number";

/// Parse a SQL expression string into a [`FilterExpr`].
///
/// The input should be the body of a WHERE clause (without the `WHERE`
/// keyword).  Supports `AND`, `OR`, `NOT`, parentheses, comparison operators
/// (`=`, `!=`/`<>`, `>`, `<`, `>=`, `<=`), `BETWEEN`, `IN`, and bare
/// identifiers as protocol existence checks.
pub fn parse(input: &str) -> Result<FilterExpr, String> {
    let dialect = GenericDialect {};
    let mut parser = Parser::new(&dialect)
        .try_with_sql(input)
        .map_err(|e| format!("SQL parse error: {e}"))?;
    let expr = parser
        .parse_expr()
        .map_err(|e| format!("SQL parse error: {e}"))?;

    // Ensure the entire input was consumed.
    if parser.peek_token().token != Token::EOF {
        return Err(format!(
            "unexpected trailing input after expression: {}",
            input
        ));
    }

    convert_expr(&expr)
}

/// Wrap an expression in `NOT` when `negated` is true.
fn maybe_negate(expr: FilterExpr, negated: bool) -> FilterExpr {
    if negated {
        FilterExpr::Not(Box::new(expr))
    } else {
        expr
    }
}

/// Recursively convert a `sqlparser` AST expression into a [`FilterExpr`].
fn convert_expr(expr: &Expr) -> Result<FilterExpr, String> {
    match expr {
        Expr::BinaryOp { left, op, right } => convert_binary_op(left, op, right),

        Expr::UnaryOp {
            op: UnaryOperator::Not,
            expr: inner,
        } => {
            let inner = convert_expr(inner)?;
            Ok(FilterExpr::Not(Box::new(inner)))
        }

        Expr::Nested(inner) => convert_expr(inner),

        Expr::Identifier(ident) => Ok(FilterExpr::Protocol(normalize_protocol_name(&ident.value))),

        // Compound identifier without comparison → protocol existence check.
        Expr::CompoundIdentifier(parts) if !parts.is_empty() => Ok(FilterExpr::Protocol(
            normalize_protocol_name(&parts[0].value),
        )),

        Expr::Between {
            expr: inner,
            negated,
            low,
            high,
        } => convert_between(inner, *negated, low, high),

        Expr::InList {
            expr: inner,
            list,
            negated,
        } => convert_in_list(inner, list, *negated),

        Expr::Value(val) => match &val.value {
            Value::Boolean(true) => Err("bare TRUE is not supported as a filter".into()),
            Value::Boolean(false) => Err("bare FALSE is not supported as a filter".into()),
            _ => Err(format!("unsupported SQL expression: {expr}")),
        },

        _ => Err(format!("unsupported SQL expression: {expr}")),
    }
}

/// Convert a binary operator expression.
fn convert_binary_op(left: &Expr, op: &BinaryOperator, right: &Expr) -> Result<FilterExpr, String> {
    match op {
        BinaryOperator::And => {
            let l = convert_expr(left)?;
            let r = convert_expr(right)?;
            Ok(FilterExpr::And(Box::new(l), Box::new(r)))
        }
        BinaryOperator::Or => {
            let l = convert_expr(left)?;
            let r = convert_expr(right)?;
            Ok(FilterExpr::Or(Box::new(l), Box::new(r)))
        }
        BinaryOperator::Eq
        | BinaryOperator::NotEq
        | BinaryOperator::Lt
        | BinaryOperator::LtEq
        | BinaryOperator::Gt
        | BinaryOperator::GtEq => convert_comparison(left, op, right),
        _ => Err(format!("unsupported operator: {op}")),
    }
}

/// Convert a comparison expression (e.g. `ipv4.src = '10.0.0.1'`).
fn convert_comparison(
    left: &Expr,
    op: &BinaryOperator,
    right: &Expr,
) -> Result<FilterExpr, String> {
    let compare_op = match op {
        BinaryOperator::Eq => CompareOp::Eq,
        BinaryOperator::NotEq => CompareOp::Ne,
        BinaryOperator::Lt => CompareOp::Lt,
        BinaryOperator::LtEq => CompareOp::Le,
        BinaryOperator::Gt => CompareOp::Gt,
        BinaryOperator::GtEq => CompareOp::Ge,
        _ => return Err(format!("unsupported comparison operator: {op}")),
    };

    let (name, field) = extract_field_ref(left)?;
    let value = extract_value(right)?;

    if name == PACKET_NUMBER_COL && field.is_none() {
        let n: u64 = value
            .parse()
            .map_err(|_| format!("packet_number requires an integer value, got '{value}'"))?;
        return convert_packet_number_comparison(compare_op, n);
    }

    let field = field.ok_or_else(|| {
        format!("comparison requires protocol.field format on left side, got '{name}'")
    })?;

    Ok(FilterExpr::Where(WhereClause::new(
        name, field, compare_op, value,
    )))
}

/// Convert a packet_number comparison into a [`FilterExpr::PacketNumber`].
fn convert_packet_number_comparison(op: CompareOp, n: u64) -> Result<FilterExpr, String> {
    let pnf = match op {
        CompareOp::Eq => PacketNumberFilter::from_ranges(vec![(n, n)]),
        CompareOp::Ge => PacketNumberFilter::from_ranges(vec![(n, u64::MAX)]),
        CompareOp::Gt => {
            if n == u64::MAX {
                return Err("packet_number > u64::MAX is always false".into());
            }
            PacketNumberFilter::from_ranges(vec![(n + 1, u64::MAX)])
        }
        CompareOp::Le => PacketNumberFilter::from_ranges(vec![(1, n)]),
        CompareOp::Lt => {
            if n <= 1 {
                return Err(
                    "packet_number < 1 is always false (packet numbers are 1-based)".into(),
                );
            }
            PacketNumberFilter::from_ranges(vec![(1, n - 1)])
        }
        CompareOp::Ne => {
            // NOT packet_number = N
            return Ok(FilterExpr::Not(Box::new(FilterExpr::PacketNumber(
                PacketNumberFilter::from_ranges(vec![(n, n)]),
            ))));
        }
    };
    Ok(FilterExpr::PacketNumber(pnf))
}

/// Extract a `(name, field)` pair from the left side of a comparison.
///
/// - `Identifier("packet_number")` → `("packet_number", None)`
/// - `CompoundIdentifier(["ipv4", "src"])` → `("ipv4", Some("src"))`
fn extract_field_ref(expr: &Expr) -> Result<(String, Option<String>), String> {
    match expr {
        Expr::Identifier(ident) => Ok((ident.value.clone(), None)),
        Expr::CompoundIdentifier(parts) if parts.len() == 2 => {
            Ok((parts[0].value.clone(), Some(parts[1].value.clone())))
        }
        Expr::CompoundIdentifier(parts) if parts.len() > 2 => {
            let protocol = parts[0].value.clone();
            let field = parts[1..]
                .iter()
                .map(|p| p.value.as_str())
                .collect::<Vec<_>>()
                .join(".");
            Ok((protocol, Some(field)))
        }
        _ => Err(format!(
            "expected field reference (protocol.field) on left side of comparison, got: {expr}"
        )),
    }
}

/// Extract a string value from the right side of a comparison.
fn extract_value(expr: &Expr) -> Result<String, String> {
    match expr {
        Expr::Value(val) => match &val.value {
            Value::SingleQuotedString(s) => Ok(s.clone()),
            Value::DoubleQuotedString(s) => Ok(s.clone()),
            Value::Number(s, _) => Ok(s.clone()),
            _ => Err(format!("unsupported value type: {}", val.value)),
        },
        Expr::UnaryOp {
            op: UnaryOperator::Minus,
            expr: inner,
        } => {
            // Handle negative numbers: -1 → "-1"
            let v = extract_value(inner)?;
            Ok(format!("-{v}"))
        }
        _ => Err(format!("expected a literal value, got: {expr}")),
    }
}

/// Convert a `BETWEEN` expression.
fn convert_between(
    inner: &Expr,
    negated: bool,
    low: &Expr,
    high: &Expr,
) -> Result<FilterExpr, String> {
    let (name, field) = extract_field_ref(inner)?;
    let low_val = extract_value(low)?;
    let high_val = extract_value(high)?;

    if name == PACKET_NUMBER_COL && field.is_none() {
        let lo: u64 = low_val
            .parse()
            .map_err(|_| format!("packet_number BETWEEN requires integers, got '{low_val}'"))?;
        let hi: u64 = high_val
            .parse()
            .map_err(|_| format!("packet_number BETWEEN requires integers, got '{high_val}'"))?;
        let expr = FilterExpr::PacketNumber(PacketNumberFilter::from_ranges(vec![(lo, hi)]));
        return Ok(maybe_negate(expr, negated));
    }

    let field = field.ok_or_else(|| {
        format!("BETWEEN requires protocol.field format on left side, got '{name}'")
    })?;
    let ge = FilterExpr::Where(WhereClause::new(
        name.clone(),
        field.clone(),
        CompareOp::Ge,
        low_val,
    ));
    let le = FilterExpr::Where(WhereClause::new(name, field, CompareOp::Le, high_val));
    let expr = FilterExpr::And(Box::new(ge), Box::new(le));
    Ok(maybe_negate(expr, negated))
}

/// Convert an `IN` list expression.
fn convert_in_list(inner: &Expr, list: &[Expr], negated: bool) -> Result<FilterExpr, String> {
    let (name, field) = extract_field_ref(inner)?;

    if name == PACKET_NUMBER_COL && field.is_none() {
        let mut ranges = Vec::with_capacity(list.len());
        for item in list {
            let val = extract_value(item)?;
            let n: u64 = val
                .parse()
                .map_err(|_| format!("packet_number IN requires integers, got '{val}'"))?;
            ranges.push((n, n));
        }
        let expr = FilterExpr::PacketNumber(PacketNumberFilter::from_ranges(ranges));
        return Ok(maybe_negate(expr, negated));
    }

    if list.is_empty() {
        return Err("IN list must not be empty".into());
    }
    let field = field
        .ok_or_else(|| format!("IN requires protocol.field format on left side, got '{name}'"))?;
    let mut exprs: Vec<FilterExpr> = Vec::with_capacity(list.len());
    for item in list {
        let val = extract_value(item)?;
        exprs.push(FilterExpr::Where(WhereClause::new(
            name.clone(),
            field.clone(),
            CompareOp::Eq,
            val,
        )));
    }
    let mut result = exprs.remove(0);
    for e in exprs {
        result = FilterExpr::Or(Box::new(result), Box::new(e));
    }
    Ok(maybe_negate(result, negated))
}

#[cfg(test)]
mod tests {
    use super::*;
    use packet_dissector_core::field::FieldValue;
    use packet_dissector_core::packet::{DissectBuffer, Packet};
    use packet_dissector_test_alloc::test_desc;

    fn make_buf(
        name: &'static str,
        fields: &[(&'static str, FieldValue<'static>)],
    ) -> DissectBuffer<'static> {
        let mut buf = DissectBuffer::new();
        buf.begin_layer(name, None, &[], 0..0);
        for (fname, fval) in fields {
            buf.push_field(test_desc(fname, fname), fval.clone(), 0..0);
        }
        buf.end_layer();
        buf
    }

    fn make_tcp_ipv4_buf() -> DissectBuffer<'static> {
        let mut buf = DissectBuffer::new();
        buf.begin_layer("IPv4", None, &[], 0..0);
        buf.push_field(
            test_desc("src", "Source"),
            FieldValue::Ipv4Addr([10, 0, 0, 1]),
            0..0,
        );
        buf.end_layer();
        buf.begin_layer("TCP", None, &[], 0..0);
        buf.push_field(
            test_desc("dst_port", "Destination Port"),
            FieldValue::U16(8080),
            0..0,
        );
        buf.end_layer();
        buf
    }

    static EMPTY_DATA: [u8; 0] = [];

    fn pkt_from<'a>(buf: &'a DissectBuffer<'static>) -> Packet<'a, 'static> {
        Packet::new(buf, &EMPTY_DATA)
    }

    // --- Basic comparisons ---

    #[test]
    fn eq_string() {
        let expr = parse("ipv4.src = '10.0.0.1'").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn eq_number() {
        let expr = parse("tcp.dst_port = 8080").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn gt_number() {
        let expr = parse("tcp.dst_port > 80").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn lt_number() {
        let expr = parse("tcp.dst_port < 9000").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn ne_number() {
        let expr = parse("tcp.dst_port != 80").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn ne_sqlstyle() {
        let expr = parse("tcp.dst_port <> 80").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    // --- Protocol existence ---

    #[test]
    fn protocol_exists() {
        let expr = parse("tcp").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn protocol_not_exists() {
        let expr = parse("dns").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(!expr.matches(&pkt_from(&buf)));
    }

    // --- Boolean operators ---

    #[test]
    fn and_expr() {
        let expr = parse("tcp AND ipv4.src = '10.0.0.1'").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn or_expr() {
        let expr = parse("dns OR tcp").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn not_expr() {
        let expr = parse("NOT dns").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    // --- Parentheses ---

    #[test]
    fn parentheses() {
        let expr = parse("(tcp OR dns) AND ipv4.src = '10.0.0.1'").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn nested_parentheses() {
        let expr = parse("NOT (dns AND (tcp OR udp))").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    // --- packet_number virtual column ---

    #[test]
    fn packet_number_eq() {
        let expr = parse("packet_number = 5").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches_with_number(&pkt_from(&buf), 5));
        assert!(!expr.matches_with_number(&pkt_from(&buf), 4));
    }

    #[test]
    fn packet_number_between() {
        let expr = parse("packet_number BETWEEN 10 AND 20").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches_with_number(&pkt_from(&buf), 10));
        assert!(expr.matches_with_number(&pkt_from(&buf), 15));
        assert!(expr.matches_with_number(&pkt_from(&buf), 20));
        assert!(!expr.matches_with_number(&pkt_from(&buf), 9));
        assert!(!expr.matches_with_number(&pkt_from(&buf), 21));
    }

    #[test]
    fn packet_number_in() {
        let expr = parse("packet_number IN (1, 5, 10)").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches_with_number(&pkt_from(&buf), 1));
        assert!(expr.matches_with_number(&pkt_from(&buf), 5));
        assert!(expr.matches_with_number(&pkt_from(&buf), 10));
        assert!(!expr.matches_with_number(&pkt_from(&buf), 3));
    }

    #[test]
    fn packet_number_gt() {
        let expr = parse("packet_number > 100").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches_with_number(&pkt_from(&buf), 101));
        assert!(!expr.matches_with_number(&pkt_from(&buf), 100));
    }

    #[test]
    fn packet_number_combined_with_protocol() {
        let expr = parse("packet_number BETWEEN 1 AND 100 AND tcp").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches_with_number(&pkt_from(&buf), 50));
        assert!(!expr.matches_with_number(&pkt_from(&buf), 150));
    }

    #[test]
    fn packet_number_only_detection() {
        let pn = parse("packet_number BETWEEN 1 AND 100").unwrap();
        assert!(pn.is_packet_number_only());

        let mixed = parse("packet_number = 1 AND tcp").unwrap();
        assert!(!mixed.is_packet_number_only());
    }

    // --- BETWEEN for fields ---

    #[test]
    fn field_between() {
        let expr = parse("tcp.dst_port BETWEEN 8000 AND 9000").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn field_between_out_of_range() {
        let expr = parse("tcp.dst_port BETWEEN 1 AND 80").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(!expr.matches(&pkt_from(&buf)));
    }

    // --- IN for fields ---

    #[test]
    fn field_in_list() {
        let expr = parse("tcp.dst_port IN (80, 443, 8080)").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(expr.matches(&pkt_from(&buf)));
    }

    #[test]
    fn field_in_list_no_match() {
        let expr = parse("tcp.dst_port IN (80, 443)").unwrap();
        let buf = make_tcp_ipv4_buf();
        assert!(!expr.matches(&pkt_from(&buf)));
    }

    // --- Negative numbers ---

    #[test]
    fn negative_number() {
        let expr = parse("test.val > -1").unwrap();
        let buf = make_buf("Test", &[("val", FieldValue::I32(0))]);
        assert!(expr.matches(&pkt_from(&buf)));
    }

    // --- Error cases ---

    #[test]
    fn empty_input_errors() {
        // Empty input will be caught by sqlparser
        assert!(parse("").is_err());
    }

    #[test]
    fn invalid_syntax() {
        assert!(parse("AND AND").is_err());
    }

    #[test]
    fn trailing_input() {
        assert!(parse("tcp extra_stuff").is_err());
    }

    // --- Nested field ---

    #[test]
    fn nested_field() {
        let expr = parse("dns.questions.name = 'example.com'").unwrap();
        let mut buf = DissectBuffer::new();
        buf.begin_layer("DNS", None, &[], 0..0);
        let arr = buf.begin_container(
            test_desc("questions", "Questions"),
            FieldValue::Array(0..0),
            0..0,
        );
        let obj = buf.begin_container(test_desc("q", "Q"), FieldValue::Object(0..0), 0..0);
        buf.push_field(
            test_desc("name", "Name"),
            FieldValue::Str("example.com"),
            0..0,
        );
        buf.end_container(obj);
        buf.end_container(arr);
        buf.end_layer();
        assert!(expr.matches(&pkt_from(&buf)));
    }
}