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
//! [`FlowExtractor`] trait and its supporting types.
//!
//! Implement this trait to teach the rest of `netring-flow` (the
//! tracker, the reassembler hook) what counts as a flow in your
//! domain. Built-in implementations live in [`crate::extract`].
use bitflags::bitflags;
use crate::view::PacketView;
/// Extract a flow descriptor from one packet.
///
/// Implementations are called once per packet on the hot path —
/// keep them cheap and stateless. Most return `Some(_)`; malformed,
/// non-IP, or out-of-scope packets return `None` and are skipped.
///
/// # Bidirectional flows
///
/// If you want A→B and B→A merged into one flow, your extractor
/// must produce the **same `Key`** for both orientations and report
/// each packet's direction via [`Extracted::orientation`]. The
/// built-in [`crate::extract::FiveTuple::bidirectional`] does this
/// by sorting `(addr, port)` pairs.
///
/// # Bounds
///
/// `Send + Sync + 'static` is required so a tracker generic over
/// this trait can be used from any task / thread.
pub trait FlowExtractor: Send + Sync + 'static {
/// The flow key. Equality + hashability identify the flow.
type Key: Eq + std::hash::Hash + Clone + Send + Sync + 'static;
/// Extract a flow descriptor from `view`.
///
/// Returns `None` if this packet is not part of any flow you
/// want to track (skipped, malformed, encap-only, ARP, etc.).
fn extract(&self, view: PacketView<'_>) -> Option<Extracted<Self::Key>>;
}
/// Result of extracting one packet.
///
/// `key` identifies the flow. `orientation` says whether `view` was
/// in the canonical direction or reversed. `l4` and `tcp` carry
/// pre-parsed protocol data that the tracker and reassembler reuse
/// without re-parsing.
#[derive(Debug, Clone)]
pub struct Extracted<K> {
/// The flow this packet belongs to.
pub key: K,
/// Orientation of *this packet* relative to the canonical form
/// of `key`. `Forward` if the natural src→dst direction matches
/// the key's a→b ordering; `Reverse` if the extractor swapped
/// to canonicalize.
///
/// The tracker translates this into [`crate::FlowSide`] (Initiator
/// / Responder) based on which orientation it saw first.
pub orientation: Orientation,
/// L4 protocol if the extractor identified one. Drives the
/// tracker's choice of timeout and whether to engage TCP state.
pub l4: Option<L4Proto>,
/// Pre-parsed TCP info for TCP packets. If `Some`, the tracker
/// runs the TCP state machine without re-parsing; if `None`,
/// TCP-specific events (Established, history string) won't fire
/// for this flow.
///
/// Built-in extractors fill this for ~zero extra cost; custom
/// extractors that don't care about TCP can leave it `None`.
pub tcp: Option<TcpInfo>,
}
/// Orientation of a packet relative to its canonical flow key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Orientation {
/// Packet's natural src→dst matches the key's a→b ordering.
Forward,
/// Extractor swapped src/dst to canonicalize; packet is
/// flowing from key.b to key.a.
Reverse,
}
/// L4 protocol identified by an extractor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "serde",
serde(tag = "kind", content = "value", rename_all = "snake_case")
)]
#[non_exhaustive]
pub enum L4Proto {
Tcp,
Udp,
Icmp,
IcmpV6,
Sctp,
Other(u8),
}
#[cfg(feature = "tracker")]
impl std::fmt::Display for L4Proto {
/// Lowercase short label matching the `flowscope_*_total{l4=…}`
/// metric vocabulary (`tcp` / `udp` / `other`). Non-TCP /
/// non-UDP families collapse to `other`; consumers needing a
/// finer label match on the variant directly.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(crate::obs::l4_label(Some(*self)))
}
}
impl crate::KeyFields for L4Proto {
/// Uppercase EVE-compatible label (`"TCP"` / `"UDP"` /
/// `"ICMP"` / `"ICMPv6"` / `"SCTP"`). Returns `None` for
/// [`L4Proto::Other`] (unknown numeric protocol).
///
/// Sibling to [`L4Proto::canonical_name`] — `proto_str` is
/// the uppercase Suricata/EVE-shaped variant (Option-
/// returning for unknown protos); `canonical_name` is the
/// lowercase always-Some metric-label variant.
fn proto_str(&self) -> Option<&'static str> {
Some(match self {
L4Proto::Tcp => "TCP",
L4Proto::Udp => "UDP",
L4Proto::Icmp => "ICMP",
L4Proto::IcmpV6 => "ICMPv6",
L4Proto::Sctp => "SCTP",
L4Proto::Other(_) => return None,
})
}
fn protocol_identifier(&self) -> Option<u8> {
Some(self.as_u8())
}
}
impl L4Proto {
/// Stable lowercase short slug for any `L4Proto`. Always
/// `Some`-equivalent (never empty, never panics):
///
/// - `Tcp` → `"tcp"`
/// - `Udp` → `"udp"`
/// - `Icmp` → `"icmp"`
/// - `IcmpV6` → `"icmp6"`
/// - `Sctp` → `"sctp"`
/// - `Other(_)` → `"other"`
///
/// Sibling to [`crate::KeyFields::proto_str`] (uppercase,
/// EVE/Suricata schema-shaped, `None` for `Other`). Use
/// this method for metric labels, log slugs, and
/// `app_label` fallbacks where lowercase + always-Some is
/// the right contract.
///
/// Plan 163 (0.14).
pub fn canonical_name(&self) -> &'static str {
match self {
L4Proto::Tcp => "tcp",
L4Proto::Udp => "udp",
L4Proto::Icmp => "icmp",
L4Proto::IcmpV6 => "icmp6",
L4Proto::Sctp => "sctp",
L4Proto::Other(_) => "other",
}
}
/// IANA IP protocol number — the wire-format value
/// carried in the IPv4 `protocol` / IPv6 `next_header`
/// header field. Used as IPFIX IE 4
/// (`protocolIdentifier`).
///
/// - `Tcp` → 6
/// - `Udp` → 17
/// - `Icmp` → 1
/// - `IcmpV6` → 58
/// - `Sctp` → 132
/// - `Other(n)` → `n`
///
/// New in 0.18.0 (issue #16 sub-piece — needed for the
/// IE-keyed [`crate::ipfix::FlowRecord`]).
pub fn as_u8(&self) -> u8 {
match self {
L4Proto::Tcp => 6,
L4Proto::Udp => 17,
L4Proto::Icmp => 1,
L4Proto::IcmpV6 => 58,
L4Proto::Sctp => 132,
L4Proto::Other(n) => *n,
}
}
}
/// Pre-parsed TCP information for a packet.
///
/// Filled by built-in extractors. Decoupled from frame layout so
/// downstream tracker / reassembler logic doesn't need to re-parse.
///
/// `#[non_exhaustive]` since 0.5.0 — additive field changes are
/// unconditionally non-breaking. External consumers read fields by
/// name; internal constructors use struct-literal syntax.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct TcpInfo {
/// Decoded TCP flags.
pub flags: TcpFlags,
/// TCP sequence number (host byte order).
pub seq: u32,
/// TCP acknowledgment number (host byte order).
pub ack: u32,
/// Offset into the frame where the TCP payload begins.
/// Relative to the frame the extractor was called with.
pub payload_offset: usize,
/// Number of payload bytes (zero for pure SYN/ACK/FIN).
pub payload_len: usize,
/// TCP receive window from the header (host byte order). Not
/// scaled — the SYN/SYN-ACK window-scale option is per-flow and
/// not currently tracked. Consumers wanting the effective window
/// should pair this with their own wscale tracking until a
/// per-flow `wscale` lands.
pub window: u16,
}
bitflags! {
/// TCP control flags from the TCP header's flags byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TcpFlags: u8 {
const FIN = 0b0000_0001;
const SYN = 0b0000_0010;
const RST = 0b0000_0100;
const PSH = 0b0000_1000;
const ACK = 0b0001_0000;
const URG = 0b0010_0000;
const ECE = 0b0100_0000;
const CWR = 0b1000_0000;
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for TcpFlags {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
self.bits().serialize(s)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for TcpFlags {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = u8::deserialize(d)?;
Ok(TcpFlags::from_bits_retain(raw))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tcp_flags_basic() {
let f = TcpFlags::SYN | TcpFlags::ACK;
assert!(f.contains(TcpFlags::SYN));
assert!(f.contains(TcpFlags::ACK));
assert!(!f.contains(TcpFlags::FIN));
}
#[test]
fn extracted_clone() {
let e: Extracted<u32> = Extracted {
key: 42,
orientation: Orientation::Forward,
l4: Some(L4Proto::Tcp),
tcp: Some(TcpInfo {
flags: TcpFlags::SYN,
seq: 1,
ack: 0,
payload_offset: 54,
payload_len: 0,
window: 8192,
}),
};
let cloned = e.clone();
assert_eq!(cloned.key, 42);
assert_eq!(cloned.orientation, Orientation::Forward);
}
#[test]
fn l4_proto_eq() {
assert_eq!(L4Proto::Tcp, L4Proto::Tcp);
assert_ne!(L4Proto::Tcp, L4Proto::Udp);
assert_eq!(L4Proto::Other(1), L4Proto::Other(1));
assert_ne!(L4Proto::Other(1), L4Proto::Other(2));
}
}