Skip to main content

zond_engine/transport/
capture.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # Packet Capture (Receive Path)
10//!
11//! The single ingest path for raw scan replies, shared by every send backend.
12//!
13//! BSD-derived kernels, macOS included, do not deliver TCP or UDP segments to raw IP
14//! sockets, so the Layer-4 raw socket that works on Linux receives nothing there.
15//! Capturing at the data-link layer via `libpcap` avoids that: BPF (macOS/BSD),
16//! `AF_PACKET` (Linux) and Npcap (Windows) all see inbound frames before the stack
17//! handles them, so one capture path behaves the same everywhere.
18//!
19//! Each interface is opened with a compiled BPF filter so the kernel drops everything
20//! except the packets a scan cares about; only matching frames are copied into
21//! userspace. Captures run on dedicated OS threads (the `libpcap` read blocks) and
22//! funnel parsed segments into a single Tokio channel, so async scan code consumes one
23//! merged stream however many interfaces are live.
24//!
25//! [`CaptureOptions`] describes a capture. Which frames the kernel admits, how much of
26//! each it keeps, and whether it accepts traffic addressed elsewhere have to be chosen
27//! together, and [`CaptureOptions::for_replies`] is the choice a scanner should take
28//! unchanged.
29
30use std::net::IpAddr;
31use std::ops::ControlFlow;
32use std::sync::Arc;
33use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
34use std::thread::{self, JoinHandle};
35use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
36
37use pcap::{Active, Capture};
38#[cfg(not(windows))]
39use std::os::unix::io::AsRawFd;
40use tokio::sync::mpsc;
41
42use crate::logging::error;
43use crate::model::capture::{CaptureCounts, IpObservation};
44use crate::model::ip::scoped::Zone;
45use crate::model::mac::MacAddr;
46use crate::protocols::ethernet::VLAN_TAG_LEN;
47use crate::protocols::sizes::{ETH_HDR_LEN, IP_V6_HDR_LEN};
48use crate::system::descriptors::Descriptor;
49use crate::transport::frame::{self, LinkType};
50use crate::{counted, info, warn};
51
52/// How much of each frame a scan's receive path keeps: a whole frame at Ethernet's
53/// standard MTU, behind the deepest link header this crate strips.
54///
55/// Sized to the largest thing a reader of these captures reads whole. A probe's answer
56/// is a few headers; an ICMP error quotes at most 576 bytes over IPv4 (RFC 1812) and
57/// 1,280 over IPv6 (RFC 4443); a UDP answer is read for a DNS header or a NetBIOS name
58/// table; and the DNS and mDNS answers the resolver sniffs, like the ARP, neighbour
59/// discovery, LLDP and CDP frames a segment sweep reads, are single frames on a
60/// standard link. Only jumbo frames, loopback and segments coalesced by interface
61/// offloads are longer, and of those a reader gets the headers and the start of the
62/// payload.
63///
64/// No larger, because on Linux the capture's ring is counted in snapshot lengths. In
65/// immediate mode `libpcap` reads through a ring of fixed slots, one frame per slot,
66/// each sized from the snapshot length; the link's MTU caps it only on an interface
67/// without segmentation offloads, which veth pairs and most server adapters are not.
68/// At `libpcap`'s default two-megabyte buffer this length makes 1,310 slots of 1,600
69/// bytes, where 65,535 makes 32. A port probe costs up to three frames: the probe
70/// leaving, its answer, and the reset the kernel sends to an unsolicited SYN-ACK.
71/// Thirty-two slots overflow within a scan's first window, and every dropped answer is
72/// a port asked again and a congestion window halved on a host that answered.
73pub const REPLY_SNAP_LEN: u32 = (ETH_HDR_LEN + 2 * VLAN_TAG_LEN + ETHERNET_MTU) as u32;
74
75/// The largest IP packet a standard Ethernet link carries in one frame (IEEE 802.3).
76const ETHERNET_MTU: usize = 1_500;
77
78/// The shortest snapshot length worth opening a capture at.
79///
80/// The deepest header stack this crate reads before it has an answer: an Ethernet
81/// header with two VLAN tags, the larger of the two IP headers, and a TCP header with
82/// full options. A capture snapped below that truncates the reply it was opened for and
83/// reports the result as silence. Every other link header this crate strips is shorter
84/// than the tagged Ethernet one.
85///
86/// A floor, not a default. [`CaptureOptions::with_snaplen`] raises anything lower to
87/// it, which also keeps a zero from reaching `libpcap`, whose manual leaves that value
88/// undefined.
89pub const MIN_SNAP_LEN: u32 =
90    (ETH_HDR_LEN + 2 * VLAN_TAG_LEN + IP_V6_HDR_LEN + TCP_MAX_HDR_LEN) as u32;
91
92/// A TCP header with the full forty bytes of options its data offset can describe.
93const TCP_MAX_HDR_LEN: usize = 60;
94
95// The floor's argument, checked at compile time since every side of it is a constant.
96const _: () = assert!(
97    MIN_SNAP_LEN as usize >= ETH_HDR_LEN + 2 * VLAN_TAG_LEN + IP_V6_HDR_LEN + TCP_MAX_HDR_LEN,
98    "the snapshot floor is below a header stack this crate parses"
99);
100const _: () = assert!(
101    REPLY_SNAP_LEN > MIN_SNAP_LEN,
102    "the snapshot length a scanner takes unchanged is below the floor"
103);
104const _: () = assert!(
105    frame::SLL_HDR_LEN <= ETH_HDR_LEN + 2 * VLAN_TAG_LEN
106        && frame::SLL2_HDR_LEN <= ETH_HDR_LEN + 2 * VLAN_TAG_LEN,
107    "a cooked link header is deeper than the one the snapshot floor was sized for"
108);
109
110/// How a capture is opened: what the kernel admits, how much of each frame it keeps,
111/// and whose traffic it accepts.
112///
113/// [`for_replies`](Self::for_replies) is the setting for a scan's receive path, and a
114/// scanner should take it unchanged. The builders are for callers reading traffic the
115/// scan did not cause, whose needs differ on every setting here.
116///
117/// The settings are not independent: a wide filter with a generous snapshot length
118/// and a default buffer is a capture that discards most of what it admits. So they are
119/// chosen together, as one value.
120///
121/// The snapshot length is also the one limit on how much of other people's traffic
122/// this process reads that the kernel enforces.
123#[must_use]
124#[derive(Debug, Clone)]
125pub struct CaptureOptions {
126    /// What the kernel admits, compiled for each link to a BPF program. Only matching
127    /// frames are copied into this process.
128    filter: CaptureFilter,
129    /// How many bytes of each matching frame to keep. The kernel discards the rest.
130    snaplen: u32,
131    /// Whether to accept frames not addressed to this host.
132    promiscuous: bool,
133    /// How much the kernel may hold for this capture before it starts discarding.
134    /// `None` leaves `libpcap`'s default in place.
135    buffer_bytes: Option<u32>,
136}
137
138impl CaptureOptions {
139    /// A capture of what was addressed to this host: the replies to probes it sent.
140    ///
141    /// Not promiscuous, unlike [`for_link_traffic`](Self::for_link_traffic). Replies
142    /// come back to this host, so frames addressed elsewhere would only be other
143    /// people's traffic, filling the buffer this scan's answers must fit in.
144    ///
145    /// Keeps a whole frame at Ethernet's standard MTU ([`REPLY_SNAP_LEN`]): everything
146    /// a reply is read for, and short enough that Linux's ring, whose slots are sized
147    /// from it, holds a scan's bursts.
148    ///
149    /// The platform's default buffer, since the snapshot length decides how many
150    /// replies fit. On Linux the default two megabytes hold 1,310 frames, about twenty
151    /// milliseconds of arrivals at the 20,000 probes a second a full-range scan reaches
152    /// over a veth pair, so the reader must fall behind by a scheduling delay, not a
153    /// round trip, before anything is lost; such a scan drops nothing whether the
154    /// processors are busy or idle. macOS's BPF and Windows' Npcap count their buffers
155    /// in bytes (a small header per frame plus what was kept), and their defaults, half
156    /// a megabyte and one, hold thousands of replies a few dozen bytes long. A larger
157    /// buffer would also buy Linux slots, but a capture is opened on every link that is
158    /// up, so its size is paid per link on every open, while the snapshot length costs
159    /// nothing.
160    pub fn for_replies(filter: impl Into<CaptureFilter>) -> Self {
161        Self {
162            filter: filter.into(),
163            snaplen: REPLY_SNAP_LEN,
164            promiscuous: false,
165            buffer_bytes: None,
166        }
167    }
168
169    /// A capture of everything the link carries that `filter` admits, whoever it was
170    /// addressed to.
171    ///
172    /// Promiscuous, unlike [`for_replies`](Self::for_replies), because several things
173    /// a segment sweep concludes arrive in frames addressed to someone else: a DHCP
174    /// server's answer is often unicast to the client that asked, and the interface may
175    /// filter out a multicast group this host never joined before `libpcap` sees it.
176    ///
177    /// `filter` does the narrowing, in the kernel: promiscuity decides what the
178    /// interface hands up, the filter decides what is copied into this process.
179    pub fn for_link_traffic(filter: impl Into<CaptureFilter>) -> Self {
180        Self {
181            promiscuous: true,
182            ..Self::for_replies(filter)
183        }
184    }
185
186    /// Keeps only the first `bytes` of each frame, discarding the rest in the kernel.
187    ///
188    /// Bounds both the copying a busy link costs this process and how much of a payload
189    /// it has no business reading it can see, a limit the kernel enforces.
190    ///
191    /// Raised to [`MIN_SNAP_LEN`] where lower, since below that a capture cannot see
192    /// the headers it exists to read. `libpcap` leaves a snapshot length of zero
193    /// undefined and its meaning has varied across versions, so it is never passed.
194    pub fn with_snaplen(mut self, bytes: u32) -> Self {
195        self.snaplen = bytes.max(MIN_SNAP_LEN);
196        self
197    }
198
199    /// Accepts frames not addressed to this host, which the interface would otherwise
200    /// discard before `libpcap` saw them.
201    ///
202    /// On a switched network this admits broadcast and multicast in full and unicast
203    /// only where the switch forwards it, so it widens what *can* be seen without
204    /// promising anything will be.
205    pub fn with_promiscuous(mut self, promiscuous: bool) -> Self {
206        self.promiscuous = promiscuous;
207        self
208    }
209
210    /// Lets the kernel hold `bytes` for this capture before it starts discarding.
211    ///
212    /// The buffer absorbs the gap between a burst arriving and this process reading
213    /// it, so it decides whether a spike becomes a `dropped` count. Worth raising for
214    /// any capture whose arrival rate the network sets, not this host's probes. On
215    /// Linux it is counted in slots sized from the snapshot length, so the two settings
216    /// decide it together; see [`REPLY_SNAP_LEN`].
217    pub fn with_buffer_bytes(mut self, bytes: u32) -> Self {
218        self.buffer_bytes = Some(bytes);
219        self
220    }
221}
222
223/// What a capture admits, in `libpcap`'s filter syntax, the syntax `tcpdump` takes.
224///
225/// Two shapes, because a filter is compiled once per link and links differ in what
226/// they can express. An [`expression`](Self::expression) is compiled as written, and a
227/// link that cannot compile it is not captured on. A set of alternatives,
228/// [`any_of`](Self::any_of), admits a frame any one of them admits; each link compiles
229/// the ones it can express and leaves the rest out.
230///
231/// # When leaving a clause out is sound
232///
233/// A clause a link cannot express names something the link does not carry. `ether
234/// dst` names a hardware address, and a tunnel, a PPP link or a loopback without an
235/// Ethernet header has none, so `libpcap` refuses to compile it there: no frame on that
236/// link could have matched. Leaving it out loses nothing, while refusing the whole
237/// filter would lose everything the other clauses admit, on a tunnel every IP packet.
238///
239/// That holds for a clause the link cannot express, not for one nothing can: a typo
240/// should not be silently dropped. So a clause a link refuses is compiled again for
241/// Ethernet, the link that expresses the most, and only left out if that succeeds.
242/// Otherwise the capture fails with [`CaptureError::Filter`] naming it.
243///
244/// Alternatives suit a capture reading several unrelated kinds of traffic, as a
245/// listener does. A scan's reply filter is an expression, since every part is needed
246/// for the scan to hear its answers, and a link that can express only some of it is
247/// refused and reported.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct CaptureFilter {
250    shape: FilterShape,
251}
252
253/// The two shapes a [`CaptureFilter`] takes, private so a filter is built through the
254/// constructors that say which one is meant.
255#[derive(Debug, Clone, PartialEq, Eq)]
256enum FilterShape {
257    /// Compiled as written, on every link or on none.
258    Expression(String),
259    /// Joined by `or`, each link taking the clauses it can express.
260    AnyOf(Vec<String>),
261}
262
263impl CaptureFilter {
264    /// A filter compiled as written, on every link or on none.
265    pub fn expression(expression: impl Into<String>) -> Self {
266        Self {
267            shape: FilterShape::Expression(expression.into()),
268        }
269    }
270
271    /// A filter admitting a frame any of `clauses` admits, each link taking the
272    /// clauses it can express.
273    ///
274    /// Each clause is a complete expression, joined to the others by `or`, so it must
275    /// parenthesise anything that would not survive that.
276    pub fn any_of<I, S>(clauses: I) -> Self
277    where
278        I: IntoIterator<Item = S>,
279        S: Into<String>,
280    {
281        Self {
282            shape: FilterShape::AnyOf(clauses.into_iter().map(Into::into).collect()),
283        }
284    }
285
286    /// The expression to compile on the link `capture` is open on, with the clauses
287    /// that link cannot express left out.
288    ///
289    /// Asks `libpcap` through the capture itself: which clauses a data-link type can
290    /// express is `libpcap`'s knowledge, and a table here would be a second copy that
291    /// could drift.
292    pub(crate) fn for_link<T: pcap::Activated + ?Sized>(
293        &self,
294        capture: &Capture<T>,
295    ) -> Result<(String, Vec<String>), CaptureError> {
296        let clauses = match &self.shape {
297            FilterShape::Expression(expression) => return Ok((expression.clone(), Vec::new())),
298            FilterShape::AnyOf(clauses) => clauses,
299        };
300
301        let mut kept = Vec::new();
302        let mut left_out = Vec::new();
303        let mut refused = None;
304        for clause in clauses {
305            match capture.compile(clause, true) {
306                Ok(_) => kept.push(clause.as_str()),
307                Err(source) => {
308                    if let Err(malformed) = compiles_for_ethernet(clause) {
309                        return Err(CaptureError::Filter {
310                            filter: clause.clone(),
311                            source: LibraryError::new(malformed),
312                        });
313                    }
314                    left_out.push(clause.clone());
315                    refused = Some(source);
316                }
317            }
318        }
319
320        match refused {
321            Some(source) if kept.is_empty() => Err(CaptureError::Filter {
322                filter: self.to_string(),
323                source: LibraryError::new(source),
324            }),
325            _ => Ok((kept.join(" or "), left_out)),
326        }
327    }
328}
329
330/// Whether `clause` compiles for Ethernet, the link expressing the most, and what
331/// `libpcap` said where it does not.
332///
333/// Uses a dead handle with no device behind it: compiling needs only a link type, so
334/// this asks nothing of the host and needs no privilege.
335fn compiles_for_ethernet(clause: &str) -> Result<(), pcap::Error> {
336    Capture::dead(pcap::Linktype::ETHERNET)?.compile(clause, true)?;
337    Ok(())
338}
339
340impl std::fmt::Display for CaptureFilter {
341    /// The filter as written, every alternative included.
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        match &self.shape {
344            FilterShape::Expression(expression) => f.write_str(expression),
345            FilterShape::AnyOf(clauses) => f.write_str(&clauses.join(" or ")),
346        }
347    }
348}
349
350impl From<String> for CaptureFilter {
351    fn from(expression: String) -> Self {
352        Self::expression(expression)
353    }
354}
355
356impl From<&str> for CaptureFilter {
357    fn from(expression: &str) -> Self {
358        Self::expression(expression)
359    }
360}
361
362/// How long a reader thread waits for a frame before checking the stop flag again.
363/// Bounds shutdown latency without busy-looping.
364///
365/// On Unix this is the timeout of the [`wait_readable`] poll, since `libpcap`'s own
366/// read timeout cannot be relied on: see [`open`].
367const READ_TIMEOUT_MS: i32 = 100;
368
369/// How many frames a reader may forward between refreshes of its kernel counters.
370///
371/// A scanner reads [`CaptureCounts`] while its capture threads are running, so the
372/// counters must be current mid-run. Refreshing only when idle would miss the case
373/// worth measuring: while frames arrive faster than they are read the loop never goes
374/// idle, and that is when a buffer overflows.
375const STATS_EVERY_FRAMES: u32 = 128;
376
377/// How long a reader thread waits before offering a frame again once the consumer's
378/// queue is full.
379///
380/// Short enough not to hold up a consumer catching up, long enough that an overrun
381/// capture does not spin a core while the kernel buffer absorbs the burst.
382const QUEUE_FULL_PAUSE: Duration = Duration::from_millis(1);
383
384/// One reply lifted off the wire: the Layer-4 segment, who sent it, which protocol it
385/// is, and what its IP header said.
386///
387/// The protocol is carried because a filter may admit more than one (a UDP port scan
388/// watches for direct UDP replies and the ICMP errors that answer them), and Layer-4
389/// headers cannot be told apart after the fact (see [`frame::IpSegment`]).
390#[non_exhaustive]
391#[derive(Debug, Clone, PartialEq, Eq)]
392pub struct CapturedSegment {
393    /// The address the segment came from.
394    pub source: IpAddr,
395    /// The address it was going to, so a capture admitting both directions can tell a
396    /// scan's own probe from the answer to it. `None` for a synthetic stream with no
397    /// IP header, as [`observation`](Self::observation) is.
398    pub destination: Option<IpAddr>,
399    /// The protocol [`bytes`](Self::bytes) should be parsed as, by its IANA number: 6
400    /// for TCP, 17 for UDP, 58 for ICMPv6.
401    pub protocol: u8,
402    /// The Layer-4 segment, link and IP headers already stripped.
403    pub bytes: Vec<u8>,
404    /// What the IP header this segment arrived under said about the stack that sent
405    /// it, or `None` if there was no IP header.
406    ///
407    /// `None` means the segment did not come off a wire: a synthetic receive stream
408    /// built through `ProbeTransport::from_parts` hands over Layer-4 bytes it composed
409    /// itself. Reporting a default TTL and zero identifier for one would claim a
410    /// measurement nobody took, which is also why
411    /// [`CaptureGuard::counts`](CaptureGuard::counts) is optional. A test exercising
412    /// something that reads these must supply one explicitly.
413    pub observation: Option<IpObservation>,
414
415    /// The hardware address the frame carrying this segment came from, where the link
416    /// had one.
417    ///
418    /// The only thing here that can say whether a reply came from the host it claims
419    /// to. Anything answering in a host's place uses that host's IP address, so
420    /// [`source`](Self::source) cannot tell a genuine answer from an intercepted one;
421    /// this can, on an on-link segment.
422    ///
423    /// Not for vendor lookup: an off-link reply carries the last-hop router's address.
424    /// See [`frame::source_mac`].
425    ///
426    /// `None` on a tunnel, PPP, loopback or raw-IP link, which carry no hardware
427    /// address, and on a synthetic stream. It does not mean the sender had none.
428    pub source_mac: Option<MacAddr>,
429
430    /// When the capture thread took delivery of this segment.
431    ///
432    /// The earliest monotonic point in the pipeline, taken in the `libpcap` callback
433    /// before the segment is queued. A round trip measured from dequeue time would
434    /// include the channel's depth and the runtime's scheduling, which on a fast link
435    /// is most of it: 4.5 ms of pipeline over a 0.1 ms path.
436    ///
437    /// Monotonic, unlike the kernel's wall-clock frame timestamp, which
438    /// [`CapturedFrame::observed_at`] carries for readers that place a finding on a
439    /// timeline. A duration needs a clock that cannot be adjusted underneath it.
440    pub received_at: Instant,
441}
442
443impl CapturedSegment {
444    /// A segment with no IP header behind it, for a receive stream that composed its
445    /// Layer-4 bytes.
446    ///
447    /// The way to build a segment outside this crate, so adding a field does not break
448    /// every synthetic transport. Set anything beyond the bytes, such as a destination
449    /// or an observed header, on the result.
450    pub fn synthetic(source: IpAddr, protocol: u8, bytes: Vec<u8>) -> Self {
451        Self {
452            source,
453            destination: None,
454            protocol,
455            bytes,
456            observation: None,
457            received_at: Instant::now(),
458            source_mac: None,
459        }
460    }
461}
462
463/// The parsed receive stream of a running capture: [`CapturedSegment`]s from every
464/// captured interface, interleaved in arrival order.
465///
466/// Bounded, like [`FrameStream`] and for the same reason. [`segments`] documents where
467/// the traffic that fills it comes from.
468pub type CaptureStream = mpsc::Receiver<CapturedSegment>;
469
470/// One frame as it came off a link, with nothing stripped.
471///
472/// The counterpart to [`CapturedSegment`], for answers outside a Layer-4 segment. An
473/// ARP exchange, a neighbour advertisement, a switch announcing itself and an 802.1Q
474/// tag all live below where [`CapturedSegment`] begins, and are gone by the time one
475/// exists.
476#[non_exhaustive]
477#[derive(Debug, Clone, PartialEq, Eq)]
478pub struct CapturedFrame {
479    /// The link this frame arrived on.
480    ///
481    /// Much of what a frame proves holds only on one segment. An IPv6 link-local
482    /// address names a different machine on every link, a switch announces itself to
483    /// the port it is announcing *about*, and a VLAN tag means nothing without the
484    /// trunk it was read from. A capture merges every link into one stream, so this
485    /// keeps the merge lossless.
486    pub zone: Zone,
487
488    /// How [`bytes`](Self::bytes) is framed, so a reader knows what it is looking at.
489    pub link: LinkType,
490
491    /// The frame, link header included.
492    ///
493    /// Possibly truncated to the [`CaptureOptions::with_snaplen`] the capture was opened
494    /// with, which limits how much of other people's traffic is read. A reader treats a
495    /// short frame as ordinary, not corrupt; every parser in [`crate::protocols`]
496    /// declines on short input.
497    pub bytes: Vec<u8>,
498
499    /// When the kernel timestamped the frame.
500    pub observed_at: SystemTime,
501
502    /// When the capture thread took delivery of this frame, on the monotonic clock a
503    /// round trip is measured against.
504    ///
505    /// The frame-stream twin of [`CapturedSegment::received_at`]: a sweep reading
506    /// replies as frames times each one from here, so queue depth and runtime
507    /// scheduling stay out of its round trips. [`observed_at`](Self::observed_at) is
508    /// earlier but on a clock that can be stepped, so it places a frame on a timeline
509    /// and this one times it.
510    pub received_at: Instant,
511}
512
513impl CapturedFrame {
514    /// A frame lifted off `zone` just now, framed as `link` says.
515    pub fn new(zone: Zone, link: LinkType, bytes: Vec<u8>) -> Self {
516        Self {
517            zone,
518            link,
519            bytes,
520            observed_at: SystemTime::now(),
521            received_at: Instant::now(),
522        }
523    }
524}
525
526/// The whole-frame receive stream produced by [`frames`]: [`CapturedFrame`]s from
527/// every captured link, interleaved in arrival order.
528///
529/// Bounded, unlike [`CaptureStream`]. The network, not this host's probes, sets the
530/// arrival rate, so the consumer is not guaranteed to keep up, and an unbounded queue
531/// would grow until the process died. [`frames`] documents what happens instead.
532pub type FrameStream = mpsc::Receiver<CapturedFrame>;
533
534/// One capture's counters, written by its reader thread and read by whoever holds the
535/// [`CaptureGuard`].
536///
537/// Atomics, because the writer is a capture thread in its hot loop: a slightly stale
538/// count leads a reader to the same conclusion, while a lock in that loop would perturb
539/// the timing being measured.
540#[derive(Debug, Default)]
541struct CaptureStats {
542    received: AtomicU64,
543    dropped: AtomicU64,
544    if_dropped: AtomicU64,
545    /// Whether this reader ended before it was told to.
546    ///
547    /// A flag here and a count in [`CaptureCounts`]: one capture either lasted or not,
548    /// and a report wants to know how many did.
549    stopped_early: AtomicBool,
550}
551
552impl CaptureStats {
553    /// Replaces the counters with what `libpcap` currently reports. The values are
554    /// cumulative from the start of the capture, so they are stored, not added.
555    fn store(&self, stat: &pcap::Stat) {
556        self.received.store(stat.received as u64, Ordering::Relaxed);
557        self.dropped.store(stat.dropped as u64, Ordering::Relaxed);
558        self.if_dropped
559            .store(stat.if_dropped as u64, Ordering::Relaxed);
560    }
561
562    fn snapshot(&self) -> CaptureCounts {
563        CaptureCounts {
564            received: self.received.load(Ordering::Relaxed),
565            dropped: self.dropped.load(Ordering::Relaxed),
566            if_dropped: self.if_dropped.load(Ordering::Relaxed),
567            stopped_early: u64::from(self.stopped_early.load(Ordering::Relaxed)),
568        }
569    }
570}
571
572/// Keeps a set of live per-interface captures running while held. Dropping it signals
573/// every reader thread to stop and waits for each, so no capture thread outlives the
574/// guard.
575///
576/// Dropping blocks for up to one read timeout, bounded by the stop flag. A thread
577/// waiting for room in a full queue also checks the flag, so a guard dropped while a
578/// consumer holds the receiver without draining it returns on the same schedule.
579///
580/// A guard is normally dropped inside the scan task, on a runtime worker, so on a
581/// multi-threaded runtime the wait goes through
582/// [`block_in_place`](tokio::task::block_in_place) and the worker is free for other
583/// tasks meanwhile. A single-threaded runtime has no other worker, and a caller outside
584/// a runtime blocks its own thread.
585///
586/// Separate from the [`CaptureStream`] it feeds, so a consumer can own the receiver
587/// (borrowing it mutably in a `select!`) while the guard keeps the threads alive
588/// beside it.
589pub struct CaptureGuard {
590    stop: Arc<AtomicBool>,
591    handles: Vec<JoinHandle<()>>,
592    /// One set of counters per live capture, shared with the thread reading it.
593    stats: Vec<Arc<CaptureStats>>,
594    /// The permits the descriptor gate has no socket for once these captures' links
595    /// are open, held out of it while they are. See [`running`](Self::running).
596    _held_back: Option<Descriptor>,
597}
598
599impl Drop for CaptureGuard {
600    fn drop(&mut self) {
601        self.stop.store(true, Ordering::Relaxed);
602
603        // A reader that panicked has already marked its capture and logged it as it
604        // unwound; see `spawn_reader`. Only the wait is left.
605        let handles = std::mem::take(&mut self.handles);
606        let wait = move || {
607            for handle in handles {
608                let _ = handle.join();
609            }
610        };
611
612        match tokio::runtime::Handle::try_current().map(|handle| handle.runtime_flavor()) {
613            Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(wait),
614            _ => wait(),
615        }
616    }
617}
618
619impl CaptureGuard {
620    /// A guard owning no capture threads, for a transport whose receive stream is
621    /// supplied directly. Reached from outside the crate only through
622    /// [`ProbeTransport::from_parts`].
623    ///
624    /// [`ProbeTransport::from_parts`]: crate::transport::probe::ProbeTransport::from_parts
625    #[cfg(any(test, feature = "test-support"))]
626    pub(crate) fn noop() -> Self {
627        Self {
628            stop: Arc::new(AtomicBool::new(true)),
629            handles: Vec::new(),
630            stats: Vec::new(),
631            _held_back: None,
632        }
633    }
634
635    /// A guard over one capture that already stopped early, with no thread behind it.
636    #[cfg(test)]
637    pub(crate) fn stopped_early() -> Self {
638        let counters = CaptureStats::default();
639        counters.stopped_early.store(true, Ordering::Relaxed);
640        Self {
641            stop: Arc::new(AtomicBool::new(true)),
642            handles: Vec::new(),
643            stats: vec![Arc::new(counters)],
644            _held_back: None,
645        }
646    }
647
648    /// A guard over the reader threads `handles`, whose links are open, taking out of
649    /// the descriptor gate what the table no longer has a socket for.
650    ///
651    /// A capture holds a descriptor per link it listens on, thirty on a laptop with a
652    /// VPN and a hypervisor, and every transport opens its own. A scan's connection
653    /// budget was read off the table when the scan started, before these were open, so
654    /// without this the connections are promised sockets the captures hold, and each
655    /// one past the table's room waits out its patience and is filed unasked. Read here,
656    /// after the links are open, the table counts them, and the permits return to the
657    /// gate when the captures close. See
658    /// [`hold_back`](crate::system::descriptors::hold_back).
659    fn running(
660        stop: Arc<AtomicBool>,
661        handles: Vec<JoinHandle<()>>,
662        stats: Vec<Arc<CaptureStats>>,
663    ) -> Self {
664        Self {
665            stop,
666            handles,
667            stats,
668            _held_back: crate::system::descriptors::hold_back(),
669        }
670    }
671
672    /// The kernel counters of every capture this guard keeps alive, summed.
673    ///
674    /// `None` when there is no capture: a transport fed a synthetic receive stream has
675    /// no kernel buffer, and reporting zero drops would claim a measurement nobody
676    /// took.
677    pub fn counts(&self) -> Option<CaptureCounts> {
678        if self.stats.is_empty() {
679            return None;
680        }
681
682        Some(
683            self.stats
684                .iter()
685                .map(|stats| stats.snapshot())
686                .fold(CaptureCounts::default(), |total, counts| total + counts),
687        )
688    }
689}
690
691/// Why a capture could not be started.
692///
693/// An interface that cannot be captured is skipped and logged: a host has several,
694/// most irrelevant to a given probe, and a virtual bridge declining should not stop a
695/// scan. Only every interface failing leaves nowhere to hear an answer, and that is
696/// [`NoInterface`](Self::NoInterface), which carries each link's own refusal.
697///
698/// Privilege is one cause among several and is named only where it is the cause. A
699/// root process can be refused a capture by a filter the link cannot express, a
700/// framing nothing here parses, or an adapter the capture driver will not bind, and
701/// blaming privilege for those misleads someone who already has it.
702/// [`is_denied`](Self::is_denied) is the question to ask.
703///
704/// `#[non_exhaustive]` because new platform-specific failures show up first in the
705/// capture layer.
706#[non_exhaustive]
707#[derive(Debug, thiserror::Error)]
708pub enum CaptureError {
709    /// No link could be captured on, so nothing could be heard.
710    ///
711    /// Carries every link's refusal, since they need not agree and the reason is what
712    /// there is to act on. Where every one was [`Denied`](Self::Denied) the message
713    /// says so in one sentence, the ordinary case of an unprivileged process; otherwise
714    /// it gives each reason once, naming the link where one link gave it and counting
715    /// them where several did.
716    #[error(
717        "no link could be captured on, so nothing could be heard: {}",
718        refusals_reason(refused)
719    )]
720    NoInterface {
721        /// Each link tried, by name, and why it could not be captured on, in the order
722        /// tried.
723        refused: Vec<(String, CaptureError)>,
724    },
725    /// Every link opened and none could be given a reader thread.
726    ///
727    /// A runtime condition: a process near its thread limit, or a cgroup capping them.
728    /// Separate from [`NoInterface`](Self::NoInterface) because the remedy differs and
729    /// has nothing to do with privilege.
730    #[error(
731        "captured {} but could not start a reader for any of them: {source}",
732        crate::logging::counted(*opened as u128, "link", "links")
733    )]
734    NoReader {
735        /// How many links opened before the threads were asked for.
736        opened: usize,
737        /// What the last spawn refused with.
738        #[source]
739        source: std::io::Error,
740    },
741    /// A link carries frames this crate cannot strip down to an IP packet.
742    ///
743    /// The capture came up, but its data-link type is one nothing here parses. Skipped,
744    /// since guessing at a framing would report a network that is not there.
745    #[error("{interface} carries data-link type {dlt}, which nothing here parses")]
746    UnsupportedLinkType {
747        /// The link that was opened.
748        interface: String,
749        /// The `libpcap` data-link type it reported.
750        dlt: i32,
751    },
752
753    /// The filter expression would not compile to a BPF program.
754    ///
755    /// Either a mistake in the expression or a link that cannot express it: an
756    /// Ethernet address means nothing on a tunnel, and `libpcap` refuses to compile one
757    /// for it. Either way the expression is what to look at, so it is named.
758    #[error("the filter `{filter}` would not compile: {source}")]
759    Filter {
760        /// The expression that was rejected.
761        filter: String,
762        /// What `libpcap` said.
763        #[source]
764        source: LibraryError,
765    },
766
767    /// One named link could not be opened, for a reason other than privilege. Unlike
768    /// `NoInterface` this names the link, because the caller asked for that one and
769    /// there is nothing to fall back to.
770    #[error("{interface} could not be opened: {source}")]
771    Open {
772        /// The link that refused.
773        interface: String,
774        /// What `libpcap` said.
775        #[source]
776        source: LibraryError,
777    },
778
779    /// One named link could not be opened because this process may not capture on it.
780    ///
781    /// Separate from [`Open`](Self::Open) because its remedy lies outside the link:
782    /// root, or whatever grants the right to capture short of it, such as membership
783    /// of `access_bpf` on macOS or `cap_net_raw` on Linux. Decided by the status
784    /// `libpcap` activated the handle with, not by its message.
785    #[error("{interface} could not be opened without privileges this process lacks: {source}")]
786    Denied {
787        /// The link that refused.
788        interface: String,
789        /// What `libpcap` said.
790        #[source]
791        source: LibraryError,
792    },
793
794    /// The process or the system ran out of descriptors partway through the links, so
795    /// a capture would have been deaf on the links it did not reach.
796    ///
797    /// Not skipped like a link that declines. A declining link is one the scan's
798    /// targets do not answer through; these are refused for a local shortage, and any
799    /// of them may be where the replies arrive. Heard on the rest alone, those replies
800    /// would read as targets that did not answer.
801    #[error(
802        "no capture on {} (file limit reached)",
803        crate::logging::counted(links.len() as u128, "link", "links")
804    )]
805    OutOfDescriptors {
806        /// The links refused a capture, by name, in the order they were tried.
807        links: Vec<String>,
808    },
809}
810
811impl CaptureError {
812    /// Whether this failure is a missing privilege and nothing else.
813    ///
814    /// True of a link that [`Denied`](Self::Denied) this process, and of a capture
815    /// with no link because every link did. A capture refused on other grounds, even
816    /// alongside links that denied it, answers false: the privilege would not have
817    /// made it work.
818    pub fn is_denied(&self) -> bool {
819        match self {
820            Self::Denied { .. } => true,
821            Self::NoInterface { refused } => {
822                !refused.is_empty() && refused.iter().all(|(_, error)| error.is_denied())
823            }
824            _ => false,
825        }
826    }
827
828    /// Whether this is one link refused because no descriptor was left to open its
829    /// capture with.
830    ///
831    /// Read from the library's words, since `libpcap` reports the shortage under the
832    /// same status as any other failure to open a device. Those words are the C
833    /// library's own text for the errno, the same this process's own errors carry, so
834    /// the match is against that.
835    pub(crate) fn is_exhausted(&self) -> bool {
836        let Self::Open { source, .. } = self else {
837            return false;
838        };
839        let pcap::Error::PcapError(message) = &source.0 else {
840            return false;
841        };
842        #[cfg(unix)]
843        {
844            [libc::EMFILE, libc::ENFILE].into_iter().any(|code| {
845                let error = std::io::Error::from_raw_os_error(code).to_string();
846                let words = error.split(" (os error").next().unwrap_or(&error);
847                message.contains(words)
848            })
849        }
850        #[cfg(not(unix))]
851        {
852            let _ = message;
853            false
854        }
855    }
856
857    /// What went wrong, without the link's name, for a line that names the link
858    /// itself.
859    ///
860    /// A capture of one link that failed is that link's own refusal, so it too is
861    /// given without the name. Of several, each keeps its name.
862    pub(crate) fn reason(&self) -> String {
863        match self {
864            Self::NoInterface { refused } => match refused.as_slice() {
865                [(_, only)] => only.reason(),
866                several => refusals_reason(several),
867            },
868            Self::Open { source, .. } => source.to_string(),
869            Self::Denied { source, .. } => {
870                format!("this process lacks the privileges to capture on it: {source}")
871            }
872            Self::UnsupportedLinkType { dlt, .. } => {
873                format!("it carries data-link type {dlt}, which nothing here parses")
874            }
875            other => other.to_string(),
876        }
877    }
878}
879
880/// Why no link could be captured on, from each link's refusal.
881///
882/// One sentence where every link was denied, which is what an unprivileged process
883/// meets. Otherwise each reason once, in the order tried: a reason one link gave by
884/// that link's name, and one several gave with how many. The reasons can differ, and
885/// a reason repeated per link would be one fact told dozens of times: a process out of
886/// descriptors meets the same refusal on every link.
887fn refusals_reason(refused: &[(String, CaptureError)]) -> String {
888    if refused.is_empty() {
889        return "there was no link to capture on".to_owned();
890    }
891    if refused.iter().all(|(_, error)| error.is_denied()) {
892        return "this process may not capture (opening a capture needs root)".to_owned();
893    }
894
895    let mut reasons: Vec<(String, &str, usize)> = Vec::new();
896    for (link, error) in refused {
897        let reason = error.reason();
898        match reasons.iter_mut().find(|(told, _, _)| *told == reason) {
899            Some((_, _, links)) => *links += 1,
900            None => reasons.push((reason, link, 1)),
901        }
902    }
903    reasons
904        .iter()
905        .map(|(reason, link, links)| match links {
906            1 => format!("{link}: {reason}"),
907            many => format!("{reason} ({many} links)"),
908        })
909        .collect::<Vec<_>>()
910        .join("; ")
911}
912
913/// What the capture library said when it refused, in its own words.
914///
915/// This crate's type, so the binding to `libpcap` or Npcap, and its release, stay
916/// internal: a caller reads the library's words through `Display`, and no signature
917/// names the binding.
918///
919/// The words are quoted bare. The binding prefixes every message with `libpcap
920/// error:`, which on Windows, where the library is Npcap, reads as a missing library
921/// when one is installed and has said exactly what it refused.
922#[derive(Debug)]
923pub struct LibraryError(pcap::Error);
924
925impl LibraryError {
926    /// Wraps what the binding returned.
927    pub(crate) fn new(error: pcap::Error) -> Self {
928        Self(error)
929    }
930}
931
932impl std::fmt::Display for LibraryError {
933    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
934        match &self.0 {
935            pcap::Error::PcapError(message) => f.write_str(message),
936            other => other.fmt(f),
937        }
938    }
939}
940
941impl std::error::Error for LibraryError {}
942
943/// Opens a filtered capture on each named link and starts reading, parsing every
944/// admitted frame down to the Layer-4 segment a scanner reads.
945///
946/// Non-IP frames are dropped, since there is no segment behind an ARP frame. For
947/// those, use [`frames`], this function's twin, which forwards whole frames.
948///
949/// # The stream is bounded
950///
951/// Most arrivals are bounded by what this host sent, and the task sending probes is
952/// the one reading this. The rest are not, as the filters show. Only
953/// [`ProbeKind::UdpResolve`](crate::transport::probe::ProbeKind) narrows to this scan
954/// in both address families. A SYN sweep admits every IPv6 TCP segment because
955/// `tcp[tcpflags]` will not compile over a next-header chain, and the three kinds that
956/// read ICMP errors admit `icmp or icmp6` whole because an error names no ports. Each
957/// is the right trade, and each leaves a rate the network sets.
958///
959/// So `queue_depth` bounds what may wait, as for [`frames`], and a full queue stalls
960/// the reader instead of discarding: the kernel buffer takes up the slack, `libpcap`
961/// counts what it drops, and the loss lands in [`CaptureCounts::dropped`], which a
962/// report already carries.
963pub fn segments(
964    links: &[Zone],
965    options: &CaptureOptions,
966    queue_depth: usize,
967) -> Result<(CaptureStream, CaptureGuard), CaptureError> {
968    let (tx, rx) = mpsc::channel(queue_depth);
969
970    let guard = spawn_captures(links, options, move |_zone, link, stop| {
971        let tx = tx.clone();
972        move |packet: &pcap::Packet<'_>| {
973            let Some((parsed, source_mac)) = frame::parse_captured(link, packet.data) else {
974                return ControlFlow::Continue(());
975            };
976
977            let mut segment = CapturedSegment {
978                source: parsed.source,
979                destination: Some(parsed.destination),
980                protocol: parsed.protocol,
981                bytes: parsed.payload.to_vec(),
982                observation: Some(parsed.observation),
983                source_mac,
984                received_at: Instant::now(),
985            };
986
987            // Waits instead of dropping, for the reason `frames` gives.
988            loop {
989                match tx.try_send(segment) {
990                    Ok(()) => return ControlFlow::Continue(()),
991                    Err(mpsc::error::TrySendError::Closed(_)) => return ControlFlow::Break(()),
992                    Err(mpsc::error::TrySendError::Full(returned)) => {
993                        // A guard being dropped ends the wait for room, since its
994                        // join would wait on this thread. See `CaptureGuard`.
995                        if stop.load(Ordering::Relaxed) {
996                            return ControlFlow::Break(());
997                        }
998                        segment = returned;
999                        thread::sleep(QUEUE_FULL_PAUSE);
1000                    }
1001                }
1002            }
1003        }
1004    })?;
1005
1006    Ok((rx, guard))
1007}
1008
1009/// Opens a filtered capture on each named link and starts reading, forwarding every
1010/// admitted frame whole.
1011///
1012/// The twin of [`segments`], for answers outside a Layer-4 segment: an ARP exchange, a
1013/// neighbour advertisement, a switch announcing itself, the VLAN a frame was tagged
1014/// with, or the hardware address behind any of them. Each frame arrives with its link,
1015/// so a finding that only means something on one segment can say which.
1016///
1017/// `queue_depth` bounds how many frames may wait for the consumer at once. Multiplied
1018/// by [`CaptureOptions::with_snaplen`] it is also the memory this costs, so the caller
1019/// states it.
1020///
1021/// # A full queue stalls the reader
1022///
1023/// When the consumer falls behind, the reader thread waits with the frame it holds.
1024/// The kernel buffer takes up the slack, and when that fills, `libpcap` counts what it
1025/// discards, so the loss lands in [`CaptureCounts::dropped`], which a report already
1026/// carries. Discarding here would be a loss counted nowhere and indistinguishable from
1027/// a network with nothing to say.
1028pub fn frames(
1029    links: &[Zone],
1030    options: &CaptureOptions,
1031    queue_depth: usize,
1032) -> Result<(FrameStream, CaptureGuard), CaptureError> {
1033    let (tx, rx) = mpsc::channel(queue_depth);
1034
1035    let guard = spawn_captures(links, options, move |zone, link, stop| {
1036        let tx = tx.clone();
1037        let zone = zone.clone();
1038        move |packet: &pcap::Packet<'_>| {
1039            let mut frame = CapturedFrame {
1040                zone: zone.clone(),
1041                link,
1042                bytes: packet.data.to_vec(),
1043                observed_at: timestamp_of(packet),
1044                received_at: Instant::now(),
1045            };
1046
1047            // Waits instead of dropping, so the loss lands in the kernel's counter;
1048            // see this function's documentation.
1049            loop {
1050                match tx.try_send(frame) {
1051                    Ok(()) => return ControlFlow::Continue(()),
1052                    Err(mpsc::error::TrySendError::Closed(_)) => return ControlFlow::Break(()),
1053                    Err(mpsc::error::TrySendError::Full(returned)) => {
1054                        // A guard being dropped ends the wait for room, since its
1055                        // join would wait on this thread. See `CaptureGuard`.
1056                        if stop.load(Ordering::Relaxed) {
1057                            return ControlFlow::Break(());
1058                        }
1059                        frame = returned;
1060                        thread::sleep(QUEUE_FULL_PAUSE);
1061                    }
1062                }
1063            }
1064        }
1065    })?;
1066
1067    Ok((rx, guard))
1068}
1069
1070/// Opens a capture on every link that will have one, starts a reader thread per
1071/// capture, and returns the guard that keeps them alive.
1072///
1073/// `deliver_for` builds the per-link closure that handles each frame, the only
1074/// difference between [`segments`] and [`frames`]. Everything else (which failures are
1075/// survivable, how threads are named and stopped, when counters refresh) lives here so
1076/// the two cannot drift.
1077///
1078/// Interfaces that fail to open, or whose data-link type this crate cannot parse, are
1079/// skipped and reported by [`tell_unheard`]: a host has many, most irrelevant to a
1080/// given capture. Only *every* link failing is an error, since a capture with no link
1081/// can never hear anything, and so is any link refused for want of a descriptor; see
1082/// [`CaptureError::OutOfDescriptors`].
1083fn spawn_captures<D>(
1084    links: &[Zone],
1085    options: &CaptureOptions,
1086    mut deliver_for: impl FnMut(&Zone, LinkType, Arc<AtomicBool>) -> D,
1087) -> Result<CaptureGuard, CaptureError>
1088where
1089    D: FnMut(&pcap::Packet<'_>) -> ControlFlow<()> + Send + 'static,
1090{
1091    let stop = Arc::new(AtomicBool::new(false));
1092    let mut handles = Vec::new();
1093    let mut stats = Vec::new();
1094
1095    // Named and counted in one line beside the per-interface ones, at verbosity 3. A
1096    // scan opens a capture on every interface that is up (twenty-six on an ordinary
1097    // laptop with a VPN and a hypervisor) once per transport, and that is where
1098    // someone asking which links were captured with which filter will look.
1099    let mut opened = 0usize;
1100    // Why the last reader thread refused to start, for the case where none did.
1101    let mut unstarted: Option<std::io::Error> = None;
1102    // The links that would not open, reported together once it is known whether any
1103    // did. See `tell_unheard`.
1104    let mut unheard: Vec<(&Zone, CaptureError)> = Vec::new();
1105
1106    for zone in links {
1107        let name = zone.name();
1108        match open(name, options) {
1109            Ok(Opened {
1110                capture,
1111                link,
1112                warning,
1113                left_out,
1114            }) => {
1115                match warning {
1116                    Some(warning) => info!(
1117                        verbosity = 3,
1118                        "capturing on {name} (link type {link:?}), which libpcap \
1119                         opened with a warning: {warning}"
1120                    ),
1121                    None => info!(verbosity = 3, "capturing on {name} (link type {link:?})"),
1122                }
1123                if !left_out.is_empty() {
1124                    info!(
1125                        verbosity = 3,
1126                        "capturing on {name} without the filter clauses it cannot express: {}",
1127                        left_out.join(" or ")
1128                    );
1129                }
1130                opened += 1;
1131
1132                let stop = stop.clone();
1133                let deliver = deliver_for(zone, link, stop.clone());
1134                let counters = Arc::new(CaptureStats::default());
1135                stats.push(counters.clone());
1136                let name = name.to_owned();
1137
1138                match spawn_reader(&name.clone(), counters, move |counters| {
1139                    reader_loop(capture, &stop, &name, counters, deliver)
1140                }) {
1141                    Ok(handle) => handles.push(handle),
1142                    // As with an open failure: a host near its thread limit still
1143                    // captures on the links it managed, and only losing all of them is
1144                    // an error.
1145                    Err(e) => {
1146                        warn!("no reader thread for {}: {e}", zone.name());
1147                        stats.pop();
1148                        unstarted = Some(e);
1149                    }
1150                }
1151            }
1152            Err(e) => unheard.push((zone, e)),
1153        }
1154    }
1155
1156    let exhausted: Vec<String> = unheard
1157        .iter()
1158        .filter(|(_, error)| error.is_exhausted())
1159        .map(|(zone, _)| zone.name().to_owned())
1160        .collect();
1161    if !exhausted.is_empty() {
1162        // Stops and joins the readers already started, closing their links.
1163        drop(CaptureGuard {
1164            stop,
1165            handles,
1166            stats,
1167            _held_back: None,
1168        });
1169        return Err(CaptureError::OutOfDescriptors { links: exhausted });
1170    }
1171
1172    if !unheard.is_empty() {
1173        tell_unheard(&unheard, opened == 0);
1174    }
1175
1176    if handles.is_empty() {
1177        return Err(match unstarted {
1178            Some(source) => CaptureError::NoReader { opened, source },
1179            None => CaptureError::NoInterface {
1180                refused: unheard
1181                    .into_iter()
1182                    .map(|(zone, error)| (zone.name().to_owned(), error))
1183                    .collect(),
1184            },
1185        });
1186    }
1187
1188    info!(
1189        verbosity = 3,
1190        "capturing on {} with filter: {}",
1191        counted(opened as u128, "interface", "interfaces"),
1192        options.filter,
1193    );
1194
1195    Ok(CaptureGuard::running(stop, handles, stats))
1196}
1197
1198/// Reports which links could not be captured on, and why: once per link for the life
1199/// of the process, and on the default console only where the scan's answers depend on
1200/// it and no error will say so.
1201///
1202/// Every transport opens its own capture on every link, so a link that refuses one
1203/// refuses them all, several times a scan, and again in every scan a front end runs.
1204/// The refusal is a fact about the machine (an adapter Npcap is not bound to, such as
1205/// a hypervisor's or a VPN's, stays that way), so it is reported once, and again only
1206/// if it comes to matter more.
1207///
1208/// How much it matters is [`loudness`]'s question. The link is named as a person knows
1209/// it, with the system's name beside it on the quiet line, for someone matching it
1210/// against the capture library's device list.
1211fn tell_unheard(unheard: &[(&Zone, CaptureError)], every_link_failed: bool) {
1212    let links = crate::system::interface::interfaces_or_none();
1213    let mut told = TOLD
1214        .lock()
1215        .unwrap_or_else(std::sync::PoisonError::into_inner);
1216
1217    for (zone, error) in unheard {
1218        let link = links.iter().find(|link| link.zone() == **zone);
1219        let loudness = loudness(
1220            every_link_failed,
1221            link.is_some_and(|link| link.carries_default_route()),
1222        );
1223        if !told.first_time(zone.name(), loudness) {
1224            continue;
1225        }
1226
1227        let known_as = link.map_or(zone.name(), |link| link.display_name());
1228        let reason = error.reason();
1229        match loudness {
1230            Loudness::Aloud => warn!("no capture on {known_as}: {reason}"),
1231            Loudness::Quiet if known_as == zone.name() => {
1232                warn!(verbosity = 1, "no capture on {known_as}: {reason}");
1233            }
1234            Loudness::Quiet => {
1235                warn!(
1236                    verbosity = 1,
1237                    "no capture on {known_as} ({}): {reason}",
1238                    zone.name()
1239                );
1240            }
1241        }
1242    }
1243}
1244
1245/// How a link that could not be captured on is told about.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1247enum Loudness {
1248    /// At verbosity 1, with the decisions behind a result: a link nothing in the scan
1249    /// was shown to need.
1250    Quiet,
1251    /// On the default console, because the scan's answers depend on it.
1252    Aloud,
1253}
1254
1255/// How loudly a link that could not be captured on is reported.
1256///
1257/// Aloud when the scan's answers depend on it and nothing else will say so: a link
1258/// carrying the default route, through which every target beyond this machine's own
1259/// segments is reached and answers, while the scan goes on without it on the other
1260/// links. Where no link could be captured on at all, the capture fails with an error
1261/// naming every link and its cause, so these lines go quiet. Otherwise the link is one
1262/// of the adapters a host keeps beside the one it uses (a hypervisor's switch, a VPN's
1263/// tunnel, a bridge), reached only by a target on its own segment: quiet, where a
1264/// reader asking what went uncovered will find it.
1265fn loudness(every_link_failed: bool, carries_default_route: bool) -> Loudness {
1266    if carries_default_route && !every_link_failed {
1267        Loudness::Aloud
1268    } else {
1269        Loudness::Quiet
1270    }
1271}
1272
1273/// The links this process has said it cannot capture on, and how loudly.
1274struct Told(std::collections::BTreeMap<String, Loudness>);
1275
1276impl Told {
1277    const fn new() -> Self {
1278        Self(std::collections::BTreeMap::new())
1279    }
1280
1281    /// Whether `link` should be reported at `loudness`: never reported, or reported
1282    /// more quietly than it now deserves. Records it either way.
1283    fn first_time(&mut self, link: &str, loudness: Loudness) -> bool {
1284        match self.0.get(link) {
1285            Some(&said) if said >= loudness => false,
1286            _ => {
1287                self.0.insert(link.to_owned(), loudness);
1288                true
1289            }
1290        }
1291    }
1292}
1293
1294/// Every link this process has said it cannot capture on. See [`tell_unheard`].
1295static TOLD: std::sync::Mutex<Told> = std::sync::Mutex::new(Told::new());
1296
1297/// Starts the thread that reads one capture, marking the capture stopped early if that
1298/// thread dies.
1299///
1300/// **A reader that panicked is a link that went deaf, and the record must say so while
1301/// the scan can still read it.** The thread is the only reader of its interface, so
1302/// every reply that would have arrived becomes silence a scanner cannot tell from a
1303/// host that did not answer; [`reader_loop`] sets the same flag when pcap ends the
1304/// link. The dying thread sets the mark as it unwinds, because every scanner reads its
1305/// capture counts while the guard is alive; set at join, it would come after the only
1306/// read.
1307///
1308/// Every reader starts here, so none runs without the mark.
1309fn spawn_reader(
1310    name: &str,
1311    counters: Arc<CaptureStats>,
1312    read: impl FnOnce(&CaptureStats) + Send + 'static,
1313) -> std::io::Result<JoinHandle<()>> {
1314    let link = name.to_owned();
1315    thread::Builder::new()
1316        .name(format!("capture-{name}"))
1317        .spawn(move || {
1318            let _mark = DeafOnUnwind {
1319                counters: &counters,
1320                link: &link,
1321            };
1322            read(&counters);
1323        })
1324}
1325
1326/// Marks a capture stopped early when its reader unwinds. See [`spawn_reader`].
1327struct DeafOnUnwind<'a> {
1328    counters: &'a CaptureStats,
1329    link: &'a str,
1330}
1331
1332impl Drop for DeafOnUnwind<'_> {
1333    fn drop(&mut self) {
1334        if thread::panicking() {
1335            self.counters.stopped_early.store(true, Ordering::Relaxed);
1336            error!(
1337                "the capture on {} failed and will hear nothing further; replies \
1338                 arriving on this link are lost from here on",
1339                self.link
1340            );
1341        }
1342    }
1343}
1344
1345/// When the kernel says it saw this frame.
1346///
1347/// Wall-clock, because it answers "when was this host last heard from", which a reader
1348/// places against everything else in the record. A frame whose timestamp cannot be
1349/// represented is stamped with the epoch: the frame is still evidence.
1350fn timestamp_of(packet: &pcap::Packet<'_>) -> SystemTime {
1351    let seconds = u64::try_from(packet.header.ts.tv_sec).unwrap_or(0);
1352    let micros = u32::try_from(packet.header.ts.tv_usec).unwrap_or(0);
1353    UNIX_EPOCH + Duration::new(seconds, micros.saturating_mul(1_000))
1354}
1355
1356/// The name of the capture device for the interface named `name`.
1357///
1358/// On Unix the two share a name. On Windows they do not: an interface is named
1359/// by its adapter GUID, `{…}`, and Npcap names the same adapter under its own
1360/// prefix, `\Device\NPF_{…}`. See [`npcap_device_name`].
1361fn device_name(name: &str) -> String {
1362    #[cfg(windows)]
1363    {
1364        npcap_device_name(name)
1365    }
1366    #[cfg(not(windows))]
1367    {
1368        name.to_owned()
1369    }
1370}
1371
1372/// The name Npcap gives the adapter an interface list names `name`.
1373///
1374/// Npcap lists an adapter as `\Device\NPF_` followed by the GUID Windows names it by,
1375/// and its device list and open call use that full form. A name already in that form,
1376/// or one that is not a GUID, such as Npcap's own loopback adapter, is passed through
1377/// unchanged.
1378#[cfg_attr(not(windows), allow(dead_code))]
1379fn npcap_device_name(name: &str) -> String {
1380    if name.starts_with('{') {
1381        format!("\\Device\\NPF_{name}")
1382    } else {
1383        name.to_owned()
1384    }
1385}
1386
1387/// A capture [`open`] brought up, with what it is and what `libpcap` said about
1388/// bringing it up.
1389struct Opened {
1390    capture: Capture<Active>,
1391    /// How its frames are framed.
1392    link: LinkType,
1393    /// The warning `libpcap` activated it under, if any. See [`libpcap`].
1394    warning: Option<String>,
1395    /// The clauses of its filter this link could not express, and so does not admit.
1396    /// See [`CaptureFilter`].
1397    left_out: Vec<String>,
1398}
1399
1400/// Opens and activates a single filtered capture, returning it with the [`LinkType`]
1401/// its frames must be parsed as.
1402///
1403/// On Unix the capture is put into non-blocking mode and the reader waits on the
1404/// descriptor itself. `libpcap`'s read timeout cannot replace that: Linux's
1405/// memory-mapped `TPACKET` path uses it only as the timeout of its own internal `poll`
1406/// and polls again instead of returning, so a blocking read on an interface seeing no
1407/// matching frames never returns and the stop flag is never checked. BSD's `BPF`
1408/// (macOS) does return on timeout.
1409fn open(name: &str, options: &CaptureOptions) -> Result<Opened, CaptureError> {
1410    let (capture, warning) = libpcap::activate(
1411        name,
1412        &libpcap::Setup {
1413            snaplen: saturating_i32(options.snaplen),
1414            promiscuous: options.promiscuous,
1415            timeout_ms: READ_TIMEOUT_MS,
1416            immediate: true,
1417            // Left alone unless asked for, so an unchosen buffer size keeps the
1418            // platform `libpcap`'s default.
1419            buffer_bytes: options.buffer_bytes.map(saturating_i32),
1420        },
1421    )?;
1422
1423    #[cfg(not(windows))]
1424    let capture = capture.setnonblock().map_err(|source| CaptureError::Open {
1425        interface: name.to_owned(),
1426        source: LibraryError::new(source),
1427    })?;
1428
1429    let mut capture = capture;
1430    let link = LinkType::from_dlt(capture.get_datalink().0);
1431    if let LinkType::Unsupported(dlt) = link {
1432        return Err(CaptureError::UnsupportedLinkType {
1433            interface: name.to_owned(),
1434            dlt,
1435        });
1436    }
1437
1438    let (filter, left_out) = options.filter.for_link(&capture)?;
1439    capture
1440        .filter(&filter, true)
1441        .map_err(|source| CaptureError::Filter {
1442            filter,
1443            source: LibraryError::new(source),
1444        })?;
1445
1446    Ok(Opened {
1447        capture,
1448        link,
1449        warning,
1450        left_out,
1451    })
1452}
1453
1454/// Narrows a byte count to the signed width `libpcap` takes, saturating.
1455///
1456/// Both settings this converts are sizes, meaningless when negative: a wrapped
1457/// snapshot length is a capture that keeps nothing, which would read as a quiet
1458/// network. [`CaptureOptions`] uses `u32`; this is where the library's `i32` is met.
1459fn saturating_i32(bytes: u32) -> i32 {
1460    i32::try_from(bytes).unwrap_or(i32::MAX)
1461}
1462
1463/// Read loop for one capture: hands every admitted frame to `deliver` until it asks to
1464/// stop, the stop flag is set, or the capture fails. No frame ready is the normal idle
1465/// case.
1466///
1467/// `deliver` gets the whole `libpcap` packet, its bytes and the header carrying the
1468/// kernel's timestamp, and returns whether to carry on. Both outputs this module offers
1469/// are built on it, so the shutdown discipline, the poll and the counter cadence exist
1470/// once.
1471///
1472/// The loop also keeps `counters` current, since what this thread fails to read in time
1473/// is invisible everywhere else: a frame the kernel discards for lack of buffer space
1474/// never reaches the channel.
1475fn reader_loop(
1476    mut capture: Capture<Active>,
1477    stop: &AtomicBool,
1478    name: &str,
1479    counters: &CaptureStats,
1480    mut deliver: impl FnMut(&pcap::Packet<'_>) -> ControlFlow<()>,
1481) {
1482    #[cfg(not(windows))]
1483    let fd = capture.as_raw_fd();
1484    let mut since_refresh: u32 = 0;
1485
1486    while !stop.load(Ordering::Relaxed) {
1487        // Whether this iteration read a frame, decided inside the match and acted on
1488        // after it: the packet borrows the capture, and refreshing the counters needs
1489        // it back.
1490        let mut read_frame = false;
1491
1492        match capture.next_packet() {
1493            Ok(packet) => {
1494                read_frame = true;
1495                if deliver(&packet).is_break() {
1496                    break;
1497                }
1498            }
1499            Err(pcap::Error::TimeoutExpired) => {}
1500            Err(e) => {
1501                // Recorded as well as logged. This thread is the only reader of this
1502                // interface, so ending here makes it deaf for the rest of the scan,
1503                // and every reply that would have arrived is silence a scanner cannot
1504                // tell from a host that did not answer. `CaptureCounts` is the record
1505                // of that loss.
1506                if ends_the_link(&e) {
1507                    counters.stopped_early.store(true, Ordering::Relaxed);
1508                    error!(
1509                        "capture on {name} stopped and will hear nothing further \
1510                         ({e}); replies arriving on this link are lost from here on"
1511                    );
1512                }
1513                break;
1514            }
1515        }
1516
1517        since_refresh += u32::from(read_frame);
1518        if since_refresh >= STATS_EVERY_FRAMES {
1519            refresh(&mut capture, counters);
1520            since_refresh = 0;
1521        }
1522
1523        // Idle is the cheapest moment to refresh: nothing waits on this thread, and a
1524        // scan that ends quietly gets a final count.
1525        if !read_frame {
1526            refresh(&mut capture, counters);
1527            since_refresh = 0;
1528            #[cfg(not(windows))]
1529            wait_readable(fd, READ_TIMEOUT_MS);
1530        }
1531    }
1532
1533    refresh(&mut capture, counters);
1534    let counts = counters.snapshot();
1535    if counts.dropped > 0 || counts.if_dropped > 0 {
1536        info!(
1537            verbosity = 1,
1538            "capture on {name} lost frames: {} dropped, {} dropped by the interface, of {} received",
1539            counts.dropped,
1540            counts.if_dropped,
1541            counts.received
1542        );
1543    }
1544}
1545
1546/// Whether a capture ending on `error` leaves the link deaf, or just reached the end
1547/// of its input.
1548///
1549/// This is what [`CaptureCounts::stopped_early`] means, as a function so it can be
1550/// tested. A live capture never runs out of packets, so `NoMorePackets` is a savefile
1551/// ending normally; anything else is a receive path that stopped part-way through a
1552/// scan.
1553///
1554/// [`CaptureCounts::stopped_early`]: crate::model::capture::CaptureCounts::stopped_early
1555fn ends_the_link(error: &pcap::Error) -> bool {
1556    !matches!(
1557        error,
1558        pcap::Error::NoMorePackets | pcap::Error::TimeoutExpired
1559    )
1560}
1561
1562/// Copies `libpcap`'s current counters into `counters`.
1563///
1564/// Failures are not reported. `pcap_stats` is unsupported on some capture sources,
1565/// which would otherwise log once per refresh for the whole scan; the counters stay
1566/// where they were, and a stalled count is visible next to a running scan.
1567fn refresh(capture: &mut Capture<Active>, counters: &CaptureStats) {
1568    if let Ok(stat) = capture.stats() {
1569        counters.store(&stat);
1570    }
1571}
1572
1573/// Waits for `fd` to have a frame ready, giving up after `timeout_ms` so the caller can
1574/// re-check its stop flag or deadline. Poll failures are not reported: the next read
1575/// reports anything really wrong, and an interrupted poll costs one extra loop.
1576#[cfg(not(windows))]
1577fn wait_readable(fd: std::os::unix::io::RawFd, timeout_ms: i32) {
1578    let mut poll_fd = libc::pollfd {
1579        fd,
1580        events: libc::POLLIN,
1581        revents: 0,
1582    };
1583
1584    // SAFETY: `poll_fd` is a single initialized `pollfd` and the count says so; `poll`
1585    // reads it and writes only `revents`.
1586    unsafe { libc::poll(&mut poll_fd, 1, timeout_ms) };
1587}
1588
1589/// A handle for putting whole frames on a link.
1590///
1591/// The send half of the library the receive half uses. Sending through another library
1592/// would open two on one interface for one scan, such as a `pnet` channel whose
1593/// receiver is discarded beside the `pcap` capture, and a discarded receiver is a
1594/// kernel buffer nothing drains.
1595///
1596/// A separate handle from the reading one, because a capture cannot be read and
1597/// written through the same borrow while a reader thread is parked in `next_packet`.
1598pub struct FrameSender {
1599    capture: Capture<Active>,
1600}
1601
1602impl FrameSender {
1603    /// Opens a send-only handle on `link`.
1604    ///
1605    /// The filter cannot match: a capture with no filter would fill a kernel buffer
1606    /// nobody reads. `less 0` asks for frames shorter than nothing.
1607    pub fn open(link: &str) -> Result<Self, CaptureError> {
1608        let (mut capture, _) = libpcap::activate(
1609            link,
1610            &libpcap::Setup {
1611                snaplen: 1,
1612                promiscuous: false,
1613                timeout_ms: 1,
1614                immediate: false,
1615                buffer_bytes: None,
1616            },
1617        )?;
1618
1619        capture
1620            .filter("less 0", true)
1621            .map_err(|source| CaptureError::Open {
1622                interface: link.to_owned(),
1623                source: LibraryError::new(source),
1624            })?;
1625
1626        Ok(Self { capture })
1627    }
1628}
1629
1630impl FrameSink for FrameSender {
1631    fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
1632        self.capture.sendpacket(frame).map_err(|e| e.to_string())
1633    }
1634}
1635
1636/// Somewhere to put a frame.
1637///
1638/// A trait because it is the seam a test drives a scanner through, as [`FrameStream`]
1639/// is on the receive side. A fake segment implements this, observes what a scanner
1640/// emits, and answers on the stream, with no interface and no privileges.
1641pub trait FrameSink: Send {
1642    /// Puts `frame` on the wire whole, link header included.
1643    ///
1644    /// The error is a string because a caller can only report it. What matters at the
1645    /// call site is that a failure means the frame did not leave.
1646    fn send_frame(&mut self, frame: &[u8]) -> Result<(), String>;
1647}
1648
1649/// One link, opened for both directions and driven by a single thread.
1650///
1651/// The shape a request-and-wait exchange wants: put a frame on the wire, then read
1652/// until the answer arrives or the deadline passes. Both halves borrow the same handle
1653/// mutably, so this is one type, and not what [`frames`] gives a scanner, whose reader
1654/// lives on its own thread.
1655///
1656/// The filter is the caller's, since the reader decides what a frame is worth.
1657pub struct FrameChannel {
1658    capture: Capture<Active>,
1659    /// How long [`next_frame`](Self::next_frame) waits for a frame. Windows has no
1660    /// descriptor to wait on, and its capture's own read timeout does the waiting.
1661    #[cfg(not(windows))]
1662    wait_ms: i32,
1663    /// The frame [`next_frame`](Self::next_frame) last read, copied out of `libpcap`'s
1664    /// buffer so reading it and waiting for it can be separate steps.
1665    frame: Vec<u8>,
1666}
1667
1668impl FrameChannel {
1669    /// Opens `link` for sending and receiving, admitting what `filter` admits.
1670    ///
1671    /// `read_timeout` bounds how long [`next_frame`](Self::next_frame) waits, so a
1672    /// caller with a deadline can honour it.
1673    pub fn open(
1674        link: &str,
1675        filter: &str,
1676        read_timeout: std::time::Duration,
1677    ) -> Result<Self, CaptureError> {
1678        let wait_ms = i32::try_from(read_timeout.as_millis()).unwrap_or(i32::MAX);
1679        let (capture, _) = libpcap::activate(
1680            link,
1681            &libpcap::Setup {
1682                snaplen: saturating_i32(REPLY_SNAP_LEN),
1683                promiscuous: false,
1684                timeout_ms: wait_ms,
1685                immediate: true,
1686                buffer_bytes: None,
1687            },
1688        )?;
1689
1690        // Non-blocking, with the wait done on the descriptor, as in `open`: on Linux a
1691        // blocking read waits for a frame whatever the read timeout says. See
1692        // `next_frame`.
1693        #[cfg(not(windows))]
1694        let capture = capture.setnonblock().map_err(|source| CaptureError::Open {
1695            interface: link.to_owned(),
1696            source: LibraryError::new(source),
1697        })?;
1698
1699        let mut capture = capture;
1700        capture
1701            .filter(filter, true)
1702            .map_err(|source| CaptureError::Filter {
1703                filter: filter.to_owned(),
1704                source: LibraryError::new(source),
1705            })?;
1706
1707        Ok(Self {
1708            capture,
1709            #[cfg(not(windows))]
1710            wait_ms,
1711            frame: Vec::new(),
1712        })
1713    }
1714
1715    /// The next frame the filter admitted, or `None` if none arrived within the read
1716    /// timeout. A caller with deadline left should ask again.
1717    ///
1718    /// # How the wait is bounded
1719    ///
1720    /// On Unix the read never blocks. A frame already waiting is returned at once;
1721    /// otherwise the wait is a `poll` on the capture's descriptor, bounded by the read
1722    /// timeout, followed by one more read. Every reader thread here does the same,
1723    /// because `libpcap`'s read timeout does not bound a blocking read on Linux: an
1724    /// address resolution waiting on a neighbour that will never answer would wait for
1725    /// an unrelated frame to pass the filter, which on a quiet link is never.
1726    ///
1727    /// The read comes before the wait because `libpcap` may already hold frames it read
1728    /// from the kernel in one batch, which the descriptor would not announce. Windows
1729    /// keeps the blocking read, whose timeout Npcap honours.
1730    pub fn next_frame(&mut self) -> Option<&[u8]> {
1731        if self.read_one() {
1732            return Some(&self.frame);
1733        }
1734
1735        #[cfg(not(windows))]
1736        {
1737            wait_readable(self.capture.as_raw_fd(), self.wait_ms);
1738            if self.read_one() {
1739                return Some(&self.frame);
1740            }
1741        }
1742
1743        None
1744    }
1745
1746    /// Reads one frame into `frame`, if one is ready, and says whether one was.
1747    fn read_one(&mut self) -> bool {
1748        match self.capture.next_packet() {
1749            Ok(packet) => {
1750                self.frame.clear();
1751                self.frame.extend_from_slice(packet.data);
1752                true
1753            }
1754            Err(_) => false,
1755        }
1756    }
1757}
1758
1759impl FrameSink for FrameChannel {
1760    fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
1761        self.capture.sendpacket(frame).map_err(|e| e.to_string())
1762    }
1763}
1764
1765/// Brings a capture handle up: the one step taken through `libpcap` directly instead
1766/// of the `pcap` crate.
1767///
1768/// # Why this step
1769///
1770/// `pcap_activate` has three kinds of answer. Zero is success and a negative status is
1771/// failure. A positive status is a *warning*: the handle is live and capturing, but not
1772/// quite what was asked for. `PCAP_WARNING_PROMISC_NOTSUP` is a link that will not go
1773/// promiscuous. `PCAP_WARNING` is, among other things, how Linux brings up a link whose
1774/// hardware type `libpcap` cannot map (a GRE tunnel, an `ip6tnl` or `ip6gre` link),
1775/// which it serves cooked as `DLT_LINUX_SLL` and [`LinkType::LinuxSll`] reads.
1776///
1777/// The `pcap` crate's `Capture::open` treats every non-zero status as failure and
1778/// closes the handle, warnings included. Through it, a GRE tunnel, or any link that
1779/// declined to be promiscuous, could not be captured on, and a scan through one would
1780/// read its targets as down.
1781///
1782/// The crate offers no way round that: a handle becomes active only through that call,
1783/// and cannot move from the crate's inactive type to its active one without closing
1784/// it or leaking its wrapper. So the handle is created and activated here and adopted
1785/// into a `Capture<Active>` immediately, through the crate's conversion for a raw
1786/// handle. From then on every read, filter, statistic, send and the close go through
1787/// the crate's API.
1788///
1789/// Forking the crate would mean carrying a fork for one comparison, and capturing on
1790/// Linux's `any` device would serve only Linux and copy every link's traffic into the
1791/// filter. The seam here is eight functions `libpcap` has exported unchanged since 1.5,
1792/// all of which the crate also declares, so linking asks nothing new of `libpcap` or
1793/// Npcap.
1794mod libpcap {
1795    use std::ffi::{CStr, CString, c_char, c_int};
1796    use std::marker::{PhantomData, PhantomPinned};
1797    use std::ptr::NonNull;
1798
1799    use pcap::{Active, Capture};
1800
1801    use super::{CaptureError, LibraryError, device_name};
1802
1803    /// `libpcap`'s capture handle, which this side only holds a pointer to.
1804    ///
1805    /// Declared here because the `pcap` crate keeps its bindings private. The pointer
1806    /// is converted to the crate's type once, in [`activate`]; both name the same C
1807    /// struct.
1808    #[repr(C)]
1809    struct Handle {
1810        _opaque: [u8; 0],
1811        _unmovable: PhantomData<(*mut u8, PhantomPinned)>,
1812    }
1813
1814    /// The size `libpcap` requires of the buffer `pcap_create` writes an error into,
1815    /// `PCAP_ERRBUF_SIZE`.
1816    const ERRBUF_SIZE: usize = 256;
1817
1818    // `pcap_activate`'s statuses, from `pcap/pcap.h`. Negative statuses are failures
1819    // and positive ones warnings; these are the ones this module names itself where
1820    // `libpcap` left its error buffer empty.
1821    const PCAP_WARNING: c_int = 1;
1822    const PCAP_WARNING_PROMISC_NOTSUP: c_int = 2;
1823    const PCAP_WARNING_TSTAMP_TYPE_NOTSUP: c_int = 3;
1824    pub(super) const PCAP_ERROR_NO_SUCH_DEVICE: c_int = -5;
1825    pub(super) const PCAP_ERROR_PERM_DENIED: c_int = -8;
1826    const PCAP_ERROR_IFACE_NOT_UP: c_int = -9;
1827    pub(super) const PCAP_ERROR_PROMISC_PERM_DENIED: c_int = -11;
1828
1829    unsafe extern "C" {
1830        fn pcap_create(source: *const c_char, errbuf: *mut c_char) -> *mut Handle;
1831        fn pcap_set_snaplen(handle: *mut Handle, snaplen: c_int) -> c_int;
1832        fn pcap_set_promisc(handle: *mut Handle, promisc: c_int) -> c_int;
1833        fn pcap_set_timeout(handle: *mut Handle, to_ms: c_int) -> c_int;
1834        fn pcap_set_immediate_mode(handle: *mut Handle, immediate: c_int) -> c_int;
1835        fn pcap_set_buffer_size(handle: *mut Handle, buffer_size: c_int) -> c_int;
1836        fn pcap_activate(handle: *mut Handle) -> c_int;
1837        fn pcap_geterr(handle: *mut Handle) -> *mut c_char;
1838    }
1839
1840    /// What a handle is set to before it is activated.
1841    ///
1842    /// Grouped because `libpcap` accepts each only on a handle not yet activated, and
1843    /// the crate's builders for them are on the type this module does not use.
1844    pub(super) struct Setup {
1845        pub(super) snaplen: c_int,
1846        pub(super) promiscuous: bool,
1847        pub(super) timeout_ms: c_int,
1848        pub(super) immediate: bool,
1849        /// `None` leaves `libpcap`'s own default in place.
1850        pub(super) buffer_bytes: Option<c_int>,
1851    }
1852
1853    /// Creates a capture handle on `link`, sets it up, and activates it, returning it
1854    /// with the warning it was activated under, if any.
1855    ///
1856    /// A warning is not a failure: the handle is live, and the warning says how it
1857    /// differs from what was asked for. The caller decides whether to report it.
1858    pub(super) fn activate(
1859        link: &str,
1860        setup: &Setup,
1861    ) -> Result<(Capture<Active>, Option<String>), CaptureError> {
1862        let device = CString::new(device_name(link)).map_err(|_| CaptureError::Open {
1863            interface: link.to_owned(),
1864            source: LibraryError::new(pcap::Error::InvalidInputString),
1865        })?;
1866
1867        let mut errbuf = [0 as c_char; ERRBUF_SIZE];
1868        // SAFETY: `device` is a NUL-terminated string that outlives the call,
1869        // and `errbuf` is the `PCAP_ERRBUF_SIZE` bytes `pcap_create` may write.
1870        let created = unsafe { pcap_create(device.as_ptr(), errbuf.as_mut_ptr()) };
1871        let Some(created) = NonNull::new(created) else {
1872            // SAFETY: on failure `pcap_create` has written a NUL-terminated message
1873            // into `errbuf`, which was zeroed, so it is terminated either way.
1874            let message = unsafe { CStr::from_ptr(errbuf.as_ptr()) };
1875            return Err(CaptureError::Open {
1876                interface: link.to_owned(),
1877                source: LibraryError::new(pcap::Error::PcapError(
1878                    message.to_string_lossy().into_owned(),
1879                )),
1880            });
1881        };
1882
1883        // Adopted before activation, so every path out of this function, the failures
1884        // below included, closes it through the crate's `Drop`, as `libpcap` asks for a
1885        // handle whose activation failed. Only the pointer is read from it until
1886        // activation succeeds.
1887        let capture: Capture<Active> = Capture::from(created.cast());
1888        let handle = capture.as_ptr().cast::<Handle>();
1889
1890        // SAFETY: `handle` is the live handle `pcap_create` returned, owned by
1891        // `capture` for the rest of this function, and not yet activated, the only
1892        // state in which these calls are defined. Each errors only on an activated
1893        // handle.
1894        unsafe {
1895            pcap_set_snaplen(handle, setup.snaplen);
1896            pcap_set_promisc(handle, c_int::from(setup.promiscuous));
1897            pcap_set_timeout(handle, setup.timeout_ms);
1898            pcap_set_immediate_mode(handle, c_int::from(setup.immediate));
1899            if let Some(bytes) = setup.buffer_bytes {
1900                pcap_set_buffer_size(handle, bytes);
1901            }
1902        }
1903
1904        // SAFETY: as above; these settings were made for this activation.
1905        let status = unsafe { pcap_activate(handle) };
1906        let message = || status_message(handle, status);
1907
1908        match status {
1909            0 => Ok((capture, None)),
1910            warning if warning > 0 => Ok((capture, Some(message()))),
1911            failure => Err(refusal(link, failure, message())),
1912        }
1913    }
1914
1915    /// The error reported for a handle that failed to activate with `status`.
1916    ///
1917    /// Privilege is read from the status alone. `libpcap` reports a missing privilege
1918    /// as its own status on every platform, while its wording differs between
1919    /// platforms and releases, so matching the words would misattribute failures.
1920    pub(super) fn refusal(link: &str, status: c_int, message: String) -> CaptureError {
1921        let source = LibraryError::new(pcap::Error::PcapError(message));
1922        match status {
1923            PCAP_ERROR_PERM_DENIED | PCAP_ERROR_PROMISC_PERM_DENIED => CaptureError::Denied {
1924                interface: link.to_owned(),
1925                source,
1926            },
1927            _ => CaptureError::Open {
1928                interface: link.to_owned(),
1929                source,
1930            },
1931        }
1932    }
1933
1934    /// What `libpcap` said about `status`, in its own words where it wrote some.
1935    ///
1936    /// `pcap_geterr` holds the detail for most statuses and is empty for a few, where
1937    /// the status is all that is known. Those are named here as `pcap_statustostr`
1938    /// would, since that function is not declared by the crate.
1939    fn status_message(handle: *mut Handle, status: c_int) -> String {
1940        // SAFETY: `handle` is live, and `pcap_geterr` returns a NUL-terminated pointer
1941        // into it, valid until the next call on the handle. It is copied out first.
1942        let said = unsafe { CStr::from_ptr(pcap_geterr(handle)) }
1943            .to_string_lossy()
1944            .into_owned();
1945        if !said.is_empty() {
1946            return said;
1947        }
1948
1949        match status {
1950            PCAP_WARNING => "a generic warning".to_owned(),
1951            PCAP_WARNING_PROMISC_NOTSUP => {
1952                "this device does not support promiscuous mode".to_owned()
1953            }
1954            PCAP_WARNING_TSTAMP_TYPE_NOTSUP => {
1955                "this device does not support the requested timestamp type".to_owned()
1956            }
1957            PCAP_ERROR_NO_SUCH_DEVICE => "no such device exists".to_owned(),
1958            PCAP_ERROR_PERM_DENIED => "permission denied".to_owned(),
1959            PCAP_ERROR_IFACE_NOT_UP => "the interface is not up".to_owned(),
1960            PCAP_ERROR_PROMISC_PERM_DENIED => {
1961                "permission denied to put it in promiscuous mode".to_owned()
1962            }
1963            other => format!("activation failed with status {other}"),
1964        }
1965    }
1966}
1967
1968// ╔════════════════════════════════════════════╗
1969// ║ ████████╗███████╗███████╗████████╗███████╗ ║
1970// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
1971// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
1972// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
1973// ║    ██║   ███████╗███████║   ██║   ███████║ ║
1974// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
1975// ╚════════════════════════════════════════════╝
1976
1977#[cfg(test)]
1978mod tests {
1979
1980    /// An adapter that refuses is named once, and the capture library's own words say
1981    /// why. The `pcap` crate prefixes every message with `libpcap error:`, which on
1982    /// Windows reads as a missing library when Npcap is installed and has said exactly
1983    /// what is wrong.
1984    #[test]
1985    fn a_refused_open_names_the_adapter_once_and_quotes_the_library() {
1986        let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
1987        let message = "Error opening adapter: Network interface was not found.";
1988        let refused = CaptureError::Open {
1989            interface: guid.to_owned(),
1990            source: LibraryError::new(pcap::Error::PcapError(message.to_owned())),
1991        };
1992
1993        assert_eq!(
1994            refused.to_string(),
1995            format!("{guid} could not be opened: {message}")
1996        );
1997        assert_eq!(refused.reason(), message, "the reason leaves the name out");
1998    }
1999
2000    /// A link refused for want of privilege is reported as such, and one refused for
2001    /// anything else is not.
2002    ///
2003    /// The status decides it: `libpcap` reports a missing privilege as its own status,
2004    /// and blaming privilege for a failure it did not cause misleads someone who
2005    /// already has it.
2006    #[test]
2007    fn only_a_refusal_libpcap_reports_as_denied_is_blamed_on_privilege() {
2008        for status in [
2009            libpcap::PCAP_ERROR_PERM_DENIED,
2010            libpcap::PCAP_ERROR_PROMISC_PERM_DENIED,
2011        ] {
2012            let refused =
2013                libpcap::refusal("eth0", status, "socket: Operation not permitted".into());
2014            assert!(refused.is_denied(), "status {status}");
2015            assert!(refused.to_string().contains("privileges"), "{refused}");
2016        }
2017
2018        for status in [libpcap::PCAP_ERROR_NO_SUCH_DEVICE, -1] {
2019            let refused = libpcap::refusal("eth0", status, "no such device".into());
2020            assert!(!refused.is_denied(), "status {status}");
2021            assert!(!refused.to_string().contains("privilege"), "{refused}");
2022        }
2023    }
2024
2025    /// A link refused because the process had no descriptor left is told apart from
2026    /// one that declined, so the capture can refuse whole instead of listening on the
2027    /// links it reached and reading the rest's replies as silence. `libpcap` gives the
2028    /// shortage the status of any failure to open, and says which it was only in the C
2029    /// library's words for the errno.
2030    #[cfg(unix)]
2031    #[test]
2032    fn a_link_refused_for_want_of_a_descriptor_is_told_apart_from_one_that_declined() {
2033        let words = |code| {
2034            let error = std::io::Error::from_raw_os_error(code).to_string();
2035            error.split(" (os error").next().unwrap().to_owned()
2036        };
2037        for code in [libc::EMFILE, libc::ENFILE] {
2038            let refused = libpcap::refusal(
2039                "utun4",
2040                -1,
2041                format!("(cannot open BPF device) /dev/bpf0: {}", words(code)),
2042            );
2043            assert!(refused.is_exhausted(), "{refused}");
2044            assert!(!refused.is_denied());
2045        }
2046
2047        let declined = libpcap::refusal("utun4", -1, "no such device".into());
2048        assert!(!declined.is_exhausted());
2049        let denied = libpcap::refusal(
2050            "utun4",
2051            libpcap::PCAP_ERROR_PERM_DENIED,
2052            words(libc::EACCES),
2053        );
2054        assert!(!denied.is_exhausted());
2055
2056        let out = CaptureError::OutOfDescriptors {
2057            links: vec!["utun4".into(), "utun5".into()],
2058        };
2059        assert_eq!(
2060            out.to_string(),
2061            "no capture on 2 links (file limit reached)"
2062        );
2063    }
2064
2065    /// A capture no link would take names each link and its reason, and blames
2066    /// privilege in one sentence only where privilege refused them all.
2067    #[test]
2068    fn a_capture_no_link_would_take_says_why_each_refused() {
2069        let denied = |link: &str| CaptureError::Denied {
2070            interface: link.to_owned(),
2071            source: LibraryError::new(pcap::Error::PcapError("Operation not permitted".into())),
2072        };
2073        let filter = CaptureError::Filter {
2074            filter: "ether dst 02:00:00:00:00:01".into(),
2075            source: LibraryError::new(pcap::Error::PcapError(
2076                "ethernet addresses supported only on ethernet/FDDI/token ring".into(),
2077            )),
2078        };
2079
2080        let unprivileged = CaptureError::NoInterface {
2081            refused: vec![
2082                ("eth0".into(), denied("eth0")),
2083                ("wg0".into(), denied("wg0")),
2084            ],
2085        };
2086        assert!(unprivileged.is_denied());
2087        assert_eq!(
2088            unprivileged.to_string(),
2089            "no link could be captured on, so nothing could be heard: this process may \
2090             not capture (opening a capture needs root)"
2091        );
2092
2093        let root = CaptureError::NoInterface {
2094            refused: vec![("wg0".into(), filter)],
2095        };
2096        assert!(!root.is_denied());
2097        let said = root.to_string();
2098        assert!(said.contains("wg0: the filter"), "{said}");
2099        assert!(said.contains("ethernet addresses"), "{said}");
2100        assert!(
2101            !said.contains("root") && !said.contains("privilege"),
2102            "{said}"
2103        );
2104
2105        let mixed = CaptureError::NoInterface {
2106            refused: vec![
2107                ("eth0".into(), denied("eth0")),
2108                (
2109                    "gre1".into(),
2110                    CaptureError::UnsupportedLinkType {
2111                        interface: "gre1".into(),
2112                        dlt: 778,
2113                    },
2114                ),
2115            ],
2116        };
2117        assert!(
2118            !mixed.is_denied(),
2119            "privilege would not have made gre1 parseable"
2120        );
2121        let said = mixed.to_string();
2122        assert!(
2123            said.contains("eth0: this process lacks the privileges"),
2124            "{said}"
2125        );
2126        assert!(
2127            said.contains("gre1: it carries data-link type 778"),
2128            "{said}"
2129        );
2130    }
2131
2132    /// Links refused for one reason are told it once, with how many there were, and a
2133    /// link refused for its own reason keeps its name.
2134    ///
2135    /// A process out of descriptors is refused on every link in the same words; told
2136    /// per link, one fact would run to two thousand characters on a machine with a few
2137    /// dozen interfaces.
2138    #[test]
2139    fn links_refused_for_one_reason_are_told_it_once() {
2140        let exhausted = |link: &str| {
2141            (
2142                link.to_owned(),
2143                CaptureError::Open {
2144                    interface: link.to_owned(),
2145                    source: LibraryError::new(pcap::Error::PcapError(
2146                        "/dev/bpf: Too many open files".into(),
2147                    )),
2148                },
2149            )
2150        };
2151        let links = ["en0", "en1", "utun0", "bridge0"];
2152
2153        let alike = CaptureError::NoInterface {
2154            refused: links.iter().map(|link| exhausted(link)).collect(),
2155        };
2156        assert_eq!(
2157            alike.to_string(),
2158            "no link could be captured on, so nothing could be heard: \
2159             /dev/bpf: Too many open files (4 links)"
2160        );
2161
2162        let mut refused: Vec<_> = links.iter().map(|link| exhausted(link)).collect();
2163        refused.insert(
2164            1,
2165            (
2166                "gre1".into(),
2167                CaptureError::UnsupportedLinkType {
2168                    interface: "gre1".into(),
2169                    dlt: 778,
2170                },
2171            ),
2172        );
2173        assert_eq!(
2174            CaptureError::NoInterface { refused }.reason(),
2175            "/dev/bpf: Too many open files (4 links); \
2176             gre1: it carries data-link type 778, which nothing here parses"
2177        );
2178    }
2179
2180    /// Through the real opening path: a link that does not exist is refused, and the
2181    /// error blames privilege exactly when the refusal was one.
2182    ///
2183    /// Which refusal a machine gives varies. An unprivileged Linux process is denied
2184    /// before the device is looked up, and a macOS user in `access_bpf` or a root
2185    /// process is told there is no such device. The property holds in both, and the
2186    /// link is named wherever privilege is not the whole answer.
2187    #[test]
2188    fn a_capture_that_could_not_open_blames_privilege_only_when_it_was_denied() {
2189        let link = Zone::unresolved("zondnone0");
2190        let refused = frames(
2191            std::slice::from_ref(&link),
2192            &CaptureOptions::for_replies("tcp"),
2193            1,
2194        )
2195        .err()
2196        .expect("no such link can be captured on");
2197        let said = refused.to_string();
2198
2199        assert_eq!(said.contains("needs root"), refused.is_denied(), "{said}");
2200        if !refused.is_denied() {
2201            assert!(said.contains("zondnone0"), "{said}");
2202            assert!(!said.contains("privilege"), "{said}");
2203        }
2204    }
2205
2206    /// A dead capture of `dlt`, which compiles filters for that link type with
2207    /// no device behind it.
2208    fn link_of(dlt: i32) -> Capture<pcap::Dead> {
2209        Capture::dead(pcap::Linktype(dlt)).expect("a dead capture")
2210    }
2211
2212    /// `DLT_RAW`, how a WireGuard or IP-in-IP tunnel comes up on Linux.
2213    const RAW: i32 = 12;
2214
2215    /// Of a set of alternatives, a link keeps the ones it can express, leaves out the
2216    /// rest, and says which it left out.
2217    #[test]
2218    fn alternatives_are_narrowed_to_what_a_link_can_express() {
2219        let filter = CaptureFilter::any_of(["(ether dst 01:00:0c:cc:cc:cc)", "(tcp)"]);
2220
2221        let (expression, left_out) = filter.for_link(&link_of(RAW)).expect("tcp compiles");
2222        assert_eq!(expression, "(tcp)");
2223        assert_eq!(left_out, ["(ether dst 01:00:0c:cc:cc:cc)"]);
2224
2225        let (expression, left_out) = filter
2226            .for_link(&link_of(1))
2227            .expect("Ethernet expresses both");
2228        assert_eq!(expression, "(ether dst 01:00:0c:cc:cc:cc) or (tcp)");
2229        assert!(left_out.is_empty());
2230    }
2231
2232    /// A clause nothing can express is a mistake, and is refused.
2233    ///
2234    /// Leaving a clause out is sound only because the link could not carry what it
2235    /// matches. A typo matches nothing anywhere, and dropping it silently would hide
2236    /// traffic on every link with nothing said.
2237    #[test]
2238    fn a_clause_no_link_can_express_is_refused_rather_than_left_out() {
2239        let filter = CaptureFilter::any_of(["(tcp)", "(ether dts 01:00:0c:cc:cc:cc)"]);
2240
2241        for dlt in [RAW, 1] {
2242            match filter.for_link(&link_of(dlt)) {
2243                Err(CaptureError::Filter { filter, .. }) => {
2244                    assert_eq!(filter, "(ether dts 01:00:0c:cc:cc:cc)");
2245                }
2246                other => panic!("a malformed clause was accepted on {dlt}: {other:?}"),
2247            }
2248        }
2249    }
2250
2251    /// A link that can express none of the alternatives is refused, naming the whole
2252    /// filter.
2253    #[test]
2254    fn a_link_that_can_express_no_alternative_is_refused() {
2255        let filter =
2256            CaptureFilter::any_of(["(ether dst 01:00:0c:cc:cc:cc)", "(ether proto 0x88cc)"]);
2257
2258        match filter.for_link(&link_of(RAW)) {
2259            Err(CaptureError::Filter { filter: named, .. }) => {
2260                assert_eq!(named, filter.to_string());
2261            }
2262            other => panic!("a filter admitting nothing was accepted: {other:?}"),
2263        }
2264    }
2265
2266    /// An expression is compiled whole. A scan's reply filter is one, since every part
2267    /// is needed to hear the answers, and a link that can express only some of it is
2268    /// refused.
2269    #[test]
2270    fn an_expression_is_never_narrowed() {
2271        let written = "tcp and ether src 02:00:00:00:00:01";
2272        let (expression, left_out) = CaptureFilter::from(written)
2273            .for_link(&link_of(RAW))
2274            .expect("an expression is handed on as written");
2275
2276        assert_eq!(expression, written);
2277        assert!(left_out.is_empty());
2278        assert!(
2279            link_of(RAW).compile(&expression, true).is_err(),
2280            "and the link then refuses it whole"
2281        );
2282    }
2283
2284    /// A frame channel bounds its own wait on the descriptor, since `libpcap`'s read
2285    /// timeout does not end a blocking read.
2286    ///
2287    /// On Linux the memory-mapped path polls again, and the read returns only when a
2288    /// frame passes the filter, so an address resolution waiting on a neighbour that
2289    /// will never answer waits as long as the link stays quiet. This holds that the
2290    /// capture is non-blocking; that the wait then ends on a quiet Linux link is Tier
2291    /// 3's to show.
2292    ///
2293    /// Needs the right to capture on loopback, and passes silently without it.
2294    #[test]
2295    fn a_frame_channel_bounds_its_wait_itself_rather_than_trusting_libpcap() {
2296        let Some(loopback) = crate::system::interface::interfaces()
2297            .expect("this machine's interfaces")
2298            .into_iter()
2299            .find(|link| link.is_loopback())
2300        else {
2301            return;
2302        };
2303
2304        let timeout = Duration::from_millis(50);
2305        let mut channel = match FrameChannel::open(loopback.name(), "less 0", timeout) {
2306            Ok(channel) => channel,
2307            Err(refused) if refused.is_denied() => return,
2308            Err(refused) => panic!("the loopback would not open: {refused}"),
2309        };
2310
2311        #[cfg(not(windows))]
2312        assert!(
2313            channel.capture.is_nonblock(),
2314            "a blocking read is bounded by nothing on Linux"
2315        );
2316
2317        let started = Instant::now();
2318        assert_eq!(channel.next_frame(), None, "`less 0` admits nothing");
2319        let waited = started.elapsed();
2320        assert!(
2321            waited >= timeout / 2 && waited < Duration::from_secs(1),
2322            "a {timeout:?} wait took {waited:?}"
2323        );
2324    }
2325
2326    /// A link the scan's answers depend on is reported on the default console, and one
2327    /// they do not where a reader asking what went uncovered looks. A host keeps
2328    /// hypervisor, VPN and bridge adapters beside the one it uses, and reporting each on
2329    /// every scan would be noise.
2330    ///
2331    /// Where no link was heard at all the capture's error names every link and its
2332    /// cause, so the lines here would only repeat it.
2333    #[test]
2334    fn a_failed_link_is_told_aloud_only_when_answers_depend_on_it() {
2335        assert_eq!(loudness(false, false), Loudness::Quiet, "a spare adapter");
2336        assert_eq!(
2337            loudness(false, true),
2338            Loudness::Aloud,
2339            "the link off-segment targets answer through"
2340        );
2341        assert_eq!(
2342            loudness(true, false),
2343            Loudness::Quiet,
2344            "no link heard at all, which the error says"
2345        );
2346        assert_eq!(
2347            loudness(true, true),
2348            Loudness::Quiet,
2349            "nor the default route's, when the error names it too"
2350        );
2351    }
2352
2353    /// Every transport a scan opens asks every link again, so a link that refused is
2354    /// reported once, and again only if it comes to matter more.
2355    #[test]
2356    fn a_failed_link_is_told_about_once_unless_it_comes_to_matter_more() {
2357        let mut told = Told::new();
2358        let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
2359
2360        assert!(told.first_time(guid, Loudness::Quiet));
2361        assert!(
2362            !told.first_time(guid, Loudness::Quiet),
2363            "a second transport"
2364        );
2365        assert!(told.first_time(guid, Loudness::Aloud), "now it matters");
2366        assert!(!told.first_time(guid, Loudness::Aloud));
2367        assert!(
2368            !told.first_time(guid, Loudness::Quiet),
2369            "said louder already"
2370        );
2371        assert!(told.first_time("eth1", Loudness::Quiet), "another link");
2372    }
2373
2374    /// Npcap opens an adapter by its own name, the Windows GUID under the driver's
2375    /// prefix. Given the bare GUID from an interface list, the capture every raw
2376    /// strategy relies on would fail to open.
2377    #[test]
2378    fn an_adapter_guid_is_named_the_way_npcap_names_it() {
2379        let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
2380        assert_eq!(npcap_device_name(guid), format!("\\Device\\NPF_{guid}"));
2381        assert_eq!(
2382            npcap_device_name(&format!("\\Device\\NPF_{guid}")),
2383            format!("\\Device\\NPF_{guid}"),
2384            "a name already in Npcap's form is left alone"
2385        );
2386        assert_eq!(npcap_device_name("en0"), "en0");
2387    }
2388
2389    /// The stamp is taken where the segment is taken, so a round trip measured against
2390    /// it carries the path and not the queue.
2391    #[test]
2392    fn a_segment_is_stamped_before_it_is_queued() {
2393        use std::net::Ipv4Addr;
2394
2395        use pnet_packet::ip::IpNextHeaderProtocols;
2396
2397        let before = Instant::now();
2398        let segment = CapturedSegment::synthetic(
2399            IpAddr::V4(Ipv4Addr::LOCALHOST),
2400            IpNextHeaderProtocols::Tcp.0,
2401            vec![0; 20],
2402        );
2403        let after = Instant::now();
2404
2405        assert!(segment.received_at >= before && segment.received_at <= after);
2406    }
2407    use super::*;
2408
2409    /// A snapshot length below what the deepest header stack needs is raised to it.
2410    ///
2411    /// The field bounds what this process can see of a payload, enforced by the
2412    /// kernel. `libpcap`'s manual leaves a zero undefined, so it must never be passed.
2413    #[test]
2414    fn a_snapshot_length_too_short_to_read_a_reply_is_raised_to_one_that_can() {
2415        for asked in [0, 1, MIN_SNAP_LEN - 1] {
2416            let options = CaptureOptions::for_replies("tcp").with_snaplen(asked);
2417            assert_eq!(
2418                options.snaplen, MIN_SNAP_LEN,
2419                "a snapshot length of {asked} reached libpcap"
2420            );
2421        }
2422
2423        // A length the caller meant is kept, on either side of the floor.
2424        for asked in [MIN_SNAP_LEN, MIN_SNAP_LEN + 1, REPLY_SNAP_LEN] {
2425            assert_eq!(
2426                CaptureOptions::for_replies("tcp")
2427                    .with_snaplen(asked)
2428                    .snaplen,
2429                asked
2430            );
2431        }
2432    }
2433
2434    /// A scan's captures keep everything a reply is read for, and no more than a
2435    /// standard Ethernet frame, at the platform's own buffer.
2436    ///
2437    /// The upper bound is what a generous setting breaks. Linux sizes its capture
2438    /// ring's slots from the snapshot length, so whole 64 KB frames fit 32 at the
2439    /// default buffer, and a scan's own bursts overflow it: answers dropped, ports
2440    /// asked again, the scan twice as slow on a path that lost nothing. The lower bound
2441    /// is the longest reply read whole, an ICMPv6 error, behind a doubly tagged
2442    /// Ethernet header. The buffer is left to the platform because a capture is opened
2443    /// on every link that is up and its buffer is paid on each.
2444    ///
2445    /// This pins the settings. That they hold a scan's bursts is measured on the wire,
2446    /// by a full-range scan's `dropped` count.
2447    #[test]
2448    fn a_scans_captures_keep_a_whole_standard_frame_and_no_more() {
2449        const STANDARD_ETHERNET_FRAME: u32 = 14 + 2 * 4 + 1_500;
2450        const LONGEST_ICMPV6_ERROR: u32 = 1_280;
2451
2452        for (opened, options) in [
2453            ("replies", CaptureOptions::for_replies("tcp")),
2454            ("link traffic", CaptureOptions::for_link_traffic("arp")),
2455        ] {
2456            assert!(
2457                options.snaplen <= STANDARD_ETHERNET_FRAME,
2458                "a capture of {opened} keeps {} bytes of a frame",
2459                options.snaplen
2460            );
2461            assert!(
2462                options.snaplen >= 14 + 2 * 4 + LONGEST_ICMPV6_ERROR,
2463                "a capture of {opened} cuts the longest reply it reads whole"
2464            );
2465            assert_eq!(
2466                options.buffer_bytes, None,
2467                "a capture of {opened} sets a buffer paid on every link"
2468            );
2469        }
2470    }
2471
2472    /// A guard over fabricated counters, standing in for one whose capture threads
2473    /// would need an interface and root.
2474    fn guard_over(stats: Vec<Arc<CaptureStats>>) -> CaptureGuard {
2475        CaptureGuard {
2476            stop: Arc::new(AtomicBool::new(true)),
2477            handles: Vec::new(),
2478            stats,
2479            _held_back: None,
2480        }
2481    }
2482
2483    fn stats_of(received: u32, dropped: u32, if_dropped: u32) -> Arc<CaptureStats> {
2484        let stats = Arc::new(CaptureStats::default());
2485        stats.store(&pcap::Stat {
2486            received,
2487            dropped,
2488            if_dropped,
2489        });
2490        stats
2491    }
2492
2493    /// A transport captures on every interface that is up, so the drop count a scanner
2494    /// acts on must cover the whole receive path: a reply lost on the interface the
2495    /// probe went out of is lost whatever the others managed.
2496    #[test]
2497    fn counts_are_summed_across_every_live_capture() {
2498        let guard = guard_over(vec![stats_of(100, 3, 1), stats_of(40, 0, 0)]);
2499
2500        assert_eq!(
2501            guard.counts(),
2502            Some(CaptureCounts {
2503                received: 140,
2504                dropped: 3,
2505                if_dropped: 1,
2506                stopped_early: 0,
2507            })
2508        );
2509    }
2510
2511    /// Which endings leave a link deaf, and which are a capture finishing.
2512    ///
2513    /// The flag is set inside a loop that needs a live capture, so the decision is a
2514    /// function and this tests it. Counting every `Err` would report a savefile read to
2515    /// its end as a lost interface; counting none would hide every lost interface.
2516    #[test]
2517    fn a_capture_that_ran_out_of_packets_did_not_lose_its_link() {
2518        assert!(!ends_the_link(&pcap::Error::NoMorePackets));
2519        assert!(!ends_the_link(&pcap::Error::TimeoutExpired));
2520
2521        for failure in [
2522            pcap::Error::PcapError("the device went away".to_string()),
2523            pcap::Error::InvalidString,
2524            pcap::Error::IoError(std::io::ErrorKind::PermissionDenied),
2525        ] {
2526            assert!(
2527                ends_the_link(&failure),
2528                "{failure:?} left the link readable"
2529            );
2530        }
2531    }
2532
2533    /// A capture that stopped is counted, in captures rather than frames, so a scan
2534    /// across several interfaces says how many went deaf.
2535    ///
2536    /// The counters are what a report carries, and a capture that ended is the most
2537    /// complete form of the loss they make visible: an interface that hears nothing
2538    /// more, whose silence a scanner cannot tell from hosts that did not answer. Logged
2539    /// but not counted, a run could report a healthy receive path with one of eight
2540    /// links dead since the first second.
2541    #[test]
2542    fn a_capture_that_stopped_early_is_counted_as_one() {
2543        let lasted = stats_of(100, 0, 0);
2544        let stopped = stats_of(4, 0, 0);
2545        stopped.stopped_early.store(true, Ordering::Relaxed);
2546
2547        assert_eq!(lasted.snapshot().stopped_early, 0);
2548        assert_eq!(stopped.snapshot().stopped_early, 1);
2549
2550        // Summed across the guard's captures, so the number is how many links were
2551        // lost.
2552        let guard = guard_over(vec![lasted, stopped, stats_of(7, 0, 0)]);
2553        let counts = guard.counts().expect("three captures");
2554        assert_eq!(counts.stopped_early, 1);
2555        assert_eq!(counts.received, 111, "the frames they did hear still count");
2556
2557        let all_stopped: Vec<_> = (0..3)
2558            .map(|_| {
2559                let stats = stats_of(1, 0, 0);
2560                stats.stopped_early.store(true, Ordering::Relaxed);
2561                stats
2562            })
2563            .collect();
2564        assert_eq!(
2565            guard_over(all_stopped)
2566                .counts()
2567                .expect("three captures")
2568                .stopped_early,
2569            3
2570        );
2571    }
2572
2573    /// The distinction the `Option` exists for: no capture is not a capture that lost
2574    /// nothing.
2575    #[test]
2576    fn a_guard_over_no_capture_reports_nothing_rather_than_zero() {
2577        assert_eq!(CaptureGuard::noop().counts(), None);
2578        assert_eq!(guard_over(Vec::new()).counts(), None);
2579    }
2580
2581    /// `pcap_stats` is cumulative from the start of the capture, so a refresh replaces
2582    /// the previous reading. Accumulating would count every dropped frame once per
2583    /// refresh.
2584    #[test]
2585    fn a_refresh_replaces_the_previous_reading_rather_than_adding_to_it() {
2586        let stats = CaptureStats::default();
2587
2588        stats.store(&pcap::Stat {
2589            received: 500,
2590            dropped: 4,
2591            if_dropped: 0,
2592        });
2593        stats.store(&pcap::Stat {
2594            received: 900,
2595            dropped: 9,
2596            if_dropped: 0,
2597        });
2598
2599        assert_eq!(
2600            stats.snapshot(),
2601            CaptureCounts {
2602                received: 900,
2603                dropped: 9,
2604                if_dropped: 0,
2605                stopped_early: 0,
2606            }
2607        );
2608    }
2609
2610    /// The flag is read while the guard is alive, as every scanner reads it: the counts
2611    /// go into the scan's report before the transport is dropped. So a reader that
2612    /// panics must record it before the guard joins it, and the counters here are the
2613    /// guard's own, with no clone held outside to read them through.
2614    #[test]
2615    fn a_panicked_reader_is_visible_in_the_counts_while_the_guard_is_alive() {
2616        let counters = Arc::new(CaptureStats::default());
2617        let handle = spawn_reader("test0", Arc::clone(&counters), |_| {
2618            panic!("a reader died the way a defect kills one")
2619        })
2620        .expect("a thread starts");
2621        let guard = CaptureGuard {
2622            stop: Arc::new(AtomicBool::new(false)),
2623            handles: vec![handle],
2624            stats: vec![counters],
2625            _held_back: None,
2626        };
2627
2628        while !guard.handles[0].is_finished() {
2629            std::thread::sleep(Duration::from_millis(1));
2630        }
2631        assert_eq!(
2632            guard.counts().expect("one capture").stopped_early,
2633            1,
2634            "a dead reader is reported only once nobody is reading any more"
2635        );
2636    }
2637
2638    /// A reader that ended cleanly is not reported as having stopped early.
2639    #[test]
2640    fn a_capture_thread_that_finished_is_not_recorded_as_stopping_early() {
2641        let counters = Arc::new(CaptureStats::default());
2642        let guard = CaptureGuard {
2643            stop: Arc::new(AtomicBool::new(false)),
2644            handles: vec![
2645                spawn_reader("test0", Arc::clone(&counters), |_| {}).expect("a thread starts"),
2646            ],
2647            stats: vec![Arc::clone(&counters)],
2648            _held_back: None,
2649        };
2650
2651        drop(guard);
2652        assert!(!counters.stopped_early.load(Ordering::Relaxed));
2653    }
2654
2655    /// Captures opened in a table the scan's connections were sized against take the
2656    /// descriptors they hold out of what those connections may hold, for as long as
2657    /// they are open.
2658    ///
2659    /// Forty free of 64 when the scan starts leaves its connections the whole gate.
2660    /// Twenty-eight links' captures then take twenty-eight of those forty, and a gate
2661    /// still promising thirty-two would send connections past the table's room to wait
2662    /// out their patience and be filed unasked.
2663    #[cfg(unix)]
2664    #[test]
2665    fn a_capture_holds_back_the_connections_its_links_took_the_room_of() {
2666        use crate::system::descriptors::testing::{exhaust, in_a_process_of_its_own};
2667        use crate::system::descriptors::{OPENED_WHILE_RUNNING, gate, hold_back};
2668
2669        if !in_a_process_of_its_own(
2670            module_path!(),
2671            "a_capture_holds_back_the_connections_its_links_took_the_room_of",
2672        ) {
2673            return;
2674        }
2675        let mut held = exhaust(64);
2676        held.truncate(held.len() - 40);
2677        let whole = gate().available_permits();
2678        let scan = hold_back();
2679        let at_start = gate().available_permits();
2680
2681        let links: Vec<std::fs::File> = (0..28)
2682            .map(|_| std::fs::File::open("/dev/null").expect("a descriptor for a link"))
2683            .collect();
2684        let guard = CaptureGuard::running(Arc::new(AtomicBool::new(true)), Vec::new(), Vec::new());
2685        let capturing = gate().available_permits();
2686        drop(guard);
2687        let closed = gate().available_permits();
2688        drop((links, scan, held));
2689
2690        assert_eq!(
2691            (whole, at_start),
2692            (32, 32),
2693            "the table had room for the gate"
2694        );
2695        assert_eq!(
2696            capturing,
2697            40 - 28 - OPENED_WHILE_RUNNING,
2698            "the connections are let hold what the captures left"
2699        );
2700        assert_eq!(closed, whole, "and the captures closing gives it back");
2701    }
2702}