flowscope 0.22.0

Passive flow & session tracking for packet capture (runtime-free, cross-platform)
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
//! Unified error type for flowscope.
//!
//! Every fallible API across the crate returns
//! [`Result<T>`](crate::Result) — an alias for `Result<T, Error>`.
//! `Error` carries:
//!
//! - a [`Module`] discriminant identifying which subsystem produced
//!   the error (HTTP / TLS / DNS / ICMP / pcap / reassembler /
//!   tracker / driver / emit / detect / aggregate / correlate /
//!   layers),
//! - an [`ErrorCode`] for ergonomic matching in user code
//!   (`Parse` / `BufferOverflow` / `Io` / `Unsupported` /
//!   `Truncated` / `Eof` / `Other`),
//! - a human-readable `message` whose format is *not* API-stable
//!   across releases (it may grow detail in patch versions),
//! - an optional `source` chain to the upstream parser library's
//!   error type (`httparse::Error`, `tls_parser::Err`,
//!   `simple_dns::SimpleDnsError`, `pcap_file::PcapError`,
//!   `std::io::Error`), so [`std::error::Error::source`] walks
//!   produce a complete trace.
//!
//! # Matching by kind
//!
//! ```
//! use flowscope::{Error, ErrorCode, Module};
//!
//! fn classify(e: &Error) {
//!     match (e.module(), e.code()) {
//!         (Module::Http, ErrorCode::BufferOverflow) => { /* … */ }
//!         (Module::Pcap, ErrorCode::Io)              => { /* … */ }
//!         _                                          => { /* … */ }
//!     }
//! }
//! ```
//!
//! # Source-chain walking
//!
//! `Error` implements `std::error::Error`, so existing tools
//! (`anyhow`, log formatters, the `?` operator) compose without
//! flowscope-specific code.
//!
//! ```no_run
//! use std::error::Error as _;
//!
//! fn print_chain(e: &flowscope::Error) {
//!     eprintln!("{e}");
//!     let mut src = e.source();
//!     while let Some(s) = src {
//!         eprintln!("  caused by: {s}");
//!         src = s.source();
//!     }
//! }
//! ```

use std::{error::Error as StdError, fmt};

/// Declares the [`Module`] enum and its `Display` slug from ONE
/// table, so the variant list and its display string can't drift
/// apart and adding a subsystem is a one-line edit (issue #139).
macro_rules! module_enum {
    (
        $(#[$enum_meta:meta])*
        pub enum $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident => $slug:literal ),+ $(,)?
        }
    ) => {
        $(#[$enum_meta])*
        pub enum $name {
            $( $(#[$vmeta])* $variant, )+
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                let s = match self {
                    $( $name::$variant => $slug, )+
                };
                f.write_str(s)
            }
        }
    };
}

module_enum! {
    /// Subsystem identifier for [`Error`].
    ///
    /// Used in `match (e.module(), e.code()) { … }` patterns.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[non_exhaustive]
    pub enum Module {
        /// HTTP parser (`flowscope::http`).
        Http => "http",
        /// TLS parser (`flowscope::tls`).
        Tls => "tls",
        /// DNS parser (`flowscope::dns`).
        Dns => "dns",
        /// ICMP parser (`flowscope::icmp`).
        Icmp => "icmp",
        /// pcap source (`flowscope::pcap`).
        Pcap => "pcap",
        /// TCP reassembler.
        Reassembler => "reassembler",
        /// Flow tracker.
        Tracker => "tracker",
        /// `flowscope::layers` per-packet introspection.
        Layers => "layers",
        /// Typed driver / slot-handle path (`flowscope::driver`).
        /// New in 0.12.0 (plan 131).
        Driver => "driver",
        /// Emit writers (`flowscope::emit`). New in 0.12.0.
        Emit => "emit",
        /// Detection primitives (`flowscope::detect`). New in 0.12.0.
        Detect => "detect",
        /// Aggregation primitives (`flowscope::aggregate`).
        /// New in 0.12.0.
        Aggregate => "aggregate",
        /// Cross-flow correlation primitives (`flowscope::correlate`).
        /// New in 0.12.0.
        Correlate => "correlate",
        /// ARP parser (`flowscope::arp`).
        Arp => "arp",
        /// IPv6 Neighbor Discovery parser (`flowscope::ndp`).
        Ndp => "ndp",
        /// LLDP parser (`flowscope::lldp`).
        Lldp => "lldp",
        /// CDP parser (`flowscope::cdp`).
        Cdp => "cdp",
        /// DHCP parser (`flowscope::dhcp`).
        Dhcp => "dhcp",
        /// SSDP parser (`flowscope::ssdp`).
        Ssdp => "ssdp",
        /// NetBIOS-NS parser (`flowscope::netbios_ns`).
        NetbiosNs => "netbios-ns",
        /// STUN parser (`flowscope::stun`).
        Stun => "stun",
        /// SSH parser (`flowscope::ssh`).
        Ssh => "ssh",
        /// NTP parser (`flowscope::ntp`).
        Ntp => "ntp",
        /// TFTP parser (`flowscope::tftp`).
        Tftp => "tftp",
        /// WireGuard parser (`flowscope::wireguard`).
        Wireguard => "wireguard",
        /// Modbus parser (`flowscope::modbus`).
        Modbus => "modbus",
        /// RDP parser (`flowscope::rdp`).
        Rdp => "rdp",
        /// SNMP parser (`flowscope::snmp`).
        Snmp => "snmp",
        /// RADIUS parser (`flowscope::radius`).
        Radius => "radius",
        /// DNP3 parser (`flowscope::dnp3`).
        Dnp3 => "dnp3",
        /// SMB parser (`flowscope::smb`).
        Smb => "smb",
        /// LDAP parser (`flowscope::ldap`).
        Ldap => "ldap",
        /// Kerberos parser (`flowscope::kerberos`).
        Kerberos => "kerberos",
        /// QUIC parser (`flowscope::quic`).
        Quic => "quic",
    }
}

/// Stable short identifier for matching in user code.
///
/// The `message` on [`Error`] is human-readable; this enum is the
/// machine-checkable axis. Pattern-match on `(module, code)` to
/// route errors without parsing strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
    /// Wire bytes did not parse cleanly.
    Parse,
    /// A bounded buffer (reassembler, parser, correlator) exceeded
    /// its configured cap.
    BufferOverflow,
    /// An I/O error surfaced from the underlying source.
    Io,
    /// The operation is recognised but not yet implemented for the
    /// observed input (e.g. an unrecognised TLS version).
    Unsupported,
    /// The input ended before the expected message boundary.
    Truncated,
    /// The source has no more data.
    Eof,
    /// A catch-all for cases that don't fit the above. Prefer one
    /// of the typed codes; reach for `Other` only when none fits.
    Other,
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            ErrorCode::Parse => "parse",
            ErrorCode::BufferOverflow => "buffer-overflow",
            ErrorCode::Io => "io",
            ErrorCode::Unsupported => "unsupported",
            ErrorCode::Truncated => "truncated",
            ErrorCode::Eof => "eof",
            ErrorCode::Other => "other",
        };
        f.write_str(s)
    }
}

/// Routing-and-context kind for an [`Error`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorKind {
    /// Subsystem that produced the error.
    pub module: Module,
    /// Stable code for matching.
    pub code: ErrorCode,
    /// Human-readable diagnostic. Format may change between
    /// releases; do not parse.
    pub message: String,
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}: {}", self.module, self.code, self.message)
    }
}

/// The unified flowscope error type.
///
/// Constructed via crate-internal helpers (`Error::parse`,
/// `Error::buffer_overflow`, `Error::io`, …); consumers
/// inspect via [`Error::module`] / [`Error::code`] /
/// [`Error::kind`] and walk the `source` chain via
/// [`std::error::Error::source`].
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    source: Option<Box<dyn StdError + Send + Sync + 'static>>,
}

impl Error {
    #[cfg(any(feature = "http", feature = "tls", feature = "dns"))]
    pub(crate) fn parse(module: Module, message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind {
                module,
                code: ErrorCode::Parse,
                message: message.into(),
            },
            source: None,
        }
    }

    #[cfg(any(feature = "extractors", feature = "pcap", feature = "http"))]
    pub(crate) fn parse_with<E>(module: Module, message: impl Into<String>, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        Self {
            kind: ErrorKind {
                module,
                code: ErrorCode::Parse,
                message: message.into(),
            },
            source: Some(Box::new(source)),
        }
    }

    #[cfg(any(feature = "http", feature = "tls"))]
    pub(crate) fn buffer_overflow(module: Module, cap: usize) -> Self {
        Self {
            kind: ErrorKind {
                module,
                code: ErrorCode::BufferOverflow,
                message: format!("buffer exceeded cap={cap}"),
            },
            source: None,
        }
    }

    #[cfg(feature = "pcap")]
    pub(crate) fn io(module: Module, source: std::io::Error) -> Self {
        Self {
            kind: ErrorKind {
                module,
                code: ErrorCode::Io,
                message: source.to_string(),
            },
            source: Some(Box::new(source)),
        }
    }

    /// General constructor used by the per-module `ParseError`
    /// → `crate::Error` conversions (issue #85). Maps a module's
    /// rich, typed parse failure onto the unified `(module, code,
    /// message)` triple without a `source` chain (the per-module
    /// enums are leaf errors).
    #[cfg(any(
        feature = "arp",
        feature = "ndp",
        feature = "lldp",
        feature = "cdp",
        feature = "dhcp",
        feature = "ssdp",
        feature = "netbios-ns",
        feature = "stun",
        feature = "ssh",
        feature = "ntp",
        feature = "tftp",
        feature = "wireguard",
        feature = "modbus",
        feature = "rdp",
        feature = "snmp",
        feature = "radius",
        feature = "dnp3",
        feature = "smb",
        feature = "ldap",
        feature = "kerberos",
        feature = "quic",
    ))]
    pub(crate) fn with_code(module: Module, code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            kind: ErrorKind {
                module,
                code,
                message: message.into(),
            },
            source: None,
        }
    }

    /// The full kind (module + code + message) of this error.
    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }

    /// The subsystem that produced this error.
    pub fn module(&self) -> Module {
        self.kind.module
    }

    /// The stable code for this error. Match on
    /// `(module(), code())` to route errors.
    pub fn code(&self) -> ErrorCode {
        self.kind.code
    }

    /// `true` for transient / per-message failures
    /// (`Parse`, `BufferOverflow`, `Truncated`, `Unsupported`);
    /// `false` for terminal failures (`Io`, `Eof`).
    ///
    /// "Recoverable" here means "the calling pipeline can keep
    /// going against the next message / packet / flow." It does
    /// not promise the *current* operation can retry.
    pub fn is_recoverable(&self) -> bool {
        matches!(
            self.kind.code,
            ErrorCode::Parse
                | ErrorCode::BufferOverflow
                | ErrorCode::Truncated
                | ErrorCode::Unsupported
        )
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.kind, f)
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.source
            .as_deref()
            .map(|s| s as &(dyn StdError + 'static))
    }
}

/// Result alias used throughout flowscope.
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(any(feature = "http", feature = "tls", feature = "dns"))]
    #[test]
    fn error_carries_module_and_code() {
        let e = Error::parse(Module::Http, "bad request line");
        assert_eq!(e.module(), Module::Http);
        assert_eq!(e.code(), ErrorCode::Parse);
        assert!(e.is_recoverable());
        assert!(e.source().is_none());
    }

    #[cfg(feature = "pcap")]
    #[test]
    fn error_wraps_source() {
        let io = std::io::Error::other("disk gone");
        let e = Error::io(Module::Pcap, io);
        assert_eq!(e.module(), Module::Pcap);
        assert_eq!(e.code(), ErrorCode::Io);
        assert!(!e.is_recoverable());
        assert!(e.source().is_some());
    }

    #[cfg(any(feature = "http", feature = "tls", feature = "dns"))]
    #[test]
    fn display_format() {
        let e = Error::parse(Module::Tls, "alert received");
        let s = format!("{e}");
        assert!(s.contains("tls"));
        assert!(s.contains("parse"));
        assert!(s.contains("alert received"));
    }

    #[test]
    fn send_sync_static() {
        fn assert_traits<T: Send + Sync + 'static>() {}
        assert_traits::<Error>();
    }

    #[cfg(feature = "pcap")]
    #[test]
    fn source_chain_walks() {
        use std::error::Error as _;
        let io = std::io::Error::other("disk gone");
        let e = Error::io(Module::Pcap, io);
        let s = e.source().unwrap();
        assert!(format!("{s}").contains("disk gone"));
    }

    #[cfg(any(feature = "http", feature = "tls"))]
    #[test]
    fn buffer_overflow_includes_cap() {
        let e = Error::buffer_overflow(Module::Http, 8192);
        assert!(e.to_string().contains("8192"));
    }

    #[test]
    fn module_display_covers_all_variants() {
        // Plan 131: new variants render as snake_case slugs.
        assert_eq!(Module::Driver.to_string(), "driver");
        assert_eq!(Module::Emit.to_string(), "emit");
        assert_eq!(Module::Detect.to_string(), "detect");
        assert_eq!(Module::Aggregate.to_string(), "aggregate");
        assert_eq!(Module::Correlate.to_string(), "correlate");
        // Pre-existing variants unchanged.
        assert_eq!(Module::Http.to_string(), "http");
        assert_eq!(Module::Layers.to_string(), "layers");
    }
}