Skip to main content

raw_ether/
capture.rs

1//! Whole frames crossing an interface, both ways, for capturing: those of
2//! chosen ethertypes the interface receives and sends, a bridge port's
3//! forwarded frames among them, each with the time the kernel saw it and
4//! its VLAN tag put back where the kernel had taken it off. The filter
5//! runs in the kernel, so frames of other ethertypes cost the program
6//! nothing, and the kernel hands frames over in blocks of a ring shared
7//! with the program, so a busy capture wakes it a few times a second
8//! rather than once a frame. Linux only so far; elsewhere opening fails
9//! as unsupported.
10
11use std::io;
12use std::time::Duration;
13
14/// The ethertypes of a VLAN tag: 802.1Q's, and 802.1ad's service tag.
15#[cfg(any(target_os = "linux", test))]
16const ETHERTYPE_VLAN: u16 = 0x8100;
17#[cfg(any(target_os = "linux", test))]
18const ETHERTYPE_SERVICE_VLAN: u16 = 0x88a8;
19
20/// Which way a captured frame crossed the interface.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Direction {
23    /// Received on the interface.
24    Inbound,
25    /// Sent out of it, by this computer or by a bridge forwarding it.
26    Outbound,
27}
28
29/// Whom a received frame was addressed to, as the interface saw it.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Addressed {
32    /// This computer.
33    Unicast,
34    Multicast,
35    Broadcast,
36    /// Another computer: heard only because the interface is promiscuous.
37    Elsewhere,
38}
39
40/// Which clock gave a captured frame its time.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Clock {
43    /// The system clock, when the kernel saw the frame.
44    System,
45    /// The interface's PTP hardware clock, when the frame crossed the
46    /// wire: received frames of a capture opened with
47    /// [`Capture::open_stamped`].
48    Hardware,
49}
50
51/// A frame a [`Capture`] took.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct Captured {
54    /// Octets of the frame written to the buffer, from its destination
55    /// address on: no more than the capture's snap length, or the buffer.
56    pub length: usize,
57    /// The frame's whole length, its VLAN tag included.
58    pub original: usize,
59    pub direction: Direction,
60    /// `None` for an outbound frame.
61    pub addressed: Option<Addressed>,
62    /// When the frame was seen, since the epoch of the clock that saw it.
63    pub time: Duration,
64    pub clock: Clock,
65}
66
67/// What a capture took and what its ring had no room for.
68#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
69pub struct Statistics {
70    /// Frames that passed the filter, those dropped included.
71    pub passed: u64,
72    /// Frames dropped because the ring, or for a stamped capture the
73    /// socket's queue, was full: the program fell behind.
74    pub dropped: u64,
75}
76
77/// Takes the frames of chosen ethertypes crossing one interface.
78pub struct Capture {
79    inner: platform::Capture,
80}
81
82impl Capture {
83    /// Opens `interface` for frames of any of `ethertypes`, tagged or not,
84    /// or of every ethertype when there are none, keeping at most `snap`
85    /// octets of each. Frames wait to be read in a ring of about `room`
86    /// octets, memory the kernel lends the program; when it fills, frames
87    /// are dropped and counted. `promiscuous` has the interface hear frames
88    /// for other computers too, as long as the capture is open; a bridge
89    /// port already does. On Linux this needs `CAP_NET_RAW`.
90    pub fn open(
91        interface: &str,
92        ethertypes: &[u16],
93        snap: u32,
94        promiscuous: bool,
95        room: usize,
96    ) -> io::Result<Self> {
97        if ethertypes.len() > MOST_ETHERTYPES {
98            return Err(io::Error::new(
99                io::ErrorKind::InvalidInput,
100                format!("a capture takes at most {MOST_ETHERTYPES} ethertypes"),
101            ));
102        }
103        Ok(Self {
104            inner: platform::Capture::open(interface, ethertypes, snap.max(1), promiscuous, room)?,
105        })
106    }
107
108    /// Writes the next frame to `buffer`, waiting up to `timeout` (forever
109    /// when `None`) for one. `None` when the time ran out or a signal
110    /// interrupted the wait. A zero timeout never waits, for taking every
111    /// frame already there.
112    pub fn receive(
113        &self,
114        buffer: &mut [u8],
115        timeout: Option<Duration>,
116    ) -> io::Result<Option<Captured>> {
117        self.inner.receive(buffer, timeout)
118    }
119
120    /// Waits up to `timeout` (forever when `None`) for frames at any of
121    /// `captures`, giving the places of those that have some.
122    pub fn ready(captures: &[&Capture], timeout: Option<Duration>) -> io::Result<Vec<usize>> {
123        let inner: Vec<&platform::Capture> =
124            captures.iter().map(|capture| &capture.inner).collect();
125        platform::Capture::ready(&inner, timeout)
126    }
127
128    /// What the capture took since last asked.
129    pub fn statistics(&self) -> io::Result<Statistics> {
130        self.inner.statistics()
131    }
132
133    /// Opens `interface` as [`open`](Self::open) does, but timing received
134    /// frames by the interface's PTP hardware clock, as they crossed the
135    /// wire, rather than by when the kernel saw them, which interrupt
136    /// moderation and a busy computer delay. The interface must stamp
137    /// received frames: ptp4l, for one, turns that on, for every frame on
138    /// interfaces that stamp all or none. Frames sent, and any the
139    /// interface did not stamp, keep the system clock's time.
140    ///
141    /// The kernel hands such frames over one at a time rather than in a
142    /// shared ring, as some drivers' time stamps (Intel's igc among them)
143    /// reach the program no other way, so it costs more for a busy
144    /// interface: it suits measuring, not long captures.
145    pub fn open_stamped(
146        interface: &str,
147        ethertypes: &[u16],
148        snap: u32,
149        promiscuous: bool,
150    ) -> io::Result<Self> {
151        if ethertypes.len() > MOST_ETHERTYPES {
152            return Err(io::Error::new(
153                io::ErrorKind::InvalidInput,
154                format!("a capture takes at most {MOST_ETHERTYPES} ethertypes"),
155            ));
156        }
157        Ok(Self {
158            inner: platform::Capture::open_stamped(
159                interface,
160                ethertypes,
161                snap.max(1),
162                promiscuous,
163            )?,
164        })
165    }
166}
167
168/// The most ethertypes a filter can test: its jumps reach 255 steps.
169const MOST_ETHERTYPES: usize = 100;
170
171/// A classic BPF instruction: code, jump if true, jump if false, constant.
172#[cfg(any(target_os = "linux", test))]
173type Step = (u16, u8, u8, u32);
174
175/// The filter keeping frames of any of `ethertypes`, after a VLAN tag or
176/// not, cut to `snap` octets; every frame when there are none. A packet
177/// socket's program sees a received frame with its tag already taken off,
178/// a sent one with the tag still in it.
179#[cfg(any(target_os = "linux", test))]
180fn program(ethertypes: &[u16], snap: u32) -> Vec<Step> {
181    const LOAD_HALF: u16 = 0x28; // ldh [k]
182    const JUMP_EQUAL: u16 = 0x15; // jeq #k
183    const RETURN: u16 = 0x06; // ret #k
184    if ethertypes.is_empty() {
185        return vec![(RETURN, 0, 0, snap)];
186    }
187    let count = ethertypes.len();
188    // The tagged frames' tests start at `tagged`, and every match jumps to
189    // the last step, `keep`. A jump counts from the step after its own.
190    let tagged = 4 + count;
191    let keep = 6 + 2 * count;
192    let mut steps = vec![
193        (LOAD_HALF, 0, 0, 12),
194        (JUMP_EQUAL, (tagged - 2) as u8, 0, u32::from(ETHERTYPE_VLAN)),
195        (
196            JUMP_EQUAL,
197            (tagged - 3) as u8,
198            0,
199            u32::from(ETHERTYPE_SERVICE_VLAN),
200        ),
201    ];
202    for (place, ethertype) in ethertypes.iter().enumerate() {
203        let at = 3 + place;
204        steps.push((JUMP_EQUAL, (keep - at - 1) as u8, 0, u32::from(*ethertype)));
205    }
206    steps.push((RETURN, 0, 0, 0));
207    steps.push((LOAD_HALF, 0, 0, 16));
208    for (place, ethertype) in ethertypes.iter().enumerate() {
209        let at = tagged + 1 + place;
210        steps.push((JUMP_EQUAL, (keep - at - 1) as u8, 0, u32::from(*ethertype)));
211    }
212    steps.push((RETURN, 0, 0, 0));
213    steps.push((RETURN, 0, 0, snap));
214    steps
215}
216
217/// Puts a VLAN tag of `tpid` and `tci` back after the source address of
218/// the `length` octets of frame in `buffer`, as it crossed the wire,
219/// cutting the end where the buffer has no room. The frame's new length.
220#[cfg(any(target_os = "linux", test))]
221fn put_back_tag(buffer: &mut [u8], length: usize, tpid: u16, tci: u16) -> usize {
222    if length < 12 || buffer.len() < 16 {
223        return length;
224    }
225    let tagged = (length + 4).min(buffer.len());
226    buffer.copy_within(12..tagged - 4, 16);
227    buffer[12..14].copy_from_slice(&tpid.to_be_bytes());
228    buffer[14..16].copy_from_slice(&tci.to_be_bytes());
229    tagged
230}
231
232/// Where things sit in a block of the kernel's capture ring, version 3 of
233/// its layout (`tpacket_block_desc` and `tpacket3_hdr` in
234/// linux/if_packet.h), all in the computer's own byte order. A block
235/// starts with its status, its count of frames and where the first is;
236/// each frame with a header saying where the next is, then the link-layer
237/// address it came from or went to, then the frame.
238#[cfg(any(target_os = "linux", test))]
239mod ring {
240    pub const BLOCK_STATUS: usize = 8;
241    pub const BLOCK_FRAMES: usize = 12;
242    pub const BLOCK_FIRST: usize = 16;
243
244    pub const NEXT: usize = 0;
245    pub const SECONDS: usize = 4;
246    pub const NANOSECONDS: usize = 8;
247    pub const SNAP: usize = 12;
248    pub const LENGTH: usize = 16;
249    pub const STATUS: usize = 20;
250    pub const MAC: usize = 24;
251    pub const VLAN_TCI: usize = 32;
252    pub const VLAN_TPID: usize = 36;
253    /// The link-layer address, after the 48-octet header; within it, the
254    /// kind of packet.
255    pub const PACKET_TYPE: usize = 48 + 10;
256
257    pub const USER: u32 = 1;
258    pub const VLAN_VALID: u32 = 1 << 4;
259    pub const VLAN_TPID_VALID: u32 = 1 << 6;
260
261    pub const HOST: u8 = 0;
262    pub const BROADCAST: u8 = 1;
263    pub const MULTICAST: u8 = 2;
264    pub const OUTGOING: u8 = 4;
265}
266
267#[cfg(any(target_os = "linux", test))]
268fn word(block: &[u8], at: usize) -> Option<u32> {
269    Some(u32::from_ne_bytes(block.get(at..at + 4)?.try_into().ok()?))
270}
271
272#[cfg(any(target_os = "linux", test))]
273fn half(block: &[u8], at: usize) -> Option<u16> {
274    Some(u16::from_ne_bytes(block.get(at..at + 2)?.try_into().ok()?))
275}
276
277/// How many frames a ring `block` holds and where the first starts.
278#[cfg(any(target_os = "linux", test))]
279fn block_frames(block: &[u8]) -> Option<(u32, usize)> {
280    Some((
281        word(block, ring::BLOCK_FRAMES)?,
282        word(block, ring::BLOCK_FIRST)? as usize,
283    ))
284}
285
286/// Copies the frame at `at` in a ring `block` to `buffer`, at most `snap`
287/// octets of it, its VLAN tag put back: the frame as captured, and how
288/// far on the next one starts. `None` when the block is not laid out as
289/// it should be.
290#[cfg(any(target_os = "linux", test))]
291fn read_frame(block: &[u8], at: usize, buffer: &mut [u8], snap: u32) -> Option<(Captured, usize)> {
292    let field = |offset: usize| word(block, at + offset);
293    let next = field(ring::NEXT)? as usize;
294    let time = Duration::new(
295        u64::from(field(ring::SECONDS)?),
296        field(ring::NANOSECONDS)?.min(999_999_999),
297    );
298    let kept = field(ring::SNAP)? as usize;
299    let mut original = field(ring::LENGTH)? as usize;
300    let status = field(ring::STATUS)?;
301    let start = at + usize::from(half(block, at + ring::MAC)?);
302    let frame = block.get(start..start + kept)?;
303    let mut length = kept.min(buffer.len());
304    buffer[..length].copy_from_slice(&frame[..length]);
305    if status & ring::VLAN_VALID != 0 {
306        let tci = field(ring::VLAN_TCI)? as u16;
307        let tpid = if status & ring::VLAN_TPID_VALID != 0 {
308            half(block, at + ring::VLAN_TPID)?
309        } else {
310            ETHERTYPE_VLAN
311        };
312        length = put_back_tag(buffer, length, tpid, tci);
313        original += 4;
314    }
315    let (direction, addressed) = match *block.get(at + ring::PACKET_TYPE)? {
316        ring::OUTGOING => (Direction::Outbound, None),
317        ring::HOST => (Direction::Inbound, Some(Addressed::Unicast)),
318        ring::MULTICAST => (Direction::Inbound, Some(Addressed::Multicast)),
319        ring::BROADCAST => (Direction::Inbound, Some(Addressed::Broadcast)),
320        _ => (Direction::Inbound, Some(Addressed::Elsewhere)),
321    };
322    let captured = Captured {
323        length: length.min(snap as usize),
324        original,
325        direction,
326        addressed,
327        time,
328        clock: Clock::System,
329    };
330    Some((captured, next))
331}
332
333/// A frame `recvmsg` wrote to `buffer`, its first `length` octets: its
334/// VLAN tag, where the kernel had `tag` (TPID and TCI) off, put back; its
335/// whole length `original` where the kernel says; timed by the interface's
336/// hardware clock where it was received and stamped, by `now` otherwise.
337#[cfg(any(target_os = "linux", test))]
338#[allow(clippy::too_many_arguments)]
339fn stamped_frame(
340    buffer: &mut [u8],
341    length: usize,
342    packet_type: u8,
343    original: Option<usize>,
344    tag: Option<(u16, u16)>,
345    hardware: Option<Duration>,
346    now: Duration,
347    snap: u32,
348) -> Captured {
349    let mut length = length.min(buffer.len());
350    let mut original = original.unwrap_or(length);
351    if let Some((tpid, tci)) = tag {
352        length = put_back_tag(buffer, length, tpid, tci);
353        original += 4;
354    }
355    let (direction, addressed) = match packet_type {
356        ring::OUTGOING => (Direction::Outbound, None),
357        ring::HOST => (Direction::Inbound, Some(Addressed::Unicast)),
358        ring::MULTICAST => (Direction::Inbound, Some(Addressed::Multicast)),
359        ring::BROADCAST => (Direction::Inbound, Some(Addressed::Broadcast)),
360        _ => (Direction::Inbound, Some(Addressed::Elsewhere)),
361    };
362    // A forwarded frame going out carries its arrival's stamp, from
363    // another port's clock: not its time here.
364    let (time, clock) = match hardware.filter(|_| direction == Direction::Inbound) {
365        Some(time) => (time, Clock::Hardware),
366        None => (now, Clock::System),
367    };
368    Captured {
369        length: length.min(snap as usize),
370        original,
371        direction,
372        addressed,
373        time,
374        clock,
375    }
376}
377
378#[cfg(target_os = "linux")]
379#[allow(unsafe_code)]
380mod platform {
381    use std::cell::Cell;
382    use std::io;
383    use std::mem::size_of;
384    use std::os::fd::{AsRawFd, OwnedFd};
385    use std::sync::atomic::{AtomicU32, Ordering};
386    use std::time::Duration;
387
388    use super::{Captured, ETHERTYPE_VLAN, Statistics, ring};
389
390    /// A ring block's size: room for the largest frame worth keeping.
391    const BLOCK: usize = 1 << 16;
392
393    /// The fewest blocks a ring has, so the kernel fills one while the
394    /// program reads another.
395    const FEWEST_BLOCKS: usize = 2;
396
397    /// How long the kernel holds a block that has frames but is not full
398    /// before handing it over: how late a frame may come to the program.
399    const HAND_OVER_MS: u32 = 100;
400
401    /// SO_TIMESTAMPING, its control messages SCM_TIMESTAMPING, and
402    /// PACKET_AUXDATA, from Linux's headers, which libc lacks for Linux.
403    const SO_TIMESTAMPING: libc::c_int = 37;
404    const PACKET_AUXDATA: libc::c_int = 8;
405
406    /// struct tpacket_auxdata, from linux/if_packet.h.
407    #[repr(C)]
408    #[derive(Clone, Copy)]
409    struct Auxdata {
410        status: u32,
411        length: u32,
412        snap: u32,
413        mac: u16,
414        net: u16,
415        vlan_tci: u16,
416        vlan_tpid: u16,
417    }
418
419    pub struct Capture {
420        fd: OwnedFd,
421        snap: u32,
422        ring: *mut u8,
423        blocks: usize,
424        /// The block being read or waited for, and within it the frames
425        /// left to read and where the next starts. With none left, the
426        /// block is the kernel's.
427        block: Cell<usize>,
428        left: Cell<u32>,
429        next: Cell<usize>,
430        /// Frames come one at a time, with their hardware time stamps,
431        /// rather than through a ring.
432        stamped: bool,
433    }
434
435    // SAFETY: the ring is mapped for this capture alone and touched only
436    // through it; sending the capture to another thread sends the ring.
437    unsafe impl Send for Capture {}
438
439    /// Sets the integer socket option `name` of `level` to `value`.
440    fn set(
441        fd: &OwnedFd,
442        level: libc::c_int,
443        name: libc::c_int,
444        value: libc::c_int,
445    ) -> io::Result<()> {
446        set_raw(fd, level, name, &value)
447    }
448
449    /// Sets the socket option `name` of `level` to the plain data `value`.
450    fn set_raw<T>(
451        fd: &OwnedFd,
452        level: libc::c_int,
453        name: libc::c_int,
454        value: &T,
455    ) -> io::Result<()> {
456        // SAFETY: `value` is plain data that lives through the call, and
457        // the length passed is its size.
458        let set = unsafe {
459            libc::setsockopt(
460                fd.as_raw_fd(),
461                level,
462                name,
463                std::ptr::from_ref(value).cast(),
464                size_of::<T>() as libc::socklen_t,
465            )
466        };
467        if set < 0 {
468            return Err(io::Error::last_os_error());
469        }
470        Ok(())
471    }
472
473    fn milliseconds(timeout: Option<Duration>) -> libc::c_int {
474        match timeout {
475            // Round up, so a short wait does not become a busy loop.
476            Some(timeout) => timeout.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32,
477            None => -1,
478        }
479    }
480
481    impl Capture {
482        /// The index of the interface named `interface`.
483        fn index(interface: &str) -> io::Result<i32> {
484            crate::interfaces::index_of(interface).ok_or_else(|| {
485                io::Error::new(
486                    io::ErrorKind::NotFound,
487                    format!("no interface named {interface}"),
488                )
489            })
490        }
491
492        /// A raw socket keeping only frames of `ethertypes`, cut to `snap`.
493        /// Opened for no protocol, so nothing arrives before the filter, and
494        /// the ring, are on.
495        fn filtered(ethertypes: &[u16], snap: u32) -> io::Result<OwnedFd> {
496            let fd = crate::broker::open(crate::broker::Kind::Raw)?;
497            let program: Vec<libc::sock_filter> = super::program(ethertypes, snap)
498                .into_iter()
499                .map(|(code, jt, jf, k)| libc::sock_filter { code, jt, jf, k })
500                .collect();
501            let filter = libc::sock_fprog {
502                len: program.len() as u16,
503                filter: program.as_ptr().cast_mut(),
504            };
505            set_raw(&fd, libc::SOL_SOCKET, libc::SO_ATTACH_FILTER, &filter)?;
506            Ok(fd)
507        }
508
509        pub fn open_stamped(
510            interface: &str,
511            ethertypes: &[u16],
512            snap: u32,
513            promiscuous: bool,
514        ) -> io::Result<Self> {
515            /// A stamped capture's receive buffer, in octets: a quarter
516            /// second of a class A stream.
517            const STAMPED_ROOM: libc::c_int = 4 << 20;
518            let index = Self::index(interface)?;
519            let fd = Self::filtered(ethertypes, snap)?;
520            set(
521                &fd,
522                libc::SOL_SOCKET,
523                SO_TIMESTAMPING,
524                (libc::SOF_TIMESTAMPING_RX_HARDWARE | libc::SOF_TIMESTAMPING_RAW_HARDWARE)
525                    as libc::c_int,
526            )?;
527            // The VLAN tag the kernel took off, to put back.
528            set(&fd, libc::SOL_PACKET, PACKET_AUXDATA, 1)?;
529            // Room for frames to wait while the program is busy: the
530            // kernel's default holds a class A stream for some 30 ms. Past
531            // the system's limit only with CAP_NET_ADMIN.
532            if set(&fd, libc::SOL_SOCKET, libc::SO_RCVBUFFORCE, STAMPED_ROOM).is_err() {
533                set(&fd, libc::SOL_SOCKET, libc::SO_RCVBUF, STAMPED_ROOM)?;
534            }
535            let capture = Self {
536                fd,
537                snap,
538                ring: std::ptr::null_mut(),
539                blocks: 0,
540                block: Cell::new(0),
541                left: Cell::new(0),
542                next: Cell::new(0),
543                stamped: true,
544            };
545            Self::attach(capture, index, promiscuous)
546        }
547
548        pub fn open(
549            interface: &str,
550            ethertypes: &[u16],
551            snap: u32,
552            promiscuous: bool,
553            room: usize,
554        ) -> io::Result<Self> {
555            let index = Self::index(interface)?;
556            let fd = Self::filtered(ethertypes, snap)?;
557            set(
558                &fd,
559                libc::SOL_PACKET,
560                libc::PACKET_VERSION,
561                libc::tpacket_versions::TPACKET_V3 as libc::c_int,
562            )?;
563            let blocks = (room / BLOCK).max(FEWEST_BLOCKS);
564            // Version 3 keeps frames of any size in a block; the frame
565            // size only has to divide it.
566            let frame = 1 << 11;
567            let request = libc::tpacket_req3 {
568                tp_block_size: BLOCK as u32,
569                tp_block_nr: blocks as u32,
570                tp_frame_size: frame,
571                tp_frame_nr: (BLOCK / frame as usize * blocks) as u32,
572                tp_retire_blk_tov: HAND_OVER_MS,
573                tp_sizeof_priv: 0,
574                tp_feature_req_word: 0,
575            };
576            set_raw(&fd, libc::SOL_PACKET, libc::PACKET_RX_RING, &request)?;
577            // SAFETY: maps the ring the kernel just made for this socket,
578            // its whole length, shared with the kernel.
579            let ring = unsafe {
580                libc::mmap(
581                    std::ptr::null_mut(),
582                    BLOCK * blocks,
583                    libc::PROT_READ | libc::PROT_WRITE,
584                    libc::MAP_SHARED,
585                    fd.as_raw_fd(),
586                    0,
587                )
588            };
589            if ring == libc::MAP_FAILED {
590                return Err(io::Error::last_os_error());
591            }
592            let capture = Self {
593                fd,
594                snap,
595                ring: ring.cast(),
596                blocks,
597                block: Cell::new(0),
598                left: Cell::new(0),
599                next: Cell::new(0),
600                stamped: false,
601            };
602            Self::attach(capture, index, promiscuous)
603        }
604
605        /// Binds the capture to the interface with `index`, promiscuous
606        /// if asked.
607        fn attach(capture: Self, index: i32, promiscuous: bool) -> io::Result<Self> {
608            // SAFETY: sockaddr_ll is plain data, valid when zeroed.
609            let mut address: libc::sockaddr_ll = unsafe { std::mem::zeroed() };
610            address.sll_family = libc::AF_PACKET as u16;
611            address.sll_protocol = (libc::ETH_P_ALL as u16).to_be();
612            address.sll_ifindex = index;
613            // SAFETY: `address` is a valid sockaddr_ll that lives through the
614            // call, and the length passed is its size.
615            let bound = unsafe {
616                libc::bind(
617                    capture.fd.as_raw_fd(),
618                    (&raw const address).cast(),
619                    size_of::<libc::sockaddr_ll>() as libc::socklen_t,
620                )
621            };
622            if bound < 0 {
623                return Err(io::Error::last_os_error());
624            }
625            if promiscuous {
626                // SAFETY: packet_mreq is plain data, valid when zeroed.
627                let mut request: libc::packet_mreq = unsafe { std::mem::zeroed() };
628                request.mr_ifindex = index;
629                request.mr_type = libc::PACKET_MR_PROMISC as u16;
630                // The membership ends as the socket closes.
631                set_raw(
632                    &capture.fd,
633                    libc::SOL_PACKET,
634                    libc::PACKET_ADD_MEMBERSHIP,
635                    &request,
636                )?;
637            }
638            Ok(capture)
639        }
640
641        /// The block being read or waited for.
642        fn block(&self) -> *mut u8 {
643            // SAFETY: the block number stays below the ring's count of
644            // blocks, so the result lies within the mapping.
645            unsafe { self.ring.add(self.block.get() * BLOCK) }
646        }
647
648        /// A block's status, which the kernel and the program hand the
649        /// block back and forth with.
650        fn status(&self) -> &AtomicU32 {
651            // SAFETY: the status is an aligned 32-bit word of the block,
652            // the mapping page-aligned, and it lives as long as `self`;
653            // the kernel and this program only ever touch it whole.
654            unsafe { AtomicU32::from_ptr(self.block().add(ring::BLOCK_STATUS).cast()) }
655        }
656
657        /// Hands the current block back to the kernel and moves to the
658        /// next.
659        fn release(&self) {
660            self.left.set(0);
661            self.status().store(0, Ordering::Release);
662            self.block.set((self.block.get() + 1) % self.blocks);
663        }
664
665        /// The next frame waiting, without waiting for one.
666        fn take(&self, buffer: &mut [u8]) -> Option<Captured> {
667            if self.stamped {
668                return self.take_stamped(buffer);
669            }
670            loop {
671                if self.left.get() == 0 {
672                    if self.status().load(Ordering::Acquire) & ring::USER == 0 {
673                        return None;
674                    }
675                    // SAFETY: the block is the program's until released, so
676                    // the kernel does not write it while this slice lives.
677                    let block = unsafe { std::slice::from_raw_parts(self.block(), BLOCK) };
678                    match super::block_frames(block) {
679                        Some((frames, first)) if frames > 0 => {
680                            self.left.set(frames);
681                            self.next.set(first);
682                        }
683                        _ => {
684                            self.release();
685                            continue;
686                        }
687                    }
688                }
689                // SAFETY: as above, the block is the program's.
690                let block = unsafe { std::slice::from_raw_parts(self.block(), BLOCK) };
691                let read = super::read_frame(block, self.next.get(), buffer, self.snap);
692                let left = self.left.get() - 1;
693                self.left.set(left);
694                match read {
695                    Some((captured, next)) => {
696                        self.next.set(self.next.get() + next);
697                        if left == 0 {
698                            self.release();
699                        }
700                        return Some(captured);
701                    }
702                    // A block not as it should be: skip what is left of it.
703                    None => self.release(),
704                }
705            }
706        }
707
708        /// The next frame waiting with its control messages, without
709        /// waiting for one.
710        fn take_stamped(&self, buffer: &mut [u8]) -> Option<Captured> {
711            // SAFETY: plain data, valid when zeroed.
712            let mut address: libc::sockaddr_ll = unsafe { std::mem::zeroed() };
713            let mut control = [0u64; 64];
714            let mut part = libc::iovec {
715                iov_base: buffer.as_mut_ptr().cast(),
716                iov_len: buffer.len(),
717            };
718            // SAFETY: plain data, valid when zeroed.
719            let mut message: libc::msghdr = unsafe { std::mem::zeroed() };
720            message.msg_name = (&raw mut address).cast();
721            message.msg_namelen = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
722            message.msg_iov = &raw mut part;
723            message.msg_iovlen = 1;
724            message.msg_control = control.as_mut_ptr().cast();
725            message.msg_controllen = size_of_val(&control) as _;
726            // SAFETY: every buffer the message points to lives through the
727            // call, with its length given.
728            let length =
729                unsafe { libc::recvmsg(self.fd.as_raw_fd(), &raw mut message, libc::MSG_DONTWAIT) };
730            if length < 0 {
731                return None;
732            }
733            let mut hardware = None;
734            let mut original = None;
735            let mut tag = None;
736            // SAFETY: the kernel wrote the control messages within
737            // `control`, and msg_controllen says how far; CMSG_FIRSTHDR and
738            // CMSG_NXTHDR stay within it.
739            let mut header = unsafe { libc::CMSG_FIRSTHDR(&raw const message) };
740            while !header.is_null() {
741                // SAFETY: a header the kernel wrote, its data after it.
742                let (level, kind, data) = unsafe {
743                    (
744                        (*header).cmsg_level,
745                        (*header).cmsg_type,
746                        libc::CMSG_DATA(header),
747                    )
748                };
749                if level == libc::SOL_SOCKET && kind == SO_TIMESTAMPING {
750                    // SAFETY: SCM_TIMESTAMPING carries three timespecs, the
751                    // last the raw hardware time.
752                    let stamps: [libc::timespec; 3] =
753                        unsafe { std::ptr::read_unaligned(data.cast()) };
754                    let raw = stamps[2];
755                    if raw.tv_sec > 0 || raw.tv_nsec > 0 {
756                        hardware = Some(Duration::new(raw.tv_sec as u64, raw.tv_nsec as u32));
757                    }
758                } else if level == libc::SOL_PACKET && kind == PACKET_AUXDATA {
759                    // SAFETY: PACKET_AUXDATA carries a tpacket_auxdata.
760                    let aux: Auxdata = unsafe { std::ptr::read_unaligned(data.cast()) };
761                    original = Some(aux.length as usize);
762                    if aux.status & ring::VLAN_VALID != 0 {
763                        let tpid = if aux.status & ring::VLAN_TPID_VALID != 0 {
764                            aux.vlan_tpid
765                        } else {
766                            ETHERTYPE_VLAN
767                        };
768                        tag = Some((tpid, aux.vlan_tci));
769                    }
770                }
771                // SAFETY: as above.
772                header = unsafe { libc::CMSG_NXTHDR(&raw const message, header) };
773            }
774            let now = std::time::SystemTime::now()
775                .duration_since(std::time::UNIX_EPOCH)
776                .unwrap_or_default();
777            Some(super::stamped_frame(
778                buffer,
779                length as usize,
780                address.sll_pkttype,
781                original,
782                tag,
783                hardware,
784                now,
785                self.snap,
786            ))
787        }
788
789        pub fn receive(
790            &self,
791            buffer: &mut [u8],
792            timeout: Option<Duration>,
793        ) -> io::Result<Option<Captured>> {
794            if let Some(captured) = self.take(buffer) {
795                return Ok(Some(captured));
796            }
797            if timeout == Some(Duration::ZERO) {
798                return Ok(None);
799            }
800            let ready = Self::ready(&[self], timeout)?;
801            if ready.is_empty() {
802                return Ok(None);
803            }
804            Ok(self.take(buffer))
805        }
806
807        pub fn ready(captures: &[&Self], timeout: Option<Duration>) -> io::Result<Vec<usize>> {
808            // A capture partway through a block has frames already.
809            let waiting: Vec<usize> = captures
810                .iter()
811                .enumerate()
812                .filter(|(_, capture)| capture.left.get() > 0)
813                .map(|(place, _)| place)
814                .collect();
815            if !waiting.is_empty() {
816                return Ok(waiting);
817            }
818            let mut polls: Vec<libc::pollfd> = captures
819                .iter()
820                .map(|capture| libc::pollfd {
821                    fd: capture.fd.as_raw_fd(),
822                    events: libc::POLLIN,
823                    revents: 0,
824                })
825                .collect();
826            // SAFETY: `polls` holds valid pollfds and lives through the call.
827            let ready = unsafe {
828                libc::poll(
829                    polls.as_mut_ptr(),
830                    polls.len() as libc::nfds_t,
831                    milliseconds(timeout),
832                )
833            };
834            if ready < 0 {
835                let error = io::Error::last_os_error();
836                return match error.kind() {
837                    io::ErrorKind::Interrupted => Ok(Vec::new()),
838                    _ => Err(error),
839                };
840            }
841            Ok(polls
842                .iter()
843                .enumerate()
844                .filter(|(_, poll)| poll.revents & libc::POLLIN != 0)
845                .map(|(place, _)| place)
846                .collect())
847        }
848
849        pub fn statistics(&self) -> io::Result<Statistics> {
850            // SAFETY: tpacket_stats is plain data, valid when zeroed.
851            let mut stats: libc::tpacket_stats = unsafe { std::mem::zeroed() };
852            let mut length = size_of::<libc::tpacket_stats>() as libc::socklen_t;
853            // SAFETY: `stats` and `length` live through the call, and the
854            // length says how much of `stats` the kernel may write, the
855            // counts a ring's statistics start with; reading resets them.
856            let read = unsafe {
857                libc::getsockopt(
858                    self.fd.as_raw_fd(),
859                    libc::SOL_PACKET,
860                    libc::PACKET_STATISTICS,
861                    (&raw mut stats).cast(),
862                    &raw mut length,
863                )
864            };
865            if read < 0 {
866                return Err(io::Error::last_os_error());
867            }
868            Ok(Statistics {
869                passed: u64::from(stats.tp_packets),
870                dropped: u64::from(stats.tp_drops),
871            })
872        }
873    }
874
875    impl Drop for Capture {
876        fn drop(&mut self) {
877            if self.ring.is_null() {
878                return;
879            }
880            // SAFETY: unmaps the ring this capture mapped, its whole
881            // length; nothing refers into it once the capture is gone.
882            unsafe {
883                libc::munmap(self.ring.cast(), BLOCK * self.blocks);
884            }
885        }
886    }
887}
888
889#[cfg(not(target_os = "linux"))]
890mod platform {
891    use std::io;
892    use std::time::Duration;
893
894    use super::{Captured, Statistics};
895
896    fn unsupported() -> io::Error {
897        io::Error::new(
898            io::ErrorKind::Unsupported,
899            "capturing is not supported on this system yet",
900        )
901    }
902
903    pub struct Capture;
904
905    impl Capture {
906        pub fn open(
907            _interface: &str,
908            _ethertypes: &[u16],
909            _snap: u32,
910            _promiscuous: bool,
911            _room: usize,
912        ) -> io::Result<Self> {
913            Err(unsupported())
914        }
915
916        pub fn receive(
917            &self,
918            _buffer: &mut [u8],
919            _timeout: Option<Duration>,
920        ) -> io::Result<Option<Captured>> {
921            Err(unsupported())
922        }
923
924        pub fn ready(_captures: &[&Self], _timeout: Option<Duration>) -> io::Result<Vec<usize>> {
925            Err(unsupported())
926        }
927
928        pub fn statistics(&self) -> io::Result<Statistics> {
929            Err(unsupported())
930        }
931
932        pub fn open_stamped(
933            _interface: &str,
934            _ethertypes: &[u16],
935            _snap: u32,
936            _promiscuous: bool,
937        ) -> io::Result<Self> {
938            Err(unsupported())
939        }
940    }
941}
942
943#[cfg(test)]
944mod tests {
945    use super::*;
946
947    /// Runs a filter of the few instructions [`program`] uses over `frame`,
948    /// as the kernel would: the octets kept, zero for none.
949    fn run(steps: &[Step], frame: &[u8]) -> u32 {
950        let mut accumulator = 0u32;
951        let mut at = 0;
952        loop {
953            let (code, jt, jf, k) = steps[at];
954            match code {
955                0x28 => {
956                    let k = k as usize;
957                    let Some(half) = frame.get(k..k + 2) else {
958                        return 0;
959                    };
960                    accumulator = u32::from(u16::from_be_bytes([half[0], half[1]]));
961                    at += 1;
962                }
963                0x15 => at += 1 + usize::from(if accumulator == k { jt } else { jf }),
964                0x06 => return k,
965                _ => panic!("unexpected instruction {code:#x}"),
966            }
967        }
968    }
969
970    fn frame(ethertypes: &[u16]) -> Vec<u8> {
971        let mut frame = vec![0u8; 12];
972        for ethertype in ethertypes {
973            frame.extend_from_slice(&ethertype.to_be_bytes());
974            if [ETHERTYPE_VLAN, ETHERTYPE_SERVICE_VLAN].contains(ethertype) {
975                frame.extend_from_slice(&[0x60, 0x02]);
976            }
977        }
978        frame.extend_from_slice(&[0; 40]);
979        frame
980    }
981
982    #[test]
983    fn the_filter_keeps_its_ethertypes_tagged_or_not() {
984        let steps = program(&[0x88f7, 0x22ea], 96);
985        assert_eq!(run(&steps, &frame(&[0x88f7])), 96);
986        assert_eq!(run(&steps, &frame(&[0x22ea])), 96);
987        assert_eq!(run(&steps, &frame(&[ETHERTYPE_VLAN, 0x88f7])), 96);
988        assert_eq!(run(&steps, &frame(&[ETHERTYPE_SERVICE_VLAN, 0x22ea])), 96);
989        assert_eq!(run(&steps, &frame(&[0x0800])), 0);
990        assert_eq!(run(&steps, &frame(&[ETHERTYPE_VLAN, 0x22f0])), 0);
991        assert_eq!(run(&steps, &[0; 13]), 0);
992    }
993
994    #[test]
995    fn the_filter_reaches_its_last_step_from_every_test() {
996        let ethertypes: Vec<u16> = (0..MOST_ETHERTYPES as u16).map(|n| 0x9000 + n).collect();
997        let steps = program(&ethertypes, u32::MAX);
998        for ethertype in &ethertypes {
999            assert_eq!(run(&steps, &frame(&[*ethertype])), u32::MAX);
1000            assert_eq!(run(&steps, &frame(&[ETHERTYPE_VLAN, *ethertype])), u32::MAX);
1001        }
1002        assert_eq!(run(&steps, &frame(&[0x8fff])), 0);
1003    }
1004
1005    #[test]
1006    fn with_no_ethertypes_the_filter_keeps_everything() {
1007        assert_eq!(program(&[], 1514), vec![(0x06, 0, 0, 1514)]);
1008    }
1009
1010    #[test]
1011    fn a_tag_goes_back_after_the_source_address() {
1012        let mut buffer = [0u8; 32];
1013        let untagged: Vec<u8> = (1..=20).collect();
1014        buffer[..20].copy_from_slice(&untagged);
1015        let length = put_back_tag(&mut buffer, 20, 0x8100, 0x6002);
1016        assert_eq!(length, 24);
1017        assert_eq!(&buffer[..12], &untagged[..12]);
1018        assert_eq!(&buffer[12..16], &[0x81, 0x00, 0x60, 0x02]);
1019        assert_eq!(&buffer[16..24], &untagged[12..]);
1020    }
1021
1022    #[test]
1023    fn a_tag_put_back_into_a_full_buffer_cuts_the_end() {
1024        let mut buffer: Vec<u8> = (1..=20).collect();
1025        let length = put_back_tag(&mut buffer, 20, 0x8100, 0x0002);
1026        assert_eq!(length, 20);
1027        assert_eq!(&buffer[12..16], &[0x81, 0x00, 0x00, 0x02]);
1028        assert_eq!(&buffer[16..20], &[13, 14, 15, 16]);
1029    }
1030
1031    /// A ring block holding `frames`, each (packet type, VLAN tag, frame),
1032    /// laid out as the kernel lays it out.
1033    fn block(frames: &[(u8, Option<u16>, &[u8])]) -> Vec<u8> {
1034        let mut block = vec![0u8; 48];
1035        let put = |block: &mut Vec<u8>, at: usize, value: u32| {
1036            block[at..at + 4].copy_from_slice(&value.to_ne_bytes());
1037        };
1038        put(&mut block, ring::BLOCK_STATUS, ring::USER);
1039        put(&mut block, ring::BLOCK_FRAMES, frames.len() as u32);
1040        put(&mut block, ring::BLOCK_FIRST, 48);
1041        for (place, (packet_type, tag, data)) in frames.iter().enumerate() {
1042            let at = block.len();
1043            let mac = 80;
1044            let size = (mac + data.len()).div_ceil(16) * 16;
1045            block.resize(at + size, 0);
1046            let last = place + 1 == frames.len();
1047            put(
1048                &mut block,
1049                at + ring::NEXT,
1050                if last { 0 } else { size as u32 },
1051            );
1052            put(&mut block, at + ring::SECONDS, 1_700_000_000);
1053            put(&mut block, at + ring::NANOSECONDS, 42 + place as u32);
1054            put(&mut block, at + ring::SNAP, data.len() as u32);
1055            put(&mut block, at + ring::LENGTH, data.len() as u32 + 100);
1056            let status = if tag.is_some() { ring::VLAN_VALID } else { 0 };
1057            put(&mut block, at + ring::STATUS, status);
1058            block[at + ring::MAC..at + ring::MAC + 2].copy_from_slice(&(mac as u16).to_ne_bytes());
1059            put(&mut block, at + ring::VLAN_TCI, u32::from(tag.unwrap_or(0)));
1060            block[at + ring::PACKET_TYPE] = *packet_type;
1061            block[at + mac..at + mac + data.len()].copy_from_slice(data);
1062        }
1063        block
1064    }
1065
1066    #[test]
1067    fn frames_come_out_of_a_ring_block_in_order() {
1068        let first: Vec<u8> = (0..20).collect();
1069        let second: Vec<u8> = (100..130).collect();
1070        let block = block(&[
1071            (ring::OUTGOING, None, &first),
1072            (ring::MULTICAST, Some(0x6002), &second),
1073        ]);
1074        let (frames, mut at) = block_frames(&block).unwrap();
1075        assert_eq!(frames, 2);
1076        let mut buffer = [0u8; 64];
1077
1078        let (captured, next) = read_frame(&block, at, &mut buffer, 1500).unwrap();
1079        assert_eq!(captured.direction, Direction::Outbound);
1080        assert_eq!(captured.addressed, None);
1081        assert_eq!(captured.length, 20);
1082        assert_eq!(captured.original, 120);
1083        assert_eq!(captured.time, Duration::new(1_700_000_000, 42));
1084        assert_eq!(&buffer[..20], &first[..]);
1085        at += next;
1086
1087        let (captured, _) = read_frame(&block, at, &mut buffer, 1500).unwrap();
1088        assert_eq!(captured.direction, Direction::Inbound);
1089        assert_eq!(captured.addressed, Some(Addressed::Multicast));
1090        assert_eq!(captured.length, 34);
1091        assert_eq!(captured.original, 134);
1092        assert_eq!(&buffer[12..16], &[0x81, 0x00, 0x60, 0x02]);
1093        assert_eq!(&buffer[16..34], &second[12..]);
1094    }
1095
1096    #[test]
1097    fn a_received_frame_takes_its_hardware_time() {
1098        let mut buffer = [0u8; 64];
1099        buffer[..20].copy_from_slice(&(0..20).collect::<Vec<u8>>());
1100        let wire = Duration::new(265_258, 495_597_656);
1101        let now = Duration::new(1_793_300_000, 0);
1102        let captured = stamped_frame(
1103            &mut buffer,
1104            20,
1105            ring::MULTICAST,
1106            Some(120),
1107            None,
1108            Some(wire),
1109            now,
1110            64,
1111        );
1112        assert_eq!((captured.time, captured.clock), (wire, Clock::Hardware));
1113        assert_eq!(captured.direction, Direction::Inbound);
1114        assert_eq!((captured.length, captured.original), (20, 120));
1115    }
1116
1117    #[test]
1118    fn a_frame_going_out_keeps_the_system_time_and_gets_its_tag_back() {
1119        let mut buffer = [0u8; 64];
1120        buffer[..20].copy_from_slice(&(0..20).collect::<Vec<u8>>());
1121        let now = Duration::new(1_793_300_000, 7);
1122        let captured = stamped_frame(
1123            &mut buffer,
1124            20,
1125            ring::OUTGOING,
1126            Some(20),
1127            Some((ETHERTYPE_VLAN, 0x6002)),
1128            Some(Duration::new(265_258, 0)),
1129            now,
1130            64,
1131        );
1132        assert_eq!((captured.time, captured.clock), (now, Clock::System));
1133        assert_eq!(captured.direction, Direction::Outbound);
1134        assert_eq!((captured.length, captured.original), (24, 24));
1135        assert_eq!(&buffer[12..16], &[0x81, 0x00, 0x60, 0x02]);
1136    }
1137
1138    #[test]
1139    fn a_frame_without_a_stamp_keeps_the_system_time() {
1140        let mut buffer = [0u8; 64];
1141        let now = Duration::new(1_793_300_000, 9);
1142        let captured = stamped_frame(&mut buffer, 20, ring::HOST, None, None, None, now, 64);
1143        assert_eq!((captured.time, captured.clock), (now, Clock::System));
1144        assert_eq!(captured.original, 20);
1145    }
1146
1147    #[test]
1148    fn a_frame_is_cut_to_the_snap_length() {
1149        let data: Vec<u8> = (0..60).collect();
1150        let block = block(&[(ring::HOST, None, &data)]);
1151        let mut buffer = [0u8; 64];
1152        let (captured, _) = read_frame(&block, 48, &mut buffer, 16).unwrap();
1153        assert_eq!(captured.length, 16);
1154        assert_eq!(captured.original, 160);
1155        assert_eq!(captured.addressed, Some(Addressed::Unicast));
1156    }
1157
1158    #[test]
1159    fn a_frame_running_past_its_block_is_refused() {
1160        let data: Vec<u8> = (0..20).collect();
1161        let mut block = block(&[(ring::HOST, None, &data)]);
1162        block[48 + ring::SNAP..48 + ring::SNAP + 4].copy_from_slice(&5000u32.to_ne_bytes());
1163        let mut buffer = [0u8; 64];
1164        assert_eq!(read_frame(&block, 48, &mut buffer, 1500), None);
1165        assert_eq!(read_frame(&block, 4000, &mut buffer, 1500), None);
1166    }
1167}