Skip to main content

raw_ether/
socket.rs

1//! Raw Ethernet frames of one ethertype on one interface.
2
3use std::io;
4use std::time::Duration;
5
6use crate::MacAddress;
7
8/// A frame received on a [`Socket`].
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct Received {
11    pub source: MacAddress,
12    /// Octets of payload written to the buffer, after the Ethernet header.
13    pub length: usize,
14    /// Sent to a multicast or broadcast address rather than to us.
15    pub group: bool,
16}
17
18/// Sends and receives the payloads of Ethernet frames of one ethertype on
19/// one interface. The kernel adds and removes the Ethernet header.
20pub struct Socket {
21    inner: platform::Socket,
22    mac: MacAddress,
23}
24
25impl Socket {
26    /// Opens `interface` for frames of `ethertype`. On Linux this needs
27    /// `CAP_NET_RAW`.
28    pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
29        let mac = crate::interfaces::mac_of(interface).ok_or_else(|| {
30            io::Error::new(
31                io::ErrorKind::NotFound,
32                format!("no Ethernet interface named {interface}"),
33            )
34        })?;
35        Ok(Self {
36            inner: platform::Socket::open(interface, ethertype)?,
37            mac,
38        })
39    }
40
41    /// The interface's MAC address, the source of every frame sent.
42    pub fn mac(&self) -> MacAddress {
43        self.mac
44    }
45
46    /// Receives frames sent to `group` as well.
47    pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
48        self.inner.join_multicast(group)
49    }
50
51    /// Hears frames of every VLAN and address the interface receives,
52    /// `on`, or no longer. An interface that drops tagged frames of VLANs
53    /// not registered with it, as Intel's igb and igc do (see
54    /// [`crate::interfaces::filters_vlans`]), hears them only so, since
55    /// registering a VLAN takes an administrator. On macOS it stays so
56    /// until the socket closes; Windows' capture always does.
57    pub fn set_promiscuous(&self, on: bool) -> io::Result<()> {
58        self.inner.set_promiscuous(on)
59    }
60
61    pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
62        self.inner.send(destination, payload)
63    }
64
65    /// Leaves out every frame this computer sends, other programs' and
66    /// what a bridge forwards out of the interface too, which would
67    /// otherwise come as if received on it: as a bridge port's own
68    /// protocols want. Linux only; elsewhere an `Unsupported` error.
69    pub fn ignore_outgoing(&self) -> io::Result<()> {
70        self.inner.ignore_outgoing()
71    }
72
73    /// Keeps only frames whose payload starts with an octet in `first`,
74    /// such as the AVTP subtypes of ATDECC, dropped before they reach the
75    /// program.
76    pub fn keep_payloads_starting(&self, first: std::ops::RangeInclusive<u8>) -> io::Result<()> {
77        self.inner
78            .keep_payloads_starting(*first.start(), *first.end())
79    }
80
81    /// Waits up to `timeout` (forever when `None`) for a frame and writes
82    /// its payload to `buffer`, cut short if the buffer is. `None` when the
83    /// time ran out or a signal interrupted the wait. Frames this socket
84    /// sent are left out; those other programs on this computer send are
85    /// not, so entities and controllers on the same computer hear each
86    /// other.
87    pub fn receive(
88        &self,
89        buffer: &mut [u8],
90        timeout: Option<Duration>,
91    ) -> io::Result<Option<Received>> {
92        self.inner.receive(buffer, timeout)
93    }
94}
95
96/// Why raw Ethernet is out of this program's reach. [`Socket::open`] and
97/// [`check_access`] return it inside their error; [`Blocked::of`] finds it.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum Blocked {
101    /// Linux: the program lacks `CAP_NET_RAW`.
102    RawCapability,
103    /// macOS: the capture devices, `/dev/bpf*`, are not open to the user.
104    CaptureDevices,
105    /// Windows: Npcap is not installed.
106    Npcap,
107    /// Windows: Npcap lets only administrators capture.
108    NpcapAdministrators,
109}
110
111impl Blocked {
112    /// The reason inside `error`, when it is one.
113    pub fn of(error: &io::Error) -> Option<Self> {
114        error.get_ref()?.downcast_ref::<Self>().copied()
115    }
116
117    #[cfg_attr(
118        not(any(target_os = "linux", target_os = "macos", windows)),
119        allow(dead_code)
120    )]
121    fn error(self) -> io::Error {
122        let kind = match self {
123            Self::Npcap => io::ErrorKind::NotFound,
124            _ => io::ErrorKind::PermissionDenied,
125        };
126        io::Error::new(kind, self)
127    }
128}
129
130impl std::fmt::Display for Blocked {
131    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        match self {
133            Self::RawCapability => {
134                // The app's helper, where it has one, else the app.
135                #[cfg(target_os = "linux")]
136                let program = crate::broker::needs_capability();
137                #[cfg(not(target_os = "linux"))]
138                let program = std::env::current_exe().ok();
139                let program = program
140                    .map(|path| path.display().to_string())
141                    .unwrap_or_else(|| "the program".to_owned());
142                write!(
143                    formatter,
144                    "raw Ethernet needs CAP_NET_RAW; grant it with: sudo setcap cap_net_raw+ep \
145                     {program}"
146                )
147            }
148            Self::CaptureDevices => formatter.write_str(
149                "raw Ethernet needs access to /dev/bpf*: install a capture helper, such as \
150                 Wireshark's ChmodBPF, and log in again",
151            ),
152            Self::Npcap => formatter.write_str(
153                "raw Ethernet needs Npcap: install it from https://npcap.com, then start the program again",
154            ),
155            Self::NpcapAdministrators => formatter.write_str(
156                "Npcap lets only administrators capture: run the program as administrator, or \
157                 reinstall Npcap without \"Restrict Npcap driver's access to Administrators \
158                 only\"",
159            ),
160        }
161    }
162}
163
164impl std::error::Error for Blocked {}
165
166/// The error for a raw socket Linux will not open without `CAP_NET_RAW`.
167#[cfg(target_os = "linux")]
168pub(crate) fn raw_capability() -> io::Error {
169    Blocked::RawCapability.error()
170}
171
172/// Whether this program may send and receive raw Ethernet at all, before
173/// any interface is picked: an error carrying [`Blocked`] when it may not.
174pub fn check_access() -> io::Result<()> {
175    platform::check_access()
176}
177
178#[cfg(target_os = "linux")]
179#[allow(unsafe_code)]
180mod platform {
181    use std::io;
182    use std::mem::{size_of, zeroed};
183    use std::os::fd::{AsRawFd, OwnedFd};
184    use std::sync::atomic::{AtomicBool, Ordering};
185    use std::time::Duration;
186
187    use super::{Received, Sent};
188    use crate::MacAddress;
189
190    pub struct Socket {
191        fd: OwnedFd,
192        index: i32,
193        ethertype: u16,
194        sent: Sent,
195        /// Whether it holds the interface promiscuous.
196        promiscuous: AtomicBool,
197    }
198
199    /// Opens a packet socket that hears nothing, which takes the same
200    /// permission as one that does.
201    pub fn check_access() -> io::Result<()> {
202        crate::broker::open(crate::broker::Kind::Datagram).map(drop)
203    }
204
205    impl Socket {
206        pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
207            let index = crate::interfaces::index_of(interface).ok_or_else(|| {
208                io::Error::new(
209                    io::ErrorKind::NotFound,
210                    format!("no interface named {interface}"),
211                )
212            })?;
213            // Opened for no protocol, so nothing arrives before the filter
214            // is on: bound to one ethertype the socket would never hear what
215            // other programs here send, which Linux hands only to sockets
216            // bound to every protocol.
217            let fd = crate::broker::open(crate::broker::Kind::Datagram)?;
218            let socket = Self {
219                fd,
220                index,
221                ethertype,
222                sent: Sent::default(),
223                promiscuous: AtomicBool::new(false),
224            };
225            socket.attach(&socket.program(None))?;
226            let mut address = socket.address(None);
227            address.sll_protocol = (libc::ETH_P_ALL as u16).to_be();
228            // SAFETY: `address` is a valid sockaddr_ll that lives through the
229            // call, and the length passed is its size.
230            let bound = unsafe {
231                libc::bind(
232                    socket.fd.as_raw_fd(),
233                    (&raw const address).cast(),
234                    size_of::<libc::sockaddr_ll>() as libc::socklen_t,
235                )
236            };
237            if bound < 0 {
238                return Err(io::Error::last_os_error());
239            }
240            Ok(socket)
241        }
242
243        /// A link-layer address on this socket's interface and ethertype,
244        /// to `destination` if given.
245        fn address(&self, destination: Option<MacAddress>) -> libc::sockaddr_ll {
246            // SAFETY: sockaddr_ll is plain data, valid when zeroed.
247            let mut address: libc::sockaddr_ll = unsafe { zeroed() };
248            address.sll_family = libc::AF_PACKET as u16;
249            address.sll_protocol = self.ethertype.to_be();
250            address.sll_ifindex = self.index;
251            if let Some(destination) = destination {
252                address.sll_halen = 6;
253                address.sll_addr[..6].copy_from_slice(&destination.0);
254            }
255            address
256        }
257
258        pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
259            self.membership(
260                libc::PACKET_ADD_MEMBERSHIP,
261                libc::PACKET_MR_MULTICAST,
262                Some(group),
263            )
264        }
265
266        pub fn set_promiscuous(&self, on: bool) -> io::Result<()> {
267            if self.promiscuous.load(Ordering::Relaxed) == on {
268                return Ok(());
269            }
270            let change = if on {
271                libc::PACKET_ADD_MEMBERSHIP
272            } else {
273                libc::PACKET_DROP_MEMBERSHIP
274            };
275            self.membership(change, libc::PACKET_MR_PROMISC, None)?;
276            self.promiscuous.store(on, Ordering::Relaxed);
277            Ok(())
278        }
279
280        /// Adds or drops, by `change`, a membership of the interface of
281        /// `kind`: a multicast `group`, or its promiscuity. The kernel
282        /// drops this socket's memberships as it closes.
283        fn membership(
284            &self,
285            change: libc::c_int,
286            kind: libc::c_int,
287            group: Option<MacAddress>,
288        ) -> io::Result<()> {
289            // SAFETY: packet_mreq is plain data, valid when zeroed.
290            let mut request: libc::packet_mreq = unsafe { zeroed() };
291            request.mr_ifindex = self.index;
292            request.mr_type = kind as u16;
293            if let Some(group) = group {
294                request.mr_alen = 6;
295                request.mr_address[..6].copy_from_slice(&group.0);
296            }
297            // SAFETY: `request` is a valid packet_mreq that lives through
298            // the call, and the length passed is its size.
299            let changed = unsafe {
300                libc::setsockopt(
301                    self.fd.as_raw_fd(),
302                    libc::SOL_PACKET,
303                    change,
304                    (&raw const request).cast(),
305                    size_of::<libc::packet_mreq>() as libc::socklen_t,
306                )
307            };
308            if changed < 0 {
309                return Err(io::Error::last_os_error());
310            }
311            Ok(())
312        }
313
314        /// A classic BPF program keeping this socket's ethertype, and of it
315        /// only payloads whose first octet is in `first`, when given. A
316        /// packet socket's program sees the payload from its start, and the
317        /// ethertype as the kernel's protocol (`SKF_AD_PROTOCOL`).
318        fn program(&self, first: Option<(u8, u8)>) -> Vec<libc::sock_filter> {
319            let step = |code: u16, jt: u8, jf: u8, k: u32| libc::sock_filter { code, jt, jf, k };
320            let protocol = 0xffff_f000; // SKF_AD_OFF + SKF_AD_PROTOCOL
321            match first {
322                None => vec![
323                    step(0x20, 0, 0, protocol),                  // ld protocol
324                    step(0x15, 0, 1, u32::from(self.ethertype)), // jeq #ethertype
325                    step(0x06, 0, 0, u32::MAX),                  // ret #-1
326                    step(0x06, 0, 0, 0),                         // ret #0
327                ],
328                Some((first, last)) => vec![
329                    step(0x20, 0, 0, protocol),                  // ld protocol
330                    step(0x15, 0, 4, u32::from(self.ethertype)), // jeq #ethertype
331                    step(0x30, 0, 0, 0),                         // ldb [0]
332                    step(0x35, 0, 2, u32::from(first)),          // jge #first
333                    step(0x25, 1, 0, u32::from(last)),           // jgt #last
334                    step(0x06, 0, 0, u32::MAX),                  // ret #-1
335                    step(0x06, 0, 0, 0),                         // ret #0
336                ],
337            }
338        }
339
340        fn attach(&self, program: &[libc::sock_filter]) -> io::Result<()> {
341            let filter = libc::sock_fprog {
342                len: program.len() as u16,
343                filter: program.as_ptr().cast_mut(),
344            };
345            // SAFETY: `filter` points at `program`, which both live through
346            // the call; the kernel copies the program and does not write it.
347            let attached = unsafe {
348                libc::setsockopt(
349                    self.fd.as_raw_fd(),
350                    libc::SOL_SOCKET,
351                    libc::SO_ATTACH_FILTER,
352                    (&raw const filter).cast(),
353                    size_of::<libc::sock_fprog>() as libc::socklen_t,
354                )
355            };
356            if attached < 0 {
357                return Err(io::Error::last_os_error());
358            }
359            Ok(())
360        }
361
362        pub fn keep_payloads_starting(&self, first: u8, last: u8) -> io::Result<()> {
363            self.attach(&self.program(Some((first, last))))
364        }
365
366        pub fn ignore_outgoing(&self) -> io::Result<()> {
367            let on: libc::c_int = 1;
368            // SAFETY: `on` is a valid c_int that lives through the call,
369            // and the length passed is its size.
370            let set = unsafe {
371                libc::setsockopt(
372                    self.fd.as_raw_fd(),
373                    libc::SOL_PACKET,
374                    libc::PACKET_IGNORE_OUTGOING,
375                    (&raw const on).cast(),
376                    size_of::<libc::c_int>() as libc::socklen_t,
377                )
378            };
379            if set < 0 {
380                return Err(io::Error::last_os_error());
381            }
382            Ok(())
383        }
384
385        pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
386            self.sent.note(payload);
387            let address = self.address(Some(destination));
388            // SAFETY: `payload` and `address` are valid for the lengths
389            // passed and live through the call.
390            let sent = unsafe {
391                libc::sendto(
392                    self.fd.as_raw_fd(),
393                    payload.as_ptr().cast(),
394                    payload.len(),
395                    0,
396                    (&raw const address).cast(),
397                    size_of::<libc::sockaddr_ll>() as libc::socklen_t,
398                )
399            };
400            if sent < 0 {
401                return Err(io::Error::last_os_error());
402            }
403            Ok(())
404        }
405
406        pub fn receive(
407            &self,
408            buffer: &mut [u8],
409            timeout: Option<Duration>,
410        ) -> io::Result<Option<Received>> {
411            let milliseconds = match timeout {
412                // Round up, so a short wait does not become a busy loop.
413                Some(timeout) => {
414                    timeout.as_nanos().div_ceil(1_000_000).min(i32::MAX as u128) as i32
415                }
416                None => -1,
417            };
418            let mut poll = libc::pollfd {
419                fd: self.fd.as_raw_fd(),
420                events: libc::POLLIN,
421                revents: 0,
422            };
423            // SAFETY: one valid pollfd, which lives through the call.
424            let ready = unsafe { libc::poll(&raw mut poll, 1, milliseconds) };
425            if ready < 0 {
426                let error = io::Error::last_os_error();
427                return match error.kind() {
428                    io::ErrorKind::Interrupted => Ok(None),
429                    _ => Err(error),
430                };
431            }
432            if ready == 0 {
433                return Ok(None);
434            }
435            loop {
436                // SAFETY: sockaddr_ll is plain data, valid when zeroed.
437                let mut address: libc::sockaddr_ll = unsafe { zeroed() };
438                let mut length = size_of::<libc::sockaddr_ll>() as libc::socklen_t;
439                // SAFETY: `buffer` and `address` are valid for the lengths
440                // passed and live through the call.
441                let received = unsafe {
442                    libc::recvfrom(
443                        self.fd.as_raw_fd(),
444                        buffer.as_mut_ptr().cast(),
445                        buffer.len(),
446                        libc::MSG_DONTWAIT,
447                        (&raw mut address).cast(),
448                        &raw mut length,
449                    )
450                };
451                if received < 0 {
452                    let error = io::Error::last_os_error();
453                    return match error.kind() {
454                        io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => Ok(None),
455                        _ => Err(error),
456                    };
457                }
458                // What this computer sends comes back as outgoing: this
459                // socket's own frames are left out, other programs' kept.
460                let outgoing = address.sll_pkttype == libc::PACKET_OUTGOING;
461                if outgoing && self.sent.heard_back(&buffer[..received as usize]) {
462                    continue;
463                }
464                let mut source = [0; 6];
465                source.copy_from_slice(&address.sll_addr[..6]);
466                return Ok(Some(Received {
467                    source: MacAddress(source),
468                    length: received as usize,
469                    group: matches!(
470                        address.sll_pkttype,
471                        libc::PACKET_MULTICAST | libc::PACKET_BROADCAST
472                    ),
473                }));
474            }
475        }
476    }
477}
478
479/// The frames a socket sent lately, to tell them from the same frames
480/// heard back: every system hands a socket the frames the computer sends,
481/// the socket's own and those of other programs alike, and only the
482/// socket's own are left out. Linux hands back the payload, the others
483/// the whole frame.
484#[cfg(any(target_os = "linux", target_os = "macos", windows))]
485#[derive(Default)]
486struct Sent {
487    recent: std::sync::Mutex<std::collections::VecDeque<(u64, std::time::Instant)>>,
488}
489
490#[cfg(any(target_os = "linux", target_os = "macos", windows))]
491impl Sent {
492    /// How long a sent frame is looked for, and how many are kept.
493    const KEPT_FOR: Duration = Duration::from_secs(2);
494    const MOST: usize = 256;
495
496    fn key(frame: &[u8]) -> u64 {
497        use std::hash::{Hash, Hasher};
498        let mut hasher = std::collections::hash_map::DefaultHasher::new();
499        frame.hash(&mut hasher);
500        hasher.finish()
501    }
502
503    /// Notes a whole frame as sent.
504    fn note(&self, frame: &[u8]) {
505        let now = std::time::Instant::now();
506        let mut recent = self
507            .recent
508            .lock()
509            .unwrap_or_else(std::sync::PoisonError::into_inner);
510        while recent
511            .front()
512            .is_some_and(|&(_, at)| now.duration_since(at) > Self::KEPT_FOR)
513            || recent.len() >= Self::MOST
514        {
515            recent.pop_front();
516        }
517        recent.push_back((Self::key(frame), now));
518    }
519
520    /// Whether a whole frame heard is one this socket sent, which is then
521    /// forgotten.
522    fn heard_back(&self, frame: &[u8]) -> bool {
523        let key = Self::key(frame);
524        let mut recent = self
525            .recent
526            .lock()
527            .unwrap_or_else(std::sync::PoisonError::into_inner);
528        match recent.iter().position(|&(sent, _)| sent == key) {
529            Some(place) => {
530                recent.remove(place);
531                true
532            }
533            None => false,
534        }
535    }
536}
537
538/// A whole Ethernet frame from `source` to `destination` of `ethertype`
539/// carrying `payload`, padded to Ethernet's least length.
540#[cfg(any(target_os = "macos", windows))]
541fn frame(source: MacAddress, destination: MacAddress, ethertype: u16, payload: &[u8]) -> Vec<u8> {
542    const LEAST: usize = 60;
543    let mut frame = Vec::with_capacity((14 + payload.len()).max(LEAST));
544    frame.extend_from_slice(&destination.0);
545    frame.extend_from_slice(&source.0);
546    frame.extend_from_slice(&ethertype.to_be_bytes());
547    frame.extend_from_slice(payload);
548    frame.resize(frame.len().max(LEAST), 0);
549    frame
550}
551
552/// What a captured frame says, when it is one of `ethertype` this socket
553/// did not send: its source and payload, written to `buffer`.
554#[cfg(any(target_os = "macos", windows))]
555fn take(frame: &[u8], ethertype: u16, sent: &Sent, buffer: &mut [u8]) -> Option<Received> {
556    if frame.len() < 14 || frame[12..14] != ethertype.to_be_bytes() || sent.heard_back(frame) {
557        return None;
558    }
559    let payload = &frame[14..];
560    let length = payload.len().min(buffer.len());
561    buffer[..length].copy_from_slice(&payload[..length]);
562    let mut source = [0; 6];
563    source.copy_from_slice(&frame[6..12]);
564    Some(Received {
565        source: MacAddress(source),
566        length,
567        group: frame[0] & 1 == 1,
568    })
569}
570
571/// A classic BPF instruction (`struct bpf_insn`).
572#[cfg(any(target_os = "macos", windows))]
573#[repr(C)]
574struct Instruction {
575    code: u16,
576    jump_true: u8,
577    jump_false: u8,
578    value: u32,
579}
580
581/// A filter program (`struct bpf_program`).
582#[cfg(any(target_os = "macos", windows))]
583#[repr(C)]
584struct Program {
585    length: u32,
586    instructions: *mut Instruction,
587}
588
589/// A filter that passes whole frames of `ethertype`, or none at all.
590#[cfg(any(target_os = "macos", windows))]
591fn filter(ethertype: Option<u16>) -> Vec<Instruction> {
592    let reject = Instruction {
593        code: 0x06, // ret #0
594        jump_true: 0,
595        jump_false: 0,
596        value: 0,
597    };
598    let Some(ethertype) = ethertype else {
599        return vec![reject];
600    };
601    // Load the ethertype, and keep the whole frame when it matches.
602    vec![
603        Instruction {
604            code: 0x28, // ldh [12]
605            jump_true: 0,
606            jump_false: 0,
607            value: 12,
608        },
609        Instruction {
610            code: 0x15, // jeq #ethertype
611            jump_true: 0,
612            jump_false: 1,
613            value: u32::from(ethertype),
614        },
615        Instruction {
616            code: 0x06, // ret #-1
617            jump_true: 0,
618            jump_false: 0,
619            value: u32::MAX,
620        },
621        reject,
622    ]
623}
624
625/// A filter that passes whole frames of `ethertype` whose payload starts
626/// with an octet from `first` to `last`.
627#[cfg(any(target_os = "macos", windows))]
628fn payload_filter(ethertype: u16, first: u8, last: u8) -> Vec<Instruction> {
629    let step = |code: u16, jump_true: u8, jump_false: u8, value: u32| Instruction {
630        code,
631        jump_true,
632        jump_false,
633        value,
634    };
635    vec![
636        step(0x28, 0, 0, 12),                   // ldh [12]
637        step(0x15, 0, 4, u32::from(ethertype)), // jeq #ethertype
638        step(0x30, 0, 0, 14),                   // ldb [14]
639        step(0x35, 0, 2, u32::from(first)),     // jge #first
640        step(0x25, 1, 0, u32::from(last)),      // jgt #last
641        step(0x06, 0, 0, u32::MAX),             // ret #-1
642        step(0x06, 0, 0, 0),                    // ret #0
643    ]
644}
645
646#[cfg(target_os = "macos")]
647#[allow(unsafe_code)]
648mod platform {
649    use std::io;
650    use std::mem::{size_of, zeroed};
651    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
652    use std::sync::Mutex;
653    use std::time::{Duration, Instant};
654
655    use super::{Program, Received, Sent};
656    use crate::MacAddress;
657
658    /// `BIOCSSEESENT`: whether the device also sees frames this computer
659    /// sends, which it must for the system's own AVB entity.
660    const SEE_SENT: libc::c_ulong = 0x8004_4277;
661    /// `SIOCADDMULTI` and `SIOCDELMULTI`.
662    const ADD_MULTICAST: libc::c_ulong = 0x8020_6931;
663    const DELETE_MULTICAST: libc::c_ulong = 0x8020_6932;
664    /// The capture buffer asked for.
665    const BUFFER: u32 = 1 << 16;
666
667    /// Frames read from the device and not yet handed out.
668    struct Pending {
669        data: Vec<u8>,
670        start: usize,
671        end: usize,
672    }
673
674    pub struct Socket {
675        fd: OwnedFd,
676        interface: String,
677        ethertype: u16,
678        mac: MacAddress,
679        pending: Mutex<Pending>,
680        sent: Sent,
681        /// Multicast groups added to the interface, to take off again.
682        joined: Mutex<Vec<MacAddress>>,
683    }
684
685    /// An interface request naming `interface`.
686    fn request(interface: &str) -> io::Result<libc::ifreq> {
687        // SAFETY: ifreq is plain data, valid when zeroed.
688        let mut request: libc::ifreq = unsafe { zeroed() };
689        let bytes = interface.as_bytes();
690        if bytes.len() >= request.ifr_name.len() {
691            return Err(io::Error::new(
692                io::ErrorKind::InvalidInput,
693                format!("no interface named {interface}"),
694            ));
695        }
696        for (place, &byte) in request.ifr_name.iter_mut().zip(bytes) {
697            *place = byte as libc::c_char;
698        }
699        Ok(request)
700    }
701
702    fn control(fd: &OwnedFd, code: libc::c_ulong, value: &mut u32) -> io::Result<()> {
703        // SAFETY: each request used here takes a pointer to a u_int, which
704        // lives through the call.
705        if unsafe { libc::ioctl(fd.as_raw_fd(), code, std::ptr::from_mut(value)) } < 0 {
706            return Err(io::Error::last_os_error());
707        }
708        Ok(())
709    }
710
711    /// A capture device opens.
712    pub fn check_access() -> io::Result<()> {
713        open_device().map(drop)
714    }
715
716    /// The first capture device free.
717    fn open_device() -> io::Result<OwnedFd> {
718        let mut denied = false;
719        for index in 0..256 {
720            let path = format!("/dev/bpf{index}\0");
721            // SAFETY: `path` is NUL-terminated and lives through the call.
722            let raw = unsafe { libc::open(path.as_ptr().cast(), libc::O_RDWR | libc::O_CLOEXEC) };
723            if raw >= 0 {
724                // SAFETY: `raw` is a descriptor this function just opened.
725                return Ok(unsafe { OwnedFd::from_raw_fd(raw) });
726            }
727            match io::Error::last_os_error().raw_os_error() {
728                Some(libc::EBUSY) => {}
729                Some(libc::EACCES | libc::EPERM) => denied = true,
730                Some(libc::ENOENT) => break,
731                _ => {}
732            }
733        }
734        Err(if denied {
735            super::Blocked::CaptureDevices.error()
736        } else {
737            io::Error::other("no free /dev/bpf device")
738        })
739    }
740
741    impl Socket {
742        pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
743            let mac = crate::interfaces::mac_of(interface).ok_or_else(|| {
744                io::Error::new(
745                    io::ErrorKind::NotFound,
746                    format!("no interface named {interface}"),
747                )
748            })?;
749            let fd = open_device()?;
750            // The buffer is sized before the device is bound.
751            let mut size = BUFFER;
752            control(&fd, libc::BIOCSBLEN, &mut size)?;
753            let mut bound = request(interface)?;
754            // SAFETY: `bound` is a valid ifreq that lives through the call.
755            if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCSETIF, &raw mut bound) } < 0 {
756                return Err(io::Error::last_os_error());
757            }
758            control(&fd, libc::BIOCIMMEDIATE, &mut 1)?;
759            // The frames written carry their own source address.
760            control(&fd, libc::BIOCSHDRCMPLT, &mut 1)?;
761            control(&fd, SEE_SENT, &mut 1)?;
762            let mut instructions = super::filter(Some(ethertype));
763            let mut program = Program {
764                length: instructions.len() as u32,
765                instructions: instructions.as_mut_ptr(),
766            };
767            // SAFETY: `program` points at `instructions`, which both live
768            // through the call.
769            if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCSETF, &raw mut program) } < 0 {
770                return Err(io::Error::last_os_error());
771            }
772            let mut length = 0;
773            control(&fd, libc::BIOCGBLEN, &mut length)?;
774            Ok(Self {
775                fd,
776                interface: interface.to_owned(),
777                ethertype,
778                mac,
779                pending: Mutex::new(Pending {
780                    data: vec![0; length.max(BUFFER) as usize],
781                    start: 0,
782                    end: 0,
783                }),
784                sent: Sent::default(),
785                joined: Mutex::new(Vec::new()),
786            })
787        }
788
789        /// Adds or takes off a multicast group on the interface.
790        fn membership(&self, group: MacAddress, code: libc::c_ulong) -> io::Result<()> {
791            let mut changed = request(&self.interface)?;
792            // SAFETY: the union's address member is plain data; writing it
793            // whole leaves the request valid.
794            unsafe {
795                let mut address: libc::sockaddr = zeroed();
796                address.sa_len = size_of::<libc::sockaddr>() as u8;
797                address.sa_family = libc::AF_UNSPEC as u8;
798                for (place, &octet) in address.sa_data.iter_mut().zip(&group.0) {
799                    *place = octet as libc::c_char;
800                }
801                changed.ifr_ifru.ifru_addr = address;
802            }
803            // SAFETY: plain system call with integer arguments.
804            let raw = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) };
805            if raw < 0 {
806                return Err(io::Error::last_os_error());
807            }
808            // SAFETY: `raw` is a socket this function just opened.
809            let query = unsafe { OwnedFd::from_raw_fd(raw) };
810            // SAFETY: `changed` is a valid ifreq that lives through the call.
811            if unsafe { libc::ioctl(query.as_raw_fd(), code, &raw mut changed) } < 0 {
812                return Err(io::Error::last_os_error());
813            }
814            Ok(())
815        }
816
817        pub fn ignore_outgoing(&self) -> io::Result<()> {
818            Err(io::Error::new(
819                io::ErrorKind::Unsupported,
820                "leaving out outgoing frames is for Linux",
821            ))
822        }
823
824        pub fn keep_payloads_starting(&self, first: u8, last: u8) -> io::Result<()> {
825            let mut instructions = super::payload_filter(self.ethertype, first, last);
826            let mut program = Program {
827                length: instructions.len() as u32,
828                instructions: instructions.as_mut_ptr(),
829            };
830            // SAFETY: `program` points at `instructions`, which both live
831            // through the call.
832            if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::BIOCSETF, &raw mut program) } < 0 {
833                return Err(io::Error::last_os_error());
834            }
835            Ok(())
836        }
837
838        pub fn join_multicast(&self, group: MacAddress) -> io::Result<()> {
839            // Adding a group to the interface takes root; without it the
840            // device listens to everything, which its filter still sorts.
841            match self.membership(group, ADD_MULTICAST) {
842                Ok(()) => {
843                    self.joined
844                        .lock()
845                        .unwrap_or_else(std::sync::PoisonError::into_inner)
846                        .push(group);
847                    Ok(())
848                }
849                Err(_) => self.set_promiscuous(true),
850            }
851        }
852
853        pub fn set_promiscuous(&self, on: bool) -> io::Result<()> {
854            // A BPF device stays promiscuous until it closes.
855            if !on {
856                return Ok(());
857            }
858            // SAFETY: BIOCPROMISC takes no argument.
859            if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::BIOCPROMISC as _) } < 0 {
860                return Err(io::Error::last_os_error());
861            }
862            Ok(())
863        }
864
865        pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
866            let frame = super::frame(self.mac, destination, self.ethertype, payload);
867            self.sent.note(&frame);
868            // SAFETY: `frame` is valid for its length through the call.
869            let written =
870                unsafe { libc::write(self.fd.as_raw_fd(), frame.as_ptr().cast(), frame.len()) };
871            if written < 0 {
872                return Err(io::Error::last_os_error());
873            }
874            Ok(())
875        }
876
877        pub fn receive(
878            &self,
879            buffer: &mut [u8],
880            timeout: Option<Duration>,
881        ) -> io::Result<Option<Received>> {
882            let deadline = timeout.map(|timeout| Instant::now() + timeout);
883            let mut pending = self
884                .pending
885                .lock()
886                .unwrap_or_else(std::sync::PoisonError::into_inner);
887            loop {
888                // The frames already read, each after a header and aligned
889                // to four octets.
890                while pending.start + size_of::<libc::bpf_hdr>() <= pending.end {
891                    let at = pending.start;
892                    // SAFETY: a whole header lies within the data read, and
893                    // is read unaligned.
894                    let header: libc::bpf_hdr =
895                        unsafe { std::ptr::read_unaligned(pending.data.as_ptr().add(at).cast()) };
896                    let start = at + usize::from(header.bh_hdrlen);
897                    let end = start + header.bh_caplen as usize;
898                    pending.start = (end + 3) & !3;
899                    if end > pending.end {
900                        pending.start = pending.end;
901                        break;
902                    }
903                    if let Some(received) = super::take(
904                        &pending.data[start..end],
905                        self.ethertype,
906                        &self.sent,
907                        buffer,
908                    ) {
909                        return Ok(Some(received));
910                    }
911                }
912                // Out of time, the device is still looked at once without
913                // waiting.
914                let wait =
915                    deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
916                if !self.readable(wait)? {
917                    return Ok(None);
918                }
919                let capacity = pending.data.len();
920                // SAFETY: the buffer is valid for its whole length through
921                // the call.
922                let read = unsafe {
923                    libc::read(
924                        self.fd.as_raw_fd(),
925                        pending.data.as_mut_ptr().cast(),
926                        capacity,
927                    )
928                };
929                if read < 0 {
930                    let error = io::Error::last_os_error();
931                    return match error.kind() {
932                        io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => Ok(None),
933                        _ => Err(error),
934                    };
935                }
936                pending.start = 0;
937                pending.end = read as usize;
938            }
939        }
940
941        /// Waits up to `wait` (forever when `None`) for frames to read.
942        fn readable(&self, wait: Option<Duration>) -> io::Result<bool> {
943            let fd = self.fd.as_raw_fd();
944            // SAFETY: fd_set is plain data, valid when zeroed, and the
945            // descriptor is below FD_SETSIZE for a process this small.
946            let mut set: libc::fd_set = unsafe { zeroed() };
947            unsafe { libc::FD_SET(fd, &raw mut set) };
948            let mut time = wait.map(|wait| libc::timeval {
949                tv_sec: wait.as_secs() as libc::time_t,
950                tv_usec: wait.subsec_micros() as libc::suseconds_t,
951            });
952            let timeout = time
953                .as_mut()
954                .map_or(std::ptr::null_mut(), std::ptr::from_mut);
955            // SAFETY: `set` and `timeout` are valid through the call.
956            let ready = unsafe {
957                libc::select(
958                    fd + 1,
959                    &raw mut set,
960                    std::ptr::null_mut(),
961                    std::ptr::null_mut(),
962                    timeout,
963                )
964            };
965            if ready < 0 {
966                let error = io::Error::last_os_error();
967                return match error.kind() {
968                    io::ErrorKind::Interrupted => Ok(false),
969                    _ => Err(error),
970                };
971            }
972            Ok(ready > 0)
973        }
974    }
975
976    impl Drop for Socket {
977        fn drop(&mut self) {
978            let joined = std::mem::take(
979                &mut *self
980                    .joined
981                    .lock()
982                    .unwrap_or_else(std::sync::PoisonError::into_inner),
983            );
984            for group in joined {
985                let _ = self.membership(group, DELETE_MULTICAST);
986            }
987        }
988    }
989}
990
991#[cfg(windows)]
992#[allow(unsafe_code)]
993mod platform {
994    use std::ffi::{CStr, CString, c_char, c_int, c_void};
995    use std::io;
996    use std::sync::{Mutex, OnceLock, PoisonError};
997    use std::time::{Duration, Instant};
998
999    use windows_sys::Win32::Foundation::{HANDLE, WAIT_FAILED};
1000    use windows_sys::Win32::System::LibraryLoader::{
1001        GetProcAddress, LOAD_WITH_ALTERED_SEARCH_PATH, LoadLibraryExW,
1002    };
1003    use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW;
1004    use windows_sys::Win32::System::Threading::{INFINITE, WaitForSingleObject};
1005
1006    use super::{Program, Received, Sent};
1007    use crate::MacAddress;
1008
1009    /// Room libpcap writes an error message to (`PCAP_ERRBUF_SIZE`).
1010    const ERROR_ROOM: usize = 256;
1011    /// The longest frame kept, and the driver buffer asked for.
1012    const SNAPSHOT: c_int = 65_535;
1013    const BUFFER: c_int = 1 << 20;
1014    /// What `pcap_activate` returns when the process may not capture
1015    /// (`PCAP_ERROR_PERM_DENIED`) or the device is gone
1016    /// (`PCAP_ERROR_NO_SUCH_DEVICE`).
1017    const PERMISSION_DENIED: c_int = -8;
1018    const NO_SUCH_DEVICE: c_int = -5;
1019
1020    /// A `pcap_t`.
1021    type Capture = *mut c_void;
1022
1023    /// `struct pcap_pkthdr`, whose `timeval` holds two 32-bit longs on
1024    /// Windows.
1025    #[repr(C)]
1026    struct PacketHeader {
1027        seconds: i32,
1028        microseconds: i32,
1029        captured: u32,
1030        length: u32,
1031    }
1032
1033    /// The parts of Npcap's wpcap.dll used here.
1034    struct Npcap {
1035        create: unsafe extern "C" fn(*const c_char, *mut c_char) -> Capture,
1036        set_snaplen: unsafe extern "C" fn(Capture, c_int) -> c_int,
1037        set_promisc: unsafe extern "C" fn(Capture, c_int) -> c_int,
1038        set_immediate_mode: unsafe extern "C" fn(Capture, c_int) -> c_int,
1039        set_buffer_size: unsafe extern "C" fn(Capture, c_int) -> c_int,
1040        activate: unsafe extern "C" fn(Capture) -> c_int,
1041        setfilter: unsafe extern "C" fn(Capture, *mut Program) -> c_int,
1042        setnonblock: unsafe extern "C" fn(Capture, c_int, *mut c_char) -> c_int,
1043        getevent: unsafe extern "C" fn(Capture) -> HANDLE,
1044        next_ex: unsafe extern "C" fn(Capture, *mut *mut PacketHeader, *mut *const u8) -> c_int,
1045        sendpacket: unsafe extern "C" fn(Capture, *const u8, c_int) -> c_int,
1046        geterr: unsafe extern "C" fn(Capture) -> *const c_char,
1047        close: unsafe extern "C" fn(Capture),
1048    }
1049
1050    /// Npcap, loaded the first time it is needed.
1051    fn npcap() -> io::Result<&'static Npcap> {
1052        static LOADED: OnceLock<Option<Npcap>> = OnceLock::new();
1053        LOADED
1054            .get_or_init(load)
1055            .as_ref()
1056            .ok_or_else(|| super::Blocked::Npcap.error())
1057    }
1058
1059    /// Npcap is installed and loads.
1060    pub fn check_access() -> io::Result<()> {
1061        npcap().map(|_| ())
1062    }
1063
1064    // Each field's type gives its function's signature.
1065    #[allow(clippy::missing_transmute_annotations)]
1066    fn load() -> Option<Npcap> {
1067        // Npcap keeps its libraries in System32\Npcap, which programs
1068        // search only when it was installed in WinPcap's compatible mode.
1069        let mut system = [0u16; 260];
1070        // SAFETY: the buffer and its length are passed together.
1071        let length =
1072            unsafe { GetSystemDirectoryW(system.as_mut_ptr(), system.len() as u32) } as usize;
1073        if length == 0 || length >= system.len() {
1074            return None;
1075        }
1076        let mut path = system[..length].to_vec();
1077        path.extend("\\Npcap\\wpcap.dll".encode_utf16());
1078        path.push(0);
1079        // SAFETY: `path` is a NUL-terminated wide string; the altered
1080        // search path finds Packet.dll beside wpcap.dll.
1081        let library = unsafe {
1082            LoadLibraryExW(
1083                path.as_ptr(),
1084                std::ptr::null_mut(),
1085                LOAD_WITH_ALTERED_SEARCH_PATH,
1086            )
1087        };
1088        if library.is_null() {
1089            return None;
1090        }
1091        // Each function by name, as the type of the field it fills; the
1092        // library is never unloaded.
1093        macro_rules! function {
1094            ($name:literal) => {{
1095                // SAFETY: the name is NUL-terminated.
1096                let address = unsafe { GetProcAddress(library, concat!($name, "\0").as_ptr()) }?;
1097                // SAFETY: libpcap declares the function with this
1098                // signature.
1099                unsafe { std::mem::transmute(address) }
1100            }};
1101        }
1102        Some(Npcap {
1103            create: function!("pcap_create"),
1104            set_snaplen: function!("pcap_set_snaplen"),
1105            set_promisc: function!("pcap_set_promisc"),
1106            set_immediate_mode: function!("pcap_set_immediate_mode"),
1107            set_buffer_size: function!("pcap_set_buffer_size"),
1108            activate: function!("pcap_activate"),
1109            setfilter: function!("pcap_setfilter"),
1110            setnonblock: function!("pcap_setnonblock"),
1111            getevent: function!("pcap_getevent"),
1112            next_ex: function!("pcap_next_ex"),
1113            sendpacket: function!("pcap_sendpacket"),
1114            geterr: function!("pcap_geterr"),
1115            close: function!("pcap_close"),
1116        })
1117    }
1118
1119    /// An open capture, closed when dropped.
1120    struct Handle(Capture);
1121
1122    // SAFETY: a pcap_t may move between threads; each is used by one
1123    // thread at a time, under its lock.
1124    unsafe impl Send for Handle {}
1125
1126    impl Drop for Handle {
1127        fn drop(&mut self) {
1128            if let Ok(npcap) = npcap() {
1129                // SAFETY: the capture is open and closed once.
1130                unsafe { (npcap.close)(self.0) };
1131            }
1132        }
1133    }
1134
1135    /// The message libpcap wrote to `error`.
1136    fn message(error: &[c_char]) -> String {
1137        // SAFETY: libpcap writes a NUL-terminated message within the room.
1138        unsafe { CStr::from_ptr(error.as_ptr()) }
1139            .to_string_lossy()
1140            .into_owned()
1141    }
1142
1143    /// The last error on a capture.
1144    fn last_error(npcap: &Npcap, handle: &Handle) -> io::Error {
1145        // SAFETY: the capture is open, and its message lives until its
1146        // next call.
1147        let text = unsafe { CStr::from_ptr((npcap.geterr)(handle.0)) }
1148            .to_string_lossy()
1149            .into_owned();
1150        io::Error::other(text)
1151    }
1152
1153    /// An activated capture on `device` that keeps frames of `ethertype`,
1154    /// or none when `None`, without waiting when there are none.
1155    fn capture(
1156        npcap: &Npcap,
1157        device: &CStr,
1158        interface: &str,
1159        promiscuous: bool,
1160        ethertype: Option<u16>,
1161    ) -> io::Result<Handle> {
1162        let mut error = [0 as c_char; ERROR_ROOM];
1163        // SAFETY: `device` is NUL-terminated and `error` has the room
1164        // libpcap needs.
1165        let opened = unsafe { (npcap.create)(device.as_ptr(), error.as_mut_ptr()) };
1166        if opened.is_null() {
1167            return Err(io::Error::other(message(&error)));
1168        }
1169        let handle = Handle(opened);
1170        // SAFETY: settings on a capture not yet active.
1171        let activated = unsafe {
1172            (npcap.set_snaplen)(opened, SNAPSHOT);
1173            (npcap.set_promisc)(opened, c_int::from(promiscuous));
1174            (npcap.set_immediate_mode)(opened, 1);
1175            (npcap.set_buffer_size)(opened, BUFFER);
1176            (npcap.activate)(opened)
1177        };
1178        match activated {
1179            PERMISSION_DENIED => return Err(super::Blocked::NpcapAdministrators.error()),
1180            NO_SUCH_DEVICE => {
1181                return Err(io::Error::new(
1182                    io::ErrorKind::NotFound,
1183                    format!("Npcap does not capture on {interface}"),
1184                ));
1185            }
1186            failed if failed < 0 => return Err(last_error(npcap, &handle)),
1187            _ => {}
1188        }
1189        let mut instructions = super::filter(ethertype);
1190        let mut program = Program {
1191            length: instructions.len() as u32,
1192            instructions: instructions.as_mut_ptr(),
1193        };
1194        // SAFETY: `program` points at `instructions`, which both live
1195        // through the call; libpcap copies the program.
1196        if unsafe { (npcap.setfilter)(opened, &raw mut program) } != 0 {
1197            return Err(last_error(npcap, &handle));
1198        }
1199        // SAFETY: `error` has the room libpcap needs.
1200        if unsafe { (npcap.setnonblock)(opened, 1, error.as_mut_ptr()) } != 0 {
1201            return Err(io::Error::other(message(&error)));
1202        }
1203        Ok(handle)
1204    }
1205
1206    pub struct Socket {
1207        /// Frames are read on one capture and sent on another, so a send
1208        /// need not wait for a read.
1209        receiver: Mutex<Handle>,
1210        sender: Mutex<Handle>,
1211        /// The event the receiving capture signals when frames wait, as an
1212        /// address so the socket can be shared between threads.
1213        event: usize,
1214        ethertype: u16,
1215        mac: MacAddress,
1216        sent: Sent,
1217    }
1218
1219    impl Socket {
1220        pub fn open(interface: &str, ethertype: u16) -> io::Result<Self> {
1221            let npcap = npcap()?;
1222            let not_found = || {
1223                io::Error::new(
1224                    io::ErrorKind::NotFound,
1225                    format!("no interface named {interface}"),
1226                )
1227            };
1228            let mac = crate::interfaces::mac_of(interface).ok_or_else(not_found)?;
1229            let device = crate::interfaces::device_of(interface)
1230                .and_then(|device| CString::new(device).ok())
1231                .ok_or_else(not_found)?;
1232            // Promiscuous, so the group addresses AVB uses reach the
1233            // capture; adapters that cannot be are opened as they are.
1234            let receiver = match capture(npcap, &device, interface, true, Some(ethertype)) {
1235                Ok(receiver) => receiver,
1236                Err(error)
1237                    if matches!(
1238                        error.kind(),
1239                        io::ErrorKind::PermissionDenied | io::ErrorKind::NotFound
1240                    ) =>
1241                {
1242                    return Err(error);
1243                }
1244                Err(_) => capture(npcap, &device, interface, false, Some(ethertype))?,
1245            };
1246            let sender = capture(npcap, &device, interface, false, None)?;
1247            // SAFETY: the capture is open; the event belongs to it.
1248            let event = unsafe { (npcap.getevent)(receiver.0) };
1249            if event.is_null() {
1250                return Err(last_error(npcap, &receiver));
1251            }
1252            Ok(Self {
1253                receiver: Mutex::new(receiver),
1254                sender: Mutex::new(sender),
1255                event: event as usize,
1256                ethertype,
1257                mac,
1258                sent: Sent::default(),
1259            })
1260        }
1261
1262        pub fn join_multicast(&self, _group: MacAddress) -> io::Result<()> {
1263            // The receiving capture is promiscuous, or, on an adapter that
1264            // cannot be, hears what the adapter does.
1265            Ok(())
1266        }
1267
1268        pub fn set_promiscuous(&self, _on: bool) -> io::Result<()> {
1269            Ok(())
1270        }
1271
1272        pub fn ignore_outgoing(&self) -> io::Result<()> {
1273            Err(io::Error::new(
1274                io::ErrorKind::Unsupported,
1275                "leaving out outgoing frames is for Linux",
1276            ))
1277        }
1278
1279        pub fn keep_payloads_starting(&self, first: u8, last: u8) -> io::Result<()> {
1280            let npcap = npcap()?;
1281            let receiver = self.receiver.lock().unwrap_or_else(PoisonError::into_inner);
1282            let mut instructions = super::payload_filter(self.ethertype, first, last);
1283            let mut program = Program {
1284                length: instructions.len() as u32,
1285                instructions: instructions.as_mut_ptr(),
1286            };
1287            // SAFETY: `program` points at `instructions`, which both live
1288            // through the call; libpcap copies the program.
1289            if unsafe { (npcap.setfilter)(receiver.0, &raw mut program) } != 0 {
1290                return Err(last_error(npcap, &receiver));
1291            }
1292            Ok(())
1293        }
1294
1295        pub fn send(&self, destination: MacAddress, payload: &[u8]) -> io::Result<()> {
1296            let npcap = npcap()?;
1297            let frame = super::frame(self.mac, destination, self.ethertype, payload);
1298            self.sent.note(&frame);
1299            let sender = self.sender.lock().unwrap_or_else(PoisonError::into_inner);
1300            // SAFETY: `frame` is valid for its length through the call.
1301            if unsafe { (npcap.sendpacket)(sender.0, frame.as_ptr(), frame.len() as c_int) } != 0 {
1302                return Err(last_error(npcap, &sender));
1303            }
1304            Ok(())
1305        }
1306
1307        pub fn receive(
1308            &self,
1309            buffer: &mut [u8],
1310            timeout: Option<Duration>,
1311        ) -> io::Result<Option<Received>> {
1312            let npcap = npcap()?;
1313            let deadline = timeout.map(|timeout| Instant::now() + timeout);
1314            let receiver = self.receiver.lock().unwrap_or_else(PoisonError::into_inner);
1315            loop {
1316                // Every frame waiting, until one is for this socket.
1317                loop {
1318                    let mut header: *mut PacketHeader = std::ptr::null_mut();
1319                    let mut data: *const u8 = std::ptr::null();
1320                    // SAFETY: the capture is open, and libpcap fills in the
1321                    // two pointers.
1322                    let read =
1323                        unsafe { (npcap.next_ex)(receiver.0, &raw mut header, &raw mut data) };
1324                    match read {
1325                        1 => {
1326                            // SAFETY: the header and the octets it counts
1327                            // stay valid until the next read.
1328                            let frame = unsafe {
1329                                std::slice::from_raw_parts(data, (*header).captured as usize)
1330                            };
1331                            if let Some(received) =
1332                                super::take(frame, self.ethertype, &self.sent, buffer)
1333                            {
1334                                return Ok(Some(received));
1335                            }
1336                        }
1337                        0 => break,
1338                        _ => return Err(last_error(npcap, &receiver)),
1339                    }
1340                }
1341                let milliseconds = match deadline {
1342                    Some(deadline) => {
1343                        let left = deadline.saturating_duration_since(Instant::now());
1344                        if left.is_zero() {
1345                            return Ok(None);
1346                        }
1347                        // Round up, so a short wait does not become a busy
1348                        // loop.
1349                        left.as_nanos()
1350                            .div_ceil(1_000_000)
1351                            .min(u128::from(INFINITE - 1)) as u32
1352                    }
1353                    None => INFINITE,
1354                };
1355                // Ready or out of time, the frames are looked at again and
1356                // the deadline decides.
1357                // SAFETY: the event belongs to the capture, which is open
1358                // through the wait.
1359                if unsafe { WaitForSingleObject(self.event as HANDLE, milliseconds) } == WAIT_FAILED
1360                {
1361                    return Err(io::Error::last_os_error());
1362                }
1363            }
1364        }
1365    }
1366}
1367
1368#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
1369mod platform {
1370    use std::io;
1371    use std::time::Duration;
1372
1373    use super::Received;
1374    use crate::MacAddress;
1375
1376    /// Not available on this system yet.
1377    pub struct Socket;
1378
1379    fn unsupported() -> io::Error {
1380        io::Error::new(
1381            io::ErrorKind::Unsupported,
1382            "raw Ethernet is not supported on this system yet",
1383        )
1384    }
1385
1386    pub fn check_access() -> io::Result<()> {
1387        Err(unsupported())
1388    }
1389
1390    impl Socket {
1391        pub fn open(_interface: &str, _ethertype: u16) -> io::Result<Self> {
1392            Err(unsupported())
1393        }
1394
1395        pub fn join_multicast(&self, _group: MacAddress) -> io::Result<()> {
1396            Err(unsupported())
1397        }
1398
1399        pub fn set_promiscuous(&self, _on: bool) -> io::Result<()> {
1400            Err(unsupported())
1401        }
1402
1403        pub fn send(&self, _destination: MacAddress, _payload: &[u8]) -> io::Result<()> {
1404            Err(unsupported())
1405        }
1406
1407        pub fn keep_payloads_starting(&self, _first: u8, _last: u8) -> io::Result<()> {
1408            Err(unsupported())
1409        }
1410
1411        pub fn ignore_outgoing(&self) -> io::Result<()> {
1412            Err(unsupported())
1413        }
1414
1415        pub fn receive(
1416            &self,
1417            _buffer: &mut [u8],
1418            _timeout: Option<Duration>,
1419        ) -> io::Result<Option<Received>> {
1420            Err(unsupported())
1421        }
1422    }
1423}