pistol 4.0.18

A Rust Library about Cybersecurity
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
use pcapture::pcapng::EnhancedPacketBlock;
use pcapture::pcapng::GeneralBlock;
use pnet::datalink;
use pnet::datalink::Channel::Ethernet;
use pnet::datalink::ChannelType;
use pnet::datalink::Config;
use pnet::datalink::MacAddr;
use pnet::datalink::NetworkInterface;
use pnet::datalink::interfaces;
use pnet::packet::Packet;
use pnet::packet::arp::ArpPacket;
use pnet::packet::ethernet::EtherType;
use pnet::packet::ethernet::EtherTypes;
use pnet::packet::ethernet::EthernetPacket;
use pnet::packet::ethernet::MutableEthernetPacket;
use pnet::packet::icmp::IcmpCode;
use pnet::packet::icmp::IcmpPacket;
use pnet::packet::icmp::IcmpType;
use pnet::packet::icmpv6::Icmpv6Code;
use pnet::packet::icmpv6::Icmpv6Packet;
use pnet::packet::icmpv6::Icmpv6Type;
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::ipv6::Ipv6Packet;
use pnet::packet::tcp::TcpPacket;
use pnet::packet::udp::UdpPacket;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::panic::Location;
use std::sync::mpsc::Receiver;
use std::sync::mpsc::channel;
use std::time::Duration;
use std::time::Instant;
use tracing::debug;
use tracing::error;
use tracing::warn;
use uuid::Uuid;

use crate::DEFAULT_TIMEOUT;
use crate::PISTOL_PCAPNG;
use crate::PISTOL_PCAPNG_FLAG;
use crate::PISTOL_RUNNER_IS_RUNNING;
use crate::PistolChannel;
use crate::UNIFIED_RECV_MATCHS;
use crate::error::PistolError;
use crate::route::RouteVia;
use crate::route::get_default_route;
use crate::route::search_route_table;

pub const ETHERNET_HEADER_SIZE: usize = 14;
pub const ARP_HEADER_SIZE: usize = 28;
pub const IPV4_HEADER_SIZE: usize = 20;
pub const IPV6_HEADER_SIZE: usize = 40;
pub const TCP_HEADER_SIZE: usize = 20;
pub const UDP_HEADER_SIZE: usize = 8;
pub const ICMP_HEADER_SIZE: usize = 8;
// big enough to store all data
pub const ETHERNET_BUFF_SIZE: usize = 4096;

pub const ICMPV6_NS_HEADER_SIZE: usize = 32;
pub const ICMPV6_RS_HEADER_SIZE: usize = 16;
// pub const ICMPV6_NA_HEADER_SIZE: usize = 32;
pub const ICMPV6_ER_HEADER_SIZE: usize = 8;
pub const ICMPV6_NI_HEADER_SIZE: usize = 32;

/// If the ICMP message is a Destination Unreachable,
/// Time Exceeded, Parameter Problem, or Source Quench,
/// the Internet header plus the first 64 bits of the original datagram's data are returned.
/// The remaining 32 bits of the ICMP message header are unused and must be zero.
/// --- From RFC 792 – Internet Control Message Protocol (ICMP) https://datatracker.ietf.org/doc/html/rfc792#page-6
fn get_icmp_payload(icmp_packet: &IcmpPacket) -> Vec<u8> {
    let icmp_type = icmp_packet.get_icmp_type();
    let icmp_payload = icmp_packet.payload().to_vec();
    if icmp_type == IcmpType(3) {
        // Destination Unreachable
        icmp_payload[4..].to_vec()
    } else if icmp_type == IcmpType(0) {
        // Source Quench - Deprecated
        icmp_payload[4..].to_vec()
    } else if icmp_type == IcmpType(11) {
        // Time Exceeded
        icmp_payload[4..].to_vec()
    } else {
        icmp_payload
    }
}

fn get_icmpv6_payload(icmpv6_packet: &Icmpv6Packet) -> Vec<u8> {
    let icmpv6_type = icmpv6_packet.get_icmpv6_type();
    let icmpv6_payload = icmpv6_packet.payload().to_vec();
    if icmpv6_type == Icmpv6Type(1) {
        // Destination Unreachable
        icmpv6_payload[4..].to_vec()
    } else if icmpv6_type == Icmpv6Type(3) {
        // Time Exceeded
        icmpv6_payload[4..].to_vec()
    } else if icmpv6_type == Icmpv6Type(4) {
        // Parameter Problem
        icmpv6_payload[4..].to_vec()
    } else if icmpv6_type == Icmpv6Type(128) || icmpv6_type == Icmpv6Type(129) {
        // Echo Request/Reply
        icmpv6_payload[4..].to_vec()
    } else {
        icmpv6_payload
    }
}

pub fn find_interface_by_index(if_index: u32) -> Option<NetworkInterface> {
    for interface in interfaces() {
        if if_index == interface.index {
            return Some(interface);
        }
    }
    None
}

/// Use source IP address to find local interface
pub fn find_interface_by_src(src_addr: IpAddr) -> Option<NetworkInterface> {
    for interface in interfaces() {
        for ip in &interface.ips {
            let i = ip.ip();
            if src_addr == i {
                return Some(interface);
            }
        }
    }
    None
}

/// When the target is a loopback address,
/// we need to update not only the value of src addr,
/// but also the value of dst addr.
#[derive(Debug, Clone, Copy)]
pub struct InferAddr {
    pub dst_addr: IpAddr,
    pub src_addr: IpAddr,
}

impl InferAddr {
    /// Returns: (dst_addr, src_addr)
    pub fn ipv4_addr(&self) -> Result<(Ipv4Addr, Ipv4Addr), PistolError> {
        if let IpAddr::V4(dst_ipv4) = self.dst_addr {
            if let IpAddr::V4(src_ipv4) = self.src_addr {
                return Ok((dst_ipv4, src_ipv4));
            }
        }
        Err(PistolError::CanNotFoundSourceAddress)
    }
    /// Returns: (dst_addr, src_addr)
    pub fn ipv6_addr(&self) -> Result<(Ipv6Addr, Ipv6Addr), PistolError> {
        if let IpAddr::V6(dst_ipv6) = self.dst_addr {
            if let IpAddr::V6(src_ipv6) = self.src_addr {
                return Ok((dst_ipv6, src_ipv6));
            }
        }
        Err(PistolError::CanNotFoundSourceAddress)
    }
}

/// The source address is inferred from the target address.
/// When the target address is a loopback address,
/// it is mapped to an internal private address
/// because the loopback address only works at the transport layer
/// and cannot send data frames.
pub fn infer_addr(
    dst_addr: IpAddr,
    src_addr: Option<IpAddr>,
) -> Result<Option<InferAddr>, PistolError> {
    if dst_addr.is_loopback() {
        for interface in interfaces() {
            if !interface.is_loopback() {
                for ipn in interface.ips {
                    match ipn.ip() {
                        IpAddr::V4(src_ipv4) => {
                            if dst_addr.is_ipv4() && src_ipv4.is_private() {
                                let ia = InferAddr {
                                    dst_addr: src_ipv4.into(),
                                    src_addr: src_ipv4.into(),
                                };
                                return Ok(Some(ia));
                            }
                        }
                        IpAddr::V6(src_ipv6) => {
                            if dst_addr.is_ipv6()
                                && (src_ipv6.is_unicast_link_local() || src_ipv6.is_unique_local())
                            {
                                let ia = InferAddr {
                                    dst_addr: src_ipv6.into(),
                                    src_addr: src_ipv6.into(),
                                };
                                return Ok(Some(ia));
                            }
                        }
                    }
                }
            }
        }
    } else {
        match src_addr {
            Some(src_addr) => {
                let ia = InferAddr { dst_addr, src_addr };
                return Ok(Some(ia));
            }
            None => match search_route_table(dst_addr)? {
                // Try to get the interface for sending through the system routing table,
                // and then get the IP on it through the interface.
                Some(route_info) => {
                    for ipn in route_info.dev.ips {
                        match ipn.ip() {
                            IpAddr::V4(src_ipv4) => {
                                if dst_addr.is_ipv4() && !src_ipv4.is_loopback() {
                                    let ia = InferAddr {
                                        dst_addr,
                                        src_addr: src_ipv4.into(),
                                    };
                                    return Ok(Some(ia));
                                }
                            }
                            IpAddr::V6(src_ipv6) => {
                                if dst_addr.is_ipv6() && !src_ipv6.is_loopback() {
                                    let ia = InferAddr {
                                        dst_addr,
                                        src_addr: src_ipv6.into(),
                                    };
                                    return Ok(Some(ia));
                                }
                            }
                        }
                    }
                }
                None => {
                    // When the above methods do not work,
                    // try to find an IP address in the same subnet as the target address
                    // in the local interface as the source address.
                    for interface in interfaces() {
                        for ipn in interface.ips {
                            if ipn.contains(dst_addr) {
                                let src_addr = ipn.ip();
                                let ia = InferAddr { dst_addr, src_addr };
                                return Ok(Some(ia));
                            }
                        }
                    }
                    // Finally, if we really can't find the source address,
                    // transform it to the address in the same network segment as the default route.
                    let (default_route, default_route6) = get_default_route()?;
                    let dr = if dst_addr.is_ipv4() {
                        if let Some(dr_ipv4) = default_route {
                            dr_ipv4
                        } else {
                            return Err(PistolError::CanNotFoundRouterAddress);
                        }
                    } else {
                        if let Some(dr_ipv6) = default_route6 {
                            dr_ipv6
                        } else {
                            return Err(PistolError::CanNotFoundRouterAddress);
                        }
                    };
                    for interface in interfaces() {
                        for ipn in interface.ips {
                            if ipn.contains(dr.via) {
                                let src_addr = ipn.ip();
                                let ia = InferAddr { dst_addr, src_addr };
                                return Ok(Some(ia));
                            }
                        }
                    }
                }
            },
        }
    }
    Ok(None)
}

#[derive(Debug, Clone, Copy)]
pub struct Layer2Match {
    pub name: &'static str,
    pub src_mac: Option<MacAddr>,         // response packet src mac
    pub dst_mac: Option<MacAddr>,         // response packet dst mac
    pub ethernet_type: Option<EtherType>, // reponse packet ethernet type
}

impl Layer2Match {
    pub fn do_match(&self, ethernet_packet: &[u8]) -> bool {
        let ethernet_packet = match EthernetPacket::new(&ethernet_packet) {
            Some(ethernet_packet) => ethernet_packet,
            None => return false,
        };
        match self.src_mac {
            Some(src_mac) => {
                if ethernet_packet.get_source() != src_mac {
                    return false; // early stop
                }
            }
            None => (), // wild match
        };

        match self.dst_mac {
            Some(dst_mac) => {
                if ethernet_packet.get_destination() != dst_mac {
                    return false;
                }
            }
            None => (),
        };
        match self.ethernet_type {
            Some(ethernet_type) => {
                if ethernet_type != ethernet_packet.get_ethertype() {
                    return false;
                }
            }
            None => (),
        };
        true
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Layer3Match {
    pub name: &'static str,
    pub layer2: Option<Layer2Match>,
    pub src_addr: Option<IpAddr>, // response packet
    pub dst_addr: Option<IpAddr>, // response packet
}

impl Layer3Match {
    pub fn do_match(&self, ethernet_packet: &[u8]) -> bool {
        let m1 = match &self.layer2 {
            Some(layers) => layers.do_match(ethernet_packet),
            None => true,
        };
        if !m1 {
            // early stop
            return false;
        }
        let ethernet_packet = match EthernetPacket::new(&ethernet_packet) {
            Some(ethernet_packet) => ethernet_packet,
            None => return false,
        };
        match ethernet_packet.get_ethertype() {
            EtherTypes::Ipv4 => {
                let ipv4_packet = match Ipv4Packet::new(ethernet_packet.payload()) {
                    Some(i) => i,
                    None => return false,
                };
                match self.src_addr {
                    Some(src_addr) => match src_addr {
                        IpAddr::V4(src_ipv4) => {
                            if ipv4_packet.get_source() != src_ipv4 {
                                return false;
                            }
                        }
                        _ => return false,
                    },
                    None => (),
                }
                match self.dst_addr {
                    Some(dst_addr) => match dst_addr {
                        IpAddr::V4(dst_ipv4) => {
                            if ipv4_packet.get_destination() != dst_ipv4 {
                                return false;
                            }
                        }
                        _ => return false,
                    },
                    None => (),
                }
                true
            }
            EtherTypes::Ipv6 => {
                let ipv6_packet = match Ipv6Packet::new(ethernet_packet.payload()) {
                    Some(i) => i,
                    None => return false,
                };
                match self.src_addr {
                    Some(src_addr) => match src_addr {
                        IpAddr::V6(src_ipv6) => {
                            if ipv6_packet.get_source() != src_ipv6 {
                                return false;
                            }
                        }
                        _ => return false,
                    },
                    None => (),
                }
                match self.dst_addr {
                    Some(dst_addr) => match dst_addr {
                        IpAddr::V6(dst_ipv6) => {
                            if ipv6_packet.get_destination() != dst_ipv6 {
                                return false;
                            }
                        }
                        _ => return false,
                    },
                    None => (),
                }
                true
            }
            EtherTypes::Arp => {
                // ARP is on layer 2.5, but here we consider it as layer 3.
                let arp_packet = match ArpPacket::new(ethernet_packet.payload()) {
                    Some(a) => a,
                    None => return false,
                };
                match self.src_addr {
                    Some(src_addr) => match src_addr {
                        IpAddr::V4(src_ipv4) => {
                            if arp_packet.get_sender_proto_addr() != src_ipv4 {
                                return false;
                            }
                        }
                        _ => return false,
                    },
                    None => (),
                }
                match self.dst_addr {
                    Some(dst_addr) => match dst_addr {
                        IpAddr::V4(dst_ipv4) => {
                            if arp_packet.get_target_proto_addr() != dst_ipv4 {
                                return false;
                            }
                        }
                        _ => return false,
                    },
                    None => (),
                };
                true
            }
            _ => false,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Layer4MatchTcpUdp {
    pub name: &'static str,
    pub layer3: Option<Layer3Match>,
    pub src_port: Option<u16>, // response tcp or udp packet src port
    pub dst_port: Option<u16>, // response tcp or udp packet dst port
}

/// for debug use, return (src_ip, dst_ip)
#[allow(dead_code)]
fn get_ip(ethernet_packet: &[u8]) -> Option<(IpAddr, IpAddr)> {
    let ethernet_packet = match EthernetPacket::new(&ethernet_packet) {
        Some(ethernet_packet) => ethernet_packet,
        None => return None,
    };

    match ethernet_packet.get_ethertype() {
        EtherTypes::Ipv4 => {
            let ipv4_packet = match Ipv4Packet::new(ethernet_packet.payload()) {
                Some(i) => i,
                None => return None,
            };
            Some((
                ipv4_packet.get_source().into(),
                ipv4_packet.get_destination().into(),
            ))
        }
        EtherTypes::Ipv6 => {
            let ipv6_packet = match Ipv6Packet::new(ethernet_packet.payload()) {
                Some(i) => i,
                None => return None,
            };
            Some((
                ipv6_packet.get_source().into(),
                ipv6_packet.get_destination().into(),
            ))
        }
        _ => None,
    }
}

impl Layer4MatchTcpUdp {
    pub fn do_match(&self, ethernet_packet: &[u8]) -> bool {
        // let mut is_debug = false;
        // if let Some((src_ip, dst_ip)) = get_ip(ethernet_packet) {
        //     let src_ipv4 = Ipv4Addr::new(192, 168, 1, 3);
        //     let dst_ipv4 = Ipv4Addr::new(192, 168, 5, 3);
        //     if src_ip == src_ipv4 && dst_ip == dst_ipv4 {
        //         is_debug = true;
        //     }
        // }

        let m1 = match &self.layer3 {
            Some(layer3) => layer3.do_match(ethernet_packet),
            None => true,
        };
        // if is_debug {
        //     println!("m1: {}", m1);
        // }
        if !m1 {
            // early stop
            return false;
        }
        let ethernet_packet = match EthernetPacket::new(&ethernet_packet) {
            Some(ethernet_packet) => ethernet_packet,
            None => return false,
        };
        let (r_src_port, r_dst_port) = match ethernet_packet.get_ethertype() {
            EtherTypes::Ipv4 => {
                let ipv4_packet = match Ipv4Packet::new(ethernet_packet.payload()) {
                    Some(i) => i,
                    None => return false,
                };
                match ipv4_packet.get_next_level_protocol() {
                    IpNextHeaderProtocols::Tcp => {
                        let tcp_packet = match TcpPacket::new(ipv4_packet.payload()) {
                            Some(t) => t,
                            None => return false,
                        };
                        (tcp_packet.get_source(), tcp_packet.get_destination())
                    }
                    IpNextHeaderProtocols::Udp => {
                        let udp_packet = match UdpPacket::new(ipv4_packet.payload()) {
                            Some(t) => t,
                            None => return false,
                        };
                        (udp_packet.get_source(), udp_packet.get_destination())
                    }
                    _ => (0, 0),
                }
            }
            EtherTypes::Ipv6 => {
                let ipv6_packet = match Ipv6Packet::new(ethernet_packet.payload()) {
                    Some(i) => i,
                    None => return false,
                };
                match ipv6_packet.get_next_header() {
                    IpNextHeaderProtocols::Tcp => {
                        let tcp_packet = match TcpPacket::new(ipv6_packet.payload()) {
                            Some(t) => t,
                            None => return false,
                        };
                        (tcp_packet.get_source(), tcp_packet.get_destination())
                    }
                    IpNextHeaderProtocols::Udp => {
                        let udp_packet = match UdpPacket::new(ipv6_packet.payload()) {
                            Some(t) => t,
                            None => return false,
                        };
                        (udp_packet.get_source(), udp_packet.get_destination())
                    }
                    _ => (0, 0),
                }
            }
            _ => (0, 0),
        };
        // if is_debug {
        //     println!("read to match src port");
        // }
        match self.src_port {
            Some(src_port) => {
                if src_port != r_src_port {
                    return false;
                }
            }
            None => (),
        };
        // if is_debug {
        //     println!("src port pass");
        //     println!(
        //         "next dst_port: {:?}, r_dst_port: {}",
        //         self.dst_port, r_dst_port
        //     );
        // }
        match self.dst_port {
            Some(dst_port) => {
                if dst_port != r_dst_port {
                    return false;
                }
            }
            None => (),
        };
        // if is_debug {
        //     println!("dst port pass");
        // }
        true
    }
}

/// Matches network layer data in icmp payload
#[derive(Debug, Clone, Copy)]
pub struct PayloadMatchIp {
    pub src_addr: Option<IpAddr>, // response packet
    pub dst_addr: Option<IpAddr>, // response packet
}

impl PayloadMatchIp {
    /// When the icmp payload contains ipv4 data
    pub fn do_match_ipv4(&self, icmp_payload: &[u8]) -> bool {
        let ipv4_packet = match Ipv4Packet::new(icmp_payload) {
            Some(i) => i,
            None => return false,
        };
        match self.src_addr {
            Some(src_addr) => match src_addr {
                IpAddr::V4(src_ipv4) => {
                    if ipv4_packet.get_source() != src_ipv4 {
                        return false;
                    }
                }
                _ => return false,
            },
            None => (),
        }
        match self.dst_addr {
            Some(dst_addr) => match dst_addr {
                IpAddr::V4(dst_ipv4) => {
                    if ipv4_packet.get_destination() != dst_ipv4 {
                        return false;
                    }
                }
                _ => return false,
            },
            None => (),
        }
        true
    }
    /// When the icmp payload contains ipv6 data, and generally, icmpv6 is used at this time
    pub fn do_match_ipv6(&self, icmpv6_payload: &[u8]) -> bool {
        let ipv6_packet = match Ipv6Packet::new(icmpv6_payload) {
            Some(i) => i,
            None => return false,
        };
        match self.src_addr {
            Some(src_addr) => match src_addr {
                IpAddr::V6(src_ipv6) => {
                    if ipv6_packet.get_source() != src_ipv6 {
                        return false;
                    }
                }
                _ => return false,
            },
            None => (),
        };
        match self.dst_addr {
            Some(dst_addr) => match dst_addr {
                IpAddr::V6(dst_ipv6) => {
                    if ipv6_packet.get_destination() != dst_ipv6 {
                        return false;
                    }
                }
                _ => return false,
            },
            None => (),
        }
        true
    }
}

/// Matches the transport layer data in icmp payload
#[derive(Debug, Clone, Copy)]
pub struct PayloadMatchTcpUdp {
    pub layer3: Option<PayloadMatchIp>,
    pub src_port: Option<u16>, // response tcp or udp packet src port
    pub dst_port: Option<u16>, // response tcp or udp packet dst port
}

impl PayloadMatchTcpUdp {
    pub fn do_match_ipv4(&self, icmp_payload: &[u8]) -> bool {
        let m1 = match self.layer3 {
            Some(layer3) => layer3.do_match_ipv4(icmp_payload),
            None => true,
        };
        if !m1 {
            // early stop
            return false;
        }
        let ipv4_packet = match Ipv4Packet::new(icmp_payload) {
            Some(i) => i,
            None => return false,
        };
        let (r_src_port, r_dst_port) = match ipv4_packet.get_next_level_protocol() {
            IpNextHeaderProtocols::Tcp => {
                let tcp_packet = match TcpPacket::new(ipv4_packet.payload()) {
                    Some(t) => t,
                    None => return false,
                };
                (tcp_packet.get_source(), tcp_packet.get_destination())
            }
            IpNextHeaderProtocols::Udp => {
                let udp_packet = match UdpPacket::new(ipv4_packet.payload()) {
                    Some(t) => t,
                    None => return false,
                };
                (udp_packet.get_source(), udp_packet.get_destination())
            }
            _ => (0, 0),
        };
        match self.src_port {
            Some(src_port) => {
                if src_port != r_src_port {
                    return false;
                }
            }
            None => (),
        }
        match self.dst_port {
            Some(dst_port) => {
                if dst_port != r_dst_port {
                    return false;
                }
            }
            None => (),
        }
        true
    }
    pub fn do_match_ipv6(&self, icmpv6_payload: &[u8]) -> bool {
        let m1 = match self.layer3 {
            Some(layer3) => layer3.do_match_ipv6(icmpv6_payload),
            None => true,
        };
        if !m1 {
            // ealry stop
            return false;
        }
        let ipv6_packet = match Ipv6Packet::new(icmpv6_payload) {
            Some(i) => i,
            None => return false,
        };
        let (r_src_port, r_dst_port) = match ipv6_packet.get_next_header() {
            IpNextHeaderProtocols::Tcp => {
                let tcp_packet = match TcpPacket::new(ipv6_packet.payload()) {
                    Some(t) => t,
                    None => return false,
                };
                (tcp_packet.get_source(), tcp_packet.get_destination())
            }
            IpNextHeaderProtocols::Udp => {
                let udp_packet = match UdpPacket::new(ipv6_packet.payload()) {
                    Some(t) => t,
                    None => return false,
                };
                (udp_packet.get_source(), udp_packet.get_destination())
            }
            _ => (0, 0),
        };
        match self.src_port {
            Some(src_port) => {
                if src_port != r_src_port {
                    return false;
                }
            }
            None => (),
        }
        match self.dst_port {
            Some(dst_port) => {
                if dst_port != r_dst_port {
                    return false;
                }
            }
            None => (),
        }
        true
    }
}

#[derive(Debug, Clone, Copy)]
pub struct PayloadMatchIcmp {
    pub layer3: Option<PayloadMatchIp>,
    pub icmp_type: Option<IcmpType>, // response icmp packet types
    pub icmp_code: Option<IcmpCode>, // response icmp packet codes
}

impl PayloadMatchIcmp {
    pub fn do_match(&self, icmp_payload: &[u8]) -> bool {
        let m1 = match self.layer3 {
            Some(layer3) => layer3.do_match_ipv4(icmp_payload),
            None => true,
        };
        if !m1 {
            // early stop
            return false;
        }
        let ipv4_packet = match Ipv4Packet::new(icmp_payload) {
            Some(i) => i,
            None => return false,
        };
        let (r_type, r_code) = match ipv4_packet.get_next_level_protocol() {
            IpNextHeaderProtocols::Icmp => match IcmpPacket::new(ipv4_packet.payload()) {
                Some(t) => (t.get_icmp_type(), t.get_icmp_code()),
                None => return false,
            },
            _ => return false,
        };
        match self.icmp_type {
            Some(t) => {
                if t != r_type {
                    return false;
                }
            }
            None => (),
        }
        match self.icmp_code {
            Some(c) => {
                if c != r_code {
                    return false;
                }
            }
            None => (),
        }
        true
    }
}

#[derive(Debug, Clone, Copy)]
pub struct PayloadMatchIcmpv6 {
    pub layer3: Option<PayloadMatchIp>,
    pub icmpv6_type: Option<Icmpv6Type>, // response icmp packet types
    pub icmpv6_code: Option<Icmpv6Code>, // response icmp packet codes
}

impl PayloadMatchIcmpv6 {
    pub fn do_match(&self, icmpv6_payload: &[u8]) -> bool {
        let m1 = match self.layer3 {
            Some(layer3) => layer3.do_match_ipv6(icmpv6_payload),
            None => true,
        };
        if !m1 {
            // early stop
            return false;
        }
        let ipv6_packet = match Ipv6Packet::new(icmpv6_payload) {
            Some(i) => i,
            None => return false,
        };
        let (r_types, r_codes) = match ipv6_packet.get_next_header() {
            IpNextHeaderProtocols::Icmpv6 => match Icmpv6Packet::new(ipv6_packet.payload()) {
                Some(t) => (t.get_icmpv6_type(), t.get_icmpv6_code()),
                None => return false,
            },
            _ => return false,
        };
        match self.icmpv6_type {
            Some(types) => {
                if types != r_types {
                    return false;
                }
            }
            None => (),
        }
        match self.icmpv6_code {
            Some(codes) => {
                if codes != r_codes {
                    return false;
                }
            }
            None => (),
        }
        true
    }
}

#[derive(Debug, Clone, Copy)]
pub enum PayloadMatch {
    PayloadMatchIp(PayloadMatchIp),
    PayloadMatchTcpUdp(PayloadMatchTcpUdp),
    PayloadMatchIcmp(PayloadMatchIcmp),
    PayloadMatchIcmpv6(PayloadMatchIcmpv6),
}

/// Because when icmp returns raw data as icmp packet payload,
/// there is no indication whether it is ipv4 data or ipv6 data.
/// But generally speaking, if ipv4 data is sent, ipv4 will be returned,
/// and the same is true for ipv6, so users need to choose two different functions.
impl PayloadMatch {
    pub fn do_match_ipv4(&self, icmp_payload: &[u8]) -> bool {
        match self {
            PayloadMatch::PayloadMatchIp(ip) => ip.do_match_ipv4(icmp_payload),
            PayloadMatch::PayloadMatchTcpUdp(tcp_udp) => tcp_udp.do_match_ipv4(icmp_payload),
            PayloadMatch::PayloadMatchIcmp(icmp) => icmp.do_match(icmp_payload),
            PayloadMatch::PayloadMatchIcmpv6(_) => false,
        }
    }
    pub fn do_match_ipv6(&self, icmpv6_payload: &[u8]) -> bool {
        match self {
            PayloadMatch::PayloadMatchIp(ip) => ip.do_match_ipv6(icmpv6_payload),
            PayloadMatch::PayloadMatchTcpUdp(tcp_udp) => tcp_udp.do_match_ipv4(icmpv6_payload),
            PayloadMatch::PayloadMatchIcmpv6(icmpv6) => icmpv6.do_match(icmpv6_payload),
            PayloadMatch::PayloadMatchIcmp(_) => false,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Layer4MatchIcmp {
    pub name: &'static str,
    pub layer3: Option<Layer3Match>,
    pub icmp_type: Option<IcmpType>,   // response icmp packet types
    pub icmp_code: Option<IcmpCode>,   // response icmp packet codes
    pub payload: Option<PayloadMatch>, // used to confirm which port the data packet is from
}

impl Layer4MatchIcmp {
    pub fn do_match(&self, ethernet_packet: &[u8]) -> bool {
        let m1 = match &self.layer3 {
            Some(layer3) => layer3.do_match(ethernet_packet),
            None => true,
        };
        if !m1 {
            // early stop
            return false;
        }
        let ethernet_packet = match EthernetPacket::new(&ethernet_packet) {
            Some(ethernet_packet) => ethernet_packet,
            None => return false,
        };
        let (r_type, r_code, icmp_payload) = match ethernet_packet.get_ethertype() {
            EtherTypes::Ipv4 => {
                let ipv4_packet = match Ipv4Packet::new(ethernet_packet.payload()) {
                    Some(i) => i,
                    None => return false,
                };
                match ipv4_packet.get_next_level_protocol() {
                    IpNextHeaderProtocols::Icmp => match IcmpPacket::new(ipv4_packet.payload()) {
                        Some(icmp_packet) => (
                            icmp_packet.get_icmp_type(),
                            icmp_packet.get_icmp_code(),
                            get_icmp_payload(&icmp_packet),
                        ),
                        None => return false,
                    },
                    _ => return false,
                }
            }
            _ => return false,
        };
        match self.icmp_type {
            Some(t) => {
                if t != r_type {
                    return false;
                }
            }
            None => (),
        }
        match self.icmp_code {
            Some(c) => {
                if c != r_code {
                    return false;
                }
            }
            None => (),
        }
        match self.payload {
            Some(payload) => payload.do_match_ipv4(&icmp_payload),
            None => true,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Layer4MatchIcmpv6 {
    pub name: &'static str,
    pub layer3: Option<Layer3Match>,
    pub icmpv6_type: Option<Icmpv6Type>, // response icmp packet types
    pub icmpv6_code: Option<Icmpv6Code>, // response icmp packet codes
    pub payload: Option<PayloadMatch>,
}

impl Layer4MatchIcmpv6 {
    pub fn do_match(&self, ethernet_packet: &[u8]) -> bool {
        let m1 = match &self.layer3 {
            Some(layer3) => layer3.do_match(ethernet_packet),
            None => true,
        };
        if !m1 {
            // early stop
            return false;
        }

        let ethernet_packet = match EthernetPacket::new(&ethernet_packet) {
            Some(ethernet_packet) => ethernet_packet,
            None => return false,
        };
        let (r_type, r_code, icmpv6_payload) = match ethernet_packet.get_ethertype() {
            EtherTypes::Ipv6 => {
                let ipv6_packet = match Ipv6Packet::new(ethernet_packet.payload()) {
                    Some(i) => i,
                    None => return false,
                };
                match ipv6_packet.get_next_header() {
                    IpNextHeaderProtocols::Icmpv6 => {
                        match Icmpv6Packet::new(ipv6_packet.payload()) {
                            Some(icmpv6_packet) => (
                                icmpv6_packet.get_icmpv6_type(),
                                icmpv6_packet.get_icmpv6_code(),
                                get_icmpv6_payload(&icmpv6_packet),
                            ),
                            None => return false,
                        }
                    }
                    _ => return false,
                }
            }
            _ => return false,
        };
        match self.icmpv6_type {
            Some(t) => {
                if t != r_type {
                    return false;
                }
            }
            None => (),
        }
        match self.icmpv6_code {
            Some(c) => {
                if c != r_code {
                    return false;
                }
            }
            None => (),
        };
        match self.payload {
            Some(payload) => payload.do_match_ipv6(&icmpv6_payload),
            None => true,
        }
    }
}

/// or rules
#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
pub enum LayerMatch {
    Layer2Match(Layer2Match),
    Layer3Match(Layer3Match),
    Layer4MatchTcpUdp(Layer4MatchTcpUdp),
    Layer4MatchIcmp(Layer4MatchIcmp),
    Layer4MatchIcmpv6(Layer4MatchIcmpv6),
}

impl LayerMatch {
    pub fn do_match(&self, ethernet_packet: &[u8]) -> bool {
        if ethernet_packet.len() > 0 {
            match self {
                LayerMatch::Layer2Match(l2) => l2.do_match(ethernet_packet),
                LayerMatch::Layer3Match(l3) => l3.do_match(ethernet_packet),
                LayerMatch::Layer4MatchTcpUdp(tcp_udp) => tcp_udp.do_match(ethernet_packet),
                LayerMatch::Layer4MatchIcmp(icmp) => icmp.do_match(ethernet_packet),
                LayerMatch::Layer4MatchIcmpv6(icmpv6) => icmpv6.do_match(ethernet_packet),
            }
        } else {
            false
        }
    }
    pub fn name(&self) -> &'static str {
        match self {
            LayerMatch::Layer2Match(l2) => l2.name,
            LayerMatch::Layer3Match(l3) => l3.name,
            LayerMatch::Layer4MatchTcpUdp(tcp_udp) => tcp_udp.name,
            LayerMatch::Layer4MatchIcmp(icmp) => icmp.name,
            LayerMatch::Layer4MatchIcmpv6(icmpv6) => icmpv6.name,
        }
    }
}

/// Capture the traffic and save into file.
pub fn layer2_capture(packet: &[u8]) -> Result<(), PistolError> {
    let ppf = match PISTOL_PCAPNG_FLAG.lock() {
        Ok(ppf) => *ppf,
        Err(e) => {
            return Err(PistolError::TryLockGlobalVarFailed {
                var_name: String::from("PISTOL_PCAPNG_FLAG"),
                e: e.to_string(),
            });
        }
    };

    if ppf {
        match PISTOL_PCAPNG.lock() {
            Ok(mut pp) => {
                // interface_id = 0 means we use the first interface we builed in fake pcapng headers
                const INTERFACE_ID: u32 = 0;
                // this is the default value of pcapture
                const SNAPLEN: usize = 65535;
                match EnhancedPacketBlock::new(INTERFACE_ID, packet, SNAPLEN) {
                    Ok(block) => {
                        let gb = GeneralBlock::EnhancedPacketBlock(block);
                        pp.append(gb);
                    }
                    Err(e) => {
                        error!("build EnhancedPacketBlock in layer2_send() failed: {}", e)
                    }
                }
            }
            Err(e) => {
                return Err(PistolError::TryLockGlobalVarFailed {
                    var_name: String::from("PISTOL_PCAPNG"),
                    e: e.to_string(),
                });
            }
        }
    }
    Ok(())
}

/// This function only recvs data.
fn layer2_set_matchs(
    layer_matchs: Vec<LayerMatch>,
) -> Result<(Receiver<Vec<u8>>, PistolChannel), PistolError> {
    // let (tx: Sender<Vec<u8>>, rx: Receiver<Vec<PistolChannel>>) = channel();
    let (tx, rx) = channel();
    let pc = PistolChannel {
        uuid: Uuid::new_v4(),
        channel: tx,
        layer_matchs,
    };

    match UNIFIED_RECV_MATCHS.lock() {
        Ok(mut urm) => urm.push(pc.clone()),
        Err(e) => {
            return Err(PistolError::TryLockGlobalVarFailed {
                var_name: String::from("UNIFIED_RECV_MATCHS"),
                e: e.to_string(),
            });
        }
    }
    Ok((rx, pc))
}

fn layer2_rm_matchs(uuid: &Uuid) -> Result<bool, PistolError> {
    match UNIFIED_RECV_MATCHS.lock() {
        Ok(mut urm) => {
            let mut urm_clone = urm.clone();
            if let Some(index) = urm_clone.iter().position(|pc| pc.uuid == *uuid) {
                urm_clone.remove(index);
                *urm = urm_clone;
                Ok(true)
            } else {
                Ok(false)
            }
        }
        Err(e) => Err(PistolError::TryLockGlobalVarFailed {
            var_name: String::from("UNIFIED_RECV_MATCHS"),
            e: e.to_string(),
        }),
    }
}

fn layer2_recv(rx: Receiver<Vec<u8>>, timeout: Option<Duration>) -> Result<Vec<u8>, PistolError> {
    let timeout = match timeout {
        Some(t) => t,
        None => Duration::from_secs_f64(DEFAULT_TIMEOUT),
    };

    // only 1 packet will be recv from match threads
    let iter = rx.recv_timeout(timeout).into_iter().take(1);
    for ethernet_packet in iter {
        return Ok(ethernet_packet);
    }
    Ok(Vec::new())
}

/// This function only sends data.
fn layer2_send(
    dst_mac: MacAddr,
    interface: NetworkInterface,
    payload: &[u8],
    payload_len: usize,
    ethernet_type: EtherType,
    timeout: Option<Duration>,
) -> Result<(), PistolError> {
    let config = Config {
        write_buffer_size: ETHERNET_BUFF_SIZE,
        read_buffer_size: ETHERNET_BUFF_SIZE,
        read_timeout: timeout,
        write_timeout: timeout,
        channel_type: ChannelType::Layer2,
        bpf_fd_attempts: 1000,
        linux_fanout: None,
        promiscuous: false,
        socket_fd: None,
    };

    let (mut sender, _) = match datalink::channel(&interface, config) {
        Ok(Ethernet(tx, rx)) => (tx, rx),
        Ok(_) => return Err(PistolError::CreateDatalinkChannelFailed),
        Err(e) => return Err(e.into()),
    };

    let src_mac = if dst_mac == MacAddr::zero() {
        MacAddr::zero()
    } else {
        match interface.mac {
            Some(m) => m,
            None => return Err(PistolError::CanNotFoundMacAddress),
        }
    };

    let ethernet_buff_len = ETHERNET_HEADER_SIZE + payload_len;
    // According to the document, the minimum length of an Ethernet data packet is 64 bytes
    // (14 bytes of header and at least 46 bytes of data and 4 bytes of FCS),
    // but I found through packet capture that nmap did not follow this convention,
    // so this padding is also cancelled here.
    // let ethernet_buff_len = if ethernet_buff_len < 60 {
    //     // padding before FCS
    //     60
    // } else {
    //     ethernet_buff_len
    // };
    let mut buff = vec![0u8; ethernet_buff_len];
    let mut ethernet_packet = match MutableEthernetPacket::new(&mut buff) {
        Some(p) => p,
        None => {
            return Err(PistolError::BuildPacketError {
                location: format!("{}", Location::caller()),
            });
        }
    };
    ethernet_packet.set_destination(dst_mac);
    ethernet_packet.set_source(src_mac);
    ethernet_packet.set_ethertype(ethernet_type);
    ethernet_packet.set_payload(payload);
    layer2_capture(&buff)?;

    match sender.send_to(&buff, Some(interface)) {
        Some(r) => match r {
            Err(e) => return Err(e.into()),
            _ => Ok(()),
        },
        None => Ok(()),
    }
}

/// In order to prevent other threads from reading and discarding data packets
/// that do not belong to them during the multi-threaded multi-packet sending process,
/// and to improve the stability of the scan, I decided to put the reception of
/// all data packets into one thread.
pub fn layer2_work(
    dst_mac: MacAddr,
    interface: NetworkInterface,
    payload: &[u8],
    payload_len: usize,
    ethernet_type: EtherType,
    layer_matchs: Vec<LayerMatch>,
    timeout: Option<Duration>,
    need_return: bool,
) -> Result<(Vec<u8>, Duration), PistolError> {
    let running = match PISTOL_RUNNER_IS_RUNNING.lock() {
        Ok(r) => *r,
        Err(e) => {
            return Err(PistolError::TryLockGlobalVarFailed {
                var_name: String::from("PISTOL_RUNNER_IS_RUNNING"),
                e: e.to_string(),
            });
        }
    };

    if running {
        let start = Instant::now();
        if need_return {
            // set the matchs
            let (rx, pc) = layer2_set_matchs(layer_matchs)?;
            layer2_send(
                dst_mac,
                interface,
                payload,
                payload_len,
                ethernet_type,
                timeout,
            )?;
            let data = layer2_recv(rx, timeout)?;
            let rtt = start.elapsed();
            // we done here and remove the matchs
            if !layer2_rm_matchs(&pc.uuid)? {
                warn!("can not found and remove recv matchs");
            }
            Ok((data, rtt))
        } else {
            layer2_send(
                dst_mac,
                interface,
                payload,
                payload_len,
                ethernet_type,
                timeout,
            )?;
            let rtt = start.elapsed();

            Ok((Vec::new(), rtt))
        }
    } else {
        Err(PistolError::PistolRunnerIsNotRunning)
    }
}

pub fn layer3_ipv4_send(
    dst_ipv4: Ipv4Addr,
    src_ipv4: Ipv4Addr,
    ethernet_payload: &[u8],
    layer_matchs: Vec<LayerMatch>,
    timeout: Option<Duration>,
    need_return: bool,
) -> Result<(Vec<u8>, Duration), PistolError> {
    let (dst_mac, interface) =
        RouteVia::get_dst_mac_and_src_if(dst_ipv4.into(), src_ipv4.into(), timeout)?;
    debug!(
        "dst addr: {}, dst mac: {}, src addr: {}, sending interface: {}, {:?}",
        dst_ipv4, dst_mac, src_ipv4, interface.name, interface.ips
    );
    let ethernet_type = EtherTypes::Ipv4;
    let payload_len = ethernet_payload.len();
    let (layer2_buff, rtt) = layer2_work(
        dst_mac,
        interface,
        ethernet_payload,
        payload_len,
        ethernet_type,
        layer_matchs,
        timeout,
        need_return,
    )?;
    Ok((layer2_payload(&layer2_buff), rtt))
}

pub fn multicast_mac(ip: Ipv6Addr) -> MacAddr {
    let ip = ip.octets();
    // 33:33:FF:xx:xx:xx
    MacAddr::new(0x33, 0x33, 0xFF, ip[13], ip[14], ip[15])
}

fn layer2_payload(buff: &[u8]) -> Vec<u8> {
    match EthernetPacket::new(buff) {
        Some(ethernet_packet) => ethernet_packet.payload().to_vec(),
        None => Vec::new(),
    }
}

pub fn layer3_ipv6_send(
    dst_ipv6: Ipv6Addr,
    src_ipv6: Ipv6Addr,
    payload: &[u8],
    layer_matchs: Vec<LayerMatch>,
    timeout: Option<Duration>,
    need_return: bool,
) -> Result<(Vec<u8>, Duration), PistolError> {
    let dst_ipv6 = if dst_ipv6.is_loopback() {
        src_ipv6
    } else {
        dst_ipv6
    };
    let (dst_mac, interface) =
        RouteVia::get_dst_mac_and_src_if(dst_ipv6.into(), src_ipv6.into(), timeout)?;

    let ethernet_type = EtherTypes::Ipv6;
    let payload_len = payload.len();
    let (layer2_buff, rtt) = layer2_work(
        dst_mac,
        interface,
        payload,
        payload_len,
        ethernet_type,
        layer_matchs,
        timeout,
        need_return,
    )?;
    Ok((layer2_payload(&layer2_buff), rtt))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::PistolLogger;
    use crate::PistolRunner;
    use pnet::packet::icmp::IcmpTypes;
    use pnet::packet::icmpv6::Icmpv6Types;
    use std::str::FromStr;
    #[test]
    fn test_infer_addr() {
        let _pr = PistolRunner::init(
            PistolLogger::Debug,
            None,
            None, // use default value
        )
        .unwrap();
        let dst_ipv4 = Ipv4Addr::new(192, 168, 5, 129);
        let ia = infer_addr(dst_ipv4.into(), None).unwrap();
        if let Some(ia) = ia {
            let timeout = Some(Duration::from_secs_f64(1.0));
            let (_mac, interface) =
                RouteVia::get_dst_mac_and_src_if(ia.dst_addr, ia.src_addr, timeout).unwrap();
            println!("{}", interface.name);
        }
        println!("{:?}", ia);
    }
    #[test]
    fn test_layer_match() {
        let data: Vec<u8> = vec![
            0x0, 0xc, 0x29, 0x5b, 0xbd, 0x5c, 0x0, 0xc, 0x29, 0x2c, 0x9, 0xe4, 0x8, 0x0, 0x45,
            0xc0, 0x0, 0x38, 0x1, 0xcd, 0x0, 0x0, 0x40, 0x1, 0xec, 0xdf, 0xc0, 0xa8, 0x5, 0x5,
            0xc0, 0xa8, 0x5, 0x3, 0x3, 0x3, 0x88, 0x6f, 0x0, 0x0, 0x0, 0x0, 0x45, 0x0, 0x0, 0x1c,
            0x81, 0x56, 0x40, 0x0, 0x40, 0x11, 0x2e, 0x22, 0xc0, 0xa8, 0x5, 0x3, 0xc0, 0xa8, 0x5,
            0x5, 0x73, 0xa, 0x1f, 0x90, 0x0, 0x8, 0xe1, 0xea,
        ];
        let dst_ipv4 = Ipv4Addr::new(192, 168, 5, 5);
        let src_ipv4 = Ipv4Addr::new(192, 168, 5, 3);
        let dst_port = 8080;
        let src_port = 29450;
        let layer3 = Layer3Match {
            name: "test layer3",
            layer2: None,
            src_addr: Some(dst_ipv4.into()),
            dst_addr: Some(src_ipv4.into()),
        };
        let payload_ip = PayloadMatchIp {
            src_addr: Some(src_ipv4.into()),
            dst_addr: Some(dst_ipv4.into()),
        };
        let payload_tcp_udp = PayloadMatchTcpUdp {
            layer3: Some(payload_ip),
            src_port: Some(src_port),
            dst_port: Some(dst_port),
        };
        let payload = PayloadMatch::PayloadMatchTcpUdp(payload_tcp_udp);
        let layer4_icmp = Layer4MatchIcmp {
            name: "test icmp",
            layer3: Some(layer3),
            icmp_type: None,
            icmp_code: None,
            payload: Some(payload),
        };
        let layer_match = LayerMatch::Layer4MatchIcmp(layer4_icmp);
        let x = layer_match.do_match(&data);
        println!("match ret: {}", x);
    }
    #[test]
    fn test_layer_match2() {
        let data = vec![
            0x0, 0xc, 0x29, 0x5b, 0xbd, 0x5c, 0x0, 0xc, 0x29, 0x2c, 0x9, 0xe4, 0x86, 0xdd, 0x60,
            0x0, 0x0, 0x0, 0x0, 0x20, 0x3a, 0xff, 0xfe, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
            0xc, 0x29, 0xff, 0xfe, 0x2c, 0x9, 0xe4, 0xfe, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
            0xc, 0x29, 0xff, 0xfe, 0x5b, 0xbd, 0x5c, 0x88, 0x0, 0x97, 0x8, 0x60, 0x0, 0x0, 0x0,
            0xfe, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xc, 0x29, 0xff, 0xfe, 0x2c, 0x9, 0xe4,
            0x2, 0x1, 0x0, 0xc, 0x29, 0x2c, 0x9, 0xe4,
        ];
        let dst_ipv6 = Ipv6Addr::from_str("fe80::20c:29ff:fe2c:9e4").unwrap();
        let src_ipv6 = Ipv6Addr::from_str("fe80::20c:29ff:fe5b:bd5c").unwrap();
        let layer3 = Layer3Match {
            name: "test layer3",
            layer2: None,
            src_addr: Some(dst_ipv6.into()),
            dst_addr: Some(src_ipv6.into()),
        };
        let layer4_icmpv6 = Layer4MatchIcmpv6 {
            name: "test icmpv6",
            layer3: Some(layer3),
            icmpv6_type: Some(Icmpv6Types::NeighborAdvert),
            icmpv6_code: None,
            payload: None,
        };
        let layer_match = LayerMatch::Layer4MatchIcmpv6(layer4_icmpv6);
        let x = layer_match.do_match(&data);
        println!("match ret: {}", x);
    }
    #[test]
    fn test_layer_match3() {
        let src_ipv4 = Ipv4Addr::new(192, 168, 5, 3);
        let dst_ipv4 = Ipv4Addr::new(192, 168, 1, 3);
        let src_port = 45982;
        let dst_port = 33434;
        let layer3 = Layer3Match {
            name: "test layer3",
            layer2: None,
            src_addr: None,
            dst_addr: Some(src_ipv4.into()),
        };
        // set the icmp payload matchs
        let payload_ip = PayloadMatchIp {
            src_addr: Some(src_ipv4.into()),
            dst_addr: Some(dst_ipv4.into()),
        };
        let payload_tcp_udp = PayloadMatchTcpUdp {
            layer3: Some(payload_ip),
            src_port: Some(src_port),
            dst_port: Some(dst_port),
        };
        let payload = PayloadMatch::PayloadMatchTcpUdp(payload_tcp_udp);
        let layer4_icmp = Layer4MatchIcmp {
            name: "test icmp",
            layer3: Some(layer3),
            icmp_type: Some(IcmpTypes::TimeExceeded),
            icmp_code: None,
            payload: Some(payload),
        };
        let layer_match_icmp_time_exceeded = LayerMatch::Layer4MatchIcmp(layer4_icmp);

        let data = vec![
            0x0, 0xc, 0x29, 0x5b, 0xbd, 0x5c, 0x0, 0x50, 0x56, 0xff, 0xa6, 0x97, 0x8, 0x0, 0x45,
            0x0, 0x0, 0x58, 0xe, 0x7f, 0x0, 0x0, 0x80, 0x1, 0xa0, 0xd0, 0xc0, 0xa8, 0x5, 0x2, 0xc0,
            0xa8, 0x5, 0x3, 0xb, 0x0, 0x7c, 0x90, 0x0, 0x0, 0x0, 0x0, 0x45, 0x0, 0x0, 0x3c, 0x9b,
            0x2f, 0x40, 0x0, 0x1, 0x11, 0x57, 0x2b, 0xc0, 0xa8, 0x5, 0x3, 0xc0, 0xa8, 0x1, 0x3,
            0xb3, 0x9e, 0x82, 0x9a, 0x0, 0x28, 0x4d, 0x9, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
            0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54,
            0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
        ];

        let ret = layer_match_icmp_time_exceeded.do_match(&data);
        println!("{}", ret);
    }
    #[test]
    fn test_layer_match4() {
        let src_ipv4 = Ipv4Addr::new(192, 168, 5, 3);
        let dst_ipv4 = Ipv4Addr::new(192, 168, 1, 3);
        let src_port = 59470;
        let dst_port = 80;

        let layer3 = Layer3Match {
            name: "test layer3",
            layer2: None,
            src_addr: None, // usually this is the address of the router, not the address of the target machine.
            dst_addr: Some(src_ipv4.into()),
        };
        let payload_ip = PayloadMatchIp {
            src_addr: Some(src_ipv4.into()),
            dst_addr: Some(dst_ipv4.into()),
        };
        let payload_tcp_udp = PayloadMatchTcpUdp {
            layer3: Some(payload_ip),
            src_port: Some(src_port),
            dst_port: Some(dst_port),
        };
        let payload = PayloadMatch::PayloadMatchTcpUdp(payload_tcp_udp);
        let layer4_icmp = Layer4MatchIcmp {
            name: "test icmp",
            layer3: Some(layer3),
            icmp_type: Some(IcmpTypes::TimeExceeded),
            icmp_code: None,
            payload: Some(payload),
        };
        let layer_match_icmp_time_exceeded = LayerMatch::Layer4MatchIcmp(layer4_icmp);

        let data = vec![
            0x0, 0xc, 0x29, 0x5b, 0xbd, 0x5c, 0x0, 0x50, 0x56, 0xff, 0xa6, 0x97, 0x8, 0x0, 0x45,
            0x0, 0x0, 0x58, 0x7, 0x5e, 0x0, 0x0, 0x80, 0x1, 0xa7, 0xf1, 0xc0, 0xa8, 0x5, 0x2, 0xc0,
            0xa8, 0x5, 0x3, 0xb, 0x0, 0x7c, 0x85, 0x0, 0x0, 0x0, 0x0, 0x45, 0x0, 0x0, 0x3c, 0x8a,
            0x1f, 0x40, 0x0, 0x1, 0x6, 0x68, 0x46, 0xc0, 0xa8, 0x5, 0x3, 0xc0, 0xa8, 0x1, 0x3,
            0xe8, 0x4e, 0x0, 0x50, 0xb9, 0xc5, 0x70, 0x4a, 0x0, 0x0, 0x0, 0x0, 0xa0, 0x2, 0x16,
            0xd0, 0xf2, 0x92, 0x0, 0x0, 0x2, 0x4, 0x5, 0xb4, 0x4, 0x2, 0x8, 0xa, 0x78, 0x46, 0x2c,
            0x56, 0x0, 0x0, 0x0, 0x0, 0x1, 0x3, 0x3, 0x2,
        ];

        let ret = layer_match_icmp_time_exceeded.do_match(&data);
        println!("{}", ret);
    }
    #[test]
    fn test_layer_match5() {
        let src_ipv4 = Ipv4Addr::new(192, 168, 5, 3);
        let dst_ipv4 = Ipv4Addr::new(192, 168, 1, 3);
        let src_port = 26845;
        let dst_port = 80;

        let layer3 = Layer3Match {
            name: "test layer3",
            layer2: None,
            src_addr: Some(dst_ipv4.into()),
            dst_addr: Some(src_ipv4.into()),
        };
        let layer4_tcp_udp = Layer4MatchTcpUdp {
            name: "test tcp_udp",
            layer3: Some(layer3),
            src_port: Some(dst_port),
            dst_port: Some(src_port),
        };
        let layer_match_tcp = LayerMatch::Layer4MatchTcpUdp(layer4_tcp_udp);

        let data = [
            0x0, 0xc, 0x29, 0x5b, 0xbd, 0x5c, 0x0, 0x50, 0x56, 0xff, 0xa6, 0x97, 0x8, 0x0, 0x45,
            0x0, 0x0, 0x28, 0xd, 0x83, 0x0, 0x0, 0x80, 0x6, 0xa5, 0xf6, 0xc0, 0xa8, 0x1, 0x3, 0xc0,
            0xa8, 0x5, 0x3, 0x0, 0x50, 0x68, 0xdd, 0x48, 0xc4, 0x1, 0xc5, 0xbf, 0x34, 0xcb, 0x88,
            0x50, 0x14, 0xfa, 0xf0, 0xef, 0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        ];

        let ret = layer_match_tcp.do_match(&data);
        println!("{}", ret);
    }
    #[test]
    fn test_layer2_send() {
        let config = Config {
            write_buffer_size: ETHERNET_BUFF_SIZE,
            read_buffer_size: ETHERNET_BUFF_SIZE,
            read_timeout: Some(Duration::new(1, 0)),
            write_timeout: Some(Duration::new(1, 0)),
            channel_type: ChannelType::Layer2,
            bpf_fd_attempts: 1000,
            linux_fanout: None,
            promiscuous: false,
            socket_fd: None,
        };

        // let dst_ipv4 = Ipv4Addr::new(192, 168, 5, 5);
        let src_ipv4 = Ipv4Addr::new(192, 168, 5, 3);
        let interface = find_interface_by_src(src_ipv4.into()).unwrap();

        let (mut sender, _) = match datalink::channel(&interface, config) {
            Ok(Ethernet(tx, rx)) => (tx, rx),
            _ => panic!("create datalink channel failed"),
        };

        // let data: Vec<u8> = vec![
        //     0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x0, 0x45, 0x0, 0x0,
        //     0x3c, 0x84, 0x7c, 0x40, 0x0, 0x40, 0x6, 0xb8, 0x3d, 0x7f, 0x0, 0x0, 0x1, 0x7f, 0x0,
        //     0x0, 0x1, 0xbb, 0xee, 0x0, 0x50, 0xe4, 0xdf, 0xeb, 0x16, 0x0, 0x0, 0x0, 0x0, 0xa0, 0x2,
        //     0xff, 0xd7, 0xfe, 0x30, 0x0, 0x0, 0x2, 0x4, 0xff, 0xd7, 0x4, 0x2, 0x8, 0xa, 0xd4, 0xb8,
        //     0xfd, 0x6, 0x0, 0x0, 0x0, 0x0, 0x1, 0x3, 0x3, 0x7,
        // ];
        let data: Vec<u8> = vec![
            0x0, 0xc, 0x29, 0x2c, 0x9, 0xe4, 0x0, 0xc, 0x29, 0x5b, 0xbd, 0x5c, 0x8, 0x0, 0x45, 0x0,
            0x0, 0x28, 0x40, 0xaa, 0x0, 0x0, 0x3a, 0x6, 0xb4, 0xcd, 0xc0, 0xa8, 0x5, 0x3, 0xc0,
            0xa8, 0x5, 0x5, 0xc7, 0xec, 0x0, 0x50, 0x0, 0x0, 0x0, 0x0, 0x99, 0xb7, 0x60, 0xf6,
            0x50, 0x10, 0x4, 0x0, 0x5d, 0x91, 0x0, 0x0,
        ];
        let _ = sender.send_to(&data, Some(interface)).unwrap();
    }
}