Skip to main content

rustnet_core/network/
parser.rs

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