packet-strata 0.3.0

A high-performance packet parsing library
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
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::hash::{Hash, Hasher};
use std::net::{Ipv4Addr, Ipv6Addr};

use crate::packet::ether::EthAddr;
use crate::packet::protocol::{EtherProto, IpProto};
use crate::{
    packet::{
        header::{LinkLayer, NetworkLayer},
        Packet,
    },
    tracker::vni::{VniId, VniLayer, VniMapper},
};

/// Common trait for all flow tuple types
///
/// This trait defines the interface for creating flow tuples from packets.
/// (e.g., 5-tuple with VNI, 3-tuple, MAC-based, etc.)
pub trait Tuple: Sized + Hash + Eq + Clone + Copy {
    type Addr: Eq;

    /// Create a new flow tuple from a packet
    fn from_packet(pkt: &Packet<'_>, vni_mapper: &mut VniMapper) -> Option<Self>;

    /// Flip the source and destination fields of the flow tuple
    fn flip(&self) -> Self;

    /// Hashes the tuple in a canonical (symmetric) way without creating a new instance.
    /// Used by `Symmetric` wrapper to ensure `Hash(A->B) == Hash(B->A)`.
    fn hash_canonical<H: Hasher>(&self, state: &mut H);

    /// Checks equality in a canonical (symmetric) way without creating a new instance.
    /// Used by `Symmetric` wrapper to ensure `Eq(A->B, B->A)`.
    fn eq_canonical(&self, other: &Self) -> bool;

    /// Checks if the tuple is symmetric (source equals destination).
    ///
    /// A tuple is considered symmetric when both the source address equals the destination
    /// address and the source port equals the destination port. This is useful for
    /// identifying self-referential connections.
    #[inline]
    fn is_symmetric(&self) -> bool {
        self.source_port() == self.dest_port() && self.source() == self.dest()
    }

    /// Returns the source address of the flow tuple.
    fn source(&self) -> Self::Addr;

    /// Returns the destination address of the flow tuple.
    fn dest(&self) -> Self::Addr;

    /// Returns the source port of the flow tuple.
    fn source_port(&self) -> u16;

    /// Returns the destination port of the flow tuple.
    fn dest_port(&self) -> u16;

    /// Returns the IP protocol of the flow tuple.
    fn protocol(&self) -> IpProto;

    /// Returns the VNI (VXLAN Network Identifier) of the flow tuple.
    fn vni(&self) -> VniId;
}

/// Helper function to extract VNI from packet tunnels
///
/// This function is shared between all Tuple implementations to avoid code duplication.
/// Returns `VNI_NULL` if there are no tunnel layers, otherwise extracts and maps the VNI stack.
#[inline]
fn extract_vni(pkt: &Packet<'_>, vni_mapper: &mut VniMapper) -> Option<VniId> {
    let network_tunnel_layers = pkt.tunnels();

    if network_tunnel_layers.is_empty() {
        return Some(VniId::default());
    }

    let vni_stack = network_tunnel_layers
        .iter()
        .map(TryInto::try_into)
        .collect::<Result<SmallVec<[VniLayer; 4]>, _>>()
        .ok()?;

    Some(vni_mapper.get_or_create_vni_id(&vni_stack))
}

/// Helper function to extract transport layer ports
///
/// Returns (src_port, dst_port) or (0, 0) if no transport layer is present.
#[inline]
fn extract_ports(pkt: &Packet<'_>) -> (u16, u16) {
    pkt.transport().map(|t| t.ports()).unwrap_or((0, 0))
}

#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct Symmetric<T: Tuple>(pub T);

impl<T: Tuple> PartialEq for Symmetric<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_canonical(&other.0)
    }
}

impl<T: Tuple> Eq for Symmetric<T> {}

impl<T: Tuple> Hash for Symmetric<T> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash_canonical(state);
    }
}

impl<T: Tuple> From<T> for Symmetric<T> {
    fn from(t: T) -> Self {
        Self(t)
    }
}

/// IPv4 5-tuple flow with VNI support
///
/// This tuple uniquely identifies a network flow using:
/// - Source and destination IPv4 addresses
/// - Source and destination ports
/// - IP protocol number
/// - Virtual Network Identifier (VNI) for tunnel-aware flow tracking
#[derive(Hash, Eq, PartialEq, Debug, Copy, Clone, Serialize, Deserialize)]
pub struct TupleV4 {
    pub src_ip: Ipv4Addr,
    pub dst_ip: Ipv4Addr,
    pub src_port: u16,
    pub dst_port: u16,
    pub protocol: IpProto,
    pub vni: VniId,
}

impl Default for TupleV4 {
    fn default() -> Self {
        Self {
            src_ip: Ipv4Addr::UNSPECIFIED,
            dst_ip: Ipv4Addr::UNSPECIFIED,
            src_port: 0,
            dst_port: 0,
            protocol: IpProto::default(),
            vni: VniId::default(),
        }
    }
}

impl TupleV4 {
    /// Create a new IPv4 flow tuple from a packet
    ///
    /// Returns `None` if the packet does not contain an IPv4 header or if VNI extraction fails.
    pub fn new(pkt: &Packet<'_>, vni_mapper: &mut VniMapper) -> Option<Self> {
        let NetworkLayer::Ipv4(ipv4) = pkt.network()? else {
            return None;
        };

        let src_ip = ipv4.header.src_ip();
        let dst_ip = ipv4.header.dst_ip();
        let protocol = ipv4.header.protocol();
        let (src_port, dst_port) = extract_ports(pkt);
        let vni = extract_vni(pkt, vni_mapper)?;

        Some(Self {
            src_ip,
            dst_ip,
            src_port,
            dst_port,
            protocol,
            vni,
        })
    }
}

impl Tuple for TupleV4 {
    type Addr = Ipv4Addr;

    #[inline]
    fn source(&self) -> Self::Addr {
        self.src_ip
    }

    #[inline]
    fn dest(&self) -> Self::Addr {
        self.dst_ip
    }

    #[inline]
    fn source_port(&self) -> u16 {
        self.src_port
    }

    #[inline]
    fn dest_port(&self) -> u16 {
        self.dst_port
    }

    #[inline]
    fn protocol(&self) -> IpProto {
        self.protocol
    }

    #[inline]
    fn vni(&self) -> VniId {
        self.vni
    }

    #[inline]
    fn from_packet(pkt: &Packet<'_>, vni_mapper: &mut VniMapper) -> Option<Self> {
        Self::new(pkt, vni_mapper)
    }

    #[inline]
    fn flip(&self) -> Self {
        Self {
            src_ip: self.dst_ip,
            dst_ip: self.src_ip,
            src_port: self.dst_port,
            dst_port: self.src_port,
            protocol: self.protocol,
            vni: self.vni,
        }
    }

    #[inline]
    fn hash_canonical<H: Hasher>(&self, state: &mut H) {
        // Hash invariant fields
        self.protocol.hash(state);
        self.vni.hash(state);

        // Hash variant fields in sorted order (src < dst)
        // This avoids creating a new struct or flipping
        if (self.src_ip, self.src_port) <= (self.dst_ip, self.dst_port) {
            self.src_ip.hash(state);
            self.src_port.hash(state);
            self.dst_ip.hash(state);
            self.dst_port.hash(state);
        } else {
            self.dst_ip.hash(state);
            self.dst_port.hash(state);
            self.src_ip.hash(state);
            self.src_port.hash(state);
        }
    }

    #[inline]
    fn eq_canonical(&self, other: &Self) -> bool {
        if self.protocol != other.protocol || self.vni != other.vni {
            return false;
        }

        // Check direct equality OR crossed equality
        // This is much cheaper than constructing a new struct
        (self.src_ip == other.src_ip
            && self.dst_ip == other.dst_ip
            && self.src_port == other.src_port
            && self.dst_port == other.dst_port)
            || (self.src_ip == other.dst_ip
                && self.dst_ip == other.src_ip
                && self.src_port == other.dst_port
                && self.dst_port == other.src_port)
    }
}

/// IPv6 5-tuple flow tuple with VNI support
///
/// This tuple uniquely identifies a network flow using:
/// - Source and destination IPv6 addresses
/// - Source and destination ports
/// - IP protocol number (next header)
/// - Virtual Network Identifier (VNI) for tunnel-aware flow tracking
#[derive(Hash, Eq, PartialEq, Debug, Copy, Clone, Serialize, Deserialize)]
pub struct TupleV6 {
    pub src_ip: Ipv6Addr,
    pub dst_ip: Ipv6Addr,
    pub src_port: u16,
    pub dst_port: u16,
    pub protocol: IpProto,
    pub vni: VniId,
}

impl Default for TupleV6 {
    fn default() -> Self {
        Self {
            src_ip: Ipv6Addr::UNSPECIFIED,
            dst_ip: Ipv6Addr::UNSPECIFIED,
            src_port: 0,
            dst_port: 0,
            protocol: IpProto::default(),
            vni: VniId::default(),
        }
    }
}

impl TupleV6 {
    /// Create a new IPv6 flow tuple from a packet
    ///
    /// Returns `None` if the packet does not contain an IPv6 header or if VNI extraction fails.
    pub fn new(pkt: &Packet<'_>, vni_mapper: &mut VniMapper) -> Option<Self> {
        let NetworkLayer::Ipv6(ipv6) = pkt.network()? else {
            return None;
        };

        let src_ip = ipv6.header.src_ip();
        let dst_ip = ipv6.header.dst_ip();
        let protocol = ipv6.header.next_header();
        let (src_port, dst_port) = extract_ports(pkt);
        let vni = extract_vni(pkt, vni_mapper)?;

        Some(Self {
            src_ip,
            dst_ip,
            src_port,
            dst_port,
            protocol,
            vni,
        })
    }
}

impl Tuple for TupleV6 {
    type Addr = Ipv6Addr;

    #[inline]
    fn source(&self) -> Self::Addr {
        self.src_ip
    }

    #[inline]
    fn dest(&self) -> Self::Addr {
        self.dst_ip
    }

    #[inline]
    fn source_port(&self) -> u16 {
        self.src_port
    }

    #[inline]
    fn dest_port(&self) -> u16 {
        self.dst_port
    }

    #[inline]
    fn protocol(&self) -> IpProto {
        self.protocol
    }

    #[inline]
    fn vni(&self) -> VniId {
        self.vni
    }

    #[inline]
    fn from_packet(pkt: &Packet<'_>, vni_mapper: &mut VniMapper) -> Option<Self> {
        Self::new(pkt, vni_mapper)
    }

    #[inline]
    fn flip(&self) -> Self {
        Self {
            src_ip: self.dst_ip,
            dst_ip: self.src_ip,
            src_port: self.dst_port,
            dst_port: self.src_port,
            protocol: self.protocol,
            vni: self.vni,
        }
    }

    #[inline]
    fn hash_canonical<H: Hasher>(&self, state: &mut H) {
        self.protocol.hash(state);
        self.vni.hash(state);

        if (self.src_ip, self.src_port) <= (self.dst_ip, self.dst_port) {
            self.src_ip.hash(state);
            self.src_port.hash(state);
            self.dst_ip.hash(state);
            self.dst_port.hash(state);
        } else {
            self.dst_ip.hash(state);
            self.dst_port.hash(state);
            self.src_ip.hash(state);
            self.src_port.hash(state);
        }
    }

    #[inline]
    fn eq_canonical(&self, other: &Self) -> bool {
        if self.protocol != other.protocol || self.vni != other.vni {
            return false;
        }

        (self.src_ip == other.src_ip
            && self.dst_ip == other.dst_ip
            && self.src_port == other.src_port
            && self.dst_port == other.dst_port)
            || (self.src_ip == other.dst_ip
                && self.dst_ip == other.src_ip
                && self.src_port == other.dst_port
                && self.dst_port == other.src_port)
    }
}

#[derive(Hash, Eq, PartialEq, Debug, Copy, Clone, Serialize, Deserialize)]
pub struct TupleEth {
    pub src: EthAddr,
    pub dst: EthAddr,
    pub protocol: EtherProto,
}

impl Default for TupleEth {
    fn default() -> Self {
        Self {
            src: EthAddr::default(),
            dst: EthAddr::default(),
            protocol: EtherProto::default(),
        }
    }
}

impl TupleEth {
    /// Create a new Ethernet flow tuple from a packet
    ///
    /// Returns `None` if the packet is not Ethernet.
    pub fn new(pkt: &Packet<'_>) -> Option<Self> {
        let LinkLayer::Ethernet(eth) = pkt.link() else {
            return None;
        };

        Some(Self {
            src: *eth.source(),
            dst: *eth.dest(),
            protocol: eth.inner_type(),
        })
    }
}

impl Tuple for TupleEth {
    type Addr = EthAddr;

    #[inline]
    fn source(&self) -> Self::Addr {
        self.src
    }

    #[inline]
    fn dest(&self) -> Self::Addr {
        self.dst
    }

    #[inline]
    fn source_port(&self) -> u16 {
        0
    }

    #[inline]
    fn dest_port(&self) -> u16 {
        0
    }

    #[inline]
    fn protocol(&self) -> IpProto {
        IpProto::default()
    }

    #[inline]
    fn vni(&self) -> VniId {
        VniId::default()
    }

    #[inline]
    fn from_packet(pkt: &Packet<'_>, _vni_mapper: &mut VniMapper) -> Option<Self> {
        Self::new(pkt)
    }

    #[inline]
    fn flip(&self) -> Self {
        Self {
            src: self.dst,
            dst: self.src,
            protocol: self.protocol,
        }
    }

    #[inline]
    fn hash_canonical<H: Hasher>(&self, state: &mut H) {
        self.protocol.hash(state);

        // EthAddr implements Ord so we can compare directly
        if self.src <= self.dst {
            self.src.hash(state);
            self.dst.hash(state);
        } else {
            self.dst.hash(state);
            self.src.hash(state);
        }
    }

    #[inline]
    fn eq_canonical(&self, other: &Self) -> bool {
        if self.protocol != other.protocol {
            return false;
        }

        (self.src == other.src && self.dst == other.dst)
            || (self.src == other.dst && self.dst == other.src)
    }
}