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