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::oui::OuiLookup;
9use crate::network::protocol;
10use crate::network::protocol::TransportParams;
11use crate::network::types::*;
12use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
13
14// Re-export TCP types
15pub use crate::network::protocol::tcp::{TcpFlags, TcpHeaderInfo};
16
17/// Result of parsing a packet
18#[derive(Debug)]
19pub struct ParsedPacket {
20    pub protocol: Protocol,
21    pub local_addr: SocketAddr,
22    pub remote_addr: SocketAddr,
23    pub tcp_header: Option<TcpHeaderInfo>, // TCP header info (seq, ack, window, flags)
24    pub protocol_state: ProtocolState,
25    pub is_outgoing: bool,
26    pub packet_len: usize,
27    pub dpi_result: Option<DpiResult>, // DPI results if available
28    pub process_name: Option<String>,  // Process name from PKTAP metadata
29    pub process_id: Option<u32>,       // Process ID from PKTAP metadata
30}
31
32impl ParsedPacket {
33    /// The flow identity this packet belongs to, derived from protocol and
34    /// addresses. `ConnectionKey` is `Copy`, so this costs nothing on the
35    /// per-packet path (no allocation, unlike the former `String` key field).
36    #[inline]
37    pub fn connection_key(&self) -> ConnectionKey {
38        ConnectionKey::new(self.protocol, self.local_addr, self.remote_addr)
39    }
40}
41
42/// Configuration for packet parsing
43///
44/// # Example
45///
46/// ```rust,ignore
47/// // Create parser with custom DPI limit
48/// let config = ParserConfig {
49///     enable_dpi: true,
50///     dpi_packet_limit: 5,  // Only inspect first 5 packets per connection
51/// };
52/// let parser = PacketParser::with_config(config);
53///
54/// // In connection tracking code:
55/// if config.should_perform_dpi(connection.packet_count) {
56///     // Perform DPI on this packet
57/// }
58/// ```
59#[derive(Clone)]
60pub struct ParserConfig {
61    pub enable_dpi: bool,
62    /// Maximum number of packets per connection to inspect with DPI
63    /// Use `should_perform_dpi()` method to check if DPI should be applied
64    pub dpi_packet_limit: usize,
65}
66
67impl Default for ParserConfig {
68    fn default() -> Self {
69        let config = Self {
70            enable_dpi: true,
71            dpi_packet_limit: 10, // Only inspect first 10 packets
72        };
73
74        // Log DPI configuration for debugging
75        log::trace!(
76            "ParserConfig: DPI {} (limit: {} packets per connection)",
77            if config.enable_dpi {
78                "enabled"
79            } else {
80                "disabled"
81            },
82            config.dpi_packet_limit
83        );
84
85        // Demonstrate usage: check if we should perform DPI on hypothetical packet counts
86        if config.enable_dpi {
87            log::trace!("  - Packet 0: DPI = {}", config.should_perform_dpi(0));
88            log::trace!(
89                "  - Packet {}: DPI = {}",
90                config.dpi_packet_limit - 1,
91                config.should_perform_dpi(config.dpi_packet_limit - 1)
92            );
93            log::trace!(
94                "  - Packet {}: DPI = {}",
95                config.dpi_packet_limit,
96                config.should_perform_dpi(config.dpi_packet_limit)
97            );
98        }
99
100        config
101    }
102}
103
104impl ParserConfig {
105    /// Check if DPI should be performed based on packet count
106    /// Returns true if packet_count is less than dpi_packet_limit
107    pub fn should_perform_dpi(&self, packet_count: usize) -> bool {
108        let should_dpi = self.enable_dpi && packet_count < self.dpi_packet_limit;
109        if !should_dpi && self.enable_dpi {
110            log::trace!(
111                "DPI skipped: packet {} exceeds limit {}",
112                packet_count,
113                self.dpi_packet_limit
114            );
115        }
116        should_dpi
117    }
118}
119
120/// Packet parser - stateless, thread-safe
121pub struct PacketParser {
122    local_ips: std::collections::HashSet<IpAddr>,
123    config: ParserConfig,
124    linktype: Option<i32>, // DLT linktype - 149 means PKTAP on macOS
125    oui_lookup: Option<OuiLookup>,
126}
127
128impl Default for PacketParser {
129    fn default() -> Self {
130        Self::new()
131    }
132}
133
134impl PacketParser {
135    /// Create a new packet parser with default configuration
136    /// Automatically detects local IP addresses from network interfaces
137    pub fn new() -> Self {
138        let mut local_ips = std::collections::HashSet::new();
139        for iface in pnet_datalink::interfaces() {
140            for ip_network in iface.ips {
141                local_ips.insert(ip_network.ip());
142            }
143        }
144        Self {
145            local_ips,
146            config: ParserConfig::default(),
147            linktype: None,
148            oui_lookup: None,
149        }
150    }
151
152    pub fn with_config(config: ParserConfig) -> Self {
153        let mut local_ips = std::collections::HashSet::new();
154        for iface in pnet_datalink::interfaces() {
155            for ip_network in iface.ips {
156                local_ips.insert(ip_network.ip());
157            }
158        }
159        Self {
160            local_ips,
161            config,
162            linktype: None,
163            oui_lookup: None,
164        }
165    }
166
167    /// Set the OUI lookup for MAC vendor resolution
168    pub fn with_oui_lookup(mut self, oui_lookup: OuiLookup) -> Self {
169        self.oui_lookup = Some(oui_lookup);
170        self
171    }
172
173    /// Set the linktype for this parser (needed for PKTAP detection)
174    pub fn with_linktype(mut self, linktype: i32) -> Self {
175        self.linktype = Some(linktype);
176
177        // Log linktype info for debugging, including TUN/TAP support
178        let link_type = link_layer::LinkLayerType::from_dlt(linktype);
179        if link_type.is_tunnel() {
180            log::debug!(
181                "Parser configured for tunnel interface: linktype {} ({:?})",
182                linktype,
183                link_type
184            );
185
186            // Log TUN/TAP parsing capabilities for documentation
187            log::trace!("TUN/TAP parsing available via link_layer::tun_tap module");
188            log::trace!("  - TUN interfaces (Layer 3): tun*, utun*");
189            log::trace!("  - TAP interfaces (Layer 2): tap*");
190        } else {
191            log::trace!(
192                "Parser configured with linktype {} ({:?})",
193                linktype,
194                link_type
195            );
196        }
197
198        self
199    }
200
201    /// Parse a raw packet using the appropriate link-layer parser
202    pub fn parse_packet(&self, data: &[u8]) -> Option<ParsedPacket> {
203        if let Some(linktype) = self.linktype {
204            // Determine the link layer type
205            let link_type = link_layer::LinkLayerType::from_dlt(linktype);
206            log::trace!(
207                "Parsing packet with linktype {} ({:?})",
208                linktype,
209                link_type
210            );
211
212            match linktype {
213                // PKTAP (macOS process metadata)
214                #[cfg(target_os = "macos")]
215                149 | 258 if pktap::is_pktap_linktype(linktype) => {
216                    log::debug!("Parsing as PKTAP (linktype {})", linktype);
217                    return self.parse_pktap_packet(data);
218                }
219                // Linux SLL (Linux "any" interface)
220                113 => {
221                    log::debug!("Parsing as Linux SLL (linktype 113)");
222                    return link_layer::linux_sll::parse_sll(data, self, None, None);
223                }
224                // Linux SLL2
225                276 => {
226                    log::debug!("Parsing as Linux SLL2 (linktype 276)");
227                    return link_layer::linux_sll::parse_sll2(data, self, None, None);
228                }
229                // TUN/TAP interfaces - use unified parser
230                0
231                | 1
232                | 12
233                | 101
234                | link_layer::dlt::LINKTYPE_IPV4
235                | link_layer::dlt::LINKTYPE_IPV6 => {
236                    log::debug!("Parsing TUN/TAP packet (linktype {})", linktype);
237                    return link_layer::tun_tap::parse_by_dlt(data, linktype, self, None, None);
238                }
239                _ => {
240                    log::debug!("Unknown linktype {}, trying Ethernet", linktype);
241                }
242            }
243        }
244
245        // Fallback: try Ethernet parsing if no linktype or unknown linktype
246        log::debug!("Using fallback Ethernet parsing");
247        link_layer::ethernet::parse(data, self, None, None)
248    }
249
250    #[cfg(target_os = "macos")]
251    fn parse_pktap_packet(&self, data: &[u8]) -> Option<ParsedPacket> {
252        let (pktap_header, payload) = pktap::parse_pktap_packet(data)?;
253        let (process_name, process_id) = pktap_header.get_process_info();
254
255        log::debug!(
256            "PKTAP packet: interface={}, process={:?}, pid={:?}, payload_len={}",
257            pktap_header.get_interface(),
258            process_name,
259            process_id,
260            payload.len()
261        );
262
263        // Now parse the inner packet based on the DLT type
264        match pktap_header.inner_dlt() {
265            1 => {
266                // DLT_EN10MB - Ethernet frame
267                // Note: macOS/XNU strips 802.1Q VLAN tags in ether_demux() before
268                // packets reach PKTAP, and libpcap on macOS does not reconstruct them.
269                // VLAN-tagged frames will never have EtherType 0x8100 here, but we
270                // delegate to ethernet::parse() to avoid duplicating the parsing logic.
271                ethernet::parse(payload, self, process_name, process_id)
272            }
273            12 => {
274                // DLT_RAW - Raw IP packet
275                if payload.is_empty() {
276                    return None;
277                }
278                let version = payload[0] >> 4;
279                match version {
280                    4 => self.parse_raw_ipv4_packet(payload, process_name, process_id),
281                    6 => self.parse_raw_ipv6_packet(payload, process_name, process_id),
282                    _ => None,
283                }
284            }
285            _ => {
286                log::debug!("Unsupported PKTAP inner DLT: {}", pktap_header.inner_dlt());
287                None
288            }
289        }
290    }
291
292    /// Parse an IPv4 packet from Ethernet frame data
293    /// (data includes the 14-byte Ethernet header)
294    pub fn parse_ipv4_packet_inner(
295        &self,
296        data: &[u8],
297        offset: usize,
298        process_name: Option<String>,
299        process_id: Option<u32>,
300    ) -> Option<ParsedPacket> {
301        let ip_data = &data[offset..];
302        if ip_data.len() < 20 {
303            return None;
304        }
305
306        let version = ip_data[0] >> 4;
307        if version != 4 {
308            return None;
309        }
310
311        // Extract actual packet length from IP header (bytes 2-3: Total Length field)
312        let ip_total_length = u16::from_be_bytes([ip_data[2], ip_data[3]]) as usize;
313        // Actual packet size = link-layer header (offset bytes) + IP total length
314        let actual_packet_len = offset + ip_total_length;
315
316        let protocol_num = ip_data[9];
317        let src_ip = IpAddr::V4(Ipv4Addr::new(
318            ip_data[12],
319            ip_data[13],
320            ip_data[14],
321            ip_data[15],
322        ));
323        let dst_ip = IpAddr::V4(Ipv4Addr::new(
324            ip_data[16],
325            ip_data[17],
326            ip_data[18],
327            ip_data[19],
328        ));
329
330        let ihl = ip_data[0] & 0x0F;
331        let ip_header_len = (ihl as usize) * 4;
332
333        if ip_data.len() < ip_header_len {
334            return None;
335        }
336
337        let transport_data = &ip_data[ip_header_len..];
338
339        let params =
340            TransportParams::new(src_ip, dst_ip, actual_packet_len, process_name, process_id);
341
342        match protocol_num {
343            1 => protocol::icmp::parse(transport_data, params, &self.local_ips),
344            2 => protocol::igmp::parse(transport_data, params, &self.local_ips),
345            6 => protocol::tcp::parse(transport_data, params, &self.config, &self.local_ips),
346            17 => protocol::udp::parse(transport_data, params, &self.config, &self.local_ips),
347            _ => None,
348        }
349    }
350
351    /// Parse an IPv6 packet from Ethernet frame data
352    /// (data includes the link-layer header of `offset` bytes)
353    pub fn parse_ipv6_packet_inner(
354        &self,
355        data: &[u8],
356        offset: usize,
357        process_name: Option<String>,
358        process_id: Option<u32>,
359    ) -> Option<ParsedPacket> {
360        let ip_data = &data[offset..];
361        if ip_data.len() < 40 {
362            return None;
363        }
364
365        let version = ip_data[0] >> 4;
366        if version != 6 {
367            return None;
368        }
369
370        // Extract actual packet length from IPv6 header (bytes 4-5: Payload Length field)
371        let ipv6_payload_length = u16::from_be_bytes([ip_data[4], ip_data[5]]) as usize;
372        // Actual packet size = link-layer header (offset bytes) + IPv6 header (40 bytes) + payload length
373        let actual_packet_len = offset + 40 + ipv6_payload_length;
374
375        let next_header = ip_data[6];
376
377        // Extract IPv6 addresses
378        let src_ip = IpAddr::V6(Ipv6Addr::new(
379            u16::from_be_bytes([ip_data[8], ip_data[9]]),
380            u16::from_be_bytes([ip_data[10], ip_data[11]]),
381            u16::from_be_bytes([ip_data[12], ip_data[13]]),
382            u16::from_be_bytes([ip_data[14], ip_data[15]]),
383            u16::from_be_bytes([ip_data[16], ip_data[17]]),
384            u16::from_be_bytes([ip_data[18], ip_data[19]]),
385            u16::from_be_bytes([ip_data[20], ip_data[21]]),
386            u16::from_be_bytes([ip_data[22], ip_data[23]]),
387        ));
388
389        let dst_ip = IpAddr::V6(Ipv6Addr::new(
390            u16::from_be_bytes([ip_data[24], ip_data[25]]),
391            u16::from_be_bytes([ip_data[26], ip_data[27]]),
392            u16::from_be_bytes([ip_data[28], ip_data[29]]),
393            u16::from_be_bytes([ip_data[30], ip_data[31]]),
394            u16::from_be_bytes([ip_data[32], ip_data[33]]),
395            u16::from_be_bytes([ip_data[34], ip_data[35]]),
396            u16::from_be_bytes([ip_data[36], ip_data[37]]),
397            u16::from_be_bytes([ip_data[38], ip_data[39]]),
398        ));
399
400        let transport_data = &ip_data[40..];
401
402        // Handle extension headers if needed
403        let (final_next_header, transport_offset) =
404            self.parse_ipv6_extension_headers(next_header, transport_data);
405        // A crafted extension header can declare a length that runs past the
406        // captured bytes, so `transport_offset` may exceed the slice length.
407        // Clamp before slicing to avoid an out-of-bounds panic (one-packet DoS).
408        let final_transport_data = &transport_data[transport_offset.min(transport_data.len())..];
409
410        let params =
411            TransportParams::new(src_ip, dst_ip, actual_packet_len, process_name, process_id);
412
413        match final_next_header {
414            58 => protocol::icmp::parse_v6(final_transport_data, params, &self.local_ips),
415            6 => protocol::tcp::parse(final_transport_data, params, &self.config, &self.local_ips),
416            17 => protocol::udp::parse(final_transport_data, params, &self.config, &self.local_ips),
417            _ => None,
418        }
419    }
420
421    /// Parse an ARP packet from Ethernet frame data
422    /// (data includes the link-layer header of `offset` bytes)
423    pub fn parse_arp_packet_inner(
424        &self,
425        data: &[u8],
426        offset: usize,
427        process_name: Option<String>,
428        process_id: Option<u32>,
429    ) -> Option<ParsedPacket> {
430        self.parse_arp_packet_with_offset(data, offset, process_name, process_id)
431    }
432
433    pub fn parse_arp_packet_with_offset(
434        &self,
435        data: &[u8],
436        header_len: usize,
437        process_name: Option<String>,
438        process_id: Option<u32>,
439    ) -> Option<ParsedPacket> {
440        let arp_data = &data[header_len..];
441        if arp_data.len() < 28 {
442            return None;
443        }
444
445        let hardware_type = u16::from_be_bytes([arp_data[0], arp_data[1]]);
446        let protocol_type = u16::from_be_bytes([arp_data[2], arp_data[3]]);
447        let opcode = u16::from_be_bytes([arp_data[6], arp_data[7]]);
448
449        if hardware_type != 1 || protocol_type != 0x0800 {
450            return None;
451        }
452
453        // Extract MAC addresses
454        let sender_mac = format!(
455            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
456            arp_data[8], arp_data[9], arp_data[10], arp_data[11], arp_data[12], arp_data[13]
457        );
458        let target_mac = format!(
459            "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
460            arp_data[18], arp_data[19], arp_data[20], arp_data[21], arp_data[22], arp_data[23]
461        );
462
463        let sender_ip = IpAddr::from([arp_data[14], arp_data[15], arp_data[16], arp_data[17]]);
464        let target_ip = IpAddr::from([arp_data[24], arp_data[25], arp_data[26], arp_data[27]]);
465
466        let operation = match opcode {
467            1 => ArpOperation::Request,
468            2 => ArpOperation::Reply,
469            _ => return None,
470        };
471
472        let sender_vendor = self
473            .oui_lookup
474            .as_ref()
475            .and_then(|oui| oui.lookup(&sender_mac).map(String::from));
476        let target_vendor = self
477            .oui_lookup
478            .as_ref()
479            .and_then(|oui| oui.lookup(&target_mac).map(String::from));
480
481        let arp_info = ArpInfo {
482            operation,
483            sender_mac,
484            sender_ip,
485            target_mac,
486            target_ip,
487            sender_vendor,
488            target_vendor,
489        };
490
491        let is_outgoing = self.local_ips.contains(&sender_ip);
492        let (local_addr, remote_addr) = if is_outgoing {
493            (SocketAddr::new(sender_ip, 0), SocketAddr::new(target_ip, 0))
494        } else {
495            (SocketAddr::new(target_ip, 0), SocketAddr::new(sender_ip, 0))
496        };
497
498        Some(ParsedPacket {
499            protocol: Protocol::Arp,
500            local_addr,
501            remote_addr,
502            tcp_header: None,
503            protocol_state: ProtocolState::Arp(arp_info),
504            is_outgoing,
505            packet_len: data.len(),
506            dpi_result: None,
507            process_name,
508            process_id,
509        })
510    }
511
512    /// Parse a raw IPv4 packet (no link-layer header)
513    /// Used by TUN devices, PKTAP DLT_RAW, and Linux Cooked Capture
514    pub fn parse_raw_ipv4_packet(
515        &self,
516        data: &[u8],
517        process_name: Option<String>,
518        process_id: Option<u32>,
519    ) -> Option<ParsedPacket> {
520        if data.len() < 20 {
521            return None;
522        }
523
524        let version = data[0] >> 4;
525        if version != 4 {
526            return None;
527        }
528
529        // Extract actual packet length from IP header (bytes 2-3: Total Length field)
530        // For raw IP packets, there's no Ethernet header
531        let actual_packet_len = u16::from_be_bytes([data[2], data[3]]) as usize;
532
533        let protocol_num = data[9];
534        let src_ip = IpAddr::V4(Ipv4Addr::new(data[12], data[13], data[14], data[15]));
535        let dst_ip = IpAddr::V4(Ipv4Addr::new(data[16], data[17], data[18], data[19]));
536
537        let ihl = data[0] & 0x0F;
538        let ip_header_len = (ihl as usize) * 4;
539
540        if data.len() < ip_header_len {
541            return None;
542        }
543
544        let transport_data = &data[ip_header_len..];
545
546        let params =
547            TransportParams::new(src_ip, dst_ip, actual_packet_len, process_name, process_id);
548
549        match protocol_num {
550            1 => protocol::icmp::parse(transport_data, params, &self.local_ips),
551            2 => protocol::igmp::parse(transport_data, params, &self.local_ips),
552            6 => protocol::tcp::parse(transport_data, params, &self.config, &self.local_ips),
553            17 => protocol::udp::parse(transport_data, params, &self.config, &self.local_ips),
554            _ => None,
555        }
556    }
557
558    /// Parse a raw IPv6 packet (no link-layer header)
559    /// Used by TUN devices, PKTAP DLT_RAW, and Linux Cooked Capture
560    pub fn parse_raw_ipv6_packet(
561        &self,
562        data: &[u8],
563        process_name: Option<String>,
564        process_id: Option<u32>,
565    ) -> Option<ParsedPacket> {
566        if data.len() < 40 {
567            return None;
568        }
569
570        let version = data[0] >> 4;
571        if version != 6 {
572            return None;
573        }
574
575        // Extract actual packet length from IPv6 header (bytes 4-5: Payload Length field)
576        // For raw IP packets, actual size = IPv6 header (40 bytes) + payload length
577        let ipv6_payload_length = u16::from_be_bytes([data[4], data[5]]) as usize;
578        let actual_packet_len = 40 + ipv6_payload_length;
579
580        let next_header = data[6];
581
582        // Extract IPv6 addresses
583        let src_ip = IpAddr::V6(Ipv6Addr::new(
584            u16::from_be_bytes([data[8], data[9]]),
585            u16::from_be_bytes([data[10], data[11]]),
586            u16::from_be_bytes([data[12], data[13]]),
587            u16::from_be_bytes([data[14], data[15]]),
588            u16::from_be_bytes([data[16], data[17]]),
589            u16::from_be_bytes([data[18], data[19]]),
590            u16::from_be_bytes([data[20], data[21]]),
591            u16::from_be_bytes([data[22], data[23]]),
592        ));
593
594        let dst_ip = IpAddr::V6(Ipv6Addr::new(
595            u16::from_be_bytes([data[24], data[25]]),
596            u16::from_be_bytes([data[26], data[27]]),
597            u16::from_be_bytes([data[28], data[29]]),
598            u16::from_be_bytes([data[30], data[31]]),
599            u16::from_be_bytes([data[32], data[33]]),
600            u16::from_be_bytes([data[34], data[35]]),
601            u16::from_be_bytes([data[36], data[37]]),
602            u16::from_be_bytes([data[38], data[39]]),
603        ));
604
605        let transport_data = &data[40..];
606
607        // Handle extension headers if needed
608        let (final_next_header, transport_offset) =
609            self.parse_ipv6_extension_headers(next_header, transport_data);
610        // A crafted extension header can declare a length that runs past the
611        // captured bytes, so `transport_offset` may exceed the slice length.
612        // Clamp before slicing to avoid an out-of-bounds panic (one-packet DoS).
613        let final_transport_data = &transport_data[transport_offset.min(transport_data.len())..];
614
615        let params =
616            TransportParams::new(src_ip, dst_ip, actual_packet_len, process_name, process_id);
617
618        match final_next_header {
619            58 => protocol::icmp::parse_v6(final_transport_data, params, &self.local_ips),
620            6 => protocol::tcp::parse(final_transport_data, params, &self.config, &self.local_ips),
621            17 => protocol::udp::parse(final_transport_data, params, &self.config, &self.local_ips),
622            _ => None,
623        }
624    }
625
626    fn parse_ipv6_extension_headers(&self, mut next_header: u8, data: &[u8]) -> (u8, usize) {
627        let mut offset = 0;
628
629        const HOP_BY_HOP: u8 = 0;
630        const ROUTING: u8 = 43;
631        const FRAGMENT: u8 = 44;
632        const ENCAPSULATING_SECURITY: u8 = 50;
633        const AUTHENTICATION: u8 = 51;
634        const DESTINATION_OPTIONS: u8 = 60;
635
636        loop {
637            match next_header {
638                HOP_BY_HOP | ROUTING | DESTINATION_OPTIONS => {
639                    if data.len() < offset + 2 {
640                        return (next_header, offset);
641                    }
642                    next_header = data[offset];
643                    let header_len = ((data[offset + 1] as usize) + 1) * 8;
644                    offset += header_len;
645                }
646                FRAGMENT => {
647                    if data.len() < offset + 8 {
648                        return (next_header, offset);
649                    }
650                    next_header = data[offset];
651                    offset += 8;
652                }
653                AUTHENTICATION => {
654                    if data.len() < offset + 2 {
655                        return (next_header, offset);
656                    }
657                    next_header = data[offset];
658                    let header_len = ((data[offset + 1] as usize) + 2) * 4;
659                    offset += header_len;
660                }
661                ENCAPSULATING_SECURITY => {
662                    return (next_header, offset);
663                }
664                _ => {
665                    return (next_header, offset);
666                }
667            }
668
669            if offset >= data.len() {
670                return (next_header, offset);
671            }
672        }
673    }
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679    use std::net::IpAddr;
680
681    /// Helper to create a parser with a specific linktype and controlled local IPs
682    /// This adds 192.168.1.100 to the local_ips set so test packets are correctly identified
683    fn create_parser_with_linktype(linktype: i32) -> PacketParser {
684        let mut parser = PacketParser::with_config(ParserConfig::default()).with_linktype(linktype);
685        // Add test IP to local_ips so the parser treats it as local
686        parser
687            .local_ips
688            .insert(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)));
689        parser
690    }
691
692    // Test fixture generators - inline versions of test packets
693    fn ethernet_ipv4_tcp_syn() -> Vec<u8> {
694        vec![
695            // Ethernet header
696            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
697            // IPv4 header
698            0x45, 0x00, 0x00, 0x28, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 192, 168, 1,
699            100, 93, 184, 216, 34, // TCP header (SYN flag)
700            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
701            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
702        ]
703    }
704
705    fn ethernet_ipv4_udp_dns() -> Vec<u8> {
706        vec![
707            // Ethernet
708            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
709            // IPv4
710            0x45, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, 192, 168, 1,
711            100, 8, 8, 8, 8, // UDP
712            0x04, 0xd2, 0x00, 0x35, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
713        ]
714    }
715
716    fn ethernet_ipv6_tcp() -> Vec<u8> {
717        vec![
718            // Ethernet
719            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x86, 0xdd,
720            // IPv6 header
721            0x60, 0x00, 0x00, 0x00, 0x00, 0x14, 0x06, 0x40, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00,
722            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8,
723            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
724            // TCP
725            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
726            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
727        ]
728    }
729
730    fn linux_sll_ipv4_tcp() -> Vec<u8> {
731        vec![
732            // Linux SLL header
733            0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x00,
734            0x08, 0x00, // IPv4
735            0x45, 0x00, 0x00, 0x28, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 192, 168, 1,
736            100, 93, 184, 216, 34, // TCP
737            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
738            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
739        ]
740    }
741
742    fn linux_sll2_ipv4_udp() -> Vec<u8> {
743        vec![
744            // Linux SLL2 header
745            0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x06, 0xaa, 0xbb,
746            0xcc, 0xdd, 0xee, 0xff, 0x00, 0x00, // IPv4
747            0x45, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x40, 0x11, 0x00, 0x00, 192, 168, 1,
748            100, 8, 8, 8, 8, // UDP
749            0x04, 0xd2, 0x00, 0x35, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
750        ]
751    }
752
753    // ====== DLT_EN10MB (Ethernet) Tests ======
754
755    #[test]
756    fn test_ethernet_ipv4_tcp_parsing() {
757        let parser = create_parser_with_linktype(1); // DLT_EN10MB
758        let packet = ethernet_ipv4_tcp_syn();
759
760        let parsed = parser.parse_packet(&packet);
761        assert!(
762            parsed.is_some(),
763            "Should parse valid Ethernet IPv4 TCP packet"
764        );
765
766        let p = parsed.unwrap();
767        assert_eq!(p.protocol, Protocol::Tcp);
768        // Source is 192.168.1.100:1234, Dest is 93.184.216.34:80
769        // Since source is local IP, local_addr should be source, remote should be dest
770        assert_eq!(p.local_addr.port(), 1234, "Local port should be 1234");
771        assert_eq!(p.remote_addr.port(), 80, "Remote port should be 80");
772        assert!(p.tcp_header.is_some());
773        assert!(p.tcp_header.unwrap().flags.syn, "SYN flag should be set");
774    }
775
776    #[test]
777    fn test_ethernet_ipv4_udp_parsing() {
778        let parser = create_parser_with_linktype(1);
779        let packet = ethernet_ipv4_udp_dns();
780
781        let parsed = parser.parse_packet(&packet);
782        assert!(parsed.is_some());
783
784        let p = parsed.unwrap();
785        assert_eq!(p.protocol, Protocol::Udp);
786        // Source: 192.168.1.100:1234, Dest: 8.8.8.8:53
787        assert_eq!(p.local_addr.port(), 1234);
788        assert_eq!(p.remote_addr.port(), 53, "Should detect DNS port");
789    }
790
791    #[test]
792    fn test_ethernet_ipv6_tcp_parsing() {
793        let parser = create_parser_with_linktype(1);
794        let packet = ethernet_ipv6_tcp();
795
796        let parsed = parser.parse_packet(&packet);
797        assert!(parsed.is_some(), "Should parse IPv6 packets");
798
799        let p = parsed.unwrap();
800        assert_eq!(p.protocol, Protocol::Tcp);
801        assert!(matches!(p.local_addr.ip(), IpAddr::V6(_)), "Should be IPv6");
802    }
803
804    #[test]
805    fn test_truncated_ethernet_packet() {
806        let parser = create_parser_with_linktype(1);
807        let truncated = vec![0x00, 0x11, 0x22]; // Only 3 bytes
808
809        let parsed = parser.parse_packet(&truncated);
810        assert!(parsed.is_none(), "Should reject truncated packets");
811    }
812
813    #[test]
814    fn test_unknown_ethertype() {
815        let parser = create_parser_with_linktype(1);
816        let packet = vec![
817            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xff,
818            0xff, // Unknown EtherType
819        ];
820
821        let parsed = parser.parse_packet(&packet);
822        assert!(parsed.is_none(), "Should reject unknown EtherType");
823    }
824
825    // ====== DLT_LINUX_SLL Tests ======
826
827    #[test]
828    fn test_linux_sll_ipv4_tcp_parsing() {
829        let parser = create_parser_with_linktype(113); // DLT_LINUX_SLL
830        let packet = linux_sll_ipv4_tcp();
831
832        let parsed = parser.parse_packet(&packet);
833        assert!(parsed.is_some(), "Should parse Linux SLL packets");
834
835        let p = parsed.unwrap();
836        assert_eq!(p.protocol, Protocol::Tcp);
837        assert_eq!(p.local_addr.port(), 1234);
838        assert_eq!(p.remote_addr.port(), 80);
839    }
840
841    #[test]
842    fn test_linux_sll_truncated() {
843        let parser = create_parser_with_linktype(113);
844        let truncated = vec![0x00, 0x00, 0x00]; // Too short
845
846        let parsed = parser.parse_packet(&truncated);
847        assert!(parsed.is_none(), "Should reject truncated SLL packets");
848    }
849
850    // ====== DLT_LINUX_SLL2 Tests ======
851
852    #[test]
853    fn test_linux_sll2_ipv4_udp_parsing() {
854        let parser = create_parser_with_linktype(276); // DLT_LINUX_SLL2
855        let packet = linux_sll2_ipv4_udp();
856
857        let parsed = parser.parse_packet(&packet);
858        assert!(parsed.is_some(), "Should parse Linux SLL2 packets");
859
860        let p = parsed.unwrap();
861        assert_eq!(p.protocol, Protocol::Udp);
862        assert_eq!(p.local_addr.port(), 1234);
863        assert_eq!(p.remote_addr.port(), 53);
864    }
865
866    #[test]
867    fn test_linux_sll2_truncated() {
868        let parser = create_parser_with_linktype(276);
869        let truncated = vec![0x08, 0x00]; // Too short for SLL2
870
871        let parsed = parser.parse_packet(&truncated);
872        assert!(parsed.is_none(), "Should reject truncated SLL2 packets");
873    }
874
875    // ====== TCP Flags Tests ======
876
877    #[test]
878    fn test_tcp_flags_parsing() {
879        use crate::network::protocol::tcp::parse_tcp_flags;
880
881        let flags = parse_tcp_flags(0x02); // SYN
882        assert!(flags.syn);
883        assert!(!flags.ack);
884        assert!(!flags.fin);
885
886        let flags = parse_tcp_flags(0x12); // SYN + ACK
887        assert!(flags.syn);
888        assert!(flags.ack);
889
890        let flags = parse_tcp_flags(0x11); // FIN + ACK
891        assert!(flags.fin);
892        assert!(flags.ack);
893    }
894
895    // ====== Parser Configuration Tests ======
896
897    #[test]
898    fn test_parser_default_config() {
899        let config = ParserConfig::default();
900        assert!(config.enable_dpi, "DPI should be enabled by default");
901        assert_eq!(config.dpi_packet_limit, 10);
902    }
903
904    #[test]
905    fn test_parser_with_linktype() {
906        let parser = PacketParser::with_config(ParserConfig::default()).with_linktype(1);
907        assert_eq!(parser.linktype, Some(1));
908    }
909
910    // ====== Local IP Detection Tests ======
911
912    #[test]
913    fn test_local_ip_detection() {
914        let parser = PacketParser::new();
915        // Should have at least loopback
916        assert!(!parser.local_ips.is_empty(), "Should detect local IPs");
917    }
918
919    // ====== Edge Cases ======
920
921    #[test]
922    fn test_empty_packet() {
923        let parser = create_parser_with_linktype(1);
924        let empty = vec![];
925        assert!(parser.parse_packet(&empty).is_none());
926    }
927
928    #[test]
929    fn test_ipv6_extension_header_overflow_does_not_panic() {
930        // Regression: a crafted IPv6 extension header can declare a length
931        // that runs far past the captured bytes. The parser used to slice
932        // `transport_data[transport_offset..]` with `transport_offset` past
933        // the end, panicking the capture thread (one-packet DoS). It must now
934        // clamp and return cleanly instead.
935        let parser = create_parser_with_linktype(1);
936        let mut packet = vec![
937            // Ethernet (ethertype 0x86dd = IPv6)
938            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x86, 0xdd,
939        ];
940        packet.extend_from_slice(&[
941            // IPv6 header: version 6, next_header = 0 (Hop-by-Hop Options)
942            0x60, 0x00, 0x00, 0x00, // version / traffic class / flow label
943            0x00, 0x02, // payload length = 2
944            0x00, // next header = Hop-by-Hop Options
945            0x40, // hop limit
946            // src addr (::1)
947            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
948            0x00, 0x01, // dst addr (::2)
949            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
950            0x00, 0x02,
951        ]);
952        // Hop-by-Hop extension header that claims (0xFF + 1) * 8 = 2048 bytes
953        // while only 2 bytes are present.
954        packet.extend_from_slice(&[0x3b /* next = no next header */, 0xff]);
955
956        // Must not panic.
957        let _ = parser.parse_packet(&packet);
958    }
959
960    #[test]
961    fn test_ipv4_with_options() {
962        let parser = create_parser_with_linktype(1);
963        let mut packet = vec![
964            // Ethernet
965            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x08, 0x00,
966            // IPv4 with IHL=6 (24 bytes header with 4 bytes options)
967            0x46, 0x00, 0x00, 0x2c, // IHL=6, Total=44
968            0x00, 0x01, 0x00, 0x00, 0x40, 0x06, 0x00, 0x00, 192, 168, 1, 100, 93, 184, 216,
969            34, // IP options (4 bytes)
970            0x01, 0x01, 0x00, 0x00,
971        ];
972        // TCP header
973        packet.extend_from_slice(&[
974            0x04, 0xd2, 0x00, 0x50, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x50, 0x02,
975            0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
976        ]);
977
978        let parsed = parser.parse_packet(&packet);
979        assert!(parsed.is_some(), "Should handle IPv4 with options");
980    }
981
982    #[test]
983    fn test_packet_length_calculation_ipv4() {
984        let parser = create_parser_with_linktype(1);
985        let packet = ethernet_ipv4_tcp_syn();
986
987        let parsed = parser.parse_packet(&packet).unwrap();
988        // IPv4 total length is 40 bytes (0x0028), plus 14 bytes Ethernet = 54
989        assert_eq!(parsed.packet_len, 54);
990    }
991
992    #[test]
993    fn test_packet_length_calculation_ipv6() {
994        let parser = create_parser_with_linktype(1);
995        let packet = ethernet_ipv6_tcp();
996
997        let parsed = parser.parse_packet(&packet).unwrap();
998        // IPv6: 14 (Ethernet) + 40 (IPv6 header) + 20 (payload) = 74
999        assert_eq!(parsed.packet_len, 74);
1000    }
1001}