protolens 0.2.1

TCP stream reassembly,application layer protocol parsing
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
#![allow(unused)]
use crate::Direction;
use crate::{L7Proto, Packet, TransProto};
use etherparse::*;
use pcap::Capture as PcapCap;
use pcap::Offline;
use std::cell::RefCell;
use std::fmt;
use std::net::IpAddr;
use std::ops::Deref;
use std::path::Path;
use std::rc::Rc;

pub(crate) const TEST_UTILS_SPORT: u16 = 5000;
pub(crate) const TEST_UTILS_DPORT: u16 = 4000;

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct MyPacket {
    pub sport: u16,
    pub dport: u16,
    pub sequence: u32,
    pub syn_flag: bool,
    pub fin_flag: bool,
    pub data: Vec<u8>,
}

impl MyPacket {
    pub(crate) fn new(seq: u32, fin: bool) -> Self {
        MyPacket {
            sport: 54321,
            dport: 8080,
            sequence: seq,
            syn_flag: false,
            fin_flag: fin,
            data: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        }
    }
}

impl Packet for MyPacket {
    fn trans_proto(&self) -> TransProto {
        TransProto::Tcp
    }

    fn sip(&self) -> IpAddr {
        IpAddr::V4(std::net::Ipv4Addr::new(1, 1, 1, 1))
    }

    fn dip(&self) -> IpAddr {
        IpAddr::V4(std::net::Ipv4Addr::new(2, 2, 2, 2))
    }

    fn tu_sport(&self) -> u16 {
        self.sport
    }

    fn tu_dport(&self) -> u16 {
        self.dport
    }

    fn seq(&self) -> u32 {
        self.sequence
    }

    fn syn(&self) -> bool {
        self.syn_flag
    }

    fn fin(&self) -> bool {
        self.fin_flag
    }

    fn payload_len(&self) -> usize {
        self.data.len()
    }

    fn payload(&self) -> &[u8] {
        &self.data
    }
}

impl Packet for Box<MyPacket> {
    fn trans_proto(&self) -> TransProto {
        (**self).trans_proto()
    }

    fn sip(&self) -> IpAddr {
        (**self).sip()
    }

    fn dip(&self) -> IpAddr {
        (**self).dip()
    }

    fn tu_sport(&self) -> u16 {
        (**self).tu_sport()
    }

    fn tu_dport(&self) -> u16 {
        (**self).tu_dport()
    }

    fn seq(&self) -> u32 {
        (**self).seq()
    }

    fn syn(&self) -> bool {
        (**self).syn()
    }

    fn fin(&self) -> bool {
        (**self).fin()
    }

    fn payload_len(&self) -> usize {
        (**self).payload_len()
    }

    fn payload(&self) -> &[u8] {
        (**self).payload()
    }
}

pub(crate) const MAX_PACKET_LEN: usize = 4096;

pub(crate) enum PacketError {
    DecodeErr,
}

#[derive(Eq, PartialEq, Clone)]
pub(crate) struct PktHeader {
    pub(crate) link: Option<Ethernet2Header>,
    pub(crate) vlan: Option<VlanHeader>,
    pub(crate) ip: Option<IpHeader>,
    pub(crate) transport: Option<TransportHeader>,
    pub(crate) payload_offset: usize,
    pub(crate) payload_len: usize,
    pub(crate) l7_proto: L7Proto,
    pub(crate) direction: Direction,
}

impl PktHeader {
    // 返回tcp或者udp的sport
    pub(crate) fn sport(&self) -> u16 {
        match &self.transport {
            Some(TransportHeader::Udp(udph)) => udph.source_port,
            Some(TransportHeader::Tcp(tcph)) => tcph.source_port,
            _ => 0,
        }
    }

    // 返回tcp或者udp的sport
    pub(crate) fn dport(&self) -> u16 {
        match &self.transport {
            Some(TransportHeader::Udp(udph)) => udph.destination_port,
            Some(TransportHeader::Tcp(tcph)) => tcph.destination_port,
            _ => 0,
        }
    }
}

#[derive(Clone)]
pub(crate) struct CapPacket {
    pub(crate) timestamp: u128,
    pub(crate) data: [u8; MAX_PACKET_LEN],
    pub(crate) data_len: usize,
    pub(crate) header: RefCell<Option<PktHeader>>,
}

impl CapPacket {
    pub(crate) fn new(ts: u128, len: usize, data: &[u8]) -> CapPacket {
        let mut pkt_data = [0; MAX_PACKET_LEN];
        pkt_data[..len].copy_from_slice(&data[..len]);

        CapPacket {
            timestamp: ts,
            data: pkt_data,
            data_len: len,
            header: RefCell::new(None),
        }
    }

    pub(crate) fn decode(&self) -> Result<(), PacketError> {
        match PacketHeaders::from_ethernet_slice(self) {
            Ok(headers) => {
                if headers.ip.is_none() || headers.transport.is_none() {
                    return Err(PacketError::DecodeErr);
                }

                let payload_offset =
                    headers.payload.as_ptr() as usize - self.data.as_ptr() as usize;
                let mut payload_len = 0;

                if let (Some(IpHeader::Version4(ipv4, _)), Some(transport)) =
                    (&headers.ip, &headers.transport)
                {
                    let ip_total_len = ipv4.total_len() as usize;
                    let ip_header_len = ipv4.ihl() as usize * 4;

                    match transport {
                        TransportHeader::Tcp(tcp_header) => {
                            let tcp_header_len = tcp_header.header_len() as usize;
                            payload_len = ip_total_len - ip_header_len - tcp_header_len;
                        }
                        TransportHeader::Udp(_) => {
                            payload_len = ip_total_len - ip_header_len - 8;
                        }
                        _ => {}
                    }
                }

                self.header.replace(Some(PktHeader {
                    link: headers.link,
                    vlan: headers.vlan,
                    ip: headers.ip,
                    transport: headers.transport,
                    payload_offset,
                    payload_len,
                    l7_proto: L7Proto::Unknown,
                    direction: Direction::C2s,
                }));
                Ok(())
            }
            Err(_) => Err(PacketError::DecodeErr),
        }
    }

    pub(crate) fn seq(&self) -> u32 {
        if let Some(TransportHeader::Tcp(tcph)) = &self.header.borrow().as_ref().unwrap().transport
        {
            tcph.sequence_number
        } else {
            0
        }
    }

    pub(crate) fn syn(&self) -> bool {
        if let Some(TransportHeader::Tcp(tcph)) = &self.header.borrow().as_ref().unwrap().transport
        {
            tcph.syn
        } else {
            false
        }
    }

    pub(crate) fn fin(&self) -> bool {
        if let Some(TransportHeader::Tcp(tcph)) = &self.header.borrow().as_ref().unwrap().transport
        {
            tcph.fin
        } else {
            false
        }
    }

    pub(crate) fn payload_len(&self) -> u32 {
        self.header
            .borrow()
            .as_ref()
            .unwrap()
            .payload_len
            .try_into()
            .unwrap()
    }
}

impl Deref for CapPacket {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl fmt::Debug for CapPacket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ip: {:?}, Packet: ts: {}, caplen: {}, data: {:?}",
            self.header.borrow().as_ref().unwrap().ip,
            self.timestamp,
            self.data_len,
            self.data
        )
    }
}

impl Packet for CapPacket {
    fn trans_proto(&self) -> TransProto {
        if let Some(TransportHeader::Tcp(_tcph)) = &self.header.borrow().as_ref().unwrap().transport
        {
            TransProto::Tcp
        } else {
            TransProto::Udp
        }
    }

    fn sip(&self) -> std::net::IpAddr {
        match &self.header.borrow().as_ref().unwrap().ip {
            Some(IpHeader::Version4(ipv4h, _)) => IpAddr::from(ipv4h.source),
            Some(IpHeader::Version6(ipv6h, _)) => IpAddr::from(ipv6h.source),
            None => IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
        }
    }

    fn dip(&self) -> std::net::IpAddr {
        match &self.header.borrow().as_ref().unwrap().ip {
            Some(IpHeader::Version4(ipv4h, _)) => IpAddr::from(ipv4h.destination),
            Some(IpHeader::Version6(ipv6h, _)) => IpAddr::from(ipv6h.destination),
            None => IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
        }
    }

    fn tu_sport(&self) -> u16 {
        self.header.borrow().as_ref().unwrap().sport()
    }

    fn tu_dport(&self) -> u16 {
        self.header.borrow().as_ref().unwrap().dport()
    }

    fn seq(&self) -> u32 {
        self.seq()
    }

    fn syn(&self) -> bool {
        self.syn()
    }

    fn fin(&self) -> bool {
        self.fin()
    }

    fn payload_len(&self) -> usize {
        self.payload_len() as usize
    }

    fn payload(&self) -> &[u8] {
        let header = self.header.borrow();
        let offset = header.as_ref().unwrap().payload_offset;
        let len = header.as_ref().unwrap().payload_len;
        &self.data[offset..offset + len]
    }
}

impl Ord for CapPacket {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.seq().cmp(&other.seq())
    }
}

impl PartialOrd for CapPacket {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for CapPacket {}

impl PartialEq for CapPacket {
    fn eq(&self, other: &Self) -> bool {
        self.seq() == other.seq()
    }
}

impl Packet for Box<CapPacket> {
    fn trans_proto(&self) -> TransProto {
        (**self).trans_proto()
    }

    fn sip(&self) -> IpAddr {
        (**self).sip()
    }

    fn dip(&self) -> IpAddr {
        (**self).dip()
    }

    fn tu_sport(&self) -> u16 {
        (**self).tu_sport()
    }

    fn tu_dport(&self) -> u16 {
        (**self).tu_dport()
    }

    fn seq(&self) -> u32 {
        (**self).seq()
    }

    fn syn(&self) -> bool {
        (**self).syn()
    }

    fn fin(&self) -> bool {
        (**self).fin()
    }

    fn payload_len(&self) -> usize {
        (**self).payload_len() as usize
    }

    fn payload(&self) -> &[u8] {
        (**self).payload()
    }
}

#[derive(Debug)]
pub(crate) enum CaptureError {}

pub(crate) struct Capture {
    cap: PcapCap<Offline>,
    pkt_num: u64,
}

impl Capture {
    pub(crate) fn init<P: AsRef<Path>>(path: P) -> Result<Capture, CaptureError> {
        let capture = Capture {
            cap: PcapCap::from_file(path).unwrap(),
            pkt_num: 0,
        };
        Ok(capture)
    }

    pub(crate) fn next_packet(&mut self, timestamp: u128) -> Option<CapPacket> {
        self.pkt_num += 1;
        match self.cap.next_packet() {
            Ok(pcap_pkt) => {
                if pcap_pkt.header.caplen > MAX_PACKET_LEN.try_into().unwrap() {
                    return None;
                }

                Some(CapPacket::new(
                    timestamp,
                    pcap_pkt.header.caplen.try_into().unwrap(),
                    pcap_pkt.data,
                ))
            }
            Err(_) => None,
        }
    }
}

pub(crate) fn build_pkt_nodata(seq: u32, fin: bool) -> CapPacket {
    //setup the packet headers
    let mut builder = PacketBuilder::ethernet2(
        [1, 2, 3, 4, 5, 6], //source mac
        [7, 8, 9, 10, 11, 12],
    ) //destionation mac
    .ipv4(
        [192, 168, 1, 1], //source ip
        [192, 168, 1, 2], //desitionation ip
        20,
    ) //time to life
    .tcp(
        TEST_UTILS_SPORT, //source port
        TEST_UTILS_DPORT, //desitnation port
        seq,              //sequence number
        1024,
    ) //window size
    //set additional tcp header fields
    .ns() //set the ns flag
    //supported flags: ns(), fin(), syn(), rst(), psh(), ece(), cwr()
    .ack(123) //ack flag + the ack number
    .urg(23) //urg flag + urgent pointer
    .options(&[
        TcpOptionElement::Noop,
        TcpOptionElement::MaximumSegmentSize(1234),
    ])
    .unwrap();
    if fin {
        builder = builder.fin();
    }

    //payload of the tcp packet
    let payload = [];
    //get some memory to store the result
    let mut result = Vec::<u8>::with_capacity(builder.size(payload.len()));
    //serialize
    //this will automatically set all length fields, checksums and identifiers (ethertype & protocol)
    builder.write(&mut result, &payload).unwrap();
    // println!("result len:{}", result.len());

    CapPacket::new(1, result.len(), &result)
}

// 独立的ack包,没有载荷
pub(crate) fn build_pkt_ack(seq: u32, ack_seq: u32) -> CapPacket {
    //setup the packet headers
    let builder = PacketBuilder::ethernet2(
        [1, 2, 3, 4, 5, 6], //source mac
        [7, 8, 9, 10, 11, 12],
    ) //destionation mac
    .ipv4(
        [192, 168, 1, 1], //source ip
        [192, 168, 1, 2], //desitionation ip
        20,
    ) //time to life
    .tcp(
        TEST_UTILS_SPORT, //source port
        TEST_UTILS_DPORT, //desitnation port
        seq,              //sequence number
        1024,
    ) //window size
    //set additional tcp header fields
    .ns() //set the ns flag
    //supported flags: ns(), fin(), syn(), rst(), psh(), ece(), cwr()
    .ack(ack_seq) //ack flag + the ack number
    .urg(23) //urg flag + urgent pointer
    .options(&[
        TcpOptionElement::Noop,
        TcpOptionElement::MaximumSegmentSize(1234),
    ])
    .unwrap();

    //payload of the tcp packet
    let payload = [];
    //get some memory to store the result
    let mut result = Vec::<u8>::with_capacity(builder.size(payload.len()));
    //serialize
    //this will automatically set all length fields, checksums and identifiers (ethertype & protocol)
    builder.write(&mut result, &payload).unwrap();
    // println!("result len:{}", result.len());

    CapPacket::new(1, result.len(), &result)
}

// 独立的syn包,没有载荷
pub(crate) fn build_pkt_syn(seq: u32) -> CapPacket {
    //setup the packet headers
    let builder = PacketBuilder::ethernet2(
        [1, 2, 3, 4, 5, 6], //source mac
        [7, 8, 9, 10, 11, 12],
    ) //destionation mac
    .ipv4(
        [192, 168, 1, 1], //source ip
        [192, 168, 1, 2], //desitionation ip
        20,
    ) //time to life
    .tcp(
        TEST_UTILS_SPORT, //source port
        TEST_UTILS_DPORT, //desitnation port
        seq,              //sequence number
        1024,
    ) //window size
    //set additional tcp header fields
    .ns() //set the ns flag
    //supported flags: ns(), fin(), syn(), rst(), psh(), ece(), cwr()
    .syn()
    .urg(23) //urg flag + urgent pointer
    .options(&[
        TcpOptionElement::Noop,
        TcpOptionElement::MaximumSegmentSize(1234),
    ])
    .unwrap();

    //payload of the tcp packet
    let payload = [];
    //get some memory to store the result
    let mut result = Vec::<u8>::with_capacity(builder.size(payload.len()));
    //serialize
    //this will automatically set all length fields, checksums and identifiers (ethertype & protocol)
    builder.write(&mut result, &payload).unwrap();
    // println!("result len:{}", result.len());

    CapPacket::new(1, result.len(), &result)
}

// 带载荷,可以带fin
pub(crate) fn build_pkt(seq: u32, fin: bool) -> CapPacket {
    //setup the packet headers
    let mut builder = PacketBuilder::ethernet2(
        [1, 2, 3, 4, 5, 6], //source mac
        [7, 8, 9, 10, 11, 12],
    ) //destionation mac
    .ipv4(
        [192, 168, 1, 1], //source ip
        [192, 168, 1, 2], //desitionation ip
        20,
    ) //time to life
    .tcp(
        TEST_UTILS_SPORT, //source port
        TEST_UTILS_DPORT, //desitnation port
        seq,              //sequence number
        1024,
    ) //window size
    //set additional tcp header fields
    .ns() //set the ns flag
    //supported flags: ns(), fin(), syn(), rst(), psh(), ece(), cwr()
    .ack(123) //ack flag + the ack number
    .urg(23) //urg flag + urgent pointer
    .options(&[
        TcpOptionElement::Noop,
        TcpOptionElement::MaximumSegmentSize(1234),
    ])
    .unwrap();
    if fin {
        builder = builder.fin();
    }

    //payload of the tcp packet
    let payload = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    //get some memory to store the result
    let mut result = Vec::<u8>::with_capacity(builder.size(payload.len()));
    //serialize
    //this will automatically set all length fields, checksums and identifiers (ethertype & protocol)
    builder.write(&mut result, &payload).unwrap();
    // println!("result len:{}", result.len());

    CapPacket::new(1, result.len(), &result)
}

// 独立的fin包,没有载荷
pub(crate) fn build_pkt_fin(seq: u32) -> CapPacket {
    build_pkt_nodata(seq, true)
}

pub(crate) fn make_pkt_data(seq: u32) -> CapPacket {
    build_pkt(seq, false)
}

// 接受任意长度的payload数组
fn build_pkt_payload_inner(
    seq: u32,
    payload: &[u8],
    sport: u16,
    dport: u16,
    fin: bool,
) -> CapPacket {
    //setup the packet headers
    let mut builder = PacketBuilder::ethernet2(
        [1, 2, 3, 4, 5, 6],    //source mac
        [7, 8, 9, 10, 11, 12], //destionation mac
    )
    .ipv4(
        [192, 168, 1, 1], //source ip
        [192, 168, 1, 2], //desitionation ip
        20,               //time to life
    )
    .tcp(
        sport, //source port
        dport, //desitnation port
        seq,   //sequence number
        1024,  //window size
    )
    //set additional tcp header fields
    .ns() //set the ns flag
    //supported flags: ns(), fin(), syn(), rst(), psh(), ece(), cwr()
    .ack(123) //ack flag + the ack number
    .urg(23) //urg flag + urgent pointer
    .options(&[
        TcpOptionElement::Noop,
        TcpOptionElement::MaximumSegmentSize(1234),
    ])
    .unwrap();
    if fin {
        builder = builder.fin();
    }

    //get some memory to store the result
    let mut result = Vec::<u8>::with_capacity(builder.size(payload.len()));
    //serialize
    //this will automatically set all length fields, checksums and identifiers (ethertype & protocol)
    builder.write(&mut result, payload).unwrap();

    CapPacket::new(1, result.len(), &result)
}

// 接受任意长度的payload数组
pub(crate) fn build_pkt_payload(seq: u32, payload: &[u8]) -> CapPacket {
    build_pkt_payload_inner(seq, payload, TEST_UTILS_SPORT, TEST_UTILS_DPORT, false)
}

pub(crate) fn build_pkt_payload_fin(seq: u32, payload: &[u8]) -> CapPacket {
    build_pkt_payload_inner(seq, payload, TEST_UTILS_SPORT, TEST_UTILS_DPORT, true)
}

pub(crate) fn build_pkt_payload2(
    seq: u32,
    payload: &[u8],
    sport: u16,
    dport: u16,
    fin: bool,
) -> CapPacket {
    build_pkt_payload_inner(seq, payload, sport, dport, fin)
}

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

    #[test]
    fn test_build_pkt() {
        let seq1 = 1;
        let pkt1 = build_pkt(seq1, true);
        let _ = pkt1.decode();

        // 使用完全限定路径调用 trait 方法
        assert_eq!(1, crate::Packet::seq(&pkt1));
        // 验证 fin 标志 (通过 trait 方法)
        assert!(crate::Packet::fin(&pkt1));
        // 验证端口 (通过 trait 方法)
        assert_eq!(TEST_UTILS_SPORT, crate::Packet::tu_sport(&pkt1));
        assert_eq!(TEST_UTILS_DPORT, crate::Packet::tu_dport(&pkt1));

        // 验证 IP (通过 header 获取)
        if let Some(IpHeader::Version4(ipv4, _)) = &pkt1.header.borrow().as_ref().unwrap().ip {
            assert_eq!([192, 168, 1, 1], ipv4.source);
            assert_eq!([192, 168, 1, 2], ipv4.destination);
        }

        // 验证 payload (通过 trait 方法)
        let expected_payload = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        assert_eq!(expected_payload.len(), crate::Packet::payload_len(&pkt1));
        assert_eq!(&expected_payload, crate::Packet::payload(&pkt1));
    }

    #[test]
    fn test_build_pkt_nodata() {
        let seq1 = 1;
        let pkt1 = build_pkt_nodata(seq1, true);
        let _ = pkt1.decode();

        // 验证序列号 (通过 trait 方法)
        assert_eq!(1, crate::Packet::seq(&pkt1));
        // 验证 fin 标志 (通过 trait 方法)
        assert!(crate::Packet::fin(&pkt1));
        // 验证端口 (通过 trait 方法)
        assert_eq!(TEST_UTILS_SPORT, crate::Packet::tu_sport(&pkt1));
        assert_eq!(TEST_UTILS_DPORT, crate::Packet::tu_dport(&pkt1));
        // 验证 IP (通过 header 获取)
        if let Some(IpHeader::Version4(ipv4, _)) = &pkt1.header.borrow().as_ref().unwrap().ip {
            assert_eq!([192, 168, 1, 1], ipv4.source);
            assert_eq!([192, 168, 1, 2], ipv4.destination);
        }
        // 验证 payload 为空 (通过 trait 方法)
        assert_eq!(0, crate::Packet::payload_len(&pkt1));
        assert!(crate::Packet::payload(&pkt1).is_empty());
    }

    #[test]
    fn test_build_pkt_ack() {
        let seq1 = 1;
        let ack_seq = 100;
        let pkt1 = build_pkt_ack(seq1, ack_seq);
        let _ = pkt1.decode();

        // 验证序列号 (通过 trait 方法)
        assert_eq!(1, crate::Packet::seq(&pkt1));
        // 验证端口 (通过 trait 方法)
        assert_eq!(TEST_UTILS_SPORT, crate::Packet::tu_sport(&pkt1));
        assert_eq!(TEST_UTILS_DPORT, crate::Packet::tu_dport(&pkt1));
        // 先获取 header 的引用
        let header = pkt1.header.borrow();
        let header_ref = header.as_ref().unwrap();
        // 验证 IP
        if let Some(IpHeader::Version4(ipv4, _)) = &header_ref.ip {
            assert_eq!([192, 168, 1, 1], ipv4.source);
            assert_eq!([192, 168, 1, 2], ipv4.destination);
        }
        // 验证 payload
        assert_eq!(0, crate::Packet::payload_len(&pkt1));
        assert!(crate::Packet::payload(&pkt1).is_empty());
        assert!(!crate::Packet::fin(&pkt1));
        // 验证 ack
        if let Some(TransportHeader::Tcp(tcp)) = &header_ref.transport {
            assert_eq!(ack_seq, tcp.acknowledgment_number);
            assert!(tcp.ack);
        }
    }

    #[test]
    fn test_build_pkt_syn() {
        let seq1 = 1;
        let pkt1 = build_pkt_syn(seq1);
        let _ = pkt1.decode();

        // 验证序列号 (通过 trait 方法)
        assert_eq!(1, crate::Packet::seq(&pkt1));
        // 验证端口 (通过 trait 方法)
        assert_eq!(TEST_UTILS_SPORT, crate::Packet::tu_sport(&pkt1));
        assert_eq!(TEST_UTILS_DPORT, crate::Packet::tu_dport(&pkt1));
        // 先获取 header 的引用
        let header = pkt1.header.borrow();
        let header_ref = header.as_ref().unwrap();
        // 验证 IP
        if let Some(IpHeader::Version4(ipv4, _)) = &header_ref.ip {
            assert_eq!([192, 168, 1, 1], ipv4.source);
            assert_eq!([192, 168, 1, 2], ipv4.destination);
        }
        // 验证 payload
        assert_eq!(0, crate::Packet::payload_len(&pkt1));
        assert!(crate::Packet::payload(&pkt1).is_empty());
        // 验证 SYN 标志
        assert!(crate::Packet::syn(&pkt1));
        assert!(!crate::Packet::fin(&pkt1));
        // 验证 TCP 标志
        if let Some(TransportHeader::Tcp(tcp)) = &header_ref.transport {
            assert!(tcp.syn);
            assert!(!tcp.ack);
        }
    }

    #[test]
    fn test_build_pkt_payload() {
        // 测试用例1:使用标准长度的payload
        let seq1 = 1;
        let custom_payload = vec![10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
        let pkt1 = build_pkt_payload(seq1, &custom_payload);
        let _ = pkt1.decode();

        // 验证序列号 (通过 trait 方法)
        assert_eq!(1, crate::Packet::seq(&pkt1));
        // 验证端口 (通过 trait 方法)
        assert_eq!(TEST_UTILS_SPORT, crate::Packet::tu_sport(&pkt1));
        assert_eq!(TEST_UTILS_DPORT, crate::Packet::tu_dport(&pkt1));
        // 先获取 header 的引用
        let header = pkt1.header.borrow();
        let header_ref = header.as_ref().unwrap();
        // 验证 IP
        if let Some(IpHeader::Version4(ipv4, _)) = &header_ref.ip {
            assert_eq!([192, 168, 1, 1], ipv4.source);
            assert_eq!([192, 168, 1, 2], ipv4.destination);
        }
        // 验证 payload
        assert_eq!(custom_payload.len(), crate::Packet::payload_len(&pkt1));
        assert_eq!(&custom_payload, crate::Packet::payload(&pkt1));
        // 验证标志位
        assert!(!crate::Packet::syn(&pkt1));
        assert!(!crate::Packet::fin(&pkt1));
        // 验证 TCP 标志
        if let Some(TransportHeader::Tcp(tcp)) = &header_ref.transport {
            assert!(!tcp.syn);
            assert!(tcp.ack); // 这个包应该有 ACK 标志
        }

        // 测试用例2:使用空payload
        let seq2 = 2;
        let empty_payload: Vec<u8> = vec![];
        let pkt2 = build_pkt_payload(seq2, &empty_payload);
        let _ = pkt2.decode();

        // 验证序列号
        assert_eq!(2, crate::Packet::seq(&pkt2));
        // 验证payload为空
        assert_eq!(0, crate::Packet::payload_len(&pkt2));
        assert!(crate::Packet::payload(&pkt2).is_empty());

        // 测试用例3:使用大型payload
        let seq3 = 3;
        let large_payload: Vec<u8> = (0..1000).map(|i| (i % 256) as u8).collect();
        let pkt3 = build_pkt_payload(seq3, &large_payload);
        let _ = pkt3.decode();

        // 验证序列号
        assert_eq!(3, crate::Packet::seq(&pkt3));
        // 验证payload大小
        assert_eq!(1000, crate::Packet::payload_len(&pkt3));
        assert_eq!(&large_payload, crate::Packet::payload(&pkt3));

        // 测试用例4:使用不同的序列号
        let seq4 = 12345;
        let custom_payload4 = vec![1, 3, 5, 7, 9];
        let pkt4 = build_pkt_payload(seq4, &custom_payload4);
        let _ = pkt4.decode();

        // 验证序列号
        assert_eq!(12345, crate::Packet::seq(&pkt4));
        // 验证payload
        assert_eq!(custom_payload4.len(), crate::Packet::payload_len(&pkt4));
        assert_eq!(&custom_payload4, crate::Packet::payload(&pkt4));
    }

    #[test]
    fn test_build_pkt_line() {
        let seq1 = 1;
        let custom_payload = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
        let pkt1 = build_pkt_payload(seq1, &custom_payload);
        let _ = pkt1.decode();

        // 验证序列号 (通过 trait 方法)
        assert_eq!(1, crate::Packet::seq(&pkt1));
        // 验证端口 (通过 trait 方法)
        assert_eq!(TEST_UTILS_SPORT, crate::Packet::tu_sport(&pkt1));
        assert_eq!(TEST_UTILS_DPORT, crate::Packet::tu_dport(&pkt1));
        // 先获取 header 的引用
        let header = pkt1.header.borrow();
        let header_ref = header.as_ref().unwrap();
        // 验证 IP
        if let Some(IpHeader::Version4(ipv4, _)) = &header_ref.ip {
            assert_eq!([192, 168, 1, 1], ipv4.source);
            assert_eq!([192, 168, 1, 2], ipv4.destination);
        }
        // 验证 payload
        assert_eq!(custom_payload.len(), crate::Packet::payload_len(&pkt1));
        assert_eq!(&custom_payload, crate::Packet::payload(&pkt1));
        // 验证标志位
        assert!(!crate::Packet::syn(&pkt1));
        assert!(!crate::Packet::fin(&pkt1));
        // 验证 TCP 标志
        if let Some(TransportHeader::Tcp(tcp)) = &header_ref.transport {
            assert!(!tcp.syn);
            assert!(tcp.ack); // 这个包应该有 ACK 标志
        }
    }
}