netring 0.29.0

High-performance zero-copy packet I/O for Linux (AF_PACKET TPACKET_V3 + AF_XDP)
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
//! Per-event context passed to handlers.
//!
//! `Ctx` lives on the dispatch stack — never heap-allocated.
//! Handlers receive a single `&mut Ctx<'_>` (alongside the typed
//! event payload) and pull what they need via methods on `Ctx`:
//!
//! ```ignore
//! Monitor::builder()
//!     .state::<MyState>()
//!     .counter::<IpAddr>(Duration::from_secs(10), Duration::from_secs(1))
//!     .on_ctx::<Http>(|req, ctx| {
//!         let counters = ctx.counter_mut::<IpAddr>();
//!         counters.bump(req.client_ip(), ctx.ts);
//!         ctx.state_mut::<MyState>().requests += 1;
//!         Ok(())
//!     });
//! ```
//!
//! ## Why method-style instead of axum-style extractors
//!
//! The first cut of this module shipped an `FromCtx` trait with
//! multi-extractor blanket impls (1..=8 arities). It doesn't
//! compile: every `<P as FromCtx>::from_ctx(&mut ctx)` call holds
//! `&mut Ctx` for as long as its return value lives, so the
//! second extractor can't re-borrow. axum gets away with this
//! because async-await sequences the borrows; sync Rust can't.
//!
//! Method accessors on `Ctx` give the same ergonomics without
//! the borrow-checker headache: each call is its own bounded
//! borrow, and the compiler tracks disjoint field accesses
//! (`state_map`, `counters`, `sink`) correctly.

use std::sync::LazyLock;

use flowscope::Timestamp;
use flowscope::well_known::LabelTable;

mod from_ctx;
mod split;

pub use from_ctx::{CounterRegistry, FlowStateRegistry, StateMap};

use crate::correlate::TimeBucketedCounter;
use crate::protocol::FlowKey;

/// Process-wide default well-known label table (inherits flowscope's
/// built-in port map). Used as the fallback for any [`Ctx`] built
/// without a monitor-supplied table — synthetic test/bench `Ctx`s and
/// the lifecycle/tick paths before a custom `.label_table(...)` lands.
static DEFAULT_LABEL_TABLE: LazyLock<LabelTable> = LazyLock::new(LabelTable::new);

/// `&'static` borrow of [`DEFAULT_LABEL_TABLE`]. The `LazyLock`
/// deref-coerces to `&LabelTable`; the static lives forever so the
/// borrow is `'static` and fits any `Ctx<'a>`.
pub(crate) fn default_label_table() -> &'static LabelTable {
    &DEFAULT_LABEL_TABLE
}

/// Tag for which capture source this event came from.
/// `SourceIdx(0)` for single-interface monitors; multi-interface
/// (Phase E) increments per registered iface.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SourceIdx(pub u8);

/// Runtime context passed to every handler invocation.
///
/// The `flow` / `ts` / `source` fields are `pub` for direct read.
/// State / counter / sink access goes through the typed accessor
/// methods so the storage maps can stay `pub(crate)`.
pub struct Ctx<'a> {
    /// The flow key for the current event, if any.
    ///
    /// Held by value (`FlowKey` is `Copy`) so dispatch sites can
    /// stamp a per-message key without lifetime gymnastics —
    /// borrowing through `Option<&'a FlowKey>` would require a
    /// place to anchor the borrow that outlives the `Ctx`.
    ///
    /// **Prefer `payload.key` over `ctx.flow` when the event
    /// payload carries one.** For lifecycle events
    /// (`FlowStarted/Ended/Established<P>`) and message events
    /// (`HttpMessage`, `DnsMessage`, …), `payload.key` is the
    /// typed value with no `Option` indirection. For non-flow
    /// events (`Tick`) `ctx.flow` is `None`. The same key is
    /// available through both paths for flow events; the field
    /// is preserved as a stable accessor for cross-cutting
    /// handlers (e.g. a tick handler that logs the most recent
    /// flow, where the typed payload doesn't carry one).
    pub flow: Option<FlowKey>,

    /// Timestamp of the current event.
    pub ts: Timestamp,

    /// Source-interface index.
    pub source: SourceIdx,

    /// 0.21 D.4: optional human-readable name set on the parent
    /// monitor via [`crate::monitor::MonitorBuilder::name`].
    /// Handlers running under multiple monitors in the same
    /// process can branch on this to disambiguate (e.g. log
    /// `target = monitor_name` or stamp `with("monitor", name)`
    /// on emitted anomalies). Borrowed from the
    /// [`Monitor`](crate::monitor::Monitor)'s
    /// owned `Box<str>` storage at dispatch time; `None` when
    /// `.name(...)` was not called.
    pub monitor_name: Option<&'a str>,

    /// Per-monitor user state, keyed by `TypeId`.
    pub(crate) state_map: &'a mut StateMap,

    /// The anomaly sink (Phase C fills in the trait body).
    pub(crate) sink: &'a mut dyn crate::anomaly::sink::AnomalySink,

    /// Per-monitor counter storage.
    pub(crate) counters: &'a mut CounterRegistry,

    /// 0.21 I.7: per-flow user state. Each `T: Default + Send +
    /// 'static` registered via
    /// [`crate::monitor::MonitorBuilder::flow_state`] gets a
    /// per-flow slot lazily created on
    /// [`Self::flow_state_mut::<T>`] access. Backed by
    /// [`flowscope::correlate::FlowStateMap`].
    pub(crate) flow_states: &'a mut FlowStateRegistry,

    /// 0.22: active well-known label table for app/protocol-label
    /// lookups (`FiveTupleKey::app_label_with`). Defaults to
    /// flowscope's built-in table; overridden per-monitor via
    /// [`crate::monitor::MonitorBuilder::label_table`]. Read through
    /// [`Self::label_table`].
    pub(crate) label_table: &'a LabelTable,

    /// 0.22: read-only flow tracker for ICMP→flow correlation
    /// ([`Self::lookup_icmp_flow`]). `Some` on the live per-packet
    /// dispatch path (the run loop borrows `driver.tracker()` here);
    /// `None` on synthetic / tick / drain `Ctx`s that have no live
    /// capture behind them.
    pub(crate) tracker: Option<&'a flowscope::FlowTracker<flowscope::extract::FiveTuple, ()>>,

    /// Issue #19: read-only ARP binding table for cross-protocol IP→MAC
    /// lookups (e.g. a TLS handler annotating a flow with the peer's MAC).
    /// `Some` only inside the ARP drain (`dispatch_arp`), where the table is
    /// borrowed `&` *after* the current frame's binding was learned; `None`
    /// everywhere else. Read through [`Self::arp_table`] (feature `arp`). The
    /// field is the unconditional `NeighborTable` type so the dozen `Ctx`
    /// construction sites stay feature-agnostic.
    #[cfg_attr(not(feature = "arp"), allow(dead_code))]
    pub(crate) arp_table:
        Option<&'a flowscope::correlate::NeighborTable<std::net::Ipv4Addr, flowscope::MacAddr>>,
}

impl<'a> Ctx<'a> {
    /// Bench-only constructor — `benches/zero_alloc.rs` needs to
    /// manually assemble a `Ctx` to drive the dispatcher without
    /// a full `Monitor`. Not part of the public API outside the
    /// bench feature.
    #[cfg(feature = "bench-zero-alloc")]
    pub fn new_for_bench(
        ts: Timestamp,
        state_map: &'a mut StateMap,
        sink: &'a mut dyn crate::anomaly::sink::AnomalySink,
        counters: &'a mut CounterRegistry,
        flow_states: &'a mut FlowStateRegistry,
    ) -> Self {
        Self {
            flow: None,
            ts,
            source: SourceIdx(0),
            monitor_name: None,
            state_map,
            sink,
            counters,
            flow_states,
            label_table: default_label_table(),
            tracker: None,
            arp_table: None,
        }
    }

    /// Constructor exposed for integration tests that need to
    /// drive the dispatcher with a custom `Ctx`. Not part of the
    /// documented public API (`#[doc(hidden)]`). `monitor_name`
    /// defaults to `None`; the `label_table` defaults to the
    /// built-in table and `tracker` to `None`; production callers
    /// in the run loop set those via the [`Ctx`] struct literal
    /// directly.
    #[doc(hidden)]
    pub fn new(
        flow: Option<FlowKey>,
        ts: Timestamp,
        source: SourceIdx,
        state_map: &'a mut StateMap,
        sink: &'a mut dyn crate::anomaly::sink::AnomalySink,
        counters: &'a mut CounterRegistry,
        flow_states: &'a mut FlowStateRegistry,
    ) -> Self {
        Self {
            flow,
            ts,
            source,
            monitor_name: None,
            state_map,
            sink,
            counters,
            flow_states,
            label_table: default_label_table(),
            tracker: None,
            arp_table: None,
        }
    }

    /// The [Community ID](https://github.com/corelight/community-id-spec) v1
    /// flow hash (`"1:<base64>"`) of the current event's flow, matching
    /// [`export::FlowRecord::community_id`](crate::export::FlowRecord::community_id)
    /// and the flow events' `community_id()` accessors. `None` when the event
    /// carries no flow key (e.g. a tick) or the flow isn't IP. Issue #123.
    #[inline]
    pub fn community_id(&self) -> Option<String> {
        self.flow
            .as_ref()
            .and_then(flowscope::KeyFields::community_id)
    }

    /// Issue #120: names observed for `ip` via the passive DNS reverse map
    /// (armed with [`MonitorBuilder::name_map`](crate::monitor::MonitorBuilder::name_map)).
    /// Returns the currently-live canonical names (most-recent first is not
    /// guaranteed). Empty when the name map isn't armed or `ip` is unknown.
    #[cfg(feature = "dns")]
    pub fn names(&self, ip: std::net::IpAddr) -> Vec<String> {
        match self.state::<crate::monitor::dns::NameMapState>() {
            Some(st) => st
                .map
                .peek_names(ip, self.ts)
                .into_iter()
                .map(|c| c.name.clone())
                .collect(),
            None => Vec::new(),
        }
    }

    /// Borrow per-monitor state `T` mutably.
    ///
    /// `T: Default` so the slot is lazy-created on first access.
    /// Pre-register via `MonitorBuilder::state::<T>()` to surface
    /// typos at build time.
    #[inline]
    pub fn state_mut<T: Default + Send + 'static>(&mut self) -> &mut T {
        self.state_map.get_or_init_mut::<T>()
    }

    /// 0.22: immutable, non-creating read of per-monitor state `T`.
    ///
    /// Sibling to [`Self::state_mut`] that neither requires `Default`
    /// nor lazy-creates: returns `None` if `T` was never registered
    /// or touched. Used by read-only views (`bandwidth()`, report
    /// snapshots) that must not mutate state behind a shared borrow.
    #[inline]
    pub fn state<T: 'static>(&self) -> Option<&T> {
        self.state_map.get::<T>()
    }

    /// 0.22: the active well-known label table for this monitor.
    ///
    /// Always returns something — the default is flowscope's built-in
    /// table; a custom one is installed via
    /// [`crate::monitor::MonitorBuilder::label_table`]. Pair with
    /// [`flowscope::extract::FiveTupleKey::app_label_with`] /
    /// `protocol_label_with` for site-custom port labelling.
    #[inline]
    pub fn label_table(&self) -> &LabelTable {
        self.label_table
    }

    /// 0.22 §3: immutable, non-panicking read of the `K`-keyed
    /// sliding-window counter. `None` if unregistered (sibling to the
    /// panicking [`Self::counter_mut`]). Used by report snapshots.
    #[inline]
    pub fn counter<K>(&self) -> Option<&TimeBucketedCounter<K>>
    where
        K: std::hash::Hash + Eq + Clone + Send + 'static,
    {
        self.counters.get::<K>()
    }

    /// 0.22 §2.3: a [`BandwidthReport`](crate::monitor::BandwidthReport)
    /// snapshot of the bandwidth slot, if
    /// [`bandwidth_by_app`](crate::monitor::MonitorBuilder::bandwidth_by_app)
    /// / [`on_bandwidth`](crate::monitor::MonitorBuilder::on_bandwidth)
    /// registered it; `None` otherwise. The report captures `self.ts`
    /// as its instant, so callers never handle a raw `Timestamp`.
    #[inline]
    pub fn bandwidth(&self) -> Option<crate::monitor::BandwidthReport<'_>> {
        let state = self.state::<crate::monitor::bandwidth::BandwidthState>()?;
        Some(crate::monitor::BandwidthReport {
            rate: &state.0,
            now: self.ts,
        })
    }

    /// 0.22: join an ICMP error's embedded inner 5-tuple back to a
    /// live flow + its stats.
    ///
    /// Returns `None` when no tracker is wired onto this `Ctx`
    /// (synthetic / tick / drain contexts) or no live flow matches
    /// the inner tuple (already evicted / never tracked). Backs the
    /// `IcmpError.stats` join in the ICMP synthesis slot.
    #[cfg(feature = "icmp")]
    #[inline]
    pub fn lookup_icmp_flow(
        &self,
        inner: &flowscope::icmp::IcmpInner,
    ) -> Option<(FlowKey, flowscope::FlowStats)> {
        self.tracker?.stats_for_inner(inner)
    }

    /// Issue #19: the read-only ARP binding table (`IP → MAC`) — the learned
    /// neighbour map behind the ARP detector.
    ///
    /// `Some` on the **flow / session / lifecycle** dispatch paths and inside
    /// the ARP drain itself (issue #23): an `on::<FlowEnded<Tcp>>` /
    /// `on::<Tls>` / `on_arp` handler can resolve a peer IP to the MAC that
    /// last claimed it (**cross-protocol IP→MAC**), or — from an ARP detector —
    /// look beyond the triggering message: cross-check the sender's gateway,
    /// count how many IPs claim one MAC (ARP-scan), or read a binding's change
    /// history. Reflects every binding learned up to and including the current
    /// batch. Enroll learning without registering an ARP handler via
    /// [`MonitorBuilder::arp_table`](crate::monitor::MonitorBuilder::arp_table).
    ///
    /// `None` on the **packet-tier** subscriptions (they run pre-flow, before
    /// the frame is even tracked) and during the **graceful-drain** shutdown
    /// flush, and always `None` when no ARP hook is armed.
    ///
    /// Look up a binding with
    /// [`peek`](flowscope::correlate::NeighborTable::peek):
    /// ```ignore
    /// if let Some(t) = ctx.arp_table()
    ///     && let Some(b) = t.peek(&some_ipv4, ctx.ts)
    /// {
    ///     // b.addr is the MAC; b.change_count, b.prior_addr, … available too.
    /// }
    /// ```
    #[cfg(feature = "arp")]
    #[inline]
    pub fn arp_table(&self) -> Option<&flowscope::correlate::ArpTable> {
        self.arp_table
    }

    /// Borrow the `K`-keyed sliding-window counter mutably.
    ///
    /// # Panics
    ///
    /// Panics if no `MonitorBuilder::counter::<K>(...)` call
    /// registered this key — a programmer error caught early in
    /// development.
    #[inline]
    pub fn counter_mut<K>(&mut self) -> &mut TimeBucketedCounter<K>
    where
        K: std::hash::Hash + Eq + Clone + Send + 'static,
    {
        self.counters.get_mut::<K>()
    }

    /// Borrow the anomaly sink mutably.
    #[inline]
    pub fn sink_mut(&mut self) -> &mut dyn crate::anomaly::sink::AnomalySink {
        self.sink
    }

    /// 0.21 I.7: borrow per-flow user state `T` mutably.
    ///
    /// Returns `None` when:
    /// - `T` was not registered via
    ///   [`crate::monitor::MonitorBuilder::flow_state::<T>`].
    /// - This `Ctx` doesn't carry a flow key
    ///   ([`Tick`](crate::protocol::event_typed::Tick) and
    ///   `TrackerAnomaly` are the only such events).
    ///
    /// Lazy-creates `T::default()` on first access for a given
    /// flow key; subsequent accesses return the same `&mut T`.
    /// The slot's last-seen timestamp refreshes on every access.
    /// Eviction happens via `FlowStateMap::feed(FlowEvent::Ended)`
    /// — when `FlowEnded<P>` lands, the slot for that key is
    /// freed.
    ///
    /// Typical use: aggregate per-flow stats inside a
    /// `FlowStarted<P>` handler, read+emit in `FlowEnded<P>`:
    ///
    /// ```ignore
    /// .on_ctx::<FlowStarted<Tcp>>(|_e, ctx| {
    ///     let s = ctx.flow_state_mut::<MyState>().unwrap();
    ///     s.bytes = 0;
    ///     Ok(())
    /// })
    /// .on_ctx::<FlowEnded<Tcp>>(|e, ctx| {
    ///     let s = ctx.flow_state_mut::<MyState>().unwrap();
    ///     ctx.emit("FlowDone", Severity::Info)
    ///         .with_metric("bytes", s.bytes as f64)
    ///         .emit();
    ///     Ok(())
    /// })
    /// ```
    #[inline]
    pub fn flow_state_mut<T>(&mut self) -> Option<&mut T>
    where
        T: Default + Send + 'static,
    {
        let key = self.flow?;
        let ts = self.ts;
        let map = self.flow_states.get_mut::<T>()?;
        Some(map.get_or_default(&key, ts))
    }

    /// Shortcut: begin an anomaly emission keyed by `kind` + `severity`
    /// using `self.ts` as the timestamp. Equivalent to
    /// `self.sink_mut().begin(kind, severity, self.ts)` but reads
    /// cleaner:
    ///
    /// ```ignore
    /// ctx.emit("FlowStartedTcp", Severity::Info)
    ///     .with_key(&evt.key)
    ///     .with_metric("count", n as f64)
    ///     .emit();
    /// ```
    ///
    /// The returned [`AnomalyWriter`](crate::anomaly::sink::AnomalyWriter)
    /// borrows the sink for its lifetime; no temporaries needed.
    #[inline]
    pub fn emit(
        &mut self,
        kind: &'static str,
        severity: crate::anomaly::Severity,
    ) -> crate::anomaly::sink::AnomalyWriter<'_> {
        let ts = self.ts;
        self.sink.begin(kind, severity, ts)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::anomaly::sink::NoopSink;

    #[derive(Default)]
    struct DemoState {
        n: u64,
    }

    fn make_ctx<'a>(
        state: &'a mut StateMap,
        sink: &'a mut NoopSink,
        counters: &'a mut CounterRegistry,
        flow_states: &'a mut FlowStateRegistry,
    ) -> Ctx<'a> {
        Ctx {
            flow: None,
            ts: Timestamp::new(0, 0),
            source: SourceIdx(0),
            monitor_name: None,
            state_map: state,
            sink,
            counters,
            flow_states,
            label_table: default_label_table(),
            tracker: None,
            arp_table: None,
        }
    }

    #[test]
    fn ctx_constructs_from_borrowed_fields() {
        let mut state = StateMap::default();
        let mut counters = CounterRegistry::default();
        let mut sink = NoopSink;
        let mut flow_states = FlowStateRegistry::default();
        let _ctx = make_ctx(&mut state, &mut sink, &mut counters, &mut flow_states);
    }

    #[test]
    fn state_mut_lazy_creates_then_returns_same() {
        let mut state = StateMap::default();
        let mut counters = CounterRegistry::default();
        let mut sink = NoopSink;
        let mut flow_states = FlowStateRegistry::default();
        let mut ctx = make_ctx(&mut state, &mut sink, &mut counters, &mut flow_states);
        ctx.state_mut::<DemoState>().n = 7;
        assert_eq!(ctx.state_mut::<DemoState>().n, 7);
    }

    #[test]
    fn sink_mut_returns_dyn_anomalysink() {
        let mut state = StateMap::default();
        let mut counters = CounterRegistry::default();
        let mut sink = NoopSink;
        let mut flow_states = FlowStateRegistry::default();
        let mut ctx = make_ctx(&mut state, &mut sink, &mut counters, &mut flow_states);
        let _: &mut dyn crate::anomaly::sink::AnomalySink = ctx.sink_mut();
    }

    #[test]
    fn counter_mut_returns_registered_counter() {
        use std::time::Duration;
        let mut state = StateMap::default();
        let mut counters = CounterRegistry::default();
        counters.register::<u16>(TimeBucketedCounter::<u16>::new_unbounded(
            Duration::from_secs(60),
            Duration::from_secs(1),
        ));
        let mut sink = NoopSink;
        let mut flow_states = FlowStateRegistry::default();
        let mut ctx = make_ctx(&mut state, &mut sink, &mut counters, &mut flow_states);
        ctx.counter_mut::<u16>().bump(42u16, Timestamp::new(0, 0));
    }

    #[test]
    fn source_idx_roundtrip() {
        assert_eq!(SourceIdx(3), SourceIdx(3));
        assert_ne!(SourceIdx(1), SourceIdx(2));
    }
}