flowscope 0.26.0

Passive flow & session tracking for packet capture (runtime-free, cross-platform)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! Internal frame-parsing helpers shared by built-in extractors.
//!
//! Wraps [`etherparse`] for the protocols it handles and adds
//! inline parsers for what it doesn't (MPLS, VXLAN, GTP-U).

use std::net::IpAddr;

use crate::extractor::TcpFlags;

/// Parsed bits of an Ethernet (or post-decap-Ethernet) frame.
pub(crate) struct ParsedFrame<'a> {
    pub ip: Option<ParsedIp<'a>>,
    pub l4: Option<ParsedL4>,
}

pub(crate) struct ParsedIp<'a> {
    pub src: IpAddr,
    pub dst: IpAddr,
    pub proto: u8,
    /// Slice of L4 payload (for inspection or hashing). Lifetime
    /// borrowed from the original frame. Consumed by the GRE
    /// decap combinator and any future inspection paths. Only the
    /// captured bytes: shorter than [`Self::l4_wire_len`] when the
    /// capture cut the packet.
    pub l4_payload: &'a [u8],
    /// Offset of `l4_payload` in the parsed frame.
    pub l4_offset: usize,
    /// Length of the IP packet on the wire, header included: the
    /// IPv4 total length / 40 + the IPv6 payload length. When the
    /// header gives no usable length (an IPv4 total length of 0 on a
    /// BIG TCP datagram over 65 535 bytes, an IPv6 jumbogram), the
    /// captured IP length.
    pub l3_len: u32,
    /// Length of the L4 region (header + payload) on the wire, as the
    /// IP header claims it; never less than `l4_payload.len()`.
    pub l4_wire_len: usize,
}

pub(crate) enum ParsedL4 {
    Tcp(ParsedTcp),
    Udp(ParsedUdp),
    Other,
}

pub(crate) struct ParsedTcp {
    pub src_port: u16,
    pub dst_port: u16,
    pub flags: TcpFlags,
    pub seq: u32,
    pub ack: u32,
    /// Offset into the original frame where the TCP payload starts.
    pub payload_offset: usize,
    /// Captured payload bytes.
    pub payload_len: usize,
    /// Payload bytes on the wire (≥ `payload_len`; larger when the
    /// capture cut the segment).
    pub wire_payload_len: usize,
    pub window: u16,
}

pub(crate) struct ParsedUdp {
    pub src_port: u16,
    pub dst_port: u16,
    /// Offset into the original frame where the UDP payload starts.
    pub payload_offset: usize,
    /// Captured payload bytes.
    pub payload_len: usize,
    /// Payload bytes on the wire (≥ `payload_len`).
    pub wire_payload_len: usize,
}

/// Parse an L2 Ethernet frame (with optional VLAN/MACsec link
/// extensions handled by `etherparse`).
///
/// Lax about the one thing a capture does to a packet: cutting its
/// end (a snap length, #212). A packet whose IP header claims more
/// bytes than were captured is parsed as far as its headers go, and
/// the lengths the headers claim are reported next to the captured
/// ones (`l3_len`, `l4_wire_len`, `wire_payload_len`). Everything
/// else that `etherparse` rejects — a malformed header or body in a
/// packet that is *not* cut short (bad TCP data offset, a short IGMP
/// message, an ARP body shorter than its address lengths, a broken
/// MACsec header, IP extension headers cut by the snap length) —
/// still skips the packet, as the strict parse did, and so do the
/// length fields etherparse's lax slicing would otherwise overrule: an
/// IPv4 total length below the header's own length (except 0 on a
/// datagram longer than 65 535 bytes, IPv4 BIG TCP), a UDP length below
/// 8 or beyond the IP payload. So does a packet cut inside its TCP /
/// UDP header: without ports there is no flow key.
pub(crate) fn parse_eth(frame: &[u8]) -> Option<ParsedFrame<'_>> {
    let sp = etherparse::LaxSlicedPacket::from_ethernet(frame).ok()?;
    parse_from_lax(&sp, frame)
}

fn parse_from_lax<'a>(
    sp: &etherparse::LaxSlicedPacket<'a>,
    frame: &'a [u8],
) -> Option<ParsedFrame<'a>> {
    use etherparse::{IpNumber, LaxNetSlice, LenSource, err::Layer, err::packet::SliceError};

    let net = sp.net.as_ref()?;
    // (src, dst, protocol, start of the IP header, length the header
    // claims, payload, IPv4 total length below the header's own length)
    let (src, dst, proto, l3_start, claimed, payload, v4_short) = match net {
        LaxNetSlice::Ipv4(v4) => {
            let h = v4.header();
            (
                IpAddr::V4(h.source_addr()),
                IpAddr::V4(h.destination_addr()),
                u8::from(h.protocol()),
                h.slice().as_ptr(),
                usize::from(h.total_len()),
                v4.payload(),
                usize::from(h.total_len()) < h.slice().len(),
            )
        }
        LaxNetSlice::Ipv6(v6) => {
            let h = v6.header();
            (
                IpAddr::V6(h.source_addr()),
                IpAddr::V6(h.destination_addr()),
                // After any IPv6 extensions, this is the L4 proto.
                u8::from(v6.payload().ip_number),
                h.slice().as_ptr(),
                40 + usize::from(h.payload_length()),
                v6.payload(),
                false,
            )
        }
        // ARP has no IP endpoints, so no flow (etherparse >= 0.17 parses it).
        LaxNetSlice::Arp(_) => return None,
    };
    // The lax slicer picks IPv4 / IPv6 by the version nibble; a
    // receiver goes by the EtherType and drops a mismatch (as the
    // strict parse did).
    let ether_type = sp.ether_payload()?.ether_type;
    let version_ok = match net {
        LaxNetSlice::Ipv4(_) => ether_type == etherparse::EtherType::IPV4,
        LaxNetSlice::Ipv6(_) => ether_type == etherparse::EtherType::IPV6,
        LaxNetSlice::Arp(_) => false,
    };
    if !version_ok {
        return None;
    }

    // The only stop tolerated is the capture running out inside the
    // transport layer of a packet whose IP header claims more bytes.
    if let Some((err, layer)) = &sp.stop_err {
        let cut = matches!(err, SliceError::Len(_))
            && payload.incomplete
            && matches!(
                layer,
                Layer::TcpHeader | Layer::UdpHeader | Layer::Icmpv4 | Layer::Icmpv6 | Layer::Igmp
            );
        if !cut {
            return None;
        }
    }
    // A TCP / UDP header the capture cut: no ports, no flow key.
    if sp.transport.is_none()
        && !payload.fragmented
        && (payload.ip_number == IpNumber::TCP || payload.ip_number == IpNumber::UDP)
    {
        return None;
    }

    let l4_payload_slice: &[u8] = payload.payload;
    // Offset of the L4 payload region (header + body for TCP/UDP)
    // relative to the original frame.
    let l4_region_offset = byte_offset(frame, l4_payload_slice)?;
    let l3_offset = (l3_start as usize).checked_sub(frame.as_ptr() as usize)?;
    let l3_header = l4_region_offset.checked_sub(l3_offset)?;
    let captured_l3 = l3_header + l4_payload_slice.len();
    // An IPv4 total length below the header's own length is malformed —
    // receivers drop the packet, so accepting it would let an injected
    // segment stand in for real bytes. etherparse's lax slicing falls
    // back to the frame length; flowscope keeps that only where the
    // field cannot hold the length: 0 on a datagram longer than 65 535
    // bytes (IPv4 BIG TCP, seen on the sending host's own capture).
    if v4_short && !(claimed == 0 && captured_l3 > usize::from(u16::MAX)) {
        return None;
    }
    // The header's own length, unless it gave none (BIG TCP total
    // length 0, IPv6 jumbogram) and etherparse fell back to the slice.
    let l3_wire = if payload.incomplete || payload.len_source != LenSource::Slice {
        claimed.max(captured_l3)
    } else {
        captured_l3
    };
    let incomplete = payload.incomplete;
    let l4_wire_len = if incomplete {
        l3_wire
            .saturating_sub(l3_header)
            .max(l4_payload_slice.len())
    } else {
        l4_payload_slice.len()
    };
    let l3_len = u32::try_from(l3_wire).unwrap_or(u32::MAX);

    let l4 = match sp.transport.as_ref() {
        Some(etherparse::TransportSlice::Tcp(tcp)) => {
            let payload = tcp.payload();
            let payload_offset = byte_offset(frame, payload).unwrap_or(l4_region_offset);
            let mut flags = TcpFlags::empty();
            if tcp.fin() {
                flags |= TcpFlags::FIN;
            }
            if tcp.syn() {
                flags |= TcpFlags::SYN;
            }
            if tcp.rst() {
                flags |= TcpFlags::RST;
            }
            if tcp.psh() {
                flags |= TcpFlags::PSH;
            }
            if tcp.ack() {
                flags |= TcpFlags::ACK;
            }
            if tcp.urg() {
                flags |= TcpFlags::URG;
            }
            if tcp.ece() {
                flags |= TcpFlags::ECE;
            }
            if tcp.cwr() {
                flags |= TcpFlags::CWR;
            }
            Some(ParsedL4::Tcp(ParsedTcp {
                src_port: tcp.source_port(),
                dst_port: tcp.destination_port(),
                flags,
                seq: tcp.sequence_number(),
                ack: tcp.acknowledgment_number(),
                payload_offset,
                payload_len: payload.len(),
                wire_payload_len: l4_wire_len
                    .saturating_sub(tcp.header_slice().len())
                    .max(payload.len()),
                window: tcp.window_size(),
            }))
        }
        Some(etherparse::TransportSlice::Udp(udp)) => {
            let payload = udp.payload();
            let payload_offset = byte_offset(frame, payload).unwrap_or(l4_region_offset);
            // UDP's length is 0 (a jumbogram: the IP payload) or covers
            // its header and fits the IP payload — the IP header's
            // claim for a cut packet. Anything else is malformed and
            // dropped by receivers, as the strict parse did. etherparse's
            // lax slicing would fall back to the captured length.
            let udp_len = usize::from(udp.length());
            if udp_len != 0 && !(8..=l4_wire_len).contains(&udp_len) {
                return None;
            }
            // A complete datagram is what UDP's length field delimits
            // (bytes after it in the IP payload — UDP options, trailing
            // data — are no truncation). A cut one is as long as that
            // field says, or as the IP header says for a jumbogram.
            let wire_payload_len = match (incomplete, udp_len) {
                (false, _) => payload.len(),
                (true, 0) => l4_wire_len.saturating_sub(8),
                (true, n) => n - 8,
            };
            Some(ParsedL4::Udp(ParsedUdp {
                src_port: udp.source_port(),
                dst_port: udp.destination_port(),
                payload_offset,
                payload_len: payload.len(),
                wire_payload_len: wire_payload_len.max(payload.len()),
            }))
        }
        Some(_) => Some(ParsedL4::Other),
        None => None,
    };

    Some(ParsedFrame {
        ip: Some(ParsedIp {
            src,
            dst,
            proto,
            l4_payload: l4_payload_slice,
            l4_offset: l4_region_offset,
            l3_len,
            l4_wire_len,
        }),
        l4,
    })
}

/// Compute the byte offset of `inner` inside `outer`, if `inner` is
/// fully contained within `outer`'s allocation. Returns None if not.
pub(crate) fn byte_offset(outer: &[u8], inner: &[u8]) -> Option<usize> {
    let outer_start = outer.as_ptr() as usize;
    let inner_start = inner.as_ptr() as usize;
    let outer_end = outer_start.checked_add(outer.len())?;
    let inner_end = inner_start.checked_add(inner.len())?;
    if inner_start < outer_start || inner_end > outer_end {
        return None;
    }
    Some(inner_start - outer_start)
}

#[cfg(any(test, feature = "test-helpers"))]
pub mod test_frames {
    //! Synthetic frame builders used across extractor tests.
    //!
    //! Available behind the `test-helpers` feature for downstream
    //! crates (proptest, fuzz harnesses, fixture generators).

    /// Build an Ethernet/IPv4/TCP frame with the given fields.
    /// Returns the byte buffer.
    #[allow(clippy::too_many_arguments)]
    pub fn ipv4_tcp(
        src_mac: [u8; 6],
        dst_mac: [u8; 6],
        src_ip: [u8; 4],
        dst_ip: [u8; 4],
        src_port: u16,
        dst_port: u16,
        seq: u32,
        ack: u32,
        flags: u8,
        payload: &[u8],
    ) -> Vec<u8> {
        use etherparse::{Ethernet2Header, IpNumber, Ipv4Header, TcpHeader};

        let mut tcp = TcpHeader::new(src_port, dst_port, seq, 8192);
        tcp.acknowledgment_number = ack;
        tcp.fin = flags & 0x01 != 0;
        tcp.syn = flags & 0x02 != 0;
        tcp.rst = flags & 0x04 != 0;
        tcp.psh = flags & 0x08 != 0;
        tcp.ack = flags & 0x10 != 0;
        tcp.urg = flags & 0x20 != 0;

        let ip = Ipv4Header::new(
            (tcp.header_len() + payload.len()) as u16,
            64,
            IpNumber::TCP,
            src_ip,
            dst_ip,
        )
        .unwrap();

        let eth = Ethernet2Header {
            destination: dst_mac,
            source: src_mac,
            ether_type: etherparse::EtherType::IPV4,
        };

        let mut out = Vec::new();
        eth.write(&mut out).unwrap();
        ip.write(&mut out).unwrap();
        tcp.write(&mut out).unwrap();
        out.extend_from_slice(payload);
        out
    }

    /// Build an Ethernet/IPv4/UDP frame.
    pub fn ipv4_udp(
        src_ip: [u8; 4],
        dst_ip: [u8; 4],
        src_port: u16,
        dst_port: u16,
        payload: &[u8],
    ) -> Vec<u8> {
        use etherparse::{Ethernet2Header, IpNumber, Ipv4Header, UdpHeader};

        let udp = UdpHeader::without_ipv4_checksum(src_port, dst_port, payload.len()).unwrap();
        let ip = Ipv4Header::new(
            (udp.header_len_u16() as usize + payload.len()) as u16,
            64,
            IpNumber::UDP,
            src_ip,
            dst_ip,
        )
        .unwrap();
        let eth = Ethernet2Header {
            destination: [0; 6],
            source: [0; 6],
            ether_type: etherparse::EtherType::IPV4,
        };

        let mut out = Vec::new();
        eth.write(&mut out).unwrap();
        ip.write(&mut out).unwrap();
        udp.write(&mut out).unwrap();
        out.extend_from_slice(payload);
        out
    }

    /// Build an Ethernet/IPv6/TCP frame.
    pub fn ipv6_tcp(
        src_ip: [u8; 16],
        dst_ip: [u8; 16],
        src_port: u16,
        dst_port: u16,
        seq: u32,
        flags: u8,
        payload: &[u8],
    ) -> Vec<u8> {
        use etherparse::{Ethernet2Header, IpNumber, Ipv6Header, TcpHeader};

        let mut tcp = TcpHeader::new(src_port, dst_port, seq, 8192);
        tcp.syn = flags & 0x02 != 0;
        tcp.ack = flags & 0x10 != 0;

        let ip = Ipv6Header {
            traffic_class: 0,
            flow_label: 0u32.try_into().unwrap(),
            payload_length: (tcp.header_len() + payload.len()) as u16,
            next_header: IpNumber::TCP,
            hop_limit: 64,
            source: src_ip,
            destination: dst_ip,
        };
        let eth = Ethernet2Header {
            destination: [0; 6],
            source: [0; 6],
            ether_type: etherparse::EtherType::IPV6,
        };

        let mut out = Vec::new();
        eth.write(&mut out).unwrap();
        ip.write(&mut out).unwrap();
        tcp.write(&mut out).unwrap();
        out.extend_from_slice(payload);
        out
    }

    /// Insert 802.1Q / 802.1ad tags, outermost first, into an Ethernet II
    /// `frame` after its MAC addresses. Each tag is `(tpid, tci)`.
    pub fn with_vlan_tags(frame: &[u8], tags: &[(u16, u16)]) -> Vec<u8> {
        let mut out = frame[..12].to_vec();
        for &(tpid, tci) in tags {
            out.extend_from_slice(&tpid.to_be_bytes());
            out.extend_from_slice(&tci.to_be_bytes());
        }
        out.extend_from_slice(&frame[12..]);
        out
    }
}

#[cfg(test)]
mod tests {
    use test_frames::*;

    use super::*;

    #[test]
    fn parse_ipv4_tcp_basic() {
        let f = ipv4_tcp(
            [0; 6],
            [0; 6],
            [10, 0, 0, 1],
            [10, 0, 0, 2],
            1234,
            80,
            1000,
            0,
            0x02,
            b"",
        );
        let parsed = parse_eth(&f).expect("parse");
        let ip = parsed.ip.unwrap();
        match ip.src {
            std::net::IpAddr::V4(a) => assert_eq!(a.octets(), [10, 0, 0, 1]),
            _ => panic!("expected ipv4"),
        }
        match parsed.l4.unwrap() {
            ParsedL4::Tcp(t) => {
                assert_eq!(t.src_port, 1234);
                assert_eq!(t.dst_port, 80);
                assert!(t.flags.contains(TcpFlags::SYN));
                assert_eq!(t.seq, 1000);
                assert_eq!(t.payload_len, 0);
            }
            _ => panic!("expected tcp"),
        }
    }

    #[test]
    fn parse_ipv4_tcp_payload_offset_correct() {
        let payload = b"hello";
        let f = ipv4_tcp(
            [0; 6],
            [0; 6],
            [1, 2, 3, 4],
            [5, 6, 7, 8],
            10,
            20,
            0,
            0,
            0x10,
            payload,
        );
        let parsed = parse_eth(&f).unwrap();
        let tcp = match parsed.l4.unwrap() {
            ParsedL4::Tcp(t) => t,
            _ => panic!(),
        };
        // Eth (14) + IP (20) + TCP (20) = 54
        assert_eq!(tcp.payload_offset, 54);
        assert_eq!(tcp.payload_len, payload.len());
        assert_eq!(
            &f[tcp.payload_offset..tcp.payload_offset + tcp.payload_len],
            payload
        );
    }

    #[test]
    fn parse_ipv4_udp_basic() {
        let f = ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 5353, 53, b"hi");
        let parsed = parse_eth(&f).unwrap();
        match parsed.l4.unwrap() {
            ParsedL4::Udp(u) => {
                assert_eq!(u.src_port, 5353);
                assert_eq!(u.dst_port, 53);
                assert_eq!(u.payload_len, 2);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn parse_ipv6_tcp_basic() {
        let f = ipv6_tcp(
            [0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
            [0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
            12345,
            443,
            500,
            0x12, // SYN | ACK
            b"",
        );
        let parsed = parse_eth(&f).unwrap();
        let ip = parsed.ip.unwrap();
        match ip.src {
            std::net::IpAddr::V6(_) => {}
            _ => panic!(),
        }
        let tcp = match parsed.l4.unwrap() {
            ParsedL4::Tcp(t) => t,
            _ => panic!(),
        };
        assert!(tcp.flags.contains(TcpFlags::SYN));
        assert!(tcp.flags.contains(TcpFlags::ACK));
    }

    #[test]
    fn parse_arp_returns_none_ip() {
        // 64-byte minimum ARP frame: Eth(14) + ARP(28) + padding(22)
        let mut f = vec![0u8; 64];
        f[0..6].copy_from_slice(&[0xff; 6]); // dst MAC
        f[6..12].copy_from_slice(&[0; 6]);
        f[12..14].copy_from_slice(&0x0806u16.to_be_bytes()); // ARP ethertype
        // ARP header (HTYPE=1, PTYPE=0x0800, HLEN=6, PLEN=4, OPER=1)
        f[14..16].copy_from_slice(&1u16.to_be_bytes());
        f[16..18].copy_from_slice(&0x0800u16.to_be_bytes());
        f[18] = 6;
        f[19] = 4;
        f[20..22].copy_from_slice(&1u16.to_be_bytes());
        let parsed = parse_eth(&f);
        // ARP doesn't yield an IP, parse should return None at the
        // net stage.
        assert!(parsed.is_none() || parsed.unwrap().ip.is_none());
    }

    #[test]
    fn parse_truncated_returns_none() {
        let f = [0u8; 5];
        assert!(parse_eth(&f).is_none());
    }

    // ── #212: lax parsing of frames a snap length cut ──────────

    fn tcp_frame(payload: &[u8]) -> Vec<u8> {
        ipv4_tcp(
            [0; 6],
            [0; 6],
            [10, 0, 0, 1],
            [10, 0, 0, 2],
            40000,
            80,
            1000,
            0,
            0x18,
            payload,
        )
    }

    #[test]
    fn lax_tcp_reports_wire_payload_len() {
        let mut f = tcp_frame(&[b'x'; 100]);
        // Ethernet (14) + IP (20) + TCP (20) + 10 payload bytes kept.
        f.truncate(64);
        let parsed = parse_eth(&f).expect("a cut segment is parsed");
        let ip = parsed.ip.unwrap();
        assert_eq!(ip.l3_len, 140, "IP total length from the header");
        assert_eq!(ip.l4_wire_len, 120);
        assert_eq!(ip.l4_payload.len(), 30, "captured L4 bytes");
        let ParsedL4::Tcp(t) = parsed.l4.unwrap() else {
            panic!("expected tcp")
        };
        assert_eq!((t.src_port, t.dst_port, t.seq), (40000, 80, 1000));
        assert_eq!((t.payload_offset, t.payload_len), (54, 10));
        assert_eq!(t.wire_payload_len, 100);
    }

    #[test]
    fn complete_tcp_has_equal_wire_and_captured_lengths() {
        let f = tcp_frame(&[b'x'; 100]);
        let parsed = parse_eth(&f).unwrap();
        assert_eq!(parsed.ip.as_ref().unwrap().l3_len, 140);
        let ParsedL4::Tcp(t) = parsed.l4.unwrap() else {
            panic!("expected tcp")
        };
        assert_eq!((t.payload_len, t.wire_payload_len), (100, 100));
    }

    #[test]
    fn lax_udp_reports_wire_payload_len() {
        let mut f = ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 5353, 53, &[7; 200]);
        f.truncate(14 + 20 + 8 + 20);
        let parsed = parse_eth(&f).expect("a cut datagram is parsed");
        assert_eq!(parsed.ip.as_ref().unwrap().l3_len, 228);
        let ParsedL4::Udp(u) = parsed.l4.unwrap() else {
            panic!("expected udp")
        };
        assert_eq!((u.payload_len, u.wire_payload_len), (20, 200));
    }

    #[test]
    fn tcp_header_cut_is_skipped() {
        let mut f = tcp_frame(&[b'x'; 100]);
        // Cut inside the TCP header: ports present, header incomplete.
        f.truncate(14 + 20 + 10);
        assert!(parse_eth(&f).is_none(), "no complete L4 header, no key");
        // Cut inside the IP header.
        f.truncate(14 + 10);
        assert!(parse_eth(&f).is_none());
    }

    #[test]
    fn malformed_igmp_content_still_skipped() {
        // A complete IPv4 packet carrying a 4-byte IGMP message (IGMP
        // needs 8): malformed, not cut — skipped as in 0.25.3.
        use etherparse::{Ethernet2Header, IpNumber, Ipv4Header};
        let ip = Ipv4Header::new(4, 1, IpNumber::IGMP, [10, 0, 0, 1], [224, 0, 0, 1]).unwrap();
        let mut f = Vec::new();
        Ethernet2Header {
            destination: [0; 6],
            source: [0; 6],
            ether_type: etherparse::EtherType::IPV4,
        }
        .write(&mut f)
        .unwrap();
        ip.write(&mut f).unwrap();
        f.extend_from_slice(&[0x11, 0, 0, 0]);
        assert!(parse_eth(&f).is_none());
        // A malformed TCP header (data offset beyond the segment) in a
        // complete packet: skipped too.
        let mut f = tcp_frame(b"");
        f[14 + 20 + 12] = 0xf0; // data offset 15 words = 60 bytes
        assert!(parse_eth(&f).is_none());
    }

    #[test]
    fn big_tcp_zero_total_len_is_tracked() {
        // IPv4 BIG TCP hands a capture on the sending host a
        // super-segment longer than 65 535 bytes, whose total length
        // field cannot say so and is 0: the frame is the length.
        let mut f = tcp_frame(&[b'x'; 1000]);
        f.resize(14 + 70_000, b'x');
        f[16] = 0;
        f[17] = 0;
        let parsed = parse_eth(&f).expect("BIG TCP frame parsed");
        let ip = parsed.ip.unwrap();
        assert_eq!(ip.l3_len as usize, 70_000, "captured IP length");
        let ParsedL4::Tcp(t) = parsed.l4.unwrap() else {
            panic!("expected tcp")
        };
        assert_eq!(
            (t.payload_len, t.wire_payload_len),
            (70_000 - 40, 70_000 - 40)
        );
    }

    #[test]
    fn ipv4_total_len_below_its_header_is_skipped() {
        // Receivers drop such a packet (0.25 skipped it): accepting it
        // would let an injected segment replace real stream bytes.
        for total_len in [0u16, 1, 19] {
            let mut f = tcp_frame(&[b'x'; 3000]);
            f[16..18].copy_from_slice(&total_len.to_be_bytes());
            assert!(parse_eth(&f).is_none(), "total length {total_len}");
        }
    }

    #[test]
    fn udp_length_must_fit_the_ip_payload() {
        // Strict UDP rule for a complete packet: 0 (jumbogram) or
        // 8 ..= the IP payload length.
        for (udp_len, ok) in [
            (0u16, true),
            (8, true),
            (48, true),
            (49, false),
            (900, false),
            (5, false),
        ] {
            let mut f = ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 53, 5000, &[0x42; 40]);
            f[14 + 20 + 4..14 + 20 + 6].copy_from_slice(&udp_len.to_be_bytes());
            assert_eq!(parse_eth(&f).is_some(), ok, "UDP length {udp_len}");
        }
        // A cut datagram: its length may exceed what was captured, not
        // what the IP header claims.
        for (udp_len, ok) in [(48u16, true), (900, false), (5, false)] {
            let mut f = ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 53, 5000, &[0x42; 40]);
            f[14 + 20 + 4..14 + 20 + 6].copy_from_slice(&udp_len.to_be_bytes());
            f.truncate(14 + 20 + 8 + 10);
            assert_eq!(parse_eth(&f).is_some(), ok, "cut, UDP length {udp_len}");
        }
    }

    /// What 0.25's strict parse extracted from a frame: endpoints,
    /// protocol, and the TCP / UDP ports and payload span.
    type Summary = (IpAddr, IpAddr, u8, Option<(u16, u16, usize, usize)>);

    fn strict_summary(frame: &[u8]) -> Option<Summary> {
        let sp = etherparse::SlicedPacket::from_ethernet(frame).ok()?;
        let (src, dst, proto) = match sp.net.as_ref()? {
            etherparse::NetSlice::Ipv4(v4) => (
                IpAddr::V4(v4.header().source_addr()),
                IpAddr::V4(v4.header().destination_addr()),
                u8::from(v4.header().protocol()),
            ),
            etherparse::NetSlice::Ipv6(v6) => (
                IpAddr::V6(v6.header().source_addr()),
                IpAddr::V6(v6.header().destination_addr()),
                u8::from(v6.payload().ip_number),
            ),
            etherparse::NetSlice::Arp(_) => return None,
        };
        let l4 = match sp.transport.as_ref() {
            Some(etherparse::TransportSlice::Tcp(t)) => Some((
                t.source_port(),
                t.destination_port(),
                byte_offset(frame, t.payload())?,
                t.payload().len(),
            )),
            Some(etherparse::TransportSlice::Udp(u)) => Some((
                u.source_port(),
                u.destination_port(),
                byte_offset(frame, u.payload())?,
                u.payload().len(),
            )),
            _ => None,
        };
        Some((src, dst, proto, l4))
    }

    fn lax_summary(frame: &[u8]) -> Option<(Summary, bool)> {
        let p = parse_eth(frame)?;
        let ip = p.ip?;
        let (l4, cut) = match p.l4 {
            Some(ParsedL4::Tcp(t)) => (
                Some((t.src_port, t.dst_port, t.payload_offset, t.payload_len)),
                t.wire_payload_len != t.payload_len,
            ),
            Some(ParsedL4::Udp(u)) => (
                Some((u.src_port, u.dst_port, u.payload_offset, u.payload_len)),
                u.wire_payload_len != u.payload_len,
            ),
            _ => (None, false),
        };
        Some(((ip.src, ip.dst, ip.proto, l4), cut))
    }

    fn incomplete(frame: &[u8]) -> bool {
        etherparse::LaxSlicedPacket::from_ethernet(frame)
            .ok()
            .and_then(|sp| {
                sp.net
                    .and_then(|n| n.ip_payload_ref().map(|p| p.incomplete))
            })
            .unwrap_or(false)
    }

    fn base_frames() -> Vec<Vec<u8>> {
        use etherparse::{
            EtherType, Ethernet2Header, IpNumber, Ipv4Header, Ipv4Options, Ipv6FlowLabel,
            Ipv6Header, Ipv6RawExtHeader, PacketBuilder, UdpHeader,
        };
        let eth = |t: EtherType| Ethernet2Header {
            source: [0; 6],
            destination: [0; 6],
            ether_type: t,
        };
        // IPv4 with 4 bytes of options, carrying UDP.
        let mut opts = {
            let mut ip =
                Ipv4Header::new(8 + 20 + 4, 64, IpNumber::UDP, [10, 0, 0, 5], [10, 0, 0, 6])
                    .unwrap();
            ip.options = Ipv4Options::try_from(&[1u8, 1, 1, 0][..]).unwrap();
            ip.total_len = ip.header_len() as u16 + 8 + 20;
            let mut f = Vec::new();
            eth(EtherType::IPV4).write(&mut f).unwrap();
            ip.write(&mut f).unwrap();
            UdpHeader::without_ipv4_checksum(7, 9, 20)
                .unwrap()
                .write(&mut f)
                .unwrap();
            f
        };
        opts.extend_from_slice(&[3; 20]);
        // IPv6 with a hop-by-hop header, carrying UDP.
        let mut hbh = {
            let ext = Ipv6RawExtHeader::new_raw(IpNumber::UDP, &[0; 6]).unwrap();
            let ip = Ipv6Header {
                traffic_class: 0,
                flow_label: Ipv6FlowLabel::ZERO,
                payload_length: (ext.header_len() + 8 + 16) as u16,
                next_header: IpNumber::IPV6_HEADER_HOP_BY_HOP,
                hop_limit: 1,
                source: [1; 16],
                destination: [2; 16],
            };
            let mut f = Vec::new();
            eth(EtherType::IPV6).write(&mut f).unwrap();
            ip.write(&mut f).unwrap();
            ext.write(&mut f).unwrap();
            UdpHeader::without_ipv4_checksum(11, 12, 16)
                .unwrap()
                .write(&mut f)
                .unwrap();
            f
        };
        hbh.extend_from_slice(&[4; 16]);
        let icmp = {
            let mut f = Vec::new();
            PacketBuilder::ethernet2([0; 6], [0; 6])
                .ipv4([10, 0, 0, 7], [10, 0, 0, 8], 64)
                .icmpv4_echo_request(1, 2)
                .write(&mut f, &[5; 24])
                .unwrap();
            f
        };
        vec![
            tcp_frame(&[b'x'; 30]),
            ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 53, 5000, &[0x42; 40]),
            ipv6_tcp([1; 16], [2; 16], 1234, 443, 7, 0x10, &[b'y'; 25]),
            with_vlan_tags(
                &ipv4_udp([10, 0, 0, 3], [10, 0, 0, 4], 123, 123, &[1; 48]),
                &[(0x8100, 7)],
            ),
            with_vlan_tags(&tcp_frame(&[b'z'; 10]), &[(0x88a8, 1), (0x8100, 2)]),
            opts,
            hbh,
            icmp,
        ]
    }

    proptest::proptest! {
        #![proptest_config(proptest::prelude::ProptestConfig::with_cases(20_000))]

        /// On a frame the capture did not cut, the lax parse extracts
        /// exactly what 0.25's strict parse did — malformed packets
        /// (that receivers drop) stay skipped.
        #[test]
        fn lax_parse_matches_strict_on_complete_frames(
            base in 0usize..8,
            edits in proptest::collection::vec((0usize..80, proptest::prelude::any::<u8>()), 1..4),
            cut in proptest::prelude::any::<bool>(),
            keep in 30usize..120,
        ) {
            let mut f = base_frames().swap_remove(base);
            for (at, v) in edits {
                if at < f.len() {
                    f[at] = v;
                }
            }
            if cut {
                f.truncate(keep.min(f.len()));
            }
            if !incomplete(&f) {
                let lax = lax_summary(&f);
                proptest::prop_assert_eq!(lax.as_ref().map(|l| l.0), strict_summary(&f));
                proptest::prop_assert!(lax.is_none_or(|l| !l.1), "complete frame read as cut");
            }
        }
    }

    #[test]
    fn ethernet_padding_is_not_payload() {
        // A minimum-size frame: 2 UDP payload bytes, then padding.
        let mut f = ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 1, 2, b"hi");
        f.resize(60, 0);
        let parsed = parse_eth(&f).unwrap();
        assert_eq!(parsed.ip.as_ref().unwrap().l3_len, 30);
        let ParsedL4::Udp(u) = parsed.l4.unwrap() else {
            panic!("expected udp")
        };
        assert_eq!((u.payload_len, u.wire_payload_len), (2, 2));
    }

    #[test]
    fn udp_surplus_area_is_not_a_truncation() {
        // UDP length 38 (30-byte payload) inside a 48-byte IP payload:
        // 10 bytes after the datagram (UDP options / trailing data).
        let mut f = ipv4_udp([10, 0, 0, 1], [10, 0, 0, 2], 5353, 53, &[1; 40]);
        f[14 + 20 + 4..14 + 20 + 6].copy_from_slice(&38u16.to_be_bytes());
        let parsed = parse_eth(&f).unwrap();
        let ParsedL4::Udp(u) = parsed.l4.unwrap() else {
            panic!("expected udp")
        };
        assert_eq!((u.payload_len, u.wire_payload_len), (30, 30));
        // Cut: the UDP length field gives the datagram's wire size.
        f.truncate(14 + 20 + 8 + 5);
        let ParsedL4::Udp(u) = parse_eth(&f).unwrap().l4.unwrap() else {
            panic!("expected udp")
        };
        assert_eq!((u.payload_len, u.wire_payload_len), (5, 30));
    }

    #[test]
    fn lax_ipv6_tcp_reports_wire_payload_len() {
        let mut f = ipv6_tcp([1; 16], [2; 16], 1234, 443, 7, 0x10, &[b'y'; 500]);
        f.truncate(14 + 40 + 20 + 30);
        let parsed = parse_eth(&f).expect("a cut IPv6 segment is parsed");
        assert_eq!(parsed.ip.as_ref().unwrap().l3_len, 40 + 20 + 500);
        let ParsedL4::Tcp(t) = parsed.l4.unwrap() else {
            panic!("expected tcp")
        };
        assert_eq!((t.payload_len, t.wire_payload_len), (30, 500));
    }

    #[test]
    fn byte_offset_basic() {
        let outer = [0u8, 1, 2, 3, 4, 5];
        let inner = &outer[2..4];
        assert_eq!(byte_offset(&outer, inner), Some(2));
    }

    #[test]
    fn byte_offset_disjoint_returns_none() {
        let outer = [0u8; 4];
        let other = [0u8; 4];
        assert_eq!(byte_offset(&outer, &other[..]), None);
    }
}