Skip to main content

zond_engine/model/
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//! What a capture saw, and what it did with it.
10//!
11//! [`CaptureCounts`] is written by the capture and read by the report. [`IpObservation`]
12//! is written by the capture and read by whatever wants to know what a stack put in its
13//! headers. Both live in the vocabulary because several modules share their shape, and
14//! a backend with no kernel buffer, such as a synthetic receive stream in a test, can
15//! still fill them in.
16
17/// What a reply's IP header said, past the addressing the scanner needed to
18/// correlate it.
19///
20/// Beyond the addresses and protocol, a header records how many hops are left, whether
21/// the datagram may be fragmented, and what identifier was stamped on it. Those are
22/// choices of the stack that sent it, nearly identical across every packet it sends,
23/// which is why a reply to an ordinary port probe says something about the machine
24/// behind it.
25///
26/// # Split by family
27///
28/// Half these fields exist in only one family: an IPv6 header has no identification
29/// field and no don't-fragment bit, since IPv6 datagrams are never fragmented in
30/// transit. In one flat struct, a rule written against `dont_fragment == false` would
31/// silently match every IPv6 packet. The enum makes such a question unaskable where it
32/// has no answer.
33///
34/// [`remaining_hops`](Self::remaining_hops) is the one field both families have, under
35/// different names.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum IpObservation {
38    /// What an IPv4 header said.
39    V4(Ipv4Observation),
40    /// What an IPv6 header said.
41    V6(Ipv6Observation),
42}
43
44impl IpObservation {
45    /// The hop counter as it arrived: an IPv4 TTL or an IPv6 hop limit.
46    ///
47    /// Every router on the path decrements it, so this is the initial value minus the
48    /// hop count. The initial value is what identifies a stack; recovering it means
49    /// knowing the host's distance. Rounding up to the nearest familiar starting value
50    /// fails silently on long paths.
51    pub fn remaining_hops(self) -> u8 {
52        match self {
53            IpObservation::V4(observed) => observed.ttl,
54            IpObservation::V6(observed) => observed.hop_limit,
55        }
56    }
57
58    /// Whether the reply arrived as a fragment.
59    ///
60    /// Check this first. A fragment's header describes the fragment, and the fields
61    /// that identify a stack, above all the window and options of the segment behind
62    /// it, belong to a different piece of the datagram or are absent. A fragmented
63    /// reply is evidence about the path, not the sender.
64    pub fn is_fragment(self) -> bool {
65        match self {
66            // Only first fragments get this far: `parse_ip_segment` refuses a
67            // non-zero fragment offset on both families, since what follows a later
68            // fragment's header is mid-payload. That refusal is what makes the More
69            // Fragments bit sufficient; the last fragment does not set it.
70            IpObservation::V4(observed) => observed.more_fragments,
71            // `walk_ipv6_headers` stops at a fragment header with a non-zero offset,
72            // so only the first fragment arrives, and it cannot be told from a whole
73            // datagram here. A caller that needs to know reads the extension header.
74            IpObservation::V6(_) => false,
75        }
76    }
77}
78
79/// The fields of an IPv4 header that describe the stack that wrote it.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub struct Ipv4Observation {
82    /// The time-to-live as it arrived, already decremented once per hop
83    /// crossed. See [`IpObservation::remaining_hops`].
84    pub ttl: u8,
85
86    /// The fragment identifier.
87    ///
88    /// Read for how it *changes* across replies: zero throughout, counting globally,
89    /// counting per connection, and random are four policies, and which one a stack
90    /// follows is close to a signature. Recorded per reply and read across them.
91    pub identification: u16,
92
93    /// Whether the sender forbade fragmentation in transit.
94    pub dont_fragment: bool,
95
96    /// Whether more fragments of this datagram follow.
97    /// See [`IpObservation::is_fragment`].
98    pub more_fragments: bool,
99
100    /// Differentiated services, six bits. Almost always zero from a host, and
101    /// interesting exactly when it is not.
102    pub dscp: u8,
103
104    /// Explicit congestion notification, two bits. What a stack echoes here is
105    /// set by whether it negotiated ECN at all, which stacks disagree about.
106    pub ecn: u8,
107}
108
109/// The fields of an IPv6 header that describe the stack that wrote it.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub struct Ipv6Observation {
112    /// The hop limit as it arrived, already decremented once per hop crossed.
113    /// See [`IpObservation::remaining_hops`].
114    pub hop_limit: u8,
115
116    /// Traffic class, eight bits: the IPv6 spelling of IPv4's DSCP and ECN
117    /// together.
118    pub traffic_class: u8,
119
120    /// The flow label, twenty bits.
121    ///
122    /// Whether a stack sets one at all is the signal: the specification allows zero,
123    /// several stacks always send zero, and others derive a value per flow.
124    pub flow_label: u32,
125}
126
127/// What became of the frames a capture's BPF filter admitted, cumulative over its
128/// lifetime, and whether it lasted the scan.
129///
130/// `dropped` matters most. It counts frames that matched the filter, reached the
131/// kernel's buffer, and were discarded because this process did not read them in time.
132/// A reply lost there is indistinguishable from a host that did not answer, and
133/// retransmission does not help if the retry's reply is lost the same way, so the
134/// scanner has to be told.
135///
136/// Compare against a scanner's own counters with care. The filters are narrow but not
137/// private: the SYN filter admits every TCP SYN and RST crossing any captured
138/// interface, so `received` includes unrelated traffic. It bounds the receive path's
139/// load, not the scan's share of it.
140#[non_exhaustive]
141#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
142pub struct CaptureCounts {
143    /// Frames the capture accepted and handed to this process.
144    pub received: u64,
145    /// Frames discarded because the buffer was full when they arrived.
146    pub dropped: u64,
147    /// Frames discarded by the interface or its driver before the capture saw
148    /// them. Not every platform reports this, so a zero is weaker evidence here
149    /// than in [`dropped`](Self::dropped).
150    pub if_dropped: u64,
151    /// How many captures ended before they were told to.
152    ///
153    /// Counted in captures, not frames. A capture whose reader stops leaves an
154    /// interface deaf for the rest of the run, and every reply that would have arrived
155    /// on it reads as a host that did not answer. Where [`dropped`](Self::dropped) says
156    /// frames were lost, this says a link was, and the counts beside it describe less
157    /// of the network than they appear to.
158    ///
159    /// A scan across eight interfaces reports how many of the eight went deaf.
160    pub stopped_early: u64,
161}
162
163impl std::ops::Add for CaptureCounts {
164    type Output = Self;
165
166    /// Saturating, like every other count in the model: a wrapped total would read as
167    /// a quiet capture.
168    fn add(self, other: Self) -> Self {
169        Self {
170            received: self.received.saturating_add(other.received),
171            dropped: self.dropped.saturating_add(other.dropped),
172            if_dropped: self.if_dropped.saturating_add(other.if_dropped),
173            stopped_early: self.stopped_early.saturating_add(other.stopped_early),
174        }
175    }
176}
177
178impl std::ops::AddAssign for CaptureCounts {
179    fn add_assign(&mut self, other: Self) {
180        *self = *self + other;
181    }
182}
183
184impl std::iter::Sum for CaptureCounts {
185    /// Totals a scan's captures. Empty sums to all zeros.
186    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
187        iter.fold(Self::default(), |total, counts| total + counts)
188    }
189}
190
191// ╔════════════════════════════════════════════╗
192// ║ ████████╗███████╗███████╗████████╗███████╗ ║
193// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
194// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
195// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
196// ║    ██║   ███████╗███████║   ██║   ███████║ ║
197// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
198// ╚════════════════════════════════════════════╝
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn counts_add_field_by_field() {
206        let total: CaptureCounts = [
207            CaptureCounts {
208                received: 10,
209                dropped: 1,
210                if_dropped: 0,
211                stopped_early: 0,
212            },
213            CaptureCounts {
214                received: 5,
215                dropped: 0,
216                if_dropped: 2,
217                stopped_early: 0,
218            },
219        ]
220        .into_iter()
221        .sum();
222
223        assert_eq!(total.received, 15);
224        assert_eq!(total.dropped, 1);
225        assert_eq!(total.if_dropped, 2);
226    }
227
228    /// A wrapped total would read as a quiet capture.
229    #[test]
230    fn a_total_too_large_to_represent_saturates_rather_than_wrapping() {
231        let huge = CaptureCounts {
232            received: u64::MAX,
233            dropped: u64::MAX,
234            if_dropped: u64::MAX,
235            stopped_early: 0,
236        };
237        let one = CaptureCounts {
238            received: 1,
239            dropped: 1,
240            if_dropped: 1,
241            stopped_early: 0,
242        };
243
244        let total = huge + one;
245
246        assert_eq!(total.received, u64::MAX);
247        assert_eq!(total.dropped, u64::MAX);
248        assert_eq!(total.if_dropped, u64::MAX);
249    }
250
251    #[test]
252    fn an_empty_sum_is_all_zeros() {
253        let total: CaptureCounts = std::iter::empty().sum();
254        assert_eq!(total, CaptureCounts::default());
255    }
256}