ferranet 0.2.0

A modern, async-first, zero-copy datalink-layer (L2) networking 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
//! The zero-copy receive surface: [`Block`], [`Frame`], and frame metadata.
//!
//! A received [`Block`] is an RAII guard. While it is alive, every [`Frame`] it yields borrows
//! directly from kernel-mapped memory — no copying. Dropping the block returns ownership of the
//! underlying storage to the kernel. This is the "valid until the end of the block" model that
//! makes safe zero-copy receive possible.

use std::time::{Duration, SystemTime};

use crate::interface::MacAddr;

#[cfg(target_os = "linux")]
use crate::sys::linux::ring::{RxBlock, RxFrames};
#[cfg(all(target_os = "linux", feature = "xdp"))]
use crate::sys::linux::xdp::{XdpBlock, XdpFrames};

/// How a received frame was addressed relative to this host, mirroring `sll_pkttype`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PacketType {
    /// Addressed to us.
    Host,
    /// A link-layer broadcast.
    Broadcast,
    /// A link-layer multicast.
    Multicast,
    /// Addressed to another host (seen because we are promiscuous).
    OtherHost,
    /// A frame we are transmitting (loopback of outgoing traffic).
    Outgoing,
    /// An unrecognised `sll_pkttype` value.
    Other(u8),
}

impl PacketType {
    /// Maps a raw `sll_pkttype` value to a [`PacketType`].
    #[must_use]
    pub fn from_raw(raw: u8) -> Self {
        match raw {
            libc::PACKET_HOST => PacketType::Host,
            libc::PACKET_BROADCAST => PacketType::Broadcast,
            libc::PACKET_MULTICAST => PacketType::Multicast,
            libc::PACKET_OTHERHOST => PacketType::OtherHost,
            libc::PACKET_OUTGOING => PacketType::Outgoing,
            other => PacketType::Other(other),
        }
    }

    /// Best-effort classification from a frame's destination MAC.
    ///
    /// Used for ring-received frames, where the kernel does not record `sll_pkttype` per frame.
    /// It can distinguish broadcast/multicast/unicast but not `Outgoing` vs `Host`.
    #[must_use]
    pub fn from_dest_mac(dest: MacAddr) -> Self {
        if dest.is_broadcast() {
            PacketType::Broadcast
        } else if dest.is_multicast() {
            PacketType::Multicast
        } else {
            PacketType::Host
        }
    }
}

/// An 802.1Q VLAN tag recovered from a received frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VlanTag {
    /// Tag Control Information (priority, DEI, and VLAN id packed together).
    pub tci: u16,
    /// Tag Protocol Identifier (e.g. `0x8100`, or `0x88a8` for QinQ).
    pub tpid: u16,
}

impl VlanTag {
    /// The 12-bit VLAN identifier.
    #[must_use]
    pub const fn vid(&self) -> u16 {
        self.tci & 0x0fff
    }

    /// The 3-bit priority code point.
    #[must_use]
    pub const fn priority(&self) -> u8 {
        (self.tci >> 13) as u8
    }
}

/// Metadata the kernel reports alongside a received frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct FrameMeta {
    /// The original on-wire length, which may exceed the captured bytes if a snap length is set.
    pub wire_len: usize,
    /// The capture timestamp, if available.
    pub timestamp: Option<SystemTime>,
    /// A VLAN tag the kernel stripped into metadata, if present.
    pub vlan: Option<VlanTag>,
    /// How the frame was addressed relative to this host.
    pub packet_type: PacketType,
}

impl FrameMeta {
    pub(crate) fn timestamp_from_parts(sec: u32, nsec: u32) -> Option<SystemTime> {
        if sec == 0 && nsec == 0 {
            None
        } else {
            Some(SystemTime::UNIX_EPOCH + Duration::new(u64::from(sec), nsec))
        }
    }
}

/// Raw, cheap-to-copy `TPACKET` header fields, kept so a frame's metadata can be decoded lazily.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RawRingMeta {
    pub wire_len: u32,
    pub ts_sec: u32,
    pub ts_nsec: u32,
    pub status: u32,
    pub vlan_tci: u16,
    pub vlan_tpid: u16,
}

/// Where a frame's metadata comes from.
///
/// The ring backend stores the raw header scalars and decodes them on demand, so the common
/// "I only want the bytes" path pays nothing for timestamp/VLAN/classification work. Other
/// backends (basic, dummy, AF_XDP) build their metadata once per receive and store it eagerly.
#[derive(Debug, Clone, Copy)]
enum MetaSource {
    Eager(FrameMeta),
    Ring(RawRingMeta),
}

/// A single received frame, borrowing its bytes from the owning [`Block`].
#[derive(Debug, Clone, Copy)]
pub struct Frame<'a> {
    data: &'a [u8],
    meta: MetaSource,
}

impl<'a> Frame<'a> {
    pub(crate) fn new(data: &'a [u8], meta: FrameMeta) -> Self {
        Frame { data, meta: MetaSource::Eager(meta) }
    }

    pub(crate) fn ring(data: &'a [u8], raw: RawRingMeta) -> Self {
        Frame { data, meta: MetaSource::Ring(raw) }
    }

    /// The captured frame bytes (including the Ethernet header for `SOCK_RAW` channels).
    #[must_use]
    pub fn data(&self) -> &'a [u8] {
        self.data
    }

    /// The original on-wire length (may exceed `data().len()` when a snap length is set).
    #[must_use]
    pub fn wire_len(&self) -> usize {
        match self.meta {
            MetaSource::Eager(m) => m.wire_len,
            MetaSource::Ring(r) => r.wire_len as usize,
        }
    }

    /// The frame's metadata (decoded on demand for ring-captured frames).
    #[must_use]
    pub fn meta(&self) -> FrameMeta {
        match self.meta {
            MetaSource::Eager(m) => m,
            MetaSource::Ring(_) => FrameMeta {
                wire_len: self.wire_len(),
                timestamp: self.timestamp(),
                vlan: self.vlan(),
                packet_type: self.packet_type(),
            },
        }
    }

    /// How the frame was addressed relative to this host.
    #[must_use]
    pub fn packet_type(&self) -> PacketType {
        match self.meta {
            MetaSource::Eager(m) => m.packet_type,
            // The ring backend does not record sll_pkttype; classify from the destination MAC.
            MetaSource::Ring(_) => self
                .data
                .get(0..6)
                .map(|b| PacketType::from_dest_mac(MacAddr([b[0], b[1], b[2], b[3], b[4], b[5]])))
                .unwrap_or(PacketType::Other(0)),
        }
    }

    /// The capture timestamp, if available.
    #[must_use]
    pub fn timestamp(&self) -> Option<SystemTime> {
        match self.meta {
            MetaSource::Eager(m) => m.timestamp,
            MetaSource::Ring(r) => FrameMeta::timestamp_from_parts(r.ts_sec, r.ts_nsec),
        }
    }

    /// The VLAN tag the kernel stripped into metadata, if any.
    #[must_use]
    pub fn vlan(&self) -> Option<VlanTag> {
        match self.meta {
            MetaSource::Eager(m) => m.vlan,
            MetaSource::Ring(r) => {
                if r.status & libc::TP_STATUS_VLAN_VALID != 0 {
                    let tpid = if r.status & libc::TP_STATUS_VLAN_TPID_VALID != 0 {
                        r.vlan_tpid
                    } else {
                        0x8100
                    };
                    Some(VlanTag { tci: r.vlan_tci, tpid })
                } else {
                    None
                }
            }
        }
    }
}

/// A batch of received frames borrowing from kernel-mapped memory.
///
/// Iterate the frames with [`Block::frames`]. When the block is dropped, its storage is returned
/// to the kernel for reuse, so frames must not outlive the block (the borrow checker enforces
/// this).
#[derive(Debug)]
pub struct Block<'a> {
    inner: BlockInner<'a>,
}

#[derive(Debug)]
enum BlockInner<'a> {
    /// A zero-copy `TPACKET_V3` block borrowed from the RX ring.
    #[cfg(target_os = "linux")]
    Ring(RxBlock<'a>),
    /// A zero-copy batch of frames borrowed from an AF_XDP UMEM.
    #[cfg(all(target_os = "linux", feature = "xdp"))]
    Xdp(XdpBlock<'a>),
    /// A single frame copied into the receiver's reusable buffer (basic, non-ring channels).
    Single(Option<Frame<'a>>),
}

impl<'a> Block<'a> {
    #[cfg(target_os = "linux")]
    pub(crate) fn from_ring(block: RxBlock<'a>) -> Self {
        Block { inner: BlockInner::Ring(block) }
    }

    #[cfg(all(target_os = "linux", feature = "xdp"))]
    pub(crate) fn from_xdp(block: XdpBlock<'a>) -> Self {
        Block { inner: BlockInner::Xdp(block) }
    }

    pub(crate) fn single(frame: Option<Frame<'a>>) -> Self {
        Block { inner: BlockInner::Single(frame) }
    }

    /// The number of frames in this block.
    #[must_use]
    pub fn len(&self) -> usize {
        match &self.inner {
            #[cfg(target_os = "linux")]
            BlockInner::Ring(b) => b.frame_count(),
            #[cfg(all(target_os = "linux", feature = "xdp"))]
            BlockInner::Xdp(b) => b.frame_count(),
            BlockInner::Single(f) => usize::from(f.is_some()),
        }
    }

    /// Returns `true` if this block contains no frames.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Whether the kernel flagged dropped packets (`TP_STATUS_LOSING`) for this batch — i.e. the
    /// ring overflowed and data was lost since the last [`Receiver::stats`](crate::Receiver::stats)
    /// call (which clears the flag). A zero-syscall, inline loss signal for the receive loop;
    /// always `false` for the basic, dummy, and AF_XDP backends (use `stats()` there).
    #[must_use]
    pub fn is_losing(&self) -> bool {
        match &self.inner {
            #[cfg(target_os = "linux")]
            BlockInner::Ring(b) => b.is_losing(),
            #[cfg(all(target_os = "linux", feature = "xdp"))]
            BlockInner::Xdp(_) => false,
            BlockInner::Single(_) => false,
        }
    }

    /// Iterates the frames in this block, each borrowing zero-copy from kernel memory.
    pub fn frames(&self) -> Frames<'_> {
        match &self.inner {
            #[cfg(target_os = "linux")]
            BlockInner::Ring(b) => Frames { inner: FramesInner::Ring(b.frames()) },
            #[cfg(all(target_os = "linux", feature = "xdp"))]
            BlockInner::Xdp(b) => Frames { inner: FramesInner::Xdp(b.frames()) },
            BlockInner::Single(f) => Frames { inner: FramesInner::Single(f.iter().copied()) },
        }
    }
}

/// Iterator over the [`Frame`]s of a [`Block`], created by [`Block::frames`].
#[derive(Debug)]
pub struct Frames<'a> {
    inner: FramesInner<'a>,
}

#[derive(Debug)]
enum FramesInner<'a> {
    #[cfg(target_os = "linux")]
    Ring(RxFrames<'a>),
    #[cfg(all(target_os = "linux", feature = "xdp"))]
    Xdp(XdpFrames<'a>),
    Single(std::iter::Copied<std::option::Iter<'a, Frame<'a>>>),
}

impl<'a> Iterator for Frames<'a> {
    type Item = Frame<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            #[cfg(target_os = "linux")]
            FramesInner::Ring(it) => it.next(),
            #[cfg(all(target_os = "linux", feature = "xdp"))]
            FramesInner::Xdp(it) => it.next(),
            FramesInner::Single(it) => it.next(),
        }
    }
}

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

    #[test]
    fn packet_type_mapping() {
        assert_eq!(PacketType::from_raw(libc::PACKET_HOST), PacketType::Host);
        assert_eq!(PacketType::from_raw(libc::PACKET_BROADCAST), PacketType::Broadcast);
        assert_eq!(PacketType::from_raw(99), PacketType::Other(99));
    }

    #[test]
    fn packet_type_from_mac() {
        assert_eq!(PacketType::from_dest_mac(MacAddr::BROADCAST), PacketType::Broadcast);
        assert_eq!(
            PacketType::from_dest_mac(MacAddr([0x01, 0, 0, 0, 0, 0])),
            PacketType::Multicast
        );
        assert_eq!(
            PacketType::from_dest_mac(MacAddr([0x02, 0, 0, 0, 0, 1])),
            PacketType::Host
        );
    }

    #[test]
    fn vlan_decoding() {
        // priority 5 (101), VID 100.
        let tag = VlanTag { tci: (5 << 13) | 100, tpid: 0x8100 };
        assert_eq!(tag.vid(), 100);
        assert_eq!(tag.priority(), 5);
    }

    proptest::proptest! {
        /// vid/priority decompose any TCI per 802.1Q: 3-bit PCP, 1-bit DEI (ignored), 12-bit VID.
        #[test]
        #[cfg_attr(miri, ignore = "proptest is slow under Miri and covers safe arithmetic")]
        fn vlan_tci_decomposition(tci in proptest::num::u16::ANY) {
            let tag = VlanTag { tci, tpid: 0x8100 };
            proptest::prop_assert!(tag.vid() <= 0x0fff);
            proptest::prop_assert!(tag.priority() <= 7);
            proptest::prop_assert_eq!(tag.vid(), tci & 0x0fff);
            proptest::prop_assert_eq!(tag.priority(), (tci >> 13) as u8);
        }
    }

    #[test]
    fn timestamp_zero_is_none() {
        assert!(FrameMeta::timestamp_from_parts(0, 0).is_none());
        assert!(FrameMeta::timestamp_from_parts(1, 0).is_some());
    }

    #[test]
    fn ring_frame_decodes_metadata_lazily() {
        let bytes = [0xff_u8; 14]; // broadcast destination MAC
        let raw = RawRingMeta {
            wire_len: 1500,
            ts_sec: 5,
            ts_nsec: 6,
            status: libc::TP_STATUS_VLAN_VALID | libc::TP_STATUS_VLAN_TPID_VALID,
            vlan_tci: 100,
            vlan_tpid: 0x8100,
        };
        let f = Frame::ring(&bytes, raw);
        assert_eq!(f.wire_len(), 1500);
        assert_eq!(f.packet_type(), PacketType::Broadcast);
        assert!(f.timestamp().is_some());
        assert_eq!(f.vlan().expect("vlan present").vid(), 100);
        // meta() rebuilds the full struct from the same lazily-decoded fields.
        let m = f.meta();
        assert_eq!(m.wire_len, 1500);
        assert_eq!(m.packet_type, PacketType::Broadcast);
    }

    #[test]
    fn ring_frame_without_vlan_or_timestamp() {
        let bytes = [0x02, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]; // unicast dst
        let raw = RawRingMeta {
            wire_len: 64,
            ts_sec: 0,
            ts_nsec: 0,
            status: 0,
            vlan_tci: 0,
            vlan_tpid: 0,
        };
        let f = Frame::ring(&bytes, raw);
        assert_eq!(f.wire_len(), 64);
        assert!(f.timestamp().is_none());
        assert!(f.vlan().is_none());
        assert_eq!(f.packet_type(), PacketType::Host);
    }

    #[test]
    fn single_block_iterates_once() {
        let bytes = [0xaa_u8; 4];
        let meta = FrameMeta {
            wire_len: 4,
            timestamp: None,
            vlan: None,
            packet_type: PacketType::Host,
        };
        let block = Block::single(Some(Frame::new(&bytes, meta)));
        assert_eq!(block.len(), 1);
        assert!(!block.is_empty());
        let collected: Vec<_> = block.frames().map(|f| f.data().len()).collect();
        assert_eq!(collected, vec![4]);

        let empty = Block::single(None);
        assert!(empty.is_empty());
        assert_eq!(empty.frames().count(), 0);
    }
}