Skip to main content

rustnet_core/network/
tracker.rs

1//! Live connection tracking.
2//!
3//! [`ConnectionTracker`] folds parsed packets into a long-lived, lifecycle-
4//! managed table of [`Connection`]s. It owns everything needed to turn a stream
5//! of [`ParsedPacket`]s into the same connection view the `rustnet` TUI shows —
6//! the active table, an archive of recently-closed ("historic") connections,
7//! RTT estimation from TCP, QUIC handshakes, and ICMP echo, plus DNS-shaped
8//! response timing, QUIC connection-ID coalescing, and timeout-based cleanup,
9//! all without any UI, capture, or process-lookup
10//! dependency.
11//!
12//! This is the piece that makes headless tools easy: pair a capture source with
13//! a parser, then feed each parsed packet to [`ConnectionTracker::ingest_at`]
14//! and periodically call [`ConnectionTracker::cleanup`]. A Prometheus exporter,
15//! a pcap post-processor, or a test harness can all reuse the exact connection
16//! semantics of the main application. Offline consumers replaying a saved trace
17//! should pass each packet's capture timestamp so connection lifetimes and
18//! timeouts follow trace time rather than the replay wall clock.
19//!
20//! ```no_run
21//! use rustnet_core::network::parser::PacketParser;
22//! use rustnet_core::network::tracker::ConnectionTracker;
23//! use std::time::SystemTime;
24//!
25//! let parser = PacketParser::new();
26//! let tracker = ConnectionTracker::new();
27//! # let frames: Vec<Vec<u8>> = Vec::new();
28//! for frame in frames {
29//!     if let Some(parsed) = parser.parse_packet(&frame) {
30//!         tracker.ingest_at(&parsed, SystemTime::now());
31//!     }
32//! }
33//! tracker.cleanup(SystemTime::now()); // expire idle/closed connections
34//! for conn in tracker.snapshot() {
35//!     println!("{} {} -> {}", conn.protocol, conn.local_addr, conn.remote_addr);
36//! }
37//! ```
38//!
39//! All methods take `&self` (the internal tables use interior mutability), so a
40//! single tracker can be wrapped in an [`std::sync::Arc`] and shared across a
41//! capture thread, a cleanup thread, and a reader thread.
42
43use crate::network::dns_attribution::DnsAttributionCache;
44use crate::network::merge::{
45    TcpMergeEvents, create_connection_from_packet, merge_packet_into_connection,
46};
47use crate::network::neighbors::{NeighborCache, NeighborEntry};
48use crate::network::parser::ParsedPacket;
49use crate::network::types::{
50    ApplicationProtocol, AttributionSource, Connection, ConnectionKey, Protocol, ProtocolState,
51    QuicPacketType, RttTracker,
52};
53use dashmap::DashMap;
54use rustc_hash::FxBuildHasher;
55use std::collections::HashMap;
56use std::sync::atomic::{AtomicUsize, Ordering};
57use std::sync::{Mutex, RwLock};
58use std::time::{Duration, SystemTime};
59
60/// Recently archived TCP tuples remain tombstoned briefly so delayed teardown
61/// packets do not create phantom established connections.
62const RECENTLY_CLOSED_TTL: Duration = Duration::from_secs(30);
63
64/// Tombstone capacity floor. `max_historic` sizes the user-facing archive,
65/// but tombstones guard correctness, so a tiny or zero `max_historic` must
66/// not strip them and reopen the phantom-connection window. Entries are a
67/// key and a timestamp; the TTL above bounds how long any of them live.
68const RECENTLY_CLOSED_MIN_ENTRIES: usize = 1024;
69
70/// Whether a QUIC packet belongs to the handshake exchange that RTT timing
71/// pairs up.
72///
73/// 0-RTT is deliberately excluded: it is client-only application data sent
74/// alongside the Initial, so treating it as a fresh send would restart the
75/// timer and report a fraction of the real round trip. 1-RTT packets carry a
76/// short header and reveal nothing to time against.
77fn is_quic_handshake_packet(packet_type: QuicPacketType) -> bool {
78    matches!(
79        packet_type,
80        QuicPacketType::Initial
81            | QuicPacketType::Handshake
82            | QuicPacketType::Retry
83            | QuicPacketType::VersionNegotiation
84    )
85}
86
87/// Whether a UDP packet's DPI classification is one the RTT tracker times.
88/// Gates the rtt lock in `measure_timings` so untimed UDP traffic (QUIC 1-RTT
89/// bulk data, SSDP, mDNS, ...) never touches the mutex on the packet path.
90fn udp_application_is_timed(application: &ApplicationProtocol) -> bool {
91    match application {
92        ApplicationProtocol::Quic(quic) => is_quic_handshake_packet(quic.packet_type),
93        ApplicationProtocol::Dns(_)
94        | ApplicationProtocol::Llmnr(_)
95        | ApplicationProtocol::NetBios(_)
96        | ApplicationProtocol::Stun(_)
97        | ApplicationProtocol::Ntp(_) => true,
98        _ => false,
99    }
100}
101
102/// The active connection table: flow key -> connection.
103///
104/// Keys are compact `Copy` structs, and the map uses FxHash — with a small
105/// fixed-size key, hashing is a handful of multiplies instead of SipHash over
106/// a formatted string. (Hash-flooding resistance isn't needed here: the table
107/// is bounded by `max_connections` and keyed by addresses, not attacker-chosen
108/// bytes of arbitrary length.)
109pub type ConnectionMap = DashMap<ConnectionKey, Connection, FxBuildHasher>;
110
111/// The historic (recently-closed) connection table.
112pub type HistoricMap = DashMap<HistoricKey, Connection, FxBuildHasher>;
113
114/// Identity of an archived (closed) connection: the flow key plus the
115/// connection's creation time, so multiple closed connections that reused the
116/// same 4-tuple don't clobber each other. (Replaces the former
117/// `"<key>:<created_at_nanos>"` string suffix.)
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
119pub struct HistoricKey {
120    pub key: ConnectionKey,
121    pub created_nanos: u128,
122}
123
124impl std::fmt::Display for HistoricKey {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "{}:{}", self.key, self.created_nanos)
127    }
128}
129
130/// Tuning knobs for a [`ConnectionTracker`].
131#[derive(Debug, Clone)]
132pub(crate) struct TrackerConfig {
133    /// Maximum number of concurrent active connections. New connections beyond
134    /// this limit are dropped (existing ones still update) to bound memory
135    /// under port scans or connection floods.
136    pub max_connections: usize,
137    /// Maximum number of recently-closed ("historic") connections retained.
138    /// Oldest-closed entries are evicted first.
139    pub max_historic: usize,
140    /// Maximum number of QUIC connection-ID -> connection-key mappings kept for
141    /// coalescing migrated QUIC connections. Cleared wholesale when exceeded.
142    pub max_quic_mappings: usize,
143    /// Whether [`ConnectionTracker::cleanup`] archives removed connections into
144    /// the historic table. Headless tools that don't need a closed-connection
145    /// view can set this to `false` to save memory.
146    pub keep_historic: bool,
147    /// Whether connections without an authoritative hostname (TLS SNI or HTTP
148    /// `Host:`) are tagged with the name from a DNS response observed on the
149    /// wire shortly before the connection appeared. Purely passive; consumers
150    /// that don't display hostnames can set this to `false`.
151    pub dns_attribution: bool,
152}
153
154impl Default for TrackerConfig {
155    fn default() -> Self {
156        Self {
157            max_connections: 50_000,
158            max_historic: 5_000,
159            max_quic_mappings: 10_000,
160            keep_historic: true,
161            dns_attribution: true,
162        }
163    }
164}
165
166/// What happened when a packet was ingested via
167/// [`ingest_at`](ConnectionTracker::ingest_at).
168///
169/// Returned so callers can layer their own concerns — global statistics,
170/// structured logging, DNS enrichment — on top of the core table update without
171/// the tracker needing to know about them.
172#[derive(Debug, Clone)]
173pub struct IngestOutcome {
174    /// The (possibly QUIC-coalesced) key under which the connection is stored.
175    /// `Copy`, and its `Display` form matches the historical string key
176    /// (`"TCP:1.2.3.4:80-TCP:5.6.7.8:443"`).
177    pub key: ConnectionKey,
178    /// `true` if this packet created a new connection entry.
179    pub created: bool,
180    /// `true` if the packet was dropped because `max_connections` was reached
181    /// (the connection did not already exist and was not inserted).
182    pub dropped: bool,
183    /// `true` when a delayed packet matched a recently archived TCP tuple and
184    /// was intentionally not turned into a new active connection.
185    pub ignored_late: bool,
186    /// Previous live generation archived by a strong new-session signal.
187    /// Historic storage receives an immutable snapshot of this connection.
188    pub archived: Option<Connection>,
189    /// New TCP retransmissions detected by this packet.
190    pub retransmits: u64,
191    /// New out-of-order TCP segments detected by this packet.
192    pub out_of_order: u64,
193    /// New TCP fast-retransmits detected by this packet.
194    pub fast_retransmits: u64,
195    /// An RTT sample, if this packet completed a handshake round trip: a TCP
196    /// SYN-ACK matching a prior SYN, or a QUIC handshake packet answering one
197    /// sent the other way.
198    pub measured_rtt: Option<Duration>,
199    /// The latest completed DNS query→response round trip, if this packet was
200    /// a response matching a pending query by transaction ID.
201    pub dns_response_time: Option<Duration>,
202    /// The first completed LLMNR query-to-response round trip, if this packet
203    /// was a response matching a pending multicast query by transaction ID.
204    pub llmnr_response_time: Option<Duration>,
205    /// The latest completed NetBIOS request-to-response round trip, if this
206    /// packet matched a pending request by transaction ID.
207    pub netbios_response_time: Option<Duration>,
208    /// The latest completed ICMP echo round trip, if this packet was a reply
209    /// matching an outgoing request by identifier and sequence number.
210    pub icmp_echo_rtt: Option<Duration>,
211    /// The latest completed STUN request→response round trip, if this packet
212    /// was a response matching a pending request by transaction ID.
213    pub stun_rtt: Option<Duration>,
214    /// The latest completed NTP request→response round trip, if this packet
215    /// was a server response echoing a pending client transmit timestamp.
216    pub ntp_rtt: Option<Duration>,
217}
218
219/// Timing measurements extracted from one packet, carried together through
220/// the connection-table update into the resulting [`IngestOutcome`].
221#[derive(Clone, Copy, Default)]
222struct PacketTimings {
223    measured_rtt: Option<Duration>,
224    dns_response_time: Option<Duration>,
225    llmnr_response_time: Option<Duration>,
226    netbios_response_time: Option<Duration>,
227    icmp_echo_rtt: Option<Duration>,
228    stun_rtt: Option<Duration>,
229    ntp_rtt: Option<Duration>,
230}
231
232impl PacketTimings {
233    /// An [`IngestOutcome`] carrying these timings, with every other field at
234    /// its quiescent value for the caller to override via struct update.
235    fn outcome(self, key: ConnectionKey) -> IngestOutcome {
236        IngestOutcome {
237            key,
238            created: false,
239            dropped: false,
240            ignored_late: false,
241            archived: None,
242            retransmits: 0,
243            out_of_order: 0,
244            fast_retransmits: 0,
245            measured_rtt: self.measured_rtt,
246            dns_response_time: self.dns_response_time,
247            llmnr_response_time: self.llmnr_response_time,
248            netbios_response_time: self.netbios_response_time,
249            icmp_echo_rtt: self.icmp_echo_rtt,
250            stun_rtt: self.stun_rtt,
251            ntp_rtt: self.ntp_rtt,
252        }
253    }
254}
255
256/// Stamp any round trips this packet completed onto its connection.
257fn apply_timings(conn: &mut Connection, timings: &PacketTimings) {
258    if let Some(rtt) = timings.measured_rtt
259        && conn.initial_rtt.is_none()
260    {
261        conn.initial_rtt = Some(rtt);
262    }
263    // Last-wins, unlike `initial_rtt`: each completed query refreshes the
264    // displayed response time.
265    if let Some(rtt) = timings.dns_response_time {
266        conn.dns_response_time = Some(rtt);
267    }
268    if let Some(rtt) = timings.llmnr_response_time {
269        conn.llmnr_response_time = Some(rtt);
270    }
271    if let Some(rtt) = timings.netbios_response_time {
272        conn.netbios_response_time = Some(rtt);
273    }
274    if let Some(rtt) = timings.icmp_echo_rtt {
275        conn.icmp_echo_rtt = Some(rtt);
276    }
277    if let Some(rtt) = timings.stun_rtt {
278        conn.stun_rtt = Some(rtt);
279    }
280    if let Some(rtt) = timings.ntp_rtt {
281        conn.ntp_rtt = Some(rtt);
282    }
283}
284
285/// A live, lifecycle-managed table of network connections built from parsed
286/// packets. See the [module docs](self) for the intended usage.
287pub struct ConnectionTracker {
288    connections: ConnectionMap,
289    historic: HistoricMap,
290    /// Coordinates moves between the active and historic maps with readers
291    /// that need one consistent retained-connection view.
292    lifecycle: RwLock<()>,
293    rtt: Mutex<RttTracker>,
294    quic_map: Mutex<HashMap<String, ConnectionKey>>,
295    recently_closed: Mutex<HashMap<ConnectionKey, SystemTime>>,
296    config: TrackerConfig,
297    /// Active-connection count maintained by `ingest_at`/`cleanup`/`clear`.
298    /// Lets the per-packet `max_connections` check be a single atomic load
299    /// instead of a `DashMap::len()` (which read-locks every shard) plus an
300    /// extra `contains_key` lookup. May transiently lag `connections.len()`
301    /// by a few entries under concurrent ingest near the limit — acceptable
302    /// for a flood-protection bound.
303    active_count: AtomicUsize,
304    /// IP -> MAC/vendor mappings learned passively from ingested ARP (IPv4)
305    /// and NDP (IPv6) packets. Outlives the connections themselves, so LAN
306    /// peers stay identified after their ARP/NDP rows are cleaned up.
307    neighbors: NeighborCache,
308    /// IP -> domain mappings learned passively from ingested DNS responses,
309    /// used to tag SNI-less connections with a hostname. Fed and drained by
310    /// `ingest_at`, pruned by `cleanup`.
311    dns_attribution: DnsAttributionCache,
312}
313
314impl ConnectionTracker {
315    /// Create a tracker with default configuration.
316    pub fn new() -> Self {
317        Self::with_config(TrackerConfig::default())
318    }
319
320    /// Create a tracker with custom [`TrackerConfig`].
321    pub(crate) fn with_config(config: TrackerConfig) -> Self {
322        Self {
323            connections: ConnectionMap::with_hasher(FxBuildHasher),
324            historic: HistoricMap::with_hasher(FxBuildHasher),
325            lifecycle: RwLock::new(()),
326            rtt: Mutex::new(RttTracker::new()),
327            quic_map: Mutex::new(HashMap::new()),
328            recently_closed: Mutex::new(HashMap::new()),
329            config,
330            active_count: AtomicUsize::new(0),
331            neighbors: NeighborCache::default(),
332            dns_attribution: DnsAttributionCache::default(),
333        }
334    }
335
336    /// Fold a parsed packet into the connection table, creating or updating the
337    /// matching connection, stamping the update with the supplied `now`.
338    ///
339    /// Pass the packet's own capture timestamp: for offline processing (pcap
340    /// replay, tests) this keeps `created_at`/`last_activity` and the
341    /// [`cleanup`](Self::cleanup) timeout sweep on trace time rather than the
342    /// replay wall clock. Live callers should also pass each packet's own
343    /// capture timestamp, not one clock read shared across a batch of packets.
344    /// Handshake RTT is the difference between two packets' `now` values, so a
345    /// shared timestamp collapses every round trip that completes within one
346    /// batch to zero.
347    pub fn ingest_at(&self, parsed: &ParsedPacket, now: SystemTime) -> IngestOutcome {
348        // Harvest IP -> MAC mappings from ARP and NDP packets; only they pay
349        // this cost.
350        match &parsed.protocol_state {
351            ProtocolState::Arp(arp_info) => self.neighbors.learn_from_arp(arp_info, now),
352            ProtocolState::Icmp {
353                ndp_neighbor: Some(neighbor),
354                ..
355            } => self.neighbors.learn_from_ndp(neighbor, now),
356            _ => {}
357        }
358
359        let timings = self.measure_timings(parsed, now);
360
361        // Passive DNS attribution: record answered A/AAAA mappings and collect
362        // the connections that were waiting on one of the answered IPs.
363        let waiters = if self.config.dns_attribution
364            && let Some(dpi) = &parsed.dpi_result
365            && let ApplicationProtocol::Dns(dns) = &dpi.application
366            && dns.is_response
367            && !dns.response_ips.is_empty()
368            && let Some(query_name) = &dns.query_name
369        {
370            self.dns_attribution.record_and_drain_pending(
371                query_name,
372                &dns.response_ips,
373                AttributionSource::CapturedDns,
374            )
375        } else {
376            Vec::new()
377        };
378
379        let outcome = self.ingest_update(parsed, now, timings);
380
381        // Tag drained waiters after the table update so the DNS packet's own
382        // row never holds an entry lock while a waiter's row is taken.
383        for waiter_key in waiters {
384            if let Some(mut conn) = self.connections.get_mut(&waiter_key) {
385                self.dns_attribution.attribute(&mut conn, waiter_key);
386            }
387        }
388
389        outcome
390    }
391
392    /// The connection-table update half of [`ingest_at`](Self::ingest_at):
393    /// resolve the key and fold the packet into the active table, splitting
394    /// off a new generation or ignoring a late teardown packet as needed.
395    fn ingest_update(
396        &self,
397        parsed: &ParsedPacket,
398        now: SystemTime,
399        timings: PacketTimings,
400    ) -> IngestOutcome {
401        // A read guard makes ordinary packet updates atomic with cleanup. The
402        // uncommon generation-split path drops it and reacquires a write guard
403        // so retained-source readers also see one consistent move.
404        let lifecycle = self
405            .lifecycle
406            .read()
407            .unwrap_or_else(std::sync::PoisonError::into_inner);
408        let key = self.resolve_connection_key(parsed);
409
410        if !self.connections.contains_key(&key) && self.is_recent_late_packet(key, parsed, now) {
411            return IngestOutcome {
412                ignored_late: true,
413                ..timings.outcome(key)
414            };
415        }
416
417        let starts_new_generation = self
418            .connections
419            .get(&key)
420            .is_some_and(|conn| Self::packet_starts_new_generation(&conn, parsed));
421        if starts_new_generation {
422            drop(lifecycle);
423            return self.ingest_new_generation(parsed, now, key, timings);
424        }
425
426        self.ingest_into_active(parsed, now, key, timings)
427    }
428
429    /// Run this packet through the RTT tracker and collect any round trips it
430    /// completed.
431    fn measure_timings(&self, parsed: &ParsedPacket, now: SystemTime) -> PacketTimings {
432        // Track RTT for TCP connections using SYN/SYN-ACK timing, and for QUIC
433        // using the long-header handshake exchange. Everything QUIC sends after
434        // the handshake is behind header protection, so this initial flight is
435        // the only round trip an on-path observer can time.
436        let mut measured_rtt: Option<Duration> = None;
437        let mut dns_response_time: Option<Duration> = None;
438        let mut llmnr_response_time: Option<Duration> = None;
439        let mut netbios_response_time: Option<Duration> = None;
440        let mut stun_rtt: Option<Duration> = None;
441        let mut ntp_rtt: Option<Duration> = None;
442        let base_key = parsed.connection_key();
443        if parsed.protocol == Protocol::Tcp
444            && let Some(tcp_header) = &parsed.tcp_header
445        {
446            if tcp_header.flags.syn && !tcp_header.flags.ack {
447                if let Ok(mut tracker) = self.rtt.lock() {
448                    tracker.record_syn(base_key, now);
449                }
450            } else if tcp_header.flags.syn
451                && tcp_header.flags.ack
452                && let Ok(mut tracker) = self.rtt.lock()
453            {
454                measured_rtt = tracker.record_syn_ack(&base_key, now);
455            }
456        } else if parsed.protocol == Protocol::Udp
457            && let Some(dpi) = &parsed.dpi_result
458            && udp_application_is_timed(&dpi.application)
459            && let Ok(mut tracker) = self.rtt.lock()
460        {
461            // One lock acquisition covers every timed UDP application; a
462            // packet carries one DPI result, so at most one arm runs.
463            match &dpi.application {
464                ApplicationProtocol::Quic(_) => {
465                    measured_rtt = tracker.record_quic_handshake(base_key, parsed.is_outgoing, now);
466                }
467                // Time DNS query→response pairs by transaction ID. Port-53
468                // gating already happened in DPI dispatch, so any Dns result
469                // here is unicast DNS (mDNS/LLMNR map to their own variants).
470                ApplicationProtocol::Dns(dns) => {
471                    dns_response_time = tracker.record_dns_packet(
472                        base_key,
473                        dns.txid,
474                        parsed.is_outgoing,
475                        dns.is_response,
476                        now,
477                    );
478                }
479                // LLMNR uses the DNS transaction ID, but sends the query to a
480                // multicast address and receives each response from a unicast
481                // address. The RTT tracker returns the multicast request row
482                // so both views can carry the first response time.
483                ApplicationProtocol::Llmnr(llmnr) => {
484                    let completed =
485                        tracker.record_llmnr_packet(base_key, llmnr, parsed.is_outgoing, now);
486                    if let Some((rtt, request_key)) = completed {
487                        llmnr_response_time = Some(rtt);
488                        self.stamp_request_row_timing(request_key, base_key, |conn| {
489                            conn.llmnr_response_time = Some(rtt);
490                        });
491                    }
492                }
493                // NetBIOS Name Service broadcasts are answered from a host's
494                // unicast address, so the RTT tracker pairs on local socket,
495                // service, and transaction ID rather than the full connection
496                // key.
497                ApplicationProtocol::NetBios(netbios) => {
498                    let completed =
499                        tracker.record_netbios_packet(base_key, netbios, parsed.is_outgoing, now);
500                    if let Some((rtt, request_key)) = completed {
501                        netbios_response_time = Some(rtt);
502                        self.stamp_request_row_timing(request_key, base_key, |conn| {
503                            conn.netbios_response_time = Some(rtt);
504                        });
505                    }
506                }
507                // STUN requests and responses share a 96-bit transaction ID
508                // that retransmits reuse, so request→response pairing is
509                // exact.
510                ApplicationProtocol::Stun(stun) => {
511                    stun_rtt = tracker.record_stun(
512                        base_key,
513                        stun.transaction_id,
514                        parsed.is_outgoing,
515                        stun.message_class,
516                        now,
517                    );
518                }
519                // NTP servers echo the client's transmit timestamp as the
520                // originate timestamp, pairing each poll with its response.
521                ApplicationProtocol::Ntp(ntp) => {
522                    ntp_rtt = tracker.record_ntp(base_key, ntp, parsed.is_outgoing, now);
523                }
524                _ => {}
525            }
526        }
527
528        // ICMP echo requests reuse one identifier for the life of a ping
529        // process, so sequence number is part of the key. That allows several
530        // subsecond requests to be pending at once and replies to arrive out of
531        // order without cross-pairing samples.
532        let echo_metadata = match &parsed.protocol_state {
533            ProtocolState::Icmp {
534                icmp_type,
535                icmp_id: Some(identifier),
536                icmp_sequence: Some(sequence),
537                ..
538            } => match icmp_type {
539                8 | 128 => Some((*identifier, *sequence, false)),
540                0 | 129 => Some((*identifier, *sequence, true)),
541                _ => None,
542            },
543            _ => None,
544        };
545        let mut icmp_echo_rtt: Option<Duration> = None;
546        if let Some((identifier, sequence, is_reply)) = echo_metadata
547            && let Ok(mut tracker) = self.rtt.lock()
548        {
549            // Loopback captures classify the reply as outgoing too (both
550            // endpoints are local), so reclassify it as incoming to let it
551            // match the pending request.
552            let is_outgoing = parsed.is_outgoing
553                && !(is_reply && parsed.local_addr.ip() == parsed.remote_addr.ip());
554            icmp_echo_rtt = tracker.record_icmp_echo(
555                base_key,
556                (identifier, sequence),
557                is_outgoing,
558                is_reply,
559                now,
560            );
561        }
562
563        PacketTimings {
564            measured_rtt,
565            dns_response_time,
566            llmnr_response_time,
567            netbios_response_time,
568            icmp_echo_rtt,
569            stun_rtt,
570            ntp_rtt,
571        }
572    }
573
574    /// Stamp a completed broadcast or multicast exchange on its request row.
575    /// The response packet's own row is updated later through `PacketTimings`.
576    fn stamp_request_row_timing(
577        &self,
578        request_key: ConnectionKey,
579        response_key: ConnectionKey,
580        stamp: impl FnOnce(&mut Connection),
581    ) {
582        if request_key != response_key
583            && let Some(mut conn) = self.connections.get_mut(&request_key)
584        {
585            stamp(&mut conn);
586        }
587    }
588
589    fn ingest_into_active(
590        &self,
591        parsed: &ParsedPacket,
592        now: SystemTime,
593        key: ConnectionKey,
594        timings: PacketTimings,
595    ) -> IngestOutcome {
596        // Prevent unbounded growth from port scans or connection floods. Only
597        // limit new connections; existing ones always get updated. The fast
598        // path is a single atomic load; only when at the cap do we pay a
599        // lookup to distinguish update-existing from drop-new. (Never call
600        // `len()` here or while holding an entry guard — it read-locks every
601        // shard.)
602        if self.active_count.load(Ordering::Relaxed) >= self.config.max_connections
603            && !self.connections.contains_key(&key)
604        {
605            return IngestOutcome {
606                dropped: true,
607                ..timings.outcome(key)
608            };
609        }
610
611        let mut created = false;
612        let mut deltas = TcpMergeEvents::default();
613        self.connections
614            .entry(key)
615            .and_modify(|conn| {
616                deltas = merge_packet_into_connection(conn, parsed, now);
617                apply_timings(conn, &timings);
618            })
619            .or_insert_with(|| {
620                created = true;
621                let mut conn = create_connection_from_packet(parsed, now);
622                apply_timings(&mut conn, &timings);
623                // Attribute a hostname (or enroll for a later DNS response)
624                // at creation. The cache only touches its own maps, so this
625                // is safe under the entry's shard lock.
626                if self.config.dns_attribution {
627                    self.dns_attribution.attribute(&mut conn, key);
628                }
629                conn
630            });
631        if created {
632            self.active_count.fetch_add(1, Ordering::Relaxed);
633        }
634
635        // Feed completed data round trips into the aggregate view, so the
636        // average RTT reflects established connections rather than only the
637        // handshakes of freshly opened ones.
638        if let Some(rtt) = deltas.rtt_sample
639            && let Ok(mut tracker) = self.rtt.lock()
640        {
641            tracker.record_data_rtt(rtt);
642        }
643
644        IngestOutcome {
645            created,
646            retransmits: deltas.retransmits,
647            out_of_order: deltas.out_of_order,
648            fast_retransmits: deltas.fast_retransmits,
649            ..timings.outcome(key)
650        }
651    }
652
653    fn ingest_new_generation(
654        &self,
655        parsed: &ParsedPacket,
656        now: SystemTime,
657        key: ConnectionKey,
658        timings: PacketTimings,
659    ) -> IngestOutcome {
660        let _lifecycle = self
661            .lifecycle
662            .write()
663            .unwrap_or_else(std::sync::PoisonError::into_inner);
664        let mut replacement_now = now;
665
666        let still_needs_split = self
667            .connections
668            .get(&key)
669            .is_some_and(|conn| Self::packet_starts_new_generation(&conn, parsed));
670        let archived = if still_needs_split {
671            self.connections.remove(&key).map(|(_, conn)| {
672                // Historic keys include `created_at`, so two generations of
673                // the same tuple must not share a creation timestamp. This is
674                // possible when several captured packets use one batch time.
675                if replacement_now <= conn.created_at {
676                    replacement_now = conn
677                        .created_at
678                        .checked_add(Duration::from_nanos(1))
679                        .unwrap_or(replacement_now);
680                }
681                self.active_count.fetch_sub(1, Ordering::Relaxed);
682                self.archive_snapshot(key, &conn, now);
683                self.record_recently_closed(key, &conn, now);
684                self.remove_quic_mappings_for_key(key);
685                // Forget the archived generation's pending enrollment so the
686                // replacement enrolls with a fresh timestamp.
687                self.dns_attribution
688                    .forget_pending(conn.remote_addr.ip(), key);
689                conn
690            })
691        } else {
692            None
693        };
694
695        // Cleanup may have removed the old generation while this packet was
696        // waiting to acquire the write guard. Reassociate any visible QUIC ID
697        // before creating the replacement.
698        self.associate_quic_id(parsed, key);
699        let mut outcome = self.ingest_into_active(parsed, replacement_now, key, timings);
700        outcome.archived = archived;
701        self.enforce_historic_limit();
702        self.prune_recently_closed(now);
703        outcome
704    }
705
706    fn resolve_connection_key(&self, parsed: &ParsedPacket) -> ConnectionKey {
707        let mut key = parsed.connection_key();
708        let Some(conn_id_hex) = Self::parsed_quic_id(parsed) else {
709            return key;
710        };
711        let Ok(mut mapping) = self.quic_map.lock() else {
712            return key;
713        };
714        if let Some(existing_key) = mapping.get(conn_id_hex) {
715            key = *existing_key;
716        } else {
717            if mapping.len() >= self.config.max_quic_mappings {
718                mapping.clear();
719            }
720            mapping.insert(conn_id_hex.to_string(), key);
721        }
722        key
723    }
724
725    fn parsed_quic_id(parsed: &ParsedPacket) -> Option<&str> {
726        let dpi = parsed.dpi_result.as_ref()?;
727        let ApplicationProtocol::Quic(quic) = &dpi.application else {
728            return None;
729        };
730        quic.connection_id_hex.as_deref()
731    }
732
733    fn associate_quic_id(&self, parsed: &ParsedPacket, key: ConnectionKey) {
734        let Some(conn_id_hex) = Self::parsed_quic_id(parsed) else {
735            return;
736        };
737        if let Ok(mut mapping) = self.quic_map.lock() {
738            if mapping.len() >= self.config.max_quic_mappings {
739                mapping.clear();
740            }
741            mapping.insert(conn_id_hex.to_string(), key);
742        }
743    }
744
745    fn packet_starts_new_generation(conn: &Connection, parsed: &ParsedPacket) -> bool {
746        if !conn.is_closing_or_terminal() {
747            return false;
748        }
749        match parsed.protocol {
750            Protocol::Tcp => parsed
751                .tcp_header
752                .as_ref()
753                .is_some_and(|header| header.flags.syn),
754            Protocol::Udp => {
755                let Some(new_id) = Self::parsed_quic_id(parsed) else {
756                    return false;
757                };
758                let Some(dpi) = conn.dpi_info.as_ref() else {
759                    return false;
760                };
761                let ApplicationProtocol::Quic(old_quic) = &dpi.application else {
762                    return false;
763                };
764                old_quic
765                    .connection_id_hex
766                    .as_deref()
767                    .is_some_and(|old_id| old_id != new_id)
768            }
769            _ => false,
770        }
771    }
772
773    fn is_recent_late_packet(
774        &self,
775        key: ConnectionKey,
776        parsed: &ParsedPacket,
777        now: SystemTime,
778    ) -> bool {
779        if parsed.protocol != Protocol::Tcp {
780            return false;
781        }
782        let Some(header) = parsed.tcp_header.as_ref() else {
783            return false;
784        };
785        let is_teardown_only = !header.flags.syn
786            && (header.flags.fin
787                || header.flags.rst
788                || (header.flags.ack && header.payload_len == 0));
789        if !is_teardown_only {
790            return false;
791        }
792        self.recently_closed
793            .lock()
794            .unwrap_or_else(std::sync::PoisonError::into_inner)
795            .get(&key)
796            .is_some_and(|closed_at| {
797                now.duration_since(*closed_at).unwrap_or_default() <= RECENTLY_CLOSED_TTL
798            })
799    }
800
801    fn archive_snapshot(&self, key: ConnectionKey, conn: &Connection, now: SystemTime) {
802        if !self.config.keep_historic {
803            return;
804        }
805        let mut historic = conn.snapshot_clone();
806        historic.is_historic = true;
807        historic.closed_at = Some(now);
808        let historic_key = HistoricKey {
809            key,
810            created_nanos: conn
811                .created_at
812                .duration_since(SystemTime::UNIX_EPOCH)
813                .unwrap_or_default()
814                .as_nanos(),
815        };
816        self.historic.insert(historic_key, historic);
817    }
818
819    fn enforce_historic_limit(&self) {
820        if self.historic.len() <= self.config.max_historic {
821            return;
822        }
823        let mut entries: Vec<(HistoricKey, SystemTime)> = self
824            .historic
825            .iter()
826            .map(|entry| {
827                let closed = entry.value().closed_at.unwrap_or(entry.value().created_at);
828                (*entry.key(), closed)
829            })
830            .collect();
831        entries.sort_by_key(|(_, closed)| *closed);
832        let to_remove = self.historic.len() - self.config.max_historic;
833        for (key, _) in entries.into_iter().take(to_remove) {
834            self.historic.remove(&key);
835        }
836    }
837
838    fn record_recently_closed(&self, key: ConnectionKey, conn: &Connection, now: SystemTime) {
839        if !conn.is_terminal() {
840            return;
841        }
842        self.recently_closed
843            .lock()
844            .unwrap_or_else(std::sync::PoisonError::into_inner)
845            .insert(key, now);
846    }
847
848    fn prune_recently_closed(&self, now: SystemTime) {
849        let mut recently_closed = self
850            .recently_closed
851            .lock()
852            .unwrap_or_else(std::sync::PoisonError::into_inner);
853        recently_closed.retain(|_, closed_at| {
854            now.duration_since(*closed_at).unwrap_or_default() <= RECENTLY_CLOSED_TTL
855        });
856        let max_entries = self.config.max_historic.max(RECENTLY_CLOSED_MIN_ENTRIES);
857        if recently_closed.len() > max_entries {
858            let mut entries: Vec<(ConnectionKey, SystemTime)> = recently_closed
859                .iter()
860                .map(|(key, closed_at)| (*key, *closed_at))
861                .collect();
862            entries.sort_by_key(|(_, closed_at)| *closed_at);
863            let to_remove = recently_closed.len() - max_entries;
864            for (key, _) in entries.into_iter().take(to_remove) {
865                recently_closed.remove(&key);
866            }
867        }
868    }
869
870    fn remove_quic_mappings_for_key(&self, key: ConnectionKey) {
871        if let Ok(mut mapping) = self.quic_map.lock() {
872            mapping.retain(|_, conn_key| *conn_key != key);
873        }
874    }
875
876    /// Remove connections whose protocol-aware timeout has elapsed as of `now`.
877    ///
878    /// Removed connections are archived into the historic table (when
879    /// `keep_historic` is set, subject to `max_historic` eviction) and their
880    /// QUIC
881    /// mappings are dropped. Returns the removed connections (in their original,
882    /// pre-archive form) so callers can emit close events or export them.
883    pub fn cleanup(&self, now: SystemTime) -> Vec<Connection> {
884        let _lifecycle = self
885            .lifecycle
886            .write()
887            .unwrap_or_else(std::sync::PoisonError::into_inner);
888        let mut removed: Vec<Connection> = Vec::new();
889        let mut removed_keys: Vec<ConnectionKey> = Vec::new();
890        let mut to_archive: Vec<(HistoricKey, Connection)> = Vec::new();
891        let keep_historic = self.config.keep_historic;
892
893        self.connections.retain(|key, conn| {
894            let should_keep = !conn.should_cleanup(now);
895            if !should_keep {
896                removed_keys.push(*key);
897                removed.push(conn.clone());
898
899                // Archive a historic copy. The historic key includes created_at
900                // so multiple closed connections sharing a 4-tuple don't clobber
901                // each other. snapshot_clone: historic connections never refresh
902                // their rates, so don't pin the (potentially large) sample
903                // buffer in the archive.
904                if keep_historic {
905                    let mut historic = conn.snapshot_clone();
906                    historic.is_historic = true;
907                    historic.closed_at = Some(now);
908                    // Cached rates describe live traffic. Carrying them into a
909                    // closed record makes Overview and Details report traffic
910                    // that can no longer occur, and leaves a moving fallback
911                    // point after the live rate history is retired.
912                    historic.current_incoming_rate_bps = 0.0;
913                    historic.current_outgoing_rate_bps = 0.0;
914                    let historic_key = HistoricKey {
915                        key: *key,
916                        created_nanos: conn
917                            .created_at
918                            .duration_since(SystemTime::UNIX_EPOCH)
919                            .unwrap_or_default()
920                            .as_nanos(),
921                    };
922                    to_archive.push((historic_key, historic));
923                }
924            }
925            should_keep
926        });
927        if !removed.is_empty() {
928            self.active_count
929                .fetch_sub(removed.len(), Ordering::Relaxed);
930            for (key, conn) in removed_keys.iter().zip(&removed) {
931                self.record_recently_closed(*key, conn, now);
932                // Drop any pending DNS-attribution enrollment so a later
933                // response cannot surface a dead key.
934                self.dns_attribution
935                    .forget_pending(conn.remote_addr.ip(), *key);
936            }
937        }
938
939        if keep_historic {
940            for (key, conn) in to_archive {
941                self.historic.insert(key, conn);
942            }
943
944            self.enforce_historic_limit();
945        }
946
947        // Clean up QUIC connection-ID mappings pointing at removed connections.
948        if !removed_keys.is_empty()
949            && let Ok(mut mapping) = self.quic_map.lock()
950        {
951            mapping.retain(|_, conn_key| !removed_keys.contains(conn_key));
952        }
953        self.prune_recently_closed(now);
954        self.dns_attribution.cleanup_tick(std::time::Instant::now());
955
956        removed
957    }
958
959    /// A point-in-time copy of the active connections.
960    ///
961    /// Note: this is a full clone, including each connection's rate-sample
962    /// buffer — the buffer is shared via `Arc`, so the *next* per-packet
963    /// update on a live connection pays a copy-on-write deep copy. Callers
964    /// that only need the cached `current_*_rate_bps` fields (any read-only
965    /// view) should prefer [`Connection::snapshot_clone`] over the entries of
966    /// [`connections`](Self::connections) to keep the packet path allocation-
967    /// free.
968    pub fn snapshot(&self) -> Vec<Connection> {
969        self.connections
970            .iter()
971            .map(|entry| entry.value().clone())
972            .collect()
973    }
974
975    /// Inspect the active and historic maps as one consistent retained view.
976    ///
977    /// Cleanup cannot move a connection between the maps while `inspect` is
978    /// running. Packet updates may still update active rows through DashMap's
979    /// per-entry locking.
980    pub fn with_retained_sources<R>(
981        &self,
982        inspect: impl FnOnce(&ConnectionMap, &HistoricMap) -> R,
983    ) -> R {
984        let _lifecycle = self
985            .lifecycle
986            .read()
987            .unwrap_or_else(std::sync::PoisonError::into_inner);
988        inspect(&self.connections, &self.historic)
989    }
990
991    /// Number of active connections.
992    pub fn len(&self) -> usize {
993        self.connections.len()
994    }
995
996    /// `true` if there are no active connections.
997    pub fn is_empty(&self) -> bool {
998        self.connections.is_empty()
999    }
1000
1001    /// Number of historic (recently-closed) connections.
1002    pub fn historic_len(&self) -> usize {
1003        self.historic.len()
1004    }
1005
1006    /// Drop all active and historic connections and reset RTT/QUIC state and
1007    /// the learned-neighbor cache.
1008    pub fn clear(&self) {
1009        let _lifecycle = self
1010            .lifecycle
1011            .write()
1012            .unwrap_or_else(std::sync::PoisonError::into_inner);
1013        self.connections.clear();
1014        self.active_count.store(0, Ordering::Relaxed);
1015        self.historic.clear();
1016        if let Ok(mut tracker) = self.rtt.lock() {
1017            tracker.clear();
1018        }
1019        if let Ok(mut mapping) = self.quic_map.lock() {
1020            mapping.clear();
1021        }
1022        self.recently_closed
1023            .lock()
1024            .unwrap_or_else(std::sync::PoisonError::into_inner)
1025            .clear();
1026        self.neighbors.clear();
1027        self.dns_attribution.clear();
1028    }
1029
1030    /// Direct access to the active connection table.
1031    ///
1032    /// Use this for in-place enrichment (e.g. attaching process, DNS, or GeoIP
1033    /// information via `iter_mut`) or custom reads. Lifecycle changes should go
1034    /// through [`ingest_at`](Self::ingest_at) and [`cleanup`](Self::cleanup) so the
1035    /// connection-count limit, RTT, and QUIC coalescing stay consistent —
1036    /// inserting or removing entries directly desyncs the internal counter
1037    /// backing the `max_connections` check.
1038    pub fn connections(&self) -> &ConnectionMap {
1039        &self.connections
1040    }
1041
1042    /// Direct access to the historic (recently-closed) connection table.
1043    pub fn historic(&self) -> &HistoricMap {
1044        &self.historic
1045    }
1046
1047    /// The ARP/NDP-learned MAC/vendor mapping for `ip`, if one has been
1048    /// observed.
1049    pub fn neighbor(&self, ip: &std::net::IpAddr) -> Option<NeighborEntry> {
1050        self.neighbors.get(ip)
1051    }
1052
1053    /// Average network RTT (in milliseconds) over the last `window_secs`
1054    /// seconds of handshake, TCP data, and ICMP echo samples. `None` if no
1055    /// samples are available.
1056    pub fn take_average_rtt(&self, window_secs: u64) -> Option<f64> {
1057        self.rtt
1058            .lock()
1059            .ok()
1060            .and_then(|mut tracker| tracker.take_average_rtt(window_secs))
1061    }
1062}
1063
1064impl Default for ConnectionTracker {
1065    fn default() -> Self {
1066        Self::new()
1067    }
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072    use super::*;
1073    use crate::network::parser::PacketParser;
1074    use crate::network::types::NetBiosOpcode;
1075
1076    impl ConnectionTracker {
1077        /// Wall-clock `ingest_at` shorthand for tests that don't exercise
1078        /// packet timing.
1079        fn ingest(&self, parsed: &ParsedPacket) -> IngestOutcome {
1080            self.ingest_at(parsed, SystemTime::now())
1081        }
1082    }
1083
1084    /// A minimal Ethernet+IPv4+UDP frame, parsed into a `ParsedPacket` so we can
1085    /// exercise the tracker with a realistic input.
1086    fn udp_frame(src_port: u16, dst_port: u16) -> Vec<u8> {
1087        let mut f = Vec::new();
1088        // Ethernet header: dst mac, src mac, ethertype IPv4 (0x0800)
1089        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 1]);
1090        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 2]);
1091        f.extend_from_slice(&[0x08, 0x00]);
1092        // IPv4 header (20 bytes)
1093        let ip_total_len = (20 + 8u16).to_be_bytes(); // ip header + udp header
1094        f.extend_from_slice(&[0x45, 0x00]);
1095        f.extend_from_slice(&ip_total_len);
1096        f.extend_from_slice(&[0, 0, 0, 0]); // id, flags/frag
1097        f.push(64); // ttl
1098        f.push(17); // protocol = UDP
1099        f.extend_from_slice(&[0, 0]); // checksum
1100        f.extend_from_slice(&[192, 168, 0, 1]); // src ip
1101        f.extend_from_slice(&[192, 168, 0, 2]); // dst ip
1102        // UDP header (8 bytes)
1103        f.extend_from_slice(&src_port.to_be_bytes());
1104        f.extend_from_slice(&dst_port.to_be_bytes());
1105        f.extend_from_slice(&8u16.to_be_bytes()); // length
1106        f.extend_from_slice(&[0, 0]); // checksum
1107        f
1108    }
1109
1110    fn parse(frame: &[u8]) -> ParsedPacket {
1111        PacketParser::new()
1112            .parse_packet(frame)
1113            .expect("frame should parse")
1114    }
1115
1116    fn tcp_packet(syn: bool, ack: bool, fin: bool, rst: bool, is_outgoing: bool) -> ParsedPacket {
1117        use crate::network::protocol::tcp::{TcpFlags, TcpHeaderInfo};
1118        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1119
1120        let mut packet = ParsedPacket::test_tcp(
1121            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
1122            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 443),
1123            TcpHeaderInfo {
1124                seq: 1_000,
1125                ack: 2_000,
1126                window: 65_535,
1127                flags: TcpFlags { syn, ack, fin, rst },
1128                payload_len: 0,
1129            },
1130        );
1131        packet.is_outgoing = is_outgoing;
1132        packet.packet_len = 60;
1133        packet
1134    }
1135
1136    fn quic_packet(packet_type: QuicPacketType, is_outgoing: bool) -> ParsedPacket {
1137        use crate::network::types::QuicInfo;
1138        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1139
1140        let mut quic = QuicInfo::new(1);
1141        quic.packet_type = packet_type;
1142
1143        let mut packet = ParsedPacket::test_udp(
1144            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
1145            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 443),
1146            ApplicationProtocol::Quic(Box::new(quic)),
1147        );
1148        packet.is_outgoing = is_outgoing;
1149        packet.packet_len = 1_200;
1150        packet
1151    }
1152
1153    fn dns_packet(txid: u16, is_outgoing: bool, is_response: bool, rcode: u8) -> ParsedPacket {
1154        use crate::network::types::{DnsInfo, DnsQueryType};
1155        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1156
1157        let mut packet = ParsedPacket::test_udp(
1158            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
1159            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 53),
1160            ApplicationProtocol::Dns(DnsInfo {
1161                query_name: Some("example.com".to_string()),
1162                query_type: Some(DnsQueryType::A),
1163                response_ips: Vec::new(),
1164                is_response,
1165                txid,
1166                rcode: is_response.then_some(rcode),
1167                nodata: None,
1168            }),
1169        );
1170        packet.is_outgoing = is_outgoing;
1171        packet.packet_len = 80;
1172        packet
1173    }
1174
1175    fn llmnr_packet(
1176        txid: u16,
1177        is_outgoing: bool,
1178        is_response: bool,
1179        remote_ip: [u8; 4],
1180    ) -> ParsedPacket {
1181        use crate::network::types::{AddrKind, DnsQueryType, LlmnrInfo};
1182        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1183
1184        let mut packet = ParsedPacket::test_udp(
1185            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
1186            SocketAddr::new(IpAddr::V4(Ipv4Addr::from(remote_ip)), 5355),
1187            ApplicationProtocol::Llmnr(LlmnrInfo {
1188                query_name: Some("workstation".to_string()),
1189                query_type: Some(DnsQueryType::A),
1190                is_response,
1191                response_ips: Vec::new(),
1192                txid,
1193            }),
1194        );
1195        if remote_ip == [224, 0, 0, 252] {
1196            packet.remote_addr_kind = AddrKind::Multicast;
1197        }
1198        packet.is_outgoing = is_outgoing;
1199        packet.packet_len = 80;
1200        packet
1201    }
1202
1203    /// An outgoing plain UDP packet (no DPI classification) to
1204    /// 203.0.113.80:9999, the flow the attribution tests try to name.
1205    fn plain_udp_packet() -> ParsedPacket {
1206        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1207
1208        let mut packet = ParsedPacket::test_base(
1209            Protocol::Udp,
1210            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
1211            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 80)), 9_999),
1212            ProtocolState::Udp,
1213        );
1214        packet.is_outgoing = true;
1215        packet.packet_len = 60;
1216        packet
1217    }
1218
1219    /// An incoming DNS response answering `query_name` with `response_ips`,
1220    /// as the passive attribution path sees it.
1221    fn dns_answer_packet(
1222        txid: u16,
1223        query_name: &str,
1224        response_ips: &[std::net::IpAddr],
1225    ) -> ParsedPacket {
1226        use crate::network::types::{DnsInfo, DnsQueryType};
1227        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1228
1229        let mut packet = ParsedPacket::test_udp(
1230            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 40_000),
1231            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 2)), 53),
1232            ApplicationProtocol::Dns(DnsInfo {
1233                query_name: Some(query_name.to_string()),
1234                query_type: Some(DnsQueryType::A),
1235                response_ips: response_ips.to_vec(),
1236                is_response: true,
1237                txid,
1238                rcode: Some(0),
1239                nodata: Some(false),
1240            }),
1241        );
1242        packet.is_outgoing = false;
1243        packet.packet_len = 120;
1244        packet
1245    }
1246
1247    fn netbios_packet(
1248        transaction_id: u16,
1249        is_outgoing: bool,
1250        opcode: NetBiosOpcode,
1251        is_response: bool,
1252        remote_ip: [u8; 4],
1253    ) -> ParsedPacket {
1254        use crate::network::types::{AddrKind, NetBiosInfo, NetBiosResponseStatus, NetBiosService};
1255        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1256
1257        let mut packet = ParsedPacket::test_udp(
1258            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 137),
1259            SocketAddr::new(IpAddr::V4(Ipv4Addr::from(remote_ip)), 137),
1260            ApplicationProtocol::NetBios(NetBiosInfo {
1261                service: NetBiosService::NameService,
1262                opcode,
1263                name: Some("FILESERVER".to_string()),
1264                transaction_id,
1265                is_response,
1266                response_status: is_response.then_some(NetBiosResponseStatus::NameService(0)),
1267            }),
1268        );
1269        if remote_ip == [255, 255, 255, 255] {
1270            packet.remote_addr_kind = AddrKind::Broadcast;
1271        }
1272        packet.is_outgoing = is_outgoing;
1273        packet.packet_len = 80;
1274        packet
1275    }
1276
1277    fn icmp_echo_packet(
1278        identifier: u16,
1279        sequence: u16,
1280        is_outgoing: bool,
1281        is_reply: bool,
1282    ) -> ParsedPacket {
1283        use crate::network::types::ProtocolState;
1284        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1285
1286        let mut packet = ParsedPacket::test_base(
1287            Protocol::Icmp,
1288            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 0),
1289            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 0),
1290            ProtocolState::Icmp {
1291                icmp_type: if is_reply { 0 } else { 8 },
1292                icmp_id: Some(identifier),
1293                icmp_sequence: Some(sequence),
1294                ndp_neighbor: None,
1295            },
1296        );
1297        packet.is_outgoing = is_outgoing;
1298        packet.packet_len = 84;
1299        packet
1300    }
1301
1302    /// Capture time for a packet `millis` into a synthetic trace. Tests drive
1303    /// `ingest_at` with these rather than the wall clock so an RTT assertion
1304    /// pins a real duration instead of however long the test loop took.
1305    fn capture_time(millis: u64) -> SystemTime {
1306        SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000) + Duration::from_millis(millis)
1307    }
1308
1309    fn arp_packet(operation: crate::network::types::ArpOperation) -> ParsedPacket {
1310        use crate::network::types::{ArpInfo, ProtocolState};
1311        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1312
1313        let mut packet = ParsedPacket::test_base(
1314            Protocol::Arp,
1315            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 132)), 0),
1316            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 0),
1317            ProtocolState::Arp(ArpInfo {
1318                operation,
1319                sender_mac: "04:d9:f5:c5:ed:e8".to_string(),
1320                sender_ip: IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)),
1321                target_mac: "68:5e:dd:09:15:5e".to_string(),
1322                target_ip: IpAddr::V4(Ipv4Addr::new(192, 168, 0, 132)),
1323                sender_vendor: Some("ASUSTek COMPUTER INC.".to_string()),
1324                target_vendor: Some("Apple, Inc.".to_string()),
1325            }),
1326        );
1327        packet.packet_len = 42;
1328        packet
1329    }
1330
1331    /// Ingesting an ARP reply must populate the neighbor cache for both the
1332    /// answering host and the requester, and the mapping must outlive the ARP
1333    /// connection row itself.
1334    #[test]
1335    fn arp_ingest_learns_neighbors() {
1336        use crate::network::types::ArpOperation;
1337        use std::net::{IpAddr, Ipv4Addr};
1338
1339        let tracker = ConnectionTracker::new();
1340        let gateway = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1));
1341        let laptop = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 132));
1342        assert!(tracker.neighbor(&gateway).is_none());
1343
1344        let outcome = tracker.ingest_at(&arp_packet(ArpOperation::Reply), capture_time(0));
1345
1346        let entry = tracker.neighbor(&gateway).expect("gateway learned");
1347        assert_eq!(entry.mac, "04:d9:f5:c5:ed:e8");
1348        assert_eq!(entry.vendor.as_deref(), Some("ASUSTek COMPUTER INC."));
1349        assert_eq!(
1350            tracker.neighbor(&laptop).expect("requester learned").mac,
1351            "68:5e:dd:09:15:5e"
1352        );
1353
1354        // The mapping survives removal of the ARP connection entry.
1355        tracker.connections().remove(&outcome.key);
1356        assert!(tracker.neighbor(&gateway).is_some());
1357    }
1358
1359    /// A full Ethernet+IPv6 frame carrying an NDP neighbor advertisement,
1360    /// so the test exercises the parser's hop-limit gate end to end.
1361    fn ndp_advertisement_frame(hop_limit: u8) -> Vec<u8> {
1362        let mut f = Vec::new();
1363        // Ethernet header: dst mac, src mac, ethertype IPv6 (0x86dd)
1364        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 1]);
1365        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 2]);
1366        f.extend_from_slice(&[0x86, 0xdd]);
1367        // IPv6 header (40 bytes)
1368        f.extend_from_slice(&[0x60, 0, 0, 0]); // version/tc/flow
1369        f.extend_from_slice(&32u16.to_be_bytes()); // payload length
1370        f.push(58); // next header = ICMPv6
1371        f.push(hop_limit);
1372        let src: std::net::Ipv6Addr = "fe80::cafe".parse().unwrap();
1373        let dst: std::net::Ipv6Addr = "ff02::1".parse().unwrap();
1374        f.extend_from_slice(&src.octets());
1375        f.extend_from_slice(&dst.octets());
1376        // ICMPv6 neighbor advertisement: header, target address, then the
1377        // target link-layer address option.
1378        f.extend_from_slice(&[136, 0, 0, 0, 0x20, 0, 0, 0]); // override flag
1379        let target: std::net::Ipv6Addr = "2001:db8::10".parse().unwrap();
1380        f.extend_from_slice(&target.octets());
1381        f.extend_from_slice(&[2, 1, 0x68, 0x5e, 0xdd, 0x09, 0x15, 0x5e]);
1382        f
1383    }
1384
1385    /// Ingesting an NDP neighbor advertisement must populate the neighbor
1386    /// cache for the advertised target address — but only when the frame
1387    /// arrived with hop limit 255, which proves it was not routed (RFC 4861).
1388    #[test]
1389    fn ndp_ingest_learns_advertised_target_at_hop_limit_255_only() {
1390        let target: std::net::IpAddr = "2001:db8::10".parse().unwrap();
1391
1392        let tracker = ConnectionTracker::new();
1393        tracker.ingest_at(&parse(&ndp_advertisement_frame(255)), capture_time(0));
1394        assert_eq!(
1395            tracker.neighbor(&target).expect("target learned").mac,
1396            "68:5e:dd:09:15:5e"
1397        );
1398
1399        let routed = ConnectionTracker::new();
1400        routed.ingest_at(&parse(&ndp_advertisement_frame(64)), capture_time(0));
1401        assert!(routed.neighbor(&target).is_none());
1402    }
1403
1404    /// QUIC's handshake is the only round trip an on-path observer can time,
1405    /// so the client Initial and the server's reply must pair up into the
1406    /// connection's initial RTT the way SYN/SYN-ACK does for TCP.
1407    ///
1408    /// The RTT must come from the packets' capture timestamps. Capture hands
1409    /// packets to processing in batches spanning up to 100 packets or 100ms, so
1410    /// a handshake this quick is processed as one microseconds-wide burst; a
1411    /// tracker that read its own clock would report 0.0ms here.
1412    #[test]
1413    fn quic_handshake_exchange_measures_initial_rtt() {
1414        let tracker = ConnectionTracker::new();
1415
1416        let client_initial =
1417            tracker.ingest_at(&quic_packet(QuicPacketType::Initial, true), capture_time(0));
1418        assert!(
1419            client_initial.measured_rtt.is_none(),
1420            "the opening Initial has nothing to pair with yet"
1421        );
1422
1423        let server_initial = tracker.ingest_at(
1424            &quic_packet(QuicPacketType::Initial, false),
1425            capture_time(18),
1426        );
1427        assert_eq!(
1428            server_initial.measured_rtt,
1429            Some(Duration::from_millis(18)),
1430            "the RTT is the gap between the two capture timestamps"
1431        );
1432        assert_eq!(
1433            tracker
1434                .connections()
1435                .get(&server_initial.key)
1436                .and_then(|conn| conn.initial_rtt),
1437            Some(Duration::from_millis(18)),
1438            "the measured RTT should land on the connection"
1439        );
1440    }
1441
1442    /// A repeated client Initial is a retransmission, not a reply, so it must
1443    /// not be read as a completed round trip.
1444    #[test]
1445    fn repeated_quic_initial_in_one_direction_measures_nothing() {
1446        let tracker = ConnectionTracker::new();
1447        tracker.ingest_at(&quic_packet(QuicPacketType::Initial, true), capture_time(0));
1448        let retransmit = tracker.ingest_at(
1449            &quic_packet(QuicPacketType::Initial, true),
1450            capture_time(250),
1451        );
1452        assert!(retransmit.measured_rtt.is_none());
1453        assert!(
1454            tracker
1455                .connections()
1456                .get(&retransmit.key)
1457                .and_then(|conn| conn.initial_rtt)
1458                .is_none()
1459        );
1460    }
1461
1462    /// rustnet watches from an endpoint, so an arriving packet followed by this
1463    /// host's own answer spans no network at all — it times the local stack's
1464    /// turnaround. Only an outbound packet may start the clock.
1465    ///
1466    /// A server's first flight is several datagrams, so this ordering shows up
1467    /// on ordinary connections once the first datagram has been paired off.
1468    #[test]
1469    fn inbound_quic_handshake_packet_does_not_start_the_clock() {
1470        let tracker = ConnectionTracker::new();
1471
1472        tracker.ingest_at(
1473            &quic_packet(QuicPacketType::Handshake, false),
1474            capture_time(0),
1475        );
1476        let local_reply = tracker.ingest_at(
1477            &quic_packet(QuicPacketType::Handshake, true),
1478            capture_time(1),
1479        );
1480        assert!(
1481            local_reply.measured_rtt.is_none(),
1482            "this host's own turnaround is not a round trip"
1483        );
1484        assert!(
1485            tracker
1486                .connections()
1487                .get(&local_reply.key)
1488                .and_then(|conn| conn.initial_rtt)
1489                .is_none()
1490        );
1491    }
1492
1493    /// Once the client Initial has been paired with the server's first
1494    /// datagram, the rest of the server's flight must not overwrite the real
1495    /// measurement with a local-turnaround one.
1496    #[test]
1497    fn later_server_flight_does_not_replace_the_handshake_rtt() {
1498        let tracker = ConnectionTracker::new();
1499
1500        tracker.ingest_at(&quic_packet(QuicPacketType::Initial, true), capture_time(0));
1501        tracker.ingest_at(
1502            &quic_packet(QuicPacketType::Initial, false),
1503            capture_time(18),
1504        );
1505
1506        // Remainder of the server's first flight, then this host's ACK.
1507        tracker.ingest_at(
1508            &quic_packet(QuicPacketType::Handshake, false),
1509            capture_time(19),
1510        );
1511        let ack = tracker.ingest_at(
1512            &quic_packet(QuicPacketType::Handshake, true),
1513            capture_time(19),
1514        );
1515        assert!(ack.measured_rtt.is_none());
1516
1517        assert_eq!(
1518            tracker
1519                .connections()
1520                .get(&ack.key)
1521                .and_then(|conn| conn.initial_rtt),
1522            Some(Duration::from_millis(18))
1523        );
1524    }
1525
1526    /// A DNS response pairs with its query by transaction ID, and the delta
1527    /// between the two capture timestamps lands on the connection. The
1528    /// transport-level `initial_rtt` must stay untouched: DNS time includes
1529    /// resolver processing.
1530    #[test]
1531    fn dns_query_response_measures_response_time() {
1532        let tracker = ConnectionTracker::new();
1533
1534        let query = tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
1535        assert!(query.dns_response_time.is_none());
1536
1537        let response = tracker.ingest_at(&dns_packet(0x1234, false, true, 0), capture_time(35));
1538        assert_eq!(
1539            response.dns_response_time,
1540            Some(Duration::from_millis(35)),
1541            "the response time is the gap between the two capture timestamps"
1542        );
1543        let conn = tracker.connections().get(&response.key).unwrap().clone();
1544        assert_eq!(conn.dns_response_time, Some(Duration::from_millis(35)));
1545        assert!(
1546            conn.initial_rtt.is_none(),
1547            "DNS timing must not pollute the transport RTT"
1548        );
1549    }
1550
1551    /// A response whose transaction ID matches no pending query (spoofed,
1552    /// expired, or captured mid-exchange) measures nothing.
1553    #[test]
1554    fn dns_response_with_unknown_txid_measures_nothing() {
1555        let tracker = ConnectionTracker::new();
1556        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
1557        let response = tracker.ingest_at(&dns_packet(0x9999, false, true, 0), capture_time(20));
1558        assert!(response.dns_response_time.is_none());
1559        assert!(
1560            tracker
1561                .connections()
1562                .get(&response.key)
1563                .and_then(|conn| conn.dns_response_time)
1564                .is_none()
1565        );
1566    }
1567
1568    /// Stub resolvers reuse one socket for many queries, so each completed
1569    /// exchange refreshes the connection's response time (last wins, unlike
1570    /// the one-shot `initial_rtt`).
1571    #[test]
1572    fn later_dns_exchange_updates_the_response_time() {
1573        let tracker = ConnectionTracker::new();
1574        tracker.ingest_at(&dns_packet(1, true, false, 0), capture_time(0));
1575        tracker.ingest_at(&dns_packet(1, false, true, 0), capture_time(35));
1576        tracker.ingest_at(&dns_packet(2, true, false, 0), capture_time(1_000));
1577        let second = tracker.ingest_at(&dns_packet(2, false, true, 0), capture_time(1_012));
1578        assert_eq!(second.dns_response_time, Some(Duration::from_millis(12)));
1579        assert_eq!(
1580            tracker
1581                .connections()
1582                .get(&second.key)
1583                .and_then(|conn| conn.dns_response_time),
1584            Some(Duration::from_millis(12))
1585        );
1586    }
1587
1588    /// When the local host is the DNS server, the inbound query followed by
1589    /// our own answer times the local resolver's turnaround, not the network,
1590    /// so it must measure nothing (mirrors the QUIC direction rule).
1591    #[test]
1592    fn local_dns_server_role_measures_nothing() {
1593        let tracker = ConnectionTracker::new();
1594        tracker.ingest_at(&dns_packet(0x1234, false, false, 0), capture_time(0));
1595        let reply = tracker.ingest_at(&dns_packet(0x1234, true, true, 0), capture_time(1));
1596        assert!(reply.dns_response_time.is_none());
1597    }
1598
1599    /// A re-sent query restarts the timer from the most recent send, so the
1600    /// measurement reflects the answered attempt, not the retry wait.
1601    #[test]
1602    fn retransmitted_dns_query_measures_from_the_last_send() {
1603        let tracker = ConnectionTracker::new();
1604        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
1605        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(1_000));
1606        let response = tracker.ingest_at(&dns_packet(0x1234, false, true, 0), capture_time(1_018));
1607        assert_eq!(response.dns_response_time, Some(Duration::from_millis(18)));
1608    }
1609
1610    /// SERVFAIL is still an answer: the round trip completed, so it is a valid
1611    /// timing sample. The response code is surfaced separately in the UI.
1612    #[test]
1613    fn dns_servfail_response_still_measures_response_time() {
1614        let tracker = ConnectionTracker::new();
1615        tracker.ingest_at(&dns_packet(0x1234, true, false, 0), capture_time(0));
1616        let response = tracker.ingest_at(&dns_packet(0x1234, false, true, 2), capture_time(40));
1617        assert_eq!(response.dns_response_time, Some(Duration::from_millis(40)));
1618    }
1619
1620    /// LLMNR sends a query to the link-local multicast group, then each
1621    /// responder replies via unicast. The first reply should time the lookup
1622    /// even though it belongs to a different connection-table key, and that
1623    /// timing should be visible from both rows.
1624    #[test]
1625    fn llmnr_multicast_query_measures_first_unicast_response_time() {
1626        let tracker = ConnectionTracker::new();
1627        let query = tracker.ingest_at(
1628            &llmnr_packet(0x1234, true, false, [224, 0, 0, 252]),
1629            capture_time(0),
1630        );
1631        assert!(query.llmnr_response_time.is_none());
1632
1633        let response = tracker.ingest_at(
1634            &llmnr_packet(0x1234, false, true, [192, 168, 0, 20]),
1635            capture_time(27),
1636        );
1637        assert_ne!(query.key, response.key);
1638        assert_eq!(
1639            response.llmnr_response_time,
1640            Some(Duration::from_millis(27))
1641        );
1642
1643        let response_conn = tracker.connections().get(&response.key).unwrap().clone();
1644        assert_eq!(
1645            response_conn.llmnr_response_time,
1646            Some(Duration::from_millis(27))
1647        );
1648        assert!(response_conn.initial_rtt.is_none());
1649
1650        let query_conn = tracker.connections().get(&query.key).unwrap().clone();
1651        assert_eq!(
1652            query_conn.llmnr_response_time,
1653            Some(Duration::from_millis(27))
1654        );
1655
1656        let second_response = tracker.ingest_at(
1657            &llmnr_packet(0x1234, false, true, [192, 168, 0, 21]),
1658            capture_time(35),
1659        );
1660        assert!(second_response.llmnr_response_time.is_none());
1661        assert!(
1662            tracker
1663                .connections()
1664                .get(&second_response.key)
1665                .and_then(|conn| conn.llmnr_response_time)
1666                .is_none()
1667        );
1668    }
1669
1670    #[test]
1671    fn llmnr_response_with_unknown_transaction_id_measures_nothing() {
1672        let tracker = ConnectionTracker::new();
1673        tracker.ingest_at(
1674            &llmnr_packet(0x1234, true, false, [224, 0, 0, 252]),
1675            capture_time(0),
1676        );
1677        let response = tracker.ingest_at(
1678            &llmnr_packet(0x9999, false, true, [192, 168, 0, 20]),
1679            capture_time(27),
1680        );
1681        assert!(response.llmnr_response_time.is_none());
1682    }
1683
1684    /// Name Service requests are normally broadcast, then answered from a
1685    /// host's unicast address. The transaction still pairs even though the
1686    /// request and response belong to different connection-table keys.
1687    #[test]
1688    fn netbios_broadcast_request_measures_unicast_response_time() {
1689        let tracker = ConnectionTracker::new();
1690        let query = tracker.ingest_at(
1691            &netbios_packet(
1692                0x1234,
1693                true,
1694                NetBiosOpcode::Query,
1695                false,
1696                [255, 255, 255, 255],
1697            ),
1698            capture_time(0),
1699        );
1700        assert!(query.netbios_response_time.is_none());
1701
1702        let response = tracker.ingest_at(
1703            &netbios_packet(
1704                0x1234,
1705                false,
1706                NetBiosOpcode::Response,
1707                true,
1708                [192, 168, 0, 20],
1709            ),
1710            capture_time(27),
1711        );
1712        assert_ne!(query.key, response.key);
1713        assert_eq!(
1714            response.netbios_response_time,
1715            Some(Duration::from_millis(27))
1716        );
1717        let conn = tracker.connections().get(&response.key).unwrap().clone();
1718        assert_eq!(conn.netbios_response_time, Some(Duration::from_millis(27)));
1719        assert!(conn.initial_rtt.is_none());
1720
1721        // The broadcast row is the one a user naturally inspects, so the
1722        // round trip must land there as well, not only on the responder.
1723        let query_conn = tracker.connections().get(&query.key).unwrap().clone();
1724        assert_eq!(
1725            query_conn.netbios_response_time,
1726            Some(Duration::from_millis(27))
1727        );
1728    }
1729
1730    #[test]
1731    fn netbios_response_with_unknown_transaction_id_measures_nothing() {
1732        let tracker = ConnectionTracker::new();
1733        tracker.ingest_at(
1734            &netbios_packet(
1735                0x1234,
1736                true,
1737                NetBiosOpcode::Query,
1738                false,
1739                [255, 255, 255, 255],
1740            ),
1741            capture_time(0),
1742        );
1743        let response = tracker.ingest_at(
1744            &netbios_packet(
1745                0x9999,
1746                false,
1747                NetBiosOpcode::Response,
1748                true,
1749                [192, 168, 0, 20],
1750            ),
1751            capture_time(27),
1752        );
1753        assert!(response.netbios_response_time.is_none());
1754    }
1755
1756    /// A WACK extends an NBNS transaction and must not consume its pending
1757    /// request. The eventual final response completes the original timing.
1758    #[test]
1759    fn netbios_wack_keeps_request_pending() {
1760        let tracker = ConnectionTracker::new();
1761        tracker.ingest_at(
1762            &netbios_packet(
1763                0x1234,
1764                true,
1765                NetBiosOpcode::Registration,
1766                false,
1767                [192, 168, 0, 2],
1768            ),
1769            capture_time(0),
1770        );
1771        let wack = tracker.ingest_at(
1772            &netbios_packet(0x1234, false, NetBiosOpcode::Wack, false, [192, 168, 0, 2]),
1773            capture_time(10),
1774        );
1775        assert!(wack.netbios_response_time.is_none());
1776
1777        let response = tracker.ingest_at(
1778            &netbios_packet(
1779                0x1234,
1780                false,
1781                NetBiosOpcode::Response,
1782                true,
1783                [192, 168, 0, 2],
1784            ),
1785            capture_time(40),
1786        );
1787        assert_eq!(
1788            response.netbios_response_time,
1789            Some(Duration::from_millis(40))
1790        );
1791    }
1792
1793    /// Subsecond ping intervals can leave several requests outstanding. The
1794    /// sequence number keeps each reply attached to its own send timestamp,
1795    /// even when replies complete out of order.
1796    #[test]
1797    fn fast_ping_pairs_each_echo_by_identifier_and_sequence() {
1798        let tracker = ConnectionTracker::new();
1799
1800        tracker.ingest_at(&icmp_echo_packet(0x1234, 1, true, false), capture_time(0));
1801        tracker.ingest_at(&icmp_echo_packet(0x1234, 2, true, false), capture_time(200));
1802        let second_reply =
1803            tracker.ingest_at(&icmp_echo_packet(0x1234, 2, false, true), capture_time(225));
1804        let first_reply =
1805            tracker.ingest_at(&icmp_echo_packet(0x1234, 1, false, true), capture_time(350));
1806
1807        assert_eq!(second_reply.icmp_echo_rtt, Some(Duration::from_millis(25)));
1808        assert_eq!(first_reply.icmp_echo_rtt, Some(Duration::from_millis(350)));
1809
1810        tracker.ingest_at(&icmp_echo_packet(0x1234, 3, true, false), capture_time(400));
1811        let third_reply =
1812            tracker.ingest_at(&icmp_echo_packet(0x1234, 3, false, true), capture_time(418));
1813        let conn = tracker
1814            .connections()
1815            .get(&third_reply.key)
1816            .expect("ping connection should exist")
1817            .clone();
1818        assert_eq!(third_reply.icmp_echo_rtt, Some(Duration::from_millis(18)));
1819        assert_eq!(conn.icmp_echo_rtt, Some(Duration::from_millis(18)));
1820        assert_eq!(conn.current_rtt(), Some(Duration::from_millis(18)));
1821    }
1822
1823    #[test]
1824    fn echo_reply_with_unknown_sequence_measures_nothing() {
1825        let tracker = ConnectionTracker::new();
1826        tracker.ingest_at(&icmp_echo_packet(7, 10, true, false), capture_time(0));
1827        let reply = tracker.ingest_at(&icmp_echo_packet(7, 11, false, true), capture_time(12));
1828
1829        assert!(reply.icmp_echo_rtt.is_none());
1830        assert!(
1831            tracker
1832                .connections()
1833                .get(&reply.key)
1834                .and_then(|conn| conn.icmp_echo_rtt)
1835                .is_none()
1836        );
1837    }
1838
1839    #[test]
1840    fn local_echo_responder_turnaround_measures_nothing() {
1841        let tracker = ConnectionTracker::new();
1842        tracker.ingest_at(&icmp_echo_packet(7, 1, false, false), capture_time(0));
1843        let reply = tracker.ingest_at(&icmp_echo_packet(7, 1, true, true), capture_time(1));
1844
1845        assert!(reply.icmp_echo_rtt.is_none());
1846    }
1847
1848    fn loopback_echo_packet(identifier: u16, sequence: u16, is_reply: bool) -> ParsedPacket {
1849        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1850
1851        let mut packet = icmp_echo_packet(identifier, sequence, true, is_reply);
1852        let loopback = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
1853        packet.local_addr = loopback;
1854        packet.remote_addr = loopback;
1855        packet
1856    }
1857
1858    /// Loopback captures classify both the request and its reply as outgoing
1859    /// because both endpoints are local. The reply must still pair up.
1860    #[test]
1861    fn loopback_ping_measures_rtt() {
1862        let tracker = ConnectionTracker::new();
1863        tracker.ingest_at(&loopback_echo_packet(9, 1, false), capture_time(0));
1864        let reply = tracker.ingest_at(&loopback_echo_packet(9, 1, true), capture_time(1));
1865
1866        assert_eq!(reply.icmp_echo_rtt, Some(Duration::from_millis(1)));
1867    }
1868
1869    /// Echo requests reveal who initiated the flow; the Details tab uses the
1870    /// direction to hide the RTT row on flows this host only answers.
1871    #[test]
1872    fn echo_request_sets_connection_direction() {
1873        let tracker = ConnectionTracker::new();
1874        let outgoing = tracker.ingest_at(&icmp_echo_packet(7, 1, true, false), capture_time(0));
1875        let direction = tracker
1876            .connections()
1877            .get(&outgoing.key)
1878            .and_then(|conn| conn.connection_direction);
1879        assert_eq!(direction, Some(true));
1880
1881        let tracker = ConnectionTracker::new();
1882        let inbound = tracker.ingest_at(&icmp_echo_packet(7, 1, false, false), capture_time(0));
1883        tracker.ingest_at(&icmp_echo_packet(7, 1, true, true), capture_time(1));
1884        let direction = tracker
1885            .connections()
1886            .get(&inbound.key)
1887            .and_then(|conn| conn.connection_direction);
1888        assert_eq!(direction, Some(false), "our reply must not flip it");
1889    }
1890
1891    fn stun_packet(
1892        transaction_id: [u8; 12],
1893        is_outgoing: bool,
1894        class: crate::network::types::StunMessageClass,
1895    ) -> ParsedPacket {
1896        use crate::network::types::{StunInfo, StunMethod};
1897        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1898
1899        let mut packet = ParsedPacket::test_udp(
1900            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 54_000),
1901            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 5)), 3478),
1902            ApplicationProtocol::Stun(StunInfo {
1903                message_class: class,
1904                method: StunMethod::Binding,
1905                transaction_id,
1906                software: None,
1907            }),
1908        );
1909        packet.is_outgoing = is_outgoing;
1910        packet.packet_len = 48;
1911        packet
1912    }
1913
1914    /// STUN binding requests and responses pair by transaction ID, giving a
1915    /// UDP flow with no handshake a real request→response time.
1916    #[test]
1917    fn stun_binding_response_measures_rtt() {
1918        use crate::network::types::StunMessageClass;
1919
1920        let tracker = ConnectionTracker::new();
1921        let txid = [3u8; 12];
1922        tracker.ingest_at(
1923            &stun_packet(txid, true, StunMessageClass::Request),
1924            capture_time(0),
1925        );
1926        let response = tracker.ingest_at(
1927            &stun_packet(txid, false, StunMessageClass::SuccessResponse),
1928            capture_time(31),
1929        );
1930
1931        assert_eq!(response.stun_rtt, Some(Duration::from_millis(31)));
1932        let conn = tracker
1933            .connections()
1934            .get(&response.key)
1935            .expect("stun connection should exist")
1936            .clone();
1937        assert_eq!(conn.stun_rtt, Some(Duration::from_millis(31)));
1938    }
1939
1940    fn ntp_packet(
1941        mode: crate::network::types::NtpMode,
1942        is_outgoing: bool,
1943        origin_timestamp: u64,
1944        transmit_timestamp: u64,
1945    ) -> ParsedPacket {
1946        use crate::network::types::NtpInfo;
1947        use std::net::{IpAddr, Ipv4Addr, SocketAddr};
1948
1949        let mut packet = ParsedPacket::test_udp(
1950            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)), 47_000),
1951            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 9)), 123),
1952            ApplicationProtocol::Ntp(NtpInfo {
1953                version: 4,
1954                mode,
1955                stratum: 2,
1956                origin_timestamp,
1957                transmit_timestamp,
1958            }),
1959        );
1960        packet.is_outgoing = is_outgoing;
1961        packet.packet_len = 90;
1962        packet
1963    }
1964
1965    /// An NTP poll pairs with its response through the originate timestamp
1966    /// echo, giving the UDP flow a request→response time.
1967    #[test]
1968    fn ntp_server_response_measures_rtt() {
1969        use crate::network::types::NtpMode;
1970
1971        let tracker = ConnectionTracker::new();
1972        tracker.ingest_at(
1973            &ntp_packet(NtpMode::Client, true, 0, 0xAABB),
1974            capture_time(0),
1975        );
1976        let response = tracker.ingest_at(
1977            &ntp_packet(NtpMode::Server, false, 0xAABB, 0xCCDD),
1978            capture_time(21),
1979        );
1980
1981        assert_eq!(response.ntp_rtt, Some(Duration::from_millis(21)));
1982        let conn = tracker
1983            .connections()
1984            .get(&response.key)
1985            .expect("ntp connection should exist")
1986            .clone();
1987        assert_eq!(conn.ntp_rtt, Some(Duration::from_millis(21)));
1988    }
1989
1990    #[test]
1991    fn stun_response_with_unknown_transaction_measures_nothing() {
1992        use crate::network::types::StunMessageClass;
1993
1994        let tracker = ConnectionTracker::new();
1995        tracker.ingest_at(
1996            &stun_packet([3u8; 12], true, StunMessageClass::Request),
1997            capture_time(0),
1998        );
1999        let response = tracker.ingest_at(
2000            &stun_packet([4u8; 12], false, StunMessageClass::SuccessResponse),
2001            capture_time(31),
2002        );
2003
2004        assert!(response.stun_rtt.is_none());
2005    }
2006
2007    /// 1-RTT packets carry a short header with nothing timeable in the clear.
2008    #[test]
2009    fn quic_one_rtt_packets_do_not_measure_rtt() {
2010        let tracker = ConnectionTracker::new();
2011        tracker.ingest_at(&quic_packet(QuicPacketType::OneRtt, true), capture_time(0));
2012        let inbound = tracker.ingest_at(
2013            &quic_packet(QuicPacketType::OneRtt, false),
2014            capture_time(18),
2015        );
2016        assert!(inbound.measured_rtt.is_none());
2017    }
2018
2019    /// The TCP handshake is timed from capture timestamps for the same reason
2020    /// the QUIC one is: SYN and SYN-ACK routinely land in a single batch.
2021    #[test]
2022    fn tcp_handshake_rtt_comes_from_capture_timestamps() {
2023        let tracker = ConnectionTracker::new();
2024
2025        tracker.ingest_at(
2026            &tcp_packet(true, false, false, false, true),
2027            capture_time(0),
2028        );
2029        let syn_ack = tracker.ingest_at(
2030            &tcp_packet(true, true, false, false, false),
2031            capture_time(12),
2032        );
2033        assert_eq!(syn_ack.measured_rtt, Some(Duration::from_millis(12)));
2034    }
2035
2036    #[test]
2037    fn ingest_creates_then_updates() {
2038        let tracker = ConnectionTracker::new();
2039        let p = parse(&udp_frame(40000, 53));
2040
2041        let first = tracker.ingest(&p);
2042        assert!(first.created, "first packet should create a connection");
2043        assert!(!first.dropped);
2044        assert_eq!(tracker.len(), 1);
2045
2046        let second = tracker.ingest(&p);
2047        assert!(!second.created, "second packet should update, not create");
2048        assert_eq!(second.key, first.key);
2049        assert_eq!(tracker.len(), 1);
2050    }
2051
2052    #[test]
2053    fn distinct_flows_are_separate_connections() {
2054        let tracker = ConnectionTracker::new();
2055        tracker.ingest(&parse(&udp_frame(40000, 53)));
2056        tracker.ingest(&parse(&udp_frame(40001, 53)));
2057        assert_eq!(tracker.len(), 2);
2058    }
2059
2060    #[test]
2061    fn max_connections_limit_drops_new_only() {
2062        let tracker = ConnectionTracker::with_config(TrackerConfig {
2063            max_connections: 1,
2064            ..TrackerConfig::default()
2065        });
2066        let a = tracker.ingest(&parse(&udp_frame(40000, 53)));
2067        assert!(a.created && !a.dropped);
2068
2069        // A different flow can't be inserted (limit reached) and is dropped.
2070        let b = tracker.ingest(&parse(&udp_frame(40001, 53)));
2071        assert!(b.dropped, "new connection beyond the limit must be dropped");
2072        assert!(!b.created);
2073        assert_eq!(tracker.len(), 1);
2074
2075        // The existing flow still updates despite the limit.
2076        let a2 = tracker.ingest(&parse(&udp_frame(40000, 53)));
2077        assert!(!a2.dropped && !a2.created);
2078    }
2079
2080    #[test]
2081    fn connection_limit_recovers_after_cleanup() {
2082        let tracker = ConnectionTracker::with_config(TrackerConfig {
2083            max_connections: 1,
2084            ..TrackerConfig::default()
2085        });
2086        assert!(tracker.ingest(&parse(&udp_frame(40000, 53))).created);
2087        assert!(tracker.ingest(&parse(&udp_frame(40001, 53))).dropped);
2088
2089        // Expire everything; the limit accounting must follow the removals.
2090        tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
2091        assert_eq!(tracker.len(), 0);
2092
2093        let c = tracker.ingest(&parse(&udp_frame(40002, 53)));
2094        assert!(
2095            c.created && !c.dropped,
2096            "slot freed by cleanup must be reusable"
2097        );
2098        assert_eq!(tracker.len(), 1);
2099    }
2100
2101    #[test]
2102    fn connection_limit_recovers_after_clear() {
2103        let tracker = ConnectionTracker::with_config(TrackerConfig {
2104            max_connections: 1,
2105            ..TrackerConfig::default()
2106        });
2107        assert!(tracker.ingest(&parse(&udp_frame(40000, 53))).created);
2108        tracker.clear();
2109        let b = tracker.ingest(&parse(&udp_frame(40001, 53)));
2110        assert!(b.created && !b.dropped, "clear() must reset the limit");
2111    }
2112
2113    #[test]
2114    fn cleanup_archives_to_historic() {
2115        let tracker = ConnectionTracker::new();
2116        tracker.ingest(&parse(&udp_frame(40000, 53)));
2117        assert_eq!(tracker.len(), 1);
2118
2119        for mut entry in tracker.connections().iter_mut() {
2120            entry.current_incoming_rate_bps = 2048.0;
2121            entry.current_outgoing_rate_bps = 1024.0;
2122        }
2123
2124        // A far-future `now` forces every connection past its timeout.
2125        let far_future = SystemTime::now() + Duration::from_secs(86_400);
2126        let removed = tracker.cleanup(far_future);
2127
2128        assert_eq!(removed.len(), 1, "the idle connection should be removed");
2129        assert!(!removed[0].is_historic, "returned form is the original");
2130        assert_eq!(tracker.len(), 0);
2131        assert_eq!(
2132            tracker.historic_len(),
2133            1,
2134            "removed conn archived as historic"
2135        );
2136        let historic = tracker.historic().iter().next().unwrap();
2137        assert_eq!(historic.current_incoming_rate_bps, 0.0);
2138        assert_eq!(historic.current_outgoing_rate_bps, 0.0);
2139    }
2140
2141    #[test]
2142    fn traffic_refreshes_a_stale_nonterminal_connection() {
2143        let tracker = ConnectionTracker::new();
2144        let packet = parse(&udp_frame(40000, 9999));
2145        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2146        tracker.ingest_at(&packet, started);
2147
2148        assert!(
2149            tracker
2150                .cleanup(started + Duration::from_secs(59))
2151                .is_empty()
2152        );
2153        tracker.ingest_at(&packet, started + Duration::from_secs(59));
2154        assert!(
2155            tracker
2156                .cleanup(started + Duration::from_secs(61))
2157                .is_empty()
2158        );
2159        assert_eq!(tracker.len(), 1);
2160    }
2161
2162    #[test]
2163    fn terminal_retransmissions_do_not_postpone_archival() {
2164        let tracker = ConnectionTracker::new();
2165        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2166        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
2167        tracker.ingest_at(
2168            &tcp_packet(false, true, false, false, false),
2169            started + Duration::from_secs(10),
2170        );
2171
2172        let conn = tracker.connections().iter().next().unwrap();
2173        assert_eq!(conn.last_activity, started + Duration::from_secs(10));
2174        assert_eq!(conn.terminal_since, Some(started));
2175        drop(conn);
2176
2177        let removed = tracker.cleanup(started + Duration::from_secs(16));
2178        assert_eq!(removed.len(), 1);
2179        assert_eq!(tracker.historic_len(), 1);
2180    }
2181
2182    #[test]
2183    fn syn_after_terminal_state_starts_a_new_generation() {
2184        use crate::network::types::{ProtocolState, TcpState};
2185
2186        let tracker = ConnectionTracker::new();
2187        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2188        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
2189
2190        let outcome = tracker.ingest_at(&tcp_packet(true, false, false, false, true), started);
2191        assert!(outcome.created);
2192        assert!(outcome.archived.is_some());
2193        assert_eq!(tracker.len(), 1);
2194        assert_eq!(tracker.historic_len(), 1);
2195
2196        let active = tracker.connections().iter().next().unwrap();
2197        assert_eq!(
2198            active.created_at,
2199            started + Duration::from_nanos(1),
2200            "a same-batch replacement needs a distinct historic identity"
2201        );
2202        assert!(matches!(
2203            active.protocol_state,
2204            ProtocolState::Tcp(TcpState::SynSent)
2205        ));
2206        assert!(!active.is_historic);
2207        drop(active);
2208
2209        let historic = tracker.historic().iter().next().unwrap();
2210        assert_eq!(historic.created_at, started);
2211        assert!(historic.is_historic);
2212        assert_eq!(historic.closed_at, Some(started));
2213        drop(historic);
2214
2215        tracker.cleanup(started + Duration::from_secs(61));
2216        assert_eq!(
2217            tracker.historic_len(),
2218            2,
2219            "archiving the replacement must not overwrite the old generation"
2220        );
2221    }
2222
2223    #[test]
2224    fn delayed_ack_after_archival_is_not_a_phantom_connection() {
2225        let tracker = ConnectionTracker::new();
2226        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2227        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
2228        tracker.cleanup(started + Duration::from_secs(16));
2229
2230        let outcome = tracker.ingest_at(
2231            &tcp_packet(false, true, false, false, false),
2232            started + Duration::from_secs(17),
2233        );
2234        assert!(outcome.ignored_late);
2235        assert!(!outcome.created);
2236        assert!(tracker.is_empty());
2237        assert_eq!(tracker.historic_len(), 1);
2238    }
2239
2240    #[test]
2241    fn payload_after_terminal_archival_starts_a_new_generation() {
2242        let tracker = ConnectionTracker::new();
2243        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2244        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
2245        tracker.cleanup(started + Duration::from_secs(16));
2246
2247        let mut packet = tcp_packet(false, true, false, false, false);
2248        packet.tcp_header.as_mut().unwrap().payload_len = 100;
2249        let outcome = tracker.ingest_at(&packet, started + Duration::from_secs(17));
2250
2251        assert!(!outcome.ignored_late);
2252        assert!(outcome.created);
2253        assert_eq!(tracker.len(), 1);
2254        assert_eq!(tracker.historic_len(), 1);
2255    }
2256
2257    #[test]
2258    fn traffic_after_idle_archival_starts_a_new_generation_immediately() {
2259        let tracker = ConnectionTracker::new();
2260        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2261        tracker.ingest_at(&tcp_packet(false, true, false, false, true), started);
2262        tracker.cleanup(started + Duration::from_secs(301));
2263
2264        let outcome = tracker.ingest_at(
2265            &tcp_packet(false, true, false, false, false),
2266            started + Duration::from_secs(302),
2267        );
2268        assert!(!outcome.ignored_late);
2269        assert!(outcome.created);
2270        assert_eq!(tracker.len(), 1);
2271        assert_eq!(tracker.historic_len(), 1);
2272    }
2273
2274    #[test]
2275    fn midstream_ack_is_allowed_after_recent_tombstone_expires() {
2276        use crate::network::types::{ProtocolState, TcpState};
2277
2278        let tracker = ConnectionTracker::new();
2279        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2280        tracker.ingest_at(&tcp_packet(false, false, false, true, true), started);
2281        tracker.cleanup(started + Duration::from_secs(16));
2282
2283        let outcome = tracker.ingest_at(
2284            &tcp_packet(false, true, false, false, false),
2285            started + Duration::from_secs(47),
2286        );
2287        assert!(!outcome.ignored_late);
2288        assert!(outcome.created);
2289        let active = tracker.connections().iter().next().unwrap();
2290        assert!(matches!(
2291            active.protocol_state,
2292            ProtocolState::Tcp(TcpState::Established)
2293        ));
2294    }
2295
2296    #[test]
2297    fn new_activity_does_not_mutate_a_historic_snapshot() {
2298        let tracker = ConnectionTracker::new();
2299        let packet = parse(&udp_frame(40000, 9999));
2300        let started = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2301        tracker.ingest_at(&packet, started);
2302        tracker.cleanup(started + Duration::from_secs(61));
2303
2304        let historic_before = tracker.historic.iter().next().unwrap().value().clone();
2305        tracker.ingest_at(&packet, started + Duration::from_secs(62));
2306        tracker.ingest_at(&packet, started + Duration::from_secs(63));
2307        let historic_after = tracker.historic.iter().next().unwrap().value().clone();
2308
2309        assert_eq!(historic_after.bytes_sent, historic_before.bytes_sent);
2310        assert_eq!(
2311            historic_after.bytes_received,
2312            historic_before.bytes_received
2313        );
2314        assert_eq!(historic_after.last_activity, historic_before.last_activity);
2315        assert_eq!(historic_after.closed_at, historic_before.closed_at);
2316        assert_eq!(tracker.len(), 1);
2317    }
2318
2319    #[test]
2320    fn retained_source_view_is_atomic_across_cleanup() {
2321        let tracker = std::sync::Arc::new(ConnectionTracker::new());
2322        tracker.ingest(&parse(&udp_frame(40000, 53)));
2323
2324        let (active_scanned_tx, active_scanned_rx) = std::sync::mpsc::channel();
2325        let (release_tx, release_rx) = std::sync::mpsc::channel();
2326        let reader_tracker = std::sync::Arc::clone(&tracker);
2327        let reader = std::thread::spawn(move || {
2328            reader_tracker.with_retained_sources(|active, historic| {
2329                let active_count = active.iter().count();
2330                active_scanned_tx.send(()).unwrap();
2331                release_rx.recv().unwrap();
2332                active_count + historic.iter().count()
2333            })
2334        });
2335
2336        active_scanned_rx.recv().unwrap();
2337        let (cleanup_started_tx, cleanup_started_rx) = std::sync::mpsc::channel();
2338        let (cleanup_done_tx, cleanup_done_rx) = std::sync::mpsc::channel();
2339        let cleanup_tracker = std::sync::Arc::clone(&tracker);
2340        let cleanup = std::thread::spawn(move || {
2341            cleanup_started_tx.send(()).unwrap();
2342            let removed = cleanup_tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
2343            cleanup_done_tx.send(removed.len()).unwrap();
2344        });
2345
2346        cleanup_started_rx.recv().unwrap();
2347        assert!(
2348            cleanup_done_rx
2349                .recv_timeout(Duration::from_millis(50))
2350                .is_err(),
2351            "cleanup must wait for the retained source view"
2352        );
2353        release_tx.send(()).unwrap();
2354
2355        assert_eq!(reader.join().unwrap(), 1);
2356        assert_eq!(cleanup_done_rx.recv().unwrap(), 1);
2357        cleanup.join().unwrap();
2358        assert_eq!(tracker.len(), 0);
2359        assert_eq!(tracker.historic_len(), 1);
2360    }
2361
2362    #[test]
2363    fn cleanup_without_keep_historic_skips_archive() {
2364        let tracker = ConnectionTracker::with_config(TrackerConfig {
2365            keep_historic: false,
2366            ..TrackerConfig::default()
2367        });
2368        tracker.ingest(&parse(&udp_frame(40000, 53)));
2369        let far_future = SystemTime::now() + Duration::from_secs(86_400);
2370        let removed = tracker.cleanup(far_future);
2371        assert_eq!(removed.len(), 1);
2372        assert_eq!(tracker.historic_len(), 0, "historic disabled");
2373    }
2374
2375    /// `max_historic` sizes the user-facing archive; it must not shrink the
2376    /// tombstone table below the floor, or closing more flows than the cap
2377    /// lets delayed teardown packets resurrect phantom connections.
2378    #[test]
2379    fn zero_max_historic_keeps_tombstones_for_all_closed_flows() {
2380        let tracker = ConnectionTracker::with_config(TrackerConfig {
2381            keep_historic: false,
2382            max_historic: 0,
2383            ..TrackerConfig::default()
2384        });
2385
2386        let start = SystemTime::now();
2387        for port in [40_000u16, 40_001] {
2388            let mut syn = tcp_packet(true, false, false, false, true);
2389            syn.local_addr.set_port(port);
2390            tracker.ingest_at(&syn, start);
2391            let mut rst = tcp_packet(false, false, false, true, true);
2392            rst.local_addr.set_port(port);
2393            tracker.ingest_at(&rst, start + Duration::from_secs(1));
2394        }
2395        assert_eq!(tracker.len(), 2);
2396
2397        let closed_at = start + Duration::from_secs(86_400);
2398        let removed = tracker.cleanup(closed_at);
2399        assert_eq!(removed.len(), 2);
2400
2401        for port in [40_000u16, 40_001] {
2402            let mut late_fin = tcp_packet(false, true, true, false, true);
2403            late_fin.local_addr.set_port(port);
2404            let outcome = tracker.ingest_at(&late_fin, closed_at + Duration::from_secs(1));
2405            assert!(
2406                outcome.ignored_late,
2407                "delayed teardown for port {port} must hit a tombstone"
2408            );
2409        }
2410        assert!(tracker.is_empty(), "no phantom connections may be created");
2411    }
2412
2413    #[test]
2414    fn ingest_at_uses_supplied_time_for_cleanup() {
2415        // A packet ingested "in the past" must be eligible for cleanup at a
2416        // `now` only slightly later than its supplied capture time — proving the
2417        // tracker stamps the connection with the caller's time, not the wall
2418        // clock. (Wall-clock stamping would make `created_at` ~= real now, so a
2419        // cleanup at trace-time + a few minutes would NOT expire it.)
2420        let tracker = ConnectionTracker::new();
2421        let capture_time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
2422        tracker.ingest_at(&parse(&udp_frame(40000, 53)), capture_time);
2423        assert_eq!(tracker.len(), 1);
2424
2425        // One day after the capture time the UDP flow is well past its timeout.
2426        let removed = tracker.cleanup(capture_time + Duration::from_secs(86_400));
2427        assert_eq!(
2428            removed.len(),
2429            1,
2430            "flow stamped at capture time should expire"
2431        );
2432        assert_eq!(tracker.len(), 0);
2433    }
2434
2435    /// A connection opened right after a captured DNS response to one of the
2436    /// answered IPs must be tagged with the query name at creation. With
2437    /// `dns_attribution` disabled, the same traffic must stay untagged.
2438    #[test]
2439    fn dns_response_attributes_a_following_connection() {
2440        let answered_ip: std::net::IpAddr = "203.0.113.80".parse().unwrap();
2441
2442        let tracker = ConnectionTracker::new();
2443        tracker.ingest_at(
2444            &dns_answer_packet(1, "cdn.example", &[answered_ip]),
2445            capture_time(0),
2446        );
2447        let outcome = tracker.ingest_at(&plain_udp_packet(), capture_time(50));
2448        assert_eq!(
2449            tracker
2450                .connections()
2451                .get(&outcome.key)
2452                .and_then(|conn| conn.attributed_hostname.as_ref().map(|a| a.name.clone())),
2453            Some("cdn.example".to_string())
2454        );
2455
2456        let disabled = ConnectionTracker::with_config(TrackerConfig {
2457            dns_attribution: false,
2458            ..TrackerConfig::default()
2459        });
2460        disabled.ingest_at(
2461            &dns_answer_packet(1, "cdn.example", &[answered_ip]),
2462            capture_time(0),
2463        );
2464        let outcome = disabled.ingest_at(&plain_udp_packet(), capture_time(50));
2465        assert!(
2466            disabled
2467                .connections()
2468                .get(&outcome.key)
2469                .unwrap()
2470                .attributed_hostname
2471                .is_none(),
2472            "the config flag must disable attribution"
2473        );
2474    }
2475
2476    /// A connection observed before any matching DNS waits in the pending
2477    /// index; the DNS response that later answers its remote IP tags it.
2478    #[test]
2479    fn late_dns_response_attributes_a_pending_connection() {
2480        let tracker = ConnectionTracker::new();
2481        let outcome = tracker.ingest_at(&plain_udp_packet(), capture_time(0));
2482        assert!(
2483            tracker
2484                .connections()
2485                .get(&outcome.key)
2486                .unwrap()
2487                .attributed_hostname
2488                .is_none()
2489        );
2490
2491        let answered_ip: std::net::IpAddr = "203.0.113.80".parse().unwrap();
2492        tracker.ingest_at(
2493            &dns_answer_packet(1, "late.example", &[answered_ip]),
2494            capture_time(200),
2495        );
2496        assert_eq!(
2497            tracker
2498                .connections()
2499                .get(&outcome.key)
2500                .and_then(|conn| conn.attributed_hostname.as_ref().map(|a| a.name.clone())),
2501            Some("late.example".to_string())
2502        );
2503    }
2504
2505    /// Cleaning up a still-pending connection must drop its enrollment, so a
2506    /// DNS response arriving after its death finds no waiter and the archived
2507    /// record stays unattributed.
2508    #[test]
2509    fn cleanup_forgets_pending_attribution_enrollments() {
2510        let tracker = ConnectionTracker::new();
2511        tracker.ingest(&plain_udp_packet());
2512        let removed = tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
2513        assert_eq!(removed.len(), 1);
2514
2515        let answered_ip: std::net::IpAddr = "203.0.113.80".parse().unwrap();
2516        tracker.ingest(&dns_answer_packet(1, "posthumous.example", &[answered_ip]));
2517        assert!(
2518            tracker
2519                .historic
2520                .iter()
2521                .all(|conn| conn.attributed_hostname.is_none()),
2522            "a response after death must not label the archived record"
2523        );
2524    }
2525
2526    #[test]
2527    fn clear_empties_everything() {
2528        let tracker = ConnectionTracker::new();
2529        tracker.ingest(&parse(&udp_frame(40000, 53)));
2530        tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
2531        assert_eq!(tracker.historic_len(), 1);
2532        tracker.clear();
2533        assert!(tracker.is_empty());
2534        assert_eq!(tracker.historic_len(), 0);
2535    }
2536}