Skip to main content

rustnet_core/network/
parser.rs

1use crate::network::dpi::DpiResult;
2use crate::network::link_layer;
3#[cfg(target_os = "macos")]
4use crate::network::link_layer::ethernet;
5#[cfg(target_os = "macos")]
6use crate::network::link_layer::pktap;
7use crate::network::local_addresses::{LocalAddresses, collect_local_addresses};
8use crate::network::oui::OuiLookup;
9use crate::network::protocol;
10use crate::network::protocol::TransportParams;
11use crate::network::types::*;
12use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
13use std::time::{Duration, Instant};
14
15const AMBIGUOUS_ENDPOINT_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
16const AMBIGUOUS_ENDPOINT_REFRESH_MAX_INTERVAL: Duration = Duration::from_secs(60);
17
18pub use crate::network::protocol::tcp::{SynWindowScale, TcpFlags, TcpHeaderInfo};
19
20/// Result of parsing a packet
21#[derive(Debug)]
22pub struct ParsedPacket {
23    pub protocol: Protocol,
24    pub local_addr: SocketAddr,
25    pub remote_addr: SocketAddr,
26    /// Endpoint address kinds, stamped centrally in `PacketParser::parse_packet`
27    /// (subnet-broadcast detection needs the parser's interface snapshot).
28    pub local_addr_kind: AddrKind,
29    pub remote_addr_kind: AddrKind,
30    /// Whether the remote endpoint is a default-gateway address, stamped
31    /// centrally alongside the address kinds from the parser's route snapshot.
32    pub remote_is_gateway: bool,
33    /// 802.1Q VID present in the captured frame. `Some(0)` is a
34    /// priority tag; `None` means no tag was observed, including stripped tags.
35    pub vlan_id: Option<u16>,
36    pub tcp_header: Option<TcpHeaderInfo>, // TCP header info (seq, ack, window, flags)
37    pub protocol_state: ProtocolState,
38    pub is_outgoing: bool,
39    pub packet_len: usize,
40    pub dpi_result: Option<DpiResult>, // DPI results if available
41    pub process_name: Option<String>,  // Process name from PKTAP metadata
42    pub process_id: Option<u32>,       // Process ID from PKTAP metadata
43}
44
45impl ParsedPacket {
46    /// Packet with the given flow fields and process attribution. The address
47    /// kinds and gateway flag start at their unicast/false defaults (they are
48    /// overwritten centrally in `PacketParser::parse_packet`), and
49    /// `tcp_header`/`dpi_result` start as `None` for the caller to fill in
50    /// where applicable.
51    #[allow(clippy::too_many_arguments)]
52    pub fn new(
53        protocol: Protocol,
54        local_addr: SocketAddr,
55        remote_addr: SocketAddr,
56        protocol_state: ProtocolState,
57        is_outgoing: bool,
58        packet_len: usize,
59        process_name: Option<String>,
60        process_id: Option<u32>,
61    ) -> Self {
62        Self {
63            protocol,
64            local_addr,
65            remote_addr,
66            local_addr_kind: AddrKind::Unicast,
67            remote_addr_kind: AddrKind::Unicast,
68            remote_is_gateway: false,
69            vlan_id: None,
70            tcp_header: None,
71            protocol_state,
72            is_outgoing,
73            packet_len,
74            dpi_result: None,
75            process_name,
76            process_id,
77        }
78    }
79
80    /// The flow identity this packet belongs to, derived from protocol and
81    /// addresses. `ConnectionKey` is `Copy`, so this costs nothing on the
82    /// per-packet path.
83    #[inline]
84    pub fn connection_key(&self) -> ConnectionKey {
85        ConnectionKey::new(self.protocol, self.local_addr, self.remote_addr)
86    }
87}
88
89/// Shared test constructors so each test module builds only the fields its
90/// scenario exercises instead of repeating the full struct literal.
91#[cfg(test)]
92impl ParsedPacket {
93    /// Baseline test packet: unicast endpoints, no TCP header, no DPI result,
94    /// no process attribution. Callers override the fields they care about.
95    pub(crate) fn test_base(
96        protocol: Protocol,
97        local_addr: SocketAddr,
98        remote_addr: SocketAddr,
99        protocol_state: ProtocolState,
100    ) -> Self {
101        Self::new(
102            protocol,
103            local_addr,
104            remote_addr,
105            protocol_state,
106            false,
107            0,
108            None,
109            None,
110        )
111    }
112
113    /// TCP test packet carrying the given header.
114    pub(crate) fn test_tcp(
115        local_addr: SocketAddr,
116        remote_addr: SocketAddr,
117        tcp_header: TcpHeaderInfo,
118    ) -> Self {
119        let mut packet = Self::test_base(
120            Protocol::Tcp,
121            local_addr,
122            remote_addr,
123            ProtocolState::Tcp(TcpState::Unknown),
124        );
125        packet.tcp_header = Some(tcp_header);
126        packet
127    }
128
129    /// UDP test packet classified by DPI as `application`.
130    pub(crate) fn test_udp(
131        local_addr: SocketAddr,
132        remote_addr: SocketAddr,
133        application: ApplicationProtocol,
134    ) -> Self {
135        let mut packet =
136            Self::test_base(Protocol::Udp, local_addr, remote_addr, ProtocolState::Udp);
137        packet.dpi_result = Some(DpiResult { application });
138        packet
139    }
140}
141
142/// Configuration for packet parsing.
143#[derive(Clone)]
144pub struct ParserConfig {
145    pub enable_dpi: bool,
146}
147
148impl Default for ParserConfig {
149    fn default() -> Self {
150        Self { enable_dpi: true }
151    }
152}
153
154/// Packet parser with a refreshable snapshot of the host's local addresses.
155pub struct PacketParser {
156    local_ips: std::collections::HashSet<IpAddr>,
157    /// Subnet-directed broadcast addresses of the host's IPv4 networks,
158    /// refreshed together with `local_ips`.
159    v4_broadcasts: std::collections::HashSet<Ipv4Addr>,
160    /// Default-gateway addresses from the host's routing table, refreshed
161    /// together with `local_ips`.
162    gateways: std::collections::HashSet<IpAddr>,
163    last_local_ip_refresh: Instant,
164    last_ambiguous_endpoint_refresh: Option<Instant>,
165    unchanged_ambiguous_refreshes: u32,
166    config: ParserConfig,
167    linktype: Option<i32>, // DLT linktype - 149 means PKTAP on macOS
168    oui_lookup: Option<std::sync::Arc<OuiLookup>>,
169}
170
171impl Default for PacketParser {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177impl PacketParser {
178    /// Create a new packet parser with default configuration
179    /// Automatically detects local IP addresses from network interfaces
180    pub fn new() -> Self {
181        Self::with_config(ParserConfig::default())
182    }
183
184    pub fn with_config(config: ParserConfig) -> Self {
185        let local = collect_local_addresses();
186        Self {
187            local_ips: local.ips,
188            v4_broadcasts: local.v4_broadcasts,
189            gateways: local.gateways,
190            last_local_ip_refresh: Instant::now(),
191            last_ambiguous_endpoint_refresh: None,
192            unchanged_ambiguous_refreshes: 0,
193            config,
194            linktype: None,
195            oui_lookup: None,
196        }
197    }
198
199    /// Set the OUI lookup for MAC vendor resolution. Accepts either an owned
200    /// `OuiLookup` or an `Arc<OuiLookup>`, so the ~3 MB vendor table can be
201    /// shared between processor threads instead of cloned.
202    pub fn with_oui_lookup(mut self, oui_lookup: impl Into<std::sync::Arc<OuiLookup>>) -> Self {
203        self.oui_lookup = Some(oui_lookup.into());
204        self
205    }
206
207    /// Set the linktype for this parser (needed for PKTAP detection)
208    pub fn with_linktype(mut self, linktype: i32) -> Self {
209        self.linktype = Some(linktype);
210
211        let link_type = link_layer::LinkLayerType::from_dlt(linktype);
212        if link_type.is_tunnel() {
213            log::debug!(
214                "Parser configured for tunnel interface: linktype {} ({:?})",
215                linktype,
216                link_type
217            );
218
219            log::trace!("TUN/TAP parsing available via link_layer::tun_tap module");
220            log::trace!("  - TUN interfaces (Layer 3): tun*, utun*");
221            log::trace!("  - TAP interfaces (Layer 2): tap*");
222        } else {
223            log::trace!(
224                "Parser configured with linktype {} ({:?})",
225                linktype,
226                link_type
227            );
228        }
229
230        self
231    }
232
233    /// Refresh the local-address snapshot from the operating system.
234    ///
235    /// Returns `true` when the set changed. Capture workers call this
236    /// periodically so DHCP renewals, VPN interfaces, and IPv6 privacy-address
237    /// rotation do not leave endpoint orientation stale for the lifetime of
238    /// the process.
239    pub fn refresh_local_ips(&mut self) -> bool {
240        self.refresh_local_ips_with(collect_local_addresses)
241    }
242
243    /// Refresh the local-address snapshot once `interval` has elapsed.
244    pub fn refresh_local_ips_if_due(&mut self, interval: Duration) -> bool {
245        if self.last_local_ip_refresh.elapsed() < interval {
246            return false;
247        }
248        self.refresh_local_ips()
249    }
250
251    /// Parse a packet and retry once after refreshing local addresses when
252    /// neither unicast endpoint is known to be local.
253    ///
254    /// This self-heals the first packet observed after an address is added,
255    /// rather than waiting for the periodic refresh. Refresh attempts caused
256    /// by unrelated forwarded traffic are rate-limited with exponential
257    /// backoff while they keep observing no change.
258    pub fn parse_packet_with_refresh(&mut self, data: &[u8]) -> Option<ParsedPacket> {
259        self.parse_packet_with_local_ip_collector(data, collect_local_addresses)
260    }
261
262    /// Classify an endpoint address against the current interface snapshot.
263    fn classify_addr(&self, ip: IpAddr) -> AddrKind {
264        match ip {
265            IpAddr::V4(v4) if v4.is_multicast() => AddrKind::Multicast,
266            IpAddr::V4(v4) if v4 == Ipv4Addr::BROADCAST || self.v4_broadcasts.contains(&v4) => {
267                AddrKind::Broadcast
268            }
269            IpAddr::V6(v6) if v6.is_multicast() => AddrKind::Multicast,
270            _ => AddrKind::Unicast,
271        }
272    }
273
274    /// Whether `ip` can plausibly be a local unicast endpoint. Subnet-directed
275    /// broadcasts are recognized via the interface prefix snapshot, so they do
276    /// not trigger ambiguous-endpoint interface re-enumeration.
277    fn is_unicast_endpoint(&self, ip: IpAddr) -> bool {
278        !ip.is_unspecified() && self.classify_addr(ip) == AddrKind::Unicast
279    }
280
281    /// Parse a raw packet and stamp both endpoint address kinds.
282    ///
283    /// The kinds are stamped here, at the single chokepoint every link-layer
284    /// path funnels through, because subnet-broadcast detection needs this
285    /// parser's interface snapshot.
286    pub fn parse_packet(&self, data: &[u8]) -> Option<ParsedPacket> {
287        let mut parsed = self.parse_packet_link_layer(data)?;
288        parsed.local_addr_kind = self.classify_addr(parsed.local_addr.ip());
289        parsed.remote_addr_kind = self.classify_addr(parsed.remote_addr.ip());
290        parsed.remote_is_gateway = parsed.remote_addr_kind == AddrKind::Unicast
291            && self.gateways.contains(&parsed.remote_addr.ip());
292        Some(parsed)
293    }
294
295    /// Parse a raw packet using the appropriate link-layer parser
296    fn parse_packet_link_layer(&self, data: &[u8]) -> Option<ParsedPacket> {
297        if let Some(linktype) = self.linktype {
298            let link_type = link_layer::LinkLayerType::from_dlt(linktype);
299            log::trace!(
300                "Parsing packet with linktype {} ({:?})",
301                linktype,
302                link_type
303            );
304
305            match linktype {
306                // PKTAP (macOS process metadata)
307                #[cfg(target_os = "macos")]
308                149 | 258 if pktap::is_pktap_linktype(linktype) => {
309                    log::debug!("Parsing as PKTAP (linktype {})", linktype);
310                    return self.parse_pktap_packet(data);
311                }
312                // Linux SLL (Linux "any" interface)
313                113 => {
314                    log::debug!("Parsing as Linux SLL (linktype 113)");
315                    return link_layer::linux_sll::parse_sll(data, self, None, None);
316                }
317                // Linux SLL2
318                276 => {
319                    log::debug!("Parsing as Linux SLL2 (linktype 276)");
320                    return link_layer::linux_sll::parse_sll2(data, self, None, None);
321                }
322                // TUN/TAP interfaces - use unified parser
323                0
324                | 1
325                | 12
326                | 101
327                | link_layer::dlt::LINKTYPE_IPV4
328                | link_layer::dlt::LINKTYPE_IPV6 => {
329                    log::debug!("Parsing TUN/TAP packet (linktype {})", linktype);
330                    return link_layer::tun_tap::parse_by_dlt(data, linktype, self, None, None);
331                }
332                _ => {
333                    log::debug!("Unknown linktype {}, trying Ethernet", linktype);
334                }
335            }
336        }
337
338        // Fallback: try Ethernet parsing if no linktype or unknown linktype
339        log::debug!("Using fallback Ethernet parsing");
340        link_layer::ethernet::parse(data, self, None, None)
341    }
342
343    fn parse_packet_with_local_ip_collector<F>(
344        &mut self,
345        data: &[u8],
346        collector: F,
347    ) -> Option<ParsedPacket>
348    where
349        F: FnOnce() -> LocalAddresses,
350    {
351        let parsed = self.parse_packet(data)?;
352        let local_ip = parsed.local_addr.ip();
353        let remote_ip = parsed.remote_addr.ip();
354
355        if self.local_ips.contains(&local_ip)
356            || self.local_ips.contains(&remote_ip)
357            || !self.is_unicast_endpoint(local_ip)
358            || !self.is_unicast_endpoint(remote_ip)
359        {
360            return Some(parsed);
361        }
362
363        let now = Instant::now();
364        if self
365            .last_ambiguous_endpoint_refresh
366            .is_some_and(|last| now.duration_since(last) < self.ambiguous_refresh_interval())
367        {
368            return Some(parsed);
369        }
370        self.last_ambiguous_endpoint_refresh = Some(now);
371
372        if self.refresh_local_ips_with(collector) {
373            self.parse_packet(data)
374        } else {
375            self.unchanged_ambiguous_refreshes =
376                self.unchanged_ambiguous_refreshes.saturating_add(1);
377            Some(parsed)
378        }
379    }
380
381    /// Interval between ambiguous-endpoint refresh attempts.
382    ///
383    /// Sustained traffic with no local endpoint (e.g. mirrored or forwarded
384    /// traffic) would otherwise re-enumerate interfaces every second forever,
385    /// so each fruitless refresh doubles the interval up to a cap. Any refresh
386    /// that observes a change resets it. Subnet-directed broadcasts are
387    /// recognized by `is_unicast_endpoint` via the interface prefix snapshot
388    /// and never reach this path.
389    fn ambiguous_refresh_interval(&self) -> Duration {
390        let factor = 1u32 << self.unchanged_ambiguous_refreshes.min(6);
391        AMBIGUOUS_ENDPOINT_REFRESH_INTERVAL
392            .saturating_mul(factor)
393            .min(AMBIGUOUS_ENDPOINT_REFRESH_MAX_INTERVAL)
394    }
395
396    fn refresh_local_ips_with<F>(&mut self, collector: F) -> bool
397    where
398        F: FnOnce() -> LocalAddresses,
399    {
400        let refreshed = collector();
401        self.last_local_ip_refresh = Instant::now();
402        if refreshed.ips == self.local_ips
403            && refreshed.v4_broadcasts == self.v4_broadcasts
404            && refreshed.gateways == self.gateways
405        {
406            return false;
407        }
408
409        log::debug!(
410            "Local address set changed: {} -> {} address(es)",
411            self.local_ips.len(),
412            refreshed.ips.len()
413        );
414        self.local_ips = refreshed.ips;
415        self.v4_broadcasts = refreshed.v4_broadcasts;
416        self.gateways = refreshed.gateways;
417        self.unchanged_ambiguous_refreshes = 0;
418        true
419    }
420
421    #[cfg(target_os = "macos")]
422    fn parse_pktap_packet(&self, data: &[u8]) -> Option<ParsedPacket> {
423        let (pktap_header, payload) = pktap::parse_pktap_packet(data)?;
424        let (process_name, process_id) = pktap_header.get_process_info();
425
426        log::debug!(
427            "PKTAP packet: interface={}, process={:?}, pid={:?}, payload_len={}",
428            pktap_header.get_interface(),
429            process_name,
430            process_id,
431            payload.len()
432        );
433
434        match pktap_header.inner_dlt() {
435            1 => {
436                // DLT_EN10MB - Ethernet frame
437                // Note: macOS/XNU strips 802.1Q VLAN tags in ether_demux() before
438                // packets reach PKTAP, and libpcap on macOS does not reconstruct them.
439                // VLAN-tagged frames will never have EtherType 0x8100 here, but we
440                // delegate to ethernet::parse() to avoid duplicating the parsing logic.
441                ethernet::parse(payload, self, process_name, process_id)
442            }
443            12 => {
444                // DLT_RAW - Raw IP packet
445                link_layer::raw_ip::parse(payload, self, process_name, process_id)
446            }
447            _ => {
448                log::debug!("Unsupported PKTAP inner DLT: {}", pktap_header.inner_dlt());
449                None
450            }
451        }
452    }
453
454    /// Parse an IPv4 packet from link-layer frame data
455    /// (data includes the link-layer header of `offset` bytes)
456    pub fn parse_ipv4_packet_inner(
457        &self,
458        data: &[u8],
459        offset: usize,
460        process_name: Option<String>,
461        process_id: Option<u32>,
462    ) -> Option<ParsedPacket> {
463        let ip_data = &data[offset..];
464        if ip_data.len() < 20 {
465            return None;
466        }
467
468        let version = ip_data[0] >> 4;
469        if version != 4 {
470            return None;
471        }
472
473        // Extract actual packet length from IP header (bytes 2-3: Total Length field)
474        let ip_total_length = u16::from_be_bytes([ip_data[2], ip_data[3]]) as usize;
475        // Actual packet size = link-layer header (offset bytes) + IP total length
476        let actual_packet_len = offset + ip_total_length;
477
478        // Bytes 6-7: flags + fragment offset. A non-first fragment carries
479        // no transport header; parsing it would read mid-payload bytes as
480        // ports and fabricate connections.
481        let fragment_offset = u16::from_be_bytes([ip_data[6], ip_data[7]]) & 0x1FFF;
482        if fragment_offset != 0 {
483            return None;
484        }
485
486        let protocol_num = ip_data[9];
487        let src_ip = IpAddr::V4(Ipv4Addr::new(
488            ip_data[12],
489            ip_data[13],
490            ip_data[14],
491            ip_data[15],
492        ));
493        let dst_ip = IpAddr::V4(Ipv4Addr::new(
494            ip_data[16],
495            ip_data[17],
496            ip_data[18],
497            ip_data[19],
498        ));
499
500        let ihl = ip_data[0] & 0x0F;
501        // IHL below 5 is invalid (the fixed header alone is 20 bytes);
502        // treating it as a header length would overlap header and payload.
503        if ihl < 5 {
504            return None;
505        }
506        let ip_header_len = (ihl as usize) * 4;
507
508        if ip_data.len() < ip_header_len {
509            return None;
510        }
511
512        let transport_data = &ip_data[ip_header_len..];
513
514        // A captured frame can carry bytes past the end of the IP datagram:
515        // Ethernet pads anything below the 60-byte minimum, and some senders
516        // append trailers. Those bytes are not transport payload, so trim the
517        // slice to the declared Total Length. Keep the untrimmed slice when the
518        // field is unusable (0 under TSO/LRO, or below the header length), and
519        // clamp to what was captured when the snaplen truncated the packet.
520        let transport_data = match ip_total_length.checked_sub(ip_header_len) {
521            Some(payload_len) => &transport_data[..payload_len.min(transport_data.len())],
522            None => transport_data,
523        };
524
525        let params =
526            TransportParams::new(src_ip, dst_ip, actual_packet_len, process_name, process_id);
527
528        match protocol_num {
529            1 => protocol::icmp::parse(transport_data, params, &self.local_ips),
530            2 => protocol::igmp::parse(transport_data, params, &self.local_ips),
531            6 => protocol::tcp::parse(transport_data, params, &self.config, &self.local_ips),
532            17 => protocol::udp::parse(transport_data, params, &self.config, &self.local_ips),
533            _ => None,
534        }
535    }
536
537    /// Parse an IPv6 packet from link-layer frame data
538    /// (data includes the link-layer header of `offset` bytes)
539    pub fn parse_ipv6_packet_inner(
540        &self,
541        data: &[u8],
542        offset: usize,
543        process_name: Option<String>,
544        process_id: Option<u32>,
545    ) -> Option<ParsedPacket> {
546        let ip_data = &data[offset..];
547        if ip_data.len() < 40 {
548            return None;
549        }
550
551        let version = ip_data[0] >> 4;
552        if version != 6 {
553            return None;
554        }
555
556        // Extract actual packet length from IPv6 header (bytes 4-5: Payload Length field)
557        let ipv6_payload_length = u16::from_be_bytes([ip_data[4], ip_data[5]]) as usize;
558        // Actual packet size = link-layer header (offset bytes) + IPv6 header (40 bytes) + payload length
559        let actual_packet_len = offset + 40 + ipv6_payload_length;
560
561        let next_header = ip_data[6];
562
563        let src_ip = IpAddr::V6(Ipv6Addr::new(
564            u16::from_be_bytes([ip_data[8], ip_data[9]]),
565            u16::from_be_bytes([ip_data[10], ip_data[11]]),
566            u16::from_be_bytes([ip_data[12], ip_data[13]]),
567            u16::from_be_bytes([ip_data[14], ip_data[15]]),
568            u16::from_be_bytes([ip_data[16], ip_data[17]]),
569            u16::from_be_bytes([ip_data[18], ip_data[19]]),
570            u16::from_be_bytes([ip_data[20], ip_data[21]]),
571            u16::from_be_bytes([ip_data[22], ip_data[23]]),
572        ));
573
574        let dst_ip = IpAddr::V6(Ipv6Addr::new(
575            u16::from_be_bytes([ip_data[24], ip_data[25]]),
576            u16::from_be_bytes([ip_data[26], ip_data[27]]),
577            u16::from_be_bytes([ip_data[28], ip_data[29]]),
578            u16::from_be_bytes([ip_data[30], ip_data[31]]),
579            u16::from_be_bytes([ip_data[32], ip_data[33]]),
580            u16::from_be_bytes([ip_data[34], ip_data[35]]),
581            u16::from_be_bytes([ip_data[36], ip_data[37]]),
582            u16::from_be_bytes([ip_data[38], ip_data[39]]),
583        ));
584
585        let transport_data = &ip_data[40..];
586
587        // Same trailing-bytes problem as IPv4: trim to the declared Payload
588        // Length so Ethernet padding is not read as transport payload. A zero
589        // means the field carries no usable length (TSO/LRO, or a jumbogram
590        // whose real size lives in a Hop-by-Hop option, RFC 2675), so the
591        // untrimmed slice is kept in that case.
592        let transport_data = if ipv6_payload_length == 0 {
593            transport_data
594        } else {
595            &transport_data[..ipv6_payload_length.min(transport_data.len())]
596        };
597
598        // Handle extension headers if needed (`None` = non-first fragment,
599        // which carries no transport header)
600        let (final_next_header, transport_offset, saw_fragment) =
601            self.parse_ipv6_extension_headers(next_header, transport_data)?;
602        // A crafted extension header can declare a length that runs past the
603        // captured bytes, so `transport_offset` may exceed the slice length.
604        // Clamp before slicing to avoid an out-of-bounds panic (one-packet DoS).
605        let final_transport_data = &transport_data[transport_offset.min(transport_data.len())..];
606
607        let params =
608            TransportParams::new(src_ip, dst_ip, actual_packet_len, process_name, process_id);
609
610        match final_next_header {
611            58 => self.parse_icmpv6(final_transport_data, params, ip_data[7], saw_fragment),
612            6 => protocol::tcp::parse(final_transport_data, params, &self.config, &self.local_ips),
613            17 => protocol::udp::parse(final_transport_data, params, &self.config, &self.local_ips),
614            _ => None,
615        }
616    }
617
618    /// Parse an ICMPv6 transport payload and, when the enclosing IPv6 header
619    /// proves on-link origin, attach any NDP-carried neighbor mapping to the
620    /// resulting `ProtocolState::Icmp`.
621    ///
622    /// NDP receivers require hop limit 255 (RFC 4861): a forged message
623    /// routed from off-link cannot arrive with it, which keeps the neighbor
624    /// cache on-link the way ARP's non-routability does for IPv4. Messages
625    /// whose extension-header chain included a Fragment Header are never
626    /// learned from: RFC 6980 forbids fragmented NDP precisely because
627    /// fragmentation lets crafted options evade validation.
628    fn parse_icmpv6(
629        &self,
630        transport_data: &[u8],
631        params: TransportParams,
632        hop_limit: u8,
633        saw_fragment: bool,
634    ) -> Option<ParsedPacket> {
635        let src_ip = params.src_ip;
636        let mut packet = protocol::icmp::parse_v6(transport_data, params, &self.local_ips)?;
637        if hop_limit == 255
638            && !saw_fragment
639            && let ProtocolState::Icmp { ndp_neighbor, .. } = &mut packet.protocol_state
640        {
641            *ndp_neighbor =
642                protocol::ndp::extract_neighbor(transport_data, src_ip, self.oui_lookup.as_deref());
643        }
644        Some(packet)
645    }
646
647    /// Parse an ARP packet from link-layer frame data
648    /// (data includes the link-layer header of `header_len` bytes)
649    pub fn parse_arp_packet_with_offset(
650        &self,
651        data: &[u8],
652        header_len: usize,
653        process_name: Option<String>,
654        process_id: Option<u32>,
655    ) -> Option<ParsedPacket> {
656        let arp_data = &data[header_len..];
657        if arp_data.len() < 28 {
658            return None;
659        }
660
661        let hardware_type = u16::from_be_bytes([arp_data[0], arp_data[1]]);
662        let protocol_type = u16::from_be_bytes([arp_data[2], arp_data[3]]);
663        let opcode = u16::from_be_bytes([arp_data[6], arp_data[7]]);
664
665        if hardware_type != 1 || protocol_type != 0x0800 {
666            return None;
667        }
668
669        let sender_mac = crate::network::oui::format_mac(&arp_data[8..14]);
670        let target_mac = crate::network::oui::format_mac(&arp_data[18..24]);
671
672        let sender_ip = IpAddr::from([arp_data[14], arp_data[15], arp_data[16], arp_data[17]]);
673        let target_ip = IpAddr::from([arp_data[24], arp_data[25], arp_data[26], arp_data[27]]);
674
675        let operation = match opcode {
676            1 => ArpOperation::Request,
677            2 => ArpOperation::Reply,
678            _ => return None,
679        };
680
681        let sender_vendor = self
682            .oui_lookup
683            .as_ref()
684            .and_then(|oui| oui.lookup(&sender_mac).map(String::from));
685        let target_vendor = self
686            .oui_lookup
687            .as_ref()
688            .and_then(|oui| oui.lookup(&target_mac).map(String::from));
689
690        let arp_info = ArpInfo {
691            operation,
692            sender_mac,
693            sender_ip,
694            target_mac,
695            target_ip,
696            sender_vendor,
697            target_vendor,
698        };
699
700        let is_outgoing = self.local_ips.contains(&sender_ip);
701        let (local_addr, remote_addr) = if is_outgoing {
702            (SocketAddr::new(sender_ip, 0), SocketAddr::new(target_ip, 0))
703        } else {
704            (SocketAddr::new(target_ip, 0), SocketAddr::new(sender_ip, 0))
705        };
706
707        Some(ParsedPacket::new(
708            Protocol::Arp,
709            local_addr,
710            remote_addr,
711            ProtocolState::Arp(arp_info),
712            is_outgoing,
713            data.len(),
714            process_name,
715            process_id,
716        ))
717    }
718
719    /// Parse a raw IPv4 packet (no link-layer header)
720    /// Used by TUN devices, PKTAP DLT_RAW, and Linux Cooked Capture
721    pub fn parse_raw_ipv4_packet(
722        &self,
723        data: &[u8],
724        process_name: Option<String>,
725        process_id: Option<u32>,
726    ) -> Option<ParsedPacket> {
727        self.parse_ipv4_packet_inner(data, 0, process_name, process_id)
728    }
729
730    /// Parse a raw IPv6 packet (no link-layer header)
731    /// Used by TUN devices, PKTAP DLT_RAW, and Linux Cooked Capture
732    pub fn parse_raw_ipv6_packet(
733        &self,
734        data: &[u8],
735        process_name: Option<String>,
736        process_id: Option<u32>,
737    ) -> Option<ParsedPacket> {
738        self.parse_ipv6_packet_inner(data, 0, process_name, process_id)
739    }
740
741    /// Walk the IPv6 extension-header chain. Returns the final next-header
742    /// value, the offset of the transport header, and whether a Fragment
743    /// Header was traversed (a first/atomic fragment still carries the
744    /// transport header, but NDP must not be learned from it, RFC 6980).
745    /// `None` for a non-first fragment: its "transport header" position
746    /// holds mid-payload bytes that must not be parsed as ports.
747    fn parse_ipv6_extension_headers(
748        &self,
749        mut next_header: u8,
750        data: &[u8],
751    ) -> Option<(u8, usize, bool)> {
752        let mut offset = 0;
753        let mut saw_fragment = false;
754
755        const HOP_BY_HOP: u8 = 0;
756        const ROUTING: u8 = 43;
757        const FRAGMENT: u8 = 44;
758        const ENCAPSULATING_SECURITY: u8 = 50;
759        const AUTHENTICATION: u8 = 51;
760        const DESTINATION_OPTIONS: u8 = 60;
761
762        loop {
763            match next_header {
764                HOP_BY_HOP | ROUTING | DESTINATION_OPTIONS => {
765                    if data.len() < offset + 2 {
766                        return Some((next_header, offset, saw_fragment));
767                    }
768                    next_header = data[offset];
769                    let header_len = ((data[offset + 1] as usize) + 1) * 8;
770                    offset += header_len;
771                }
772                FRAGMENT => {
773                    saw_fragment = true;
774                    if data.len() < offset + 8 {
775                        return Some((next_header, offset, saw_fragment));
776                    }
777                    // Bytes 2-3: fragment offset (upper 13 bits). Only the
778                    // first fragment (offset 0) carries the transport header.
779                    let fragment_offset =
780                        u16::from_be_bytes([data[offset + 2], data[offset + 3]]) >> 3;
781                    if fragment_offset != 0 {
782                        return None;
783                    }
784                    next_header = data[offset];
785                    offset += 8;
786                }
787                AUTHENTICATION => {
788                    if data.len() < offset + 2 {
789                        return Some((next_header, offset, saw_fragment));
790                    }
791                    next_header = data[offset];
792                    let header_len = ((data[offset + 1] as usize) + 2) * 4;
793                    offset += header_len;
794                }
795                ENCAPSULATING_SECURITY => {
796                    return Some((next_header, offset, saw_fragment));
797                }
798                _ => {
799                    return Some((next_header, offset, saw_fragment));
800                }
801            }
802
803            if offset >= data.len() {
804                return Some((next_header, offset, saw_fragment));
805            }
806        }
807    }
808}
809
810#[cfg(test)]
811mod tests {
812    use super::*;
813    use std::net::IpAddr;
814
815    fn local_addresses(ips: impl IntoIterator<Item = IpAddr>) -> LocalAddresses {
816        LocalAddresses {
817            ips: ips.into_iter().collect(),
818            ..LocalAddresses::default()
819        }
820    }
821
822    fn local_addresses_with_gateways(
823        ips: impl IntoIterator<Item = IpAddr>,
824        gateways: impl IntoIterator<Item = IpAddr>,
825    ) -> LocalAddresses {
826        LocalAddresses {
827            gateways: gateways.into_iter().collect(),
828            ..local_addresses(ips)
829        }
830    }
831
832    /// Helper to create a parser with a specific linktype and controlled local IPs
833    /// This adds 192.168.1.100 to the local_ips set so test packets are correctly identified
834    fn create_parser_with_linktype(linktype: i32) -> PacketParser {
835        let mut parser = PacketParser::with_config(ParserConfig::default()).with_linktype(linktype);
836        // Add test IP to local_ips so the parser treats it as local
837        parser
838            .local_ips
839            .insert(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)));
840        parser
841    }
842
843    // Test fixture generators
844    fn ethernet_ipv4_tcp_syn() -> Vec<u8> {
845        vec![
846            // Ethernet header
847            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
848            // IPv4 header
849            0x45, 0x00, 0x00, 0x28, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 192, 168, 1,
850            100, 93, 184, 216, 34, // TCP header (SYN flag)
851            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
852            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
853        ]
854    }
855
856    fn ethernet_ipv4_udp_dns() -> Vec<u8> {
857        vec![
858            // Ethernet
859            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
860            // IPv4
861            0x45, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, 192, 168, 1,
862            100, 8, 8, 8, 8, // UDP
863            0x04, 0xd2, 0x00, 0x35, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
864        ]
865    }
866
867    fn ethernet_ipv4_udp(src: [u8; 4], dst: [u8; 4]) -> Vec<u8> {
868        vec![
869            // Ethernet
870            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
871            // IPv4
872            0x45, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, src[0], src[1],
873            src[2], src[3], dst[0], dst[1], dst[2], dst[3], // UDP: 60236 -> 51234
874            0xeb, 0x4c, 0xc8, 0x22, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
875        ]
876    }
877
878    fn ethernet_ipv6_tcp() -> Vec<u8> {
879        vec![
880            // Ethernet
881            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x86, 0xdd,
882            // IPv6 header
883            0x60, 0x00, 0x00, 0x00, 0x00, 0x14, 0x06, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00,
884            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8,
885            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
886            // TCP
887            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
888            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
889        ]
890    }
891
892    /// Ethernet IPv6 ICMPv6 Neighbor Solicitation from fe80::2 for fe80::1,
893    /// carrying a source link-layer option, hop limit 255. `fragmented`
894    /// inserts an atomic Fragment Header (offset 0) before the ICMPv6 header.
895    fn ethernet_ipv6_ndp_solicitation(fragmented: bool) -> Vec<u8> {
896        let mut icmpv6 = vec![135, 0, 0, 0, 0, 0, 0, 0]; // NS header
897        icmpv6.extend_from_slice(&[
898            0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01, // target fe80::1
899        ]);
900        icmpv6.extend_from_slice(&[1, 1, 0x68, 0x5e, 0xdd, 0x09, 0x15, 0x5e]); // source LL option
901
902        let (next_header, payload) = if fragmented {
903            let mut p = vec![58, 0, 0, 0, 0, 0, 0, 1]; // atomic fragment, offset 0
904            p.extend_from_slice(&icmpv6);
905            (44u8, p)
906        } else {
907            (58u8, icmpv6)
908        };
909
910        let mut frame = vec![
911            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x86, 0xdd,
912            0x60, 0x00, 0x00, 0x00,
913        ];
914        frame.extend_from_slice(&(payload.len() as u16).to_be_bytes());
915        frame.push(next_header);
916        frame.push(255); // hop limit
917        frame.extend_from_slice(&[
918            0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02, // src fe80::2
919        ]);
920        frame.extend_from_slice(&[
921            0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01, // dst fe80::1
922        ]);
923        frame.extend_from_slice(&payload);
924        frame
925    }
926
927    fn linux_sll_ipv4_tcp() -> Vec<u8> {
928        vec![
929            // Linux SLL header
930            0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x00,
931            0x08, 0x00, // IPv4
932            0x45, 0x00, 0x00, 0x28, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 192, 168, 1,
933            100, 93, 184, 216, 34, // TCP
934            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
935            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
936        ]
937    }
938
939    fn linux_sll2_ipv4_udp() -> Vec<u8> {
940        vec![
941            // Linux SLL2 header
942            0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x06, 0xaa, 0xbb,
943            0xcc, 0xdd, 0xee, 0xff, 0x00, 0x00, // IPv4
944            0x45, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, 192, 168, 1,
945            100, 8, 8, 8, 8, // UDP
946            0x04, 0xd2, 0x00, 0x35, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
947        ]
948    }
949
950    #[test]
951    fn test_ethernet_ipv4_tcp_parsing() {
952        let parser = create_parser_with_linktype(1); // DLT_EN10MB
953        let packet = ethernet_ipv4_tcp_syn();
954
955        let parsed = parser.parse_packet(&packet);
956        assert!(
957            parsed.is_some(),
958            "Should parse valid Ethernet IPv4 TCP packet"
959        );
960
961        let p = parsed.unwrap();
962        assert_eq!(p.protocol, Protocol::Tcp);
963        // Source is 192.168.1.100:1234, Dest is 93.184.216.34:80
964        // Since source is local IP, local_addr should be source, remote should be dest
965        assert_eq!(p.local_addr.port(), 1234, "Local port should be 1234");
966        assert_eq!(p.remote_addr.port(), 80, "Remote port should be 80");
967        assert!(p.tcp_header.is_some());
968        assert!(p.tcp_header.unwrap().flags.syn, "SYN flag should be set");
969    }
970
971    #[test]
972    fn ndp_is_learned_at_hop_limit_255_but_never_from_fragments() {
973        let parser = create_parser_with_linktype(1); // DLT_EN10MB
974
975        let parsed = parser
976            .parse_packet(&ethernet_ipv6_ndp_solicitation(false))
977            .expect("NDP solicitation should parse");
978        match &parsed.protocol_state {
979            ProtocolState::Icmp {
980                ndp_neighbor: Some(neighbor),
981                ..
982            } => {
983                assert_eq!(neighbor.ip, "fe80::2".parse::<IpAddr>().unwrap());
984                assert_eq!(neighbor.mac, "68:5e:dd:09:15:5e");
985            }
986            other => panic!("expected a learned NDP neighbor, got {:?}", other),
987        }
988
989        // RFC 6980: an NDP message whose header chain includes a Fragment
990        // Header must be ignored, even a first/atomic fragment.
991        let parsed = parser
992            .parse_packet(&ethernet_ipv6_ndp_solicitation(true))
993            .expect("fragmented solicitation should still parse as ICMPv6");
994        assert!(matches!(
995            &parsed.protocol_state,
996            ProtocolState::Icmp {
997                ndp_neighbor: None,
998                ..
999            }
1000        ));
1001    }
1002
1003    #[test]
1004    fn test_ethernet_ipv4_udp_parsing() {
1005        let parser = create_parser_with_linktype(1);
1006        let packet = ethernet_ipv4_udp_dns();
1007
1008        let parsed = parser.parse_packet(&packet);
1009        assert!(parsed.is_some());
1010
1011        let p = parsed.unwrap();
1012        assert_eq!(p.protocol, Protocol::Udp);
1013        // Source: 192.168.1.100:1234, Dest: 8.8.8.8:53
1014        assert_eq!(p.local_addr.port(), 1234);
1015        assert_eq!(p.remote_addr.port(), 53, "Should detect DNS port");
1016    }
1017
1018    #[test]
1019    fn test_ethernet_ipv6_tcp_parsing() {
1020        let parser = create_parser_with_linktype(1);
1021        let packet = ethernet_ipv6_tcp();
1022
1023        let parsed = parser.parse_packet(&packet);
1024        assert!(parsed.is_some(), "Should parse IPv6 packets");
1025
1026        let p = parsed.unwrap();
1027        assert_eq!(p.protocol, Protocol::Tcp);
1028        assert!(matches!(p.local_addr.ip(), IpAddr::V6(_)), "Should be IPv6");
1029    }
1030
1031    #[test]
1032    fn test_truncated_ethernet_packet() {
1033        let parser = create_parser_with_linktype(1);
1034        let truncated = vec![0x00, 0x11, 0x22]; // Only 3 bytes
1035
1036        let parsed = parser.parse_packet(&truncated);
1037        assert!(parsed.is_none(), "Should reject truncated packets");
1038    }
1039
1040    #[test]
1041    fn vlan_metadata_survives_ethernet_and_cooked_ipv4_ipv6_and_arp() {
1042        let parser = create_parser_with_linktype(1);
1043        let mut arp = vec![0xff; 6];
1044        arp.extend_from_slice(&[0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x06]);
1045        arp.extend_from_slice(&[
1046            0, 1, 0x08, 0, 6, 4, 0, 1, // Ethernet/IPv4 ARP request
1047            0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 192, 168, 1, 100, 0, 0, 0, 0, 0, 0, 192, 168, 1, 1,
1048        ]);
1049        for frame in [
1050            ethernet_ipv4_tcp_syn(),
1051            ethernet_ipv4_udp_dns(),
1052            ethernet_ipv6_tcp(),
1053            arp,
1054        ] {
1055            let untagged = parser.parse_packet(&frame).unwrap();
1056            assert_eq!(untagged.vlan_id, None);
1057            for (linktype, header_len, proto_offset) in [(113, 16, 14), (276, 20, 0)] {
1058                let cooked_parser = create_parser_with_linktype(linktype);
1059                let mut cooked = vec![0; header_len];
1060                cooked[proto_offset..proto_offset + 2].copy_from_slice(&frame[12..14]);
1061                cooked.extend_from_slice(&frame[14..]);
1062                let plain = cooked_parser.parse_packet(&cooked).unwrap();
1063                assert_eq!(plain.vlan_id, None);
1064                for vlan_id in [0u16, 42, 4094] {
1065                    let mut tagged = cooked.clone();
1066                    tagged[proto_offset..proto_offset + 2].copy_from_slice(&[0x81, 0x00]);
1067                    let tci = (0xf000 | vlan_id).to_be_bytes();
1068                    tagged.splice(
1069                        header_len..header_len,
1070                        [tci[0], tci[1], frame[12], frame[13]],
1071                    );
1072                    let parsed = cooked_parser.parse_packet(&tagged).unwrap();
1073                    assert_eq!(parsed.vlan_id, Some(vlan_id));
1074                    assert_eq!(parsed.connection_key(), plain.connection_key());
1075                }
1076            }
1077            for vlan_id in [0u16, 42, 4094] {
1078                let mut tagged = frame.clone();
1079                // PCP and DEI must not become part of the VID.
1080                let tci = (0xf000 | vlan_id).to_be_bytes();
1081                tagged.splice(12..12, [0x81, 0x00, tci[0], tci[1]]);
1082                let parsed = parser.parse_packet(&tagged).unwrap();
1083                assert_eq!(parsed.vlan_id, Some(vlan_id));
1084                assert_eq!(parsed.connection_key(), untagged.connection_key());
1085                assert_eq!(parsed.packet_len, untagged.packet_len + 4);
1086            }
1087        }
1088    }
1089
1090    #[test]
1091    fn test_unknown_ethertype() {
1092        let parser = create_parser_with_linktype(1);
1093        let packet = vec![
1094            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xff,
1095            0xff, // Unknown EtherType
1096        ];
1097
1098        let parsed = parser.parse_packet(&packet);
1099        assert!(parsed.is_none(), "Should reject unknown EtherType");
1100    }
1101
1102    #[test]
1103    fn test_linux_sll_ipv4_tcp_parsing() {
1104        let parser = create_parser_with_linktype(113); // DLT_LINUX_SLL
1105        let packet = linux_sll_ipv4_tcp();
1106
1107        let parsed = parser.parse_packet(&packet);
1108        assert!(parsed.is_some(), "Should parse Linux SLL packets");
1109
1110        let p = parsed.unwrap();
1111        assert_eq!(p.protocol, Protocol::Tcp);
1112        assert_eq!(p.local_addr.port(), 1234);
1113        assert_eq!(p.remote_addr.port(), 80);
1114    }
1115
1116    #[test]
1117    fn test_linux_sll_truncated() {
1118        let parser = create_parser_with_linktype(113);
1119        let truncated = vec![0x00, 0x00, 0x00]; // Too short
1120
1121        let parsed = parser.parse_packet(&truncated);
1122        assert!(parsed.is_none(), "Should reject truncated SLL packets");
1123    }
1124
1125    #[test]
1126    fn test_linux_sll2_ipv4_udp_parsing() {
1127        let parser = create_parser_with_linktype(276); // DLT_LINUX_SLL2
1128        let packet = linux_sll2_ipv4_udp();
1129
1130        let parsed = parser.parse_packet(&packet);
1131        assert!(parsed.is_some(), "Should parse Linux SLL2 packets");
1132
1133        let p = parsed.unwrap();
1134        assert_eq!(p.protocol, Protocol::Udp);
1135        assert_eq!(p.local_addr.port(), 1234);
1136        assert_eq!(p.remote_addr.port(), 53);
1137    }
1138
1139    #[test]
1140    fn test_linux_sll2_truncated() {
1141        let parser = create_parser_with_linktype(276);
1142        let truncated = vec![0x08, 0x00]; // Too short for SLL2
1143
1144        let parsed = parser.parse_packet(&truncated);
1145        assert!(parsed.is_none(), "Should reject truncated SLL2 packets");
1146    }
1147
1148    #[test]
1149    fn test_parser_default_config() {
1150        let config = ParserConfig::default();
1151        assert!(config.enable_dpi, "DPI should be enabled by default");
1152    }
1153
1154    #[test]
1155    fn test_parser_with_linktype() {
1156        let parser = PacketParser::with_config(ParserConfig::default()).with_linktype(1);
1157        assert_eq!(parser.linktype, Some(1));
1158    }
1159
1160    #[test]
1161    fn test_local_ip_detection() {
1162        let parser = PacketParser::new();
1163        // Should have at least loopback
1164        assert!(!parser.local_ips.is_empty(), "Should detect local IPs");
1165    }
1166
1167    #[test]
1168    fn classify_addr_recognizes_broadcast_and_multicast() {
1169        let mut parser = create_parser_with_linktype(1);
1170        parser.v4_broadcasts.insert(Ipv4Addr::new(192, 168, 1, 255));
1171
1172        assert_eq!(
1173            parser.classify_addr(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 255))),
1174            AddrKind::Broadcast,
1175            "subnet-directed broadcast from the interface snapshot"
1176        );
1177        assert_eq!(
1178            parser.classify_addr(IpAddr::V4(Ipv4Addr::BROADCAST)),
1179            AddrKind::Broadcast
1180        );
1181        assert_eq!(
1182            parser.classify_addr(IpAddr::V4(Ipv4Addr::new(224, 0, 0, 251))),
1183            AddrKind::Multicast
1184        );
1185        assert_eq!(
1186            parser.classify_addr(IpAddr::V6(
1187                "ff02::fb".parse().expect("valid fixture address")
1188            )),
1189            AddrKind::Multicast
1190        );
1191        assert_eq!(
1192            parser.classify_addr(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 254))),
1193            AddrKind::Unicast,
1194            "adjacent host must not be mistaken for the broadcast address"
1195        );
1196        assert_eq!(
1197            parser.classify_addr(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))),
1198            AddrKind::Unicast
1199        );
1200    }
1201
1202    #[test]
1203    fn incoming_subnet_broadcast_is_stamped_and_skips_refresh() {
1204        use std::cell::Cell;
1205
1206        let mut parser = create_parser_with_linktype(1);
1207        parser.v4_broadcasts.insert(Ipv4Addr::new(192, 168, 1, 255));
1208        // Peer -> subnet broadcast; neither endpoint is a local unicast address
1209        let packet = ethernet_ipv4_udp([192, 168, 1, 52], [192, 168, 1, 255]);
1210        let collector_calls = Cell::new(0u32);
1211
1212        let parsed = parser
1213            .parse_packet_with_local_ip_collector(&packet, || {
1214                collector_calls.set(collector_calls.get() + 1);
1215                LocalAddresses::default()
1216            })
1217            .expect("packet should parse");
1218
1219        assert_eq!(
1220            parsed.local_addr.ip(),
1221            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 255))
1222        );
1223        assert_eq!(parsed.local_addr_kind, AddrKind::Broadcast);
1224        assert_eq!(parsed.remote_addr_kind, AddrKind::Unicast);
1225        assert_eq!(
1226            collector_calls.get(),
1227            0,
1228            "a recognized subnet broadcast must not re-enumerate interfaces"
1229        );
1230    }
1231
1232    #[test]
1233    fn outgoing_broadcast_marks_the_remote_side() {
1234        let mut parser = create_parser_with_linktype(1);
1235        parser.v4_broadcasts.insert(Ipv4Addr::new(192, 168, 1, 255));
1236        // The local host (192.168.1.100) sends to the subnet broadcast
1237        let packet = ethernet_ipv4_udp([192, 168, 1, 100], [192, 168, 1, 255]);
1238
1239        let parsed = parser.parse_packet(&packet).expect("packet should parse");
1240
1241        assert!(parsed.is_outgoing);
1242        assert_eq!(parsed.local_addr_kind, AddrKind::Unicast);
1243        assert_eq!(parsed.remote_addr_kind, AddrKind::Broadcast);
1244    }
1245
1246    #[test]
1247    fn gateway_remote_endpoint_is_stamped() {
1248        let mut parser = create_parser_with_linktype(1);
1249        parser
1250            .gateways
1251            .insert(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)));
1252
1253        // The local host (192.168.1.100) talks to the gateway
1254        let packet = ethernet_ipv4_udp([192, 168, 1, 100], [192, 168, 1, 1]);
1255        let parsed = parser.parse_packet(&packet).expect("packet should parse");
1256        assert_eq!(parsed.remote_addr_kind, AddrKind::Unicast);
1257        assert!(parsed.remote_is_gateway);
1258
1259        // An ordinary peer on the same subnet must not be marked
1260        let packet = ethernet_ipv4_udp([192, 168, 1, 100], [192, 168, 1, 52]);
1261        let parsed = parser.parse_packet(&packet).expect("packet should parse");
1262        assert!(!parsed.remote_is_gateway);
1263    }
1264
1265    #[test]
1266    fn broadcast_remote_is_never_marked_as_gateway() {
1267        let mut parser = create_parser_with_linktype(1);
1268        parser.v4_broadcasts.insert(Ipv4Addr::new(192, 168, 1, 255));
1269        parser
1270            .gateways
1271            .insert(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 255)));
1272
1273        let packet = ethernet_ipv4_udp([192, 168, 1, 100], [192, 168, 1, 255]);
1274        let parsed = parser.parse_packet(&packet).expect("packet should parse");
1275        assert_eq!(parsed.remote_addr_kind, AddrKind::Broadcast);
1276        assert!(!parsed.remote_is_gateway);
1277    }
1278
1279    #[test]
1280    fn refresh_picks_up_gateway_changes() {
1281        let mut parser = create_parser_with_linktype(1);
1282        parser.local_ips = [IpAddr::V4(Ipv4Addr::LOCALHOST)].into_iter().collect();
1283        parser.v4_broadcasts.clear();
1284        parser.gateways.clear();
1285        let gateway = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
1286        let collector =
1287            || local_addresses_with_gateways([IpAddr::V4(Ipv4Addr::LOCALHOST)], [gateway]);
1288
1289        assert!(
1290            parser.refresh_local_ips_with(collector),
1291            "a gateway-only change must count as a snapshot change"
1292        );
1293        assert!(parser.gateways.contains(&gateway));
1294        assert!(
1295            !parser.refresh_local_ips_with(collector),
1296            "an unchanged snapshot must not report a change"
1297        );
1298    }
1299
1300    #[test]
1301    fn ambiguous_ipv6_packet_refreshes_local_addresses_and_reorients_endpoints() {
1302        let mut parser = create_parser_with_linktype(1);
1303        parser.local_ips.clear();
1304        parser.local_ips.insert(IpAddr::V4(Ipv4Addr::LOCALHOST));
1305        parser.local_ips.insert(IpAddr::V6(Ipv6Addr::LOCALHOST));
1306        let packet = ethernet_ipv6_tcp();
1307
1308        let stale = parser.parse_packet(&packet).expect("packet should parse");
1309        assert!(!stale.is_outgoing);
1310        assert_eq!(stale.local_addr.port(), 80);
1311
1312        let new_local = IpAddr::V6("2001:db8::1".parse().expect("valid fixture address"));
1313        let corrected = parser
1314            .parse_packet_with_local_ip_collector(&packet, || {
1315                local_addresses([
1316                    IpAddr::V4(Ipv4Addr::LOCALHOST),
1317                    IpAddr::V6(Ipv6Addr::LOCALHOST),
1318                    new_local,
1319                ])
1320            })
1321            .expect("packet should be reparsed");
1322
1323        assert!(corrected.is_outgoing);
1324        assert_eq!(corrected.local_addr.ip(), new_local);
1325        assert_eq!(corrected.local_addr.port(), 1234);
1326        assert_eq!(corrected.remote_addr.port(), 80);
1327    }
1328
1329    #[test]
1330    fn refresh_replaces_addresses_that_are_no_longer_assigned() {
1331        let mut parser = create_parser_with_linktype(1);
1332        let old = IpAddr::V6("2001:db8::1".parse().expect("valid old address"));
1333        let new = IpAddr::V6("2001:db8::2".parse().expect("valid new address"));
1334        parser.local_ips = [old].into_iter().collect();
1335
1336        assert!(parser.refresh_local_ips_with(|| local_addresses([new])));
1337        assert!(!parser.local_ips.contains(&old));
1338        assert!(parser.local_ips.contains(&new));
1339    }
1340
1341    #[test]
1342    fn ambiguous_refresh_is_rate_limited_between_packets() {
1343        use std::cell::Cell;
1344
1345        let mut parser = create_parser_with_linktype(1);
1346        parser.local_ips.clear();
1347        parser.local_ips.insert(IpAddr::V4(Ipv4Addr::LOCALHOST));
1348        let packet = ethernet_ipv6_tcp();
1349        let collector_calls = Cell::new(0u32);
1350        let unchanged_collector = || {
1351            collector_calls.set(collector_calls.get() + 1);
1352            local_addresses([IpAddr::V4(Ipv4Addr::LOCALHOST)])
1353        };
1354
1355        parser
1356            .parse_packet_with_local_ip_collector(&packet, unchanged_collector)
1357            .expect("packet should parse");
1358        parser
1359            .parse_packet_with_local_ip_collector(&packet, unchanged_collector)
1360            .expect("packet should parse");
1361
1362        assert_eq!(
1363            collector_calls.get(),
1364            1,
1365            "second ambiguous packet within the refresh interval must not re-enumerate"
1366        );
1367    }
1368
1369    #[test]
1370    fn fruitless_ambiguous_refreshes_back_off_exponentially() {
1371        let mut parser = create_parser_with_linktype(1);
1372        assert_eq!(parser.ambiguous_refresh_interval(), Duration::from_secs(1));
1373
1374        parser.unchanged_ambiguous_refreshes = 3;
1375        assert_eq!(parser.ambiguous_refresh_interval(), Duration::from_secs(8));
1376
1377        parser.unchanged_ambiguous_refreshes = 100;
1378        assert_eq!(
1379            parser.ambiguous_refresh_interval(),
1380            AMBIGUOUS_ENDPOINT_REFRESH_MAX_INTERVAL
1381        );
1382
1383        let new = IpAddr::V6("2001:db8::99".parse().expect("valid address"));
1384        assert!(parser.refresh_local_ips_with(|| local_addresses([new])));
1385        assert_eq!(
1386            parser.unchanged_ambiguous_refreshes, 0,
1387            "a refresh that observes a change must reset the backoff"
1388        );
1389    }
1390
1391    #[test]
1392    fn periodic_refresh_waits_for_interval() {
1393        let mut parser = create_parser_with_linktype(1);
1394        let bogus = IpAddr::V6("2001:db8::dead".parse().expect("valid address"));
1395        parser.local_ips = [bogus].into_iter().collect();
1396
1397        assert!(!parser.refresh_local_ips_if_due(Duration::from_secs(3600)));
1398        assert!(
1399            parser.local_ips.contains(&bogus),
1400            "snapshot must be untouched before the interval elapses"
1401        );
1402
1403        assert!(parser.refresh_local_ips_if_due(Duration::ZERO));
1404        assert!(!parser.local_ips.contains(&bogus));
1405    }
1406
1407    #[test]
1408    fn test_empty_packet() {
1409        let parser = create_parser_with_linktype(1);
1410        let empty = vec![];
1411        assert!(parser.parse_packet(&empty).is_none());
1412    }
1413
1414    #[test]
1415    fn test_ipv6_extension_header_overflow_does_not_panic() {
1416        // A crafted IPv6 extension header can declare a length that runs far
1417        // past the captured bytes; the parser must clamp and return cleanly
1418        // rather than slice past the end (one-packet DoS of the capture thread).
1419        let parser = create_parser_with_linktype(1);
1420        let mut packet = vec![
1421            // Ethernet (ethertype 0x86dd = IPv6)
1422            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x86, 0xdd,
1423        ];
1424        packet.extend_from_slice(&[
1425            // IPv6 header: version 6, next_header = 0 (Hop-by-Hop Options)
1426            0x60, 0x00, 0x00, 0x00, // version / traffic class / flow label
1427            0x00, 0x02, // payload length = 2
1428            0x00, // next header = Hop-by-Hop Options
1429            0x40, // hop limit
1430            // src addr (::1)
1431            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1432            0x00, 0x01, // dst addr (::2)
1433            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1434            0x00, 0x02,
1435        ]);
1436        // Hop-by-Hop extension header that claims (0xFF + 1) * 8 = 2048 bytes
1437        // while only 2 bytes are present.
1438        packet.extend_from_slice(&[0x3b /* next = no next header */, 0xff]);
1439
1440        // Must not panic.
1441        let _ = parser.parse_packet(&packet);
1442    }
1443
1444    #[test]
1445    fn test_ipv4_with_options() {
1446        let parser = create_parser_with_linktype(1);
1447        let mut packet = vec![
1448            // Ethernet
1449            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
1450            // IPv4 with IHL=6 (24 bytes header with 4 bytes options)
1451            0x46, 0x00, 0x00, 0x2c, // IHL=6, Total=44
1452            0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 192, 168, 1, 100, 93, 184, 216,
1453            34, // IP options (4 bytes)
1454            0x01, 0x01, 0x00, 0x00,
1455        ];
1456        // TCP header
1457        packet.extend_from_slice(&[
1458            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
1459            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
1460        ]);
1461
1462        let parsed = parser.parse_packet(&packet);
1463        assert!(parsed.is_some(), "Should handle IPv4 with options");
1464    }
1465
1466    #[test]
1467    fn test_packet_length_calculation_ipv4() {
1468        let parser = create_parser_with_linktype(1);
1469        let packet = ethernet_ipv4_tcp_syn();
1470
1471        let parsed = parser.parse_packet(&packet).unwrap();
1472        // IPv4 total length is 40 bytes (0x0028), plus 14 bytes Ethernet = 54
1473        assert_eq!(parsed.packet_len, 54);
1474    }
1475
1476    #[test]
1477    fn test_packet_length_calculation_ipv6() {
1478        let parser = create_parser_with_linktype(1);
1479        let packet = ethernet_ipv6_tcp();
1480
1481        let parsed = parser.parse_packet(&packet).unwrap();
1482        // IPv6: 14 (Ethernet) + 40 (IPv6 header) + 20 (payload) = 74
1483        assert_eq!(parsed.packet_len, 74);
1484    }
1485
1486    #[test]
1487    fn test_ethernet_padding_is_not_counted_as_tcp_payload() {
1488        let parser = create_parser_with_linktype(1);
1489        // A bare SYN is 54 bytes on the wire, so the NIC pads it to the
1490        // 60-byte Ethernet minimum. Those 6 bytes sit past the end of the
1491        // IP datagram and must not be reported as payload.
1492        let mut packet = ethernet_ipv4_tcp_syn();
1493        assert_eq!(packet.len(), 54);
1494        packet.extend_from_slice(&[0x00; 6]);
1495
1496        let parsed = parser.parse_packet(&packet).unwrap();
1497        assert_eq!(parsed.tcp_header.unwrap().payload_len, 0);
1498    }
1499
1500    #[test]
1501    fn test_trailing_bytes_are_not_read_as_tcp_payload() {
1502        let parser = create_parser_with_linktype(1);
1503        // The IPv4 Total Length still says 40 (header + bare TCP header), so
1504        // everything appended here is outside the datagram. Reading it as
1505        // payload would hand DPI bytes the sender never put in the segment.
1506        let mut packet = ethernet_ipv4_tcp_syn();
1507        packet.extend_from_slice(b"SSH-2.0-OpenSSH_9.6\r\n");
1508
1509        let parsed = parser.parse_packet(&packet).unwrap();
1510        assert_eq!(parsed.tcp_header.unwrap().payload_len, 0);
1511        assert!(parsed.dpi_result.is_none());
1512    }
1513
1514    #[test]
1515    fn test_ipv6_padding_is_not_counted_as_tcp_payload() {
1516        let parser = create_parser_with_linktype(1);
1517        // IPv6 Payload Length is 20 (TCP header only); the appended bytes are
1518        // past the end of the datagram.
1519        let mut packet = ethernet_ipv6_tcp();
1520        packet.extend_from_slice(&[0x00; 6]);
1521
1522        let parsed = parser.parse_packet(&packet).unwrap();
1523        assert_eq!(parsed.tcp_header.unwrap().payload_len, 0);
1524    }
1525
1526    #[test]
1527    fn test_real_payload_is_preserved() {
1528        let parser = create_parser_with_linktype(1);
1529        // Total Length 0x002c = 44: 20 IPv4 + 20 TCP + 4 payload bytes.
1530        let mut packet = ethernet_ipv4_tcp_syn();
1531        packet[16] = 0x00;
1532        packet[17] = 0x2c;
1533        packet.extend_from_slice(b"data");
1534
1535        let parsed = parser.parse_packet(&packet).unwrap();
1536        assert_eq!(parsed.tcp_header.unwrap().payload_len, 4);
1537    }
1538
1539    #[test]
1540    fn test_truncated_capture_keeps_captured_payload() {
1541        let parser = create_parser_with_linktype(1);
1542        // Total Length claims 1500 bytes but the snaplen cut the capture
1543        // short. The payload must be what was captured, not what was claimed.
1544        let mut packet = ethernet_ipv4_tcp_syn();
1545        packet[16] = 0x05;
1546        packet[17] = 0xdc;
1547        packet.extend_from_slice(b"data");
1548
1549        let parsed = parser.parse_packet(&packet).unwrap();
1550        assert_eq!(parsed.tcp_header.unwrap().payload_len, 4);
1551    }
1552
1553    #[test]
1554    fn test_sll_padding_is_not_counted_as_tcp_payload() {
1555        let parser = create_parser_with_linktype(113); // LINUX_SLL
1556        // Cooked captures keep the Ethernet padding of short frames, so the
1557        // bytes past the IP Total Length must be trimmed here as well.
1558        let mut packet = linux_sll_ipv4_tcp();
1559        packet.extend_from_slice(&[0x00; 6]);
1560
1561        let parsed = parser.parse_packet(&packet).unwrap();
1562        assert_eq!(parsed.tcp_header.unwrap().payload_len, 0);
1563    }
1564
1565    #[test]
1566    fn test_raw_ip_trailing_bytes_are_not_read_as_tcp_payload() {
1567        let parser = create_parser_with_linktype(12); // DLT_RAW
1568        // Raw IP capture: strip the Ethernet header from the fixture and
1569        // append bytes past the datagram end.
1570        let mut packet = ethernet_ipv4_tcp_syn()[14..].to_vec();
1571        packet.extend_from_slice(b"SSH-2.0-OpenSSH_9.6\r\n");
1572
1573        let parsed = parser.parse_packet(&packet).unwrap();
1574        assert_eq!(parsed.tcp_header.unwrap().payload_len, 0);
1575        assert!(parsed.dpi_result.is_none());
1576    }
1577
1578    #[test]
1579    fn test_raw_ipv6_padding_is_not_counted_as_tcp_payload() {
1580        let parser = create_parser_with_linktype(12); // DLT_RAW
1581        let mut packet = ethernet_ipv6_tcp()[14..].to_vec();
1582        packet.extend_from_slice(&[0x00; 6]);
1583
1584        let parsed = parser.parse_packet(&packet).unwrap();
1585        assert_eq!(parsed.tcp_header.unwrap().payload_len, 0);
1586    }
1587
1588    #[test]
1589    fn test_zero_total_length_keeps_full_payload() {
1590        let parser = create_parser_with_linktype(1);
1591        // TSO/LRO can hand up a segment with Total Length 0. The field is
1592        // unusable, so the captured bytes are kept rather than dropped.
1593        let mut packet = ethernet_ipv4_tcp_syn();
1594        packet[16] = 0x00;
1595        packet[17] = 0x00;
1596        packet.extend_from_slice(b"data");
1597
1598        let parsed = parser.parse_packet(&packet).unwrap();
1599        assert_eq!(parsed.tcp_header.unwrap().payload_len, 4);
1600    }
1601}