zond-engine 0.15.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Probe Transport
//!
//! One handle the raw scanners send probes through and receive replies from,
//! independent of *how* those packets reach the wire.
//!
//! Sending and receiving are deliberately split across two mechanisms,
//! because the constraints differ by direction and by OS:
//!
//! - **Receiving** always goes through a `libpcap` capture
//!   ([`crate::transport::capture`]). A raw Layer-4 socket receives replies on
//!   Linux but *not* on macOS/BSD, whose kernels never hand TCP/UDP to raw
//!   sockets; capturing at the link layer is the one path that works
//!   everywhere.
//! - **Sending** goes through a [`ProbeSender`]. The default
//!   [`RawIpSender`] emits segments over a raw Layer-4 socket, which *sends*
//!   fine on every supported Unix (only receiving that way is broken) and
//!   lets the kernel handle routing, ARP/NDP, and fragmentation. A future
//!   Ethernet [`ProbeSender`] can build frames itself for Windows - where
//!   raw TCP sends are blocked - or for deliberately bypassing the host
//!   stack, without any scanner having to know the difference.
//!
//! The trait is what makes that swappable: [`ProbeTransport`] owns a
//! `Box<dyn ProbeSender>` and a capture-fed receive stream, and every scanner
//! depends only on those two things.

use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;

use pnet_packet::Packet;
use pnet_packet::ip::{IpNextHeaderProtocol, IpNextHeaderProtocols};

use crate::model::capture::CaptureCounts;
use crate::model::ip::scoped::Zone;
use crate::model::mac::MacAddr;
use crate::transport::capture::{self, CaptureGuard, CaptureOptions, CaptureStream};
use crate::transport::link::EthernetSender;
use crate::transport::raw::{self, TransportSenderHandle, TransportType};

/// How many captured segments may wait for a scanner to read them.
///
/// Deep enough that a burst of genuine replies is never what stalls the reader,
/// and shallow enough that traffic the filter could not narrow cannot grow
/// without bound: at [`REPLY_SNAP_LEN`](capture::REPLY_SNAP_LEN) a full queue is
/// a bounded number of megabytes rather than however much the network sends.
/// See [`capture::segments`] for which filters leave that possible and why.
const REPLY_QUEUE_DEPTH: usize = 4096;

/// The error [`SendMode::from_str`] returns, carrying the names that would have
/// worked so a front end can print it verbatim.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown send mode '{input}', expected one of: auto, raw_socket, ethernet")]
pub struct UnknownSendMode {
    /// What the caller wrote.
    pub input: String,
}

/// How the privileged (raw) scanners put probe packets on the wire.
///
/// Only affects the raw-socket SYN paths; the unprivileged TCP-connect
/// fallback and the on-link ARP/ICMPv6 [`LocalScanner`](crate::scanner)
/// discovery are unaffected.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SendMode {
    /// Pick per platform: a raw Layer-4 socket on Unix - which the kernel
    /// routes, ARPs, and fragments for us, and which works through VPN
    /// tunnels - and self-built Layer-2 Ethernet frames on Windows, where the
    /// OS blocks raw-socket TCP sends outright.
    #[default]
    Auto,
    /// Force a raw Layer-4 socket regardless of platform.
    RawSocket,
    /// Force self-built Layer-2 Ethernet frames, bypassing the host IP stack
    /// (and the local firewall / connection tracking that a raw-socket send
    /// still traverses). Requires an Ethernet-capable interface and can't
    /// reach loopback or tunnel-only destinations.
    Ethernet,
}
impl SendMode {
    /// Every mode, in the order a front end should offer them.
    pub const ALL: [SendMode; 3] = [SendMode::Auto, SendMode::RawSocket, SendMode::Ethernet];

    /// The name this mode is written under, wherever it arrives as text.
    pub const fn name(self) -> &'static str {
        match self {
            SendMode::Auto => "auto",
            SendMode::RawSocket => "raw_socket",
            SendMode::Ethernet => "ethernet",
        }
    }
}
impl fmt::Display for SendMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}
impl FromStr for SendMode {
    type Err = UnknownSendMode;

    /// Parses a mode name, ignoring case and surrounding whitespace, so a choice
    /// arriving as text - from an argument, a form field, a settings file -
    /// needs no mapping table of its own.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::transport::probe::SendMode;
    ///
    /// assert_eq!("Ethernet".parse(), Ok(SendMode::Ethernet));
    /// assert!("layer2".parse::<SendMode>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_ascii_lowercase();
        Self::ALL
            .into_iter()
            .find(|mode| mode.name() == name)
            .ok_or_else(|| UnknownSendMode {
                input: s.to_string(),
            })
    }
}

/// Which kind of raw probe traffic a [`ProbeTransport`] carries. Determines
/// both the raw socket(s) opened for sending and the kernel BPF filter that
/// decides which captured frames are worth copying to userspace.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum ProbeKind {
    /// TCP SYN probes and their SYN+ACK / RST replies, over IPv4 and IPv6,
    /// where the sender picks a fresh source port per probe.
    TcpSyn,
    /// TCP port probes and their replies, for a scan that sends every probe
    /// from one source port.
    TcpProbe {
        /// The port every probe in the scan leaves from, and so the port its
        /// replies come back to. One fixed port is what makes the TCP half of
        /// this filter expressible for both address families: `dst port`
        /// compiles over IPv6 where the flag test in [`ProbeKind::TcpSyn`]
        /// cannot, so a scan using this kind sees only its own answers instead
        /// of every IPv6 TCP segment on the host.
        reply_port: u16,
        /// Whether ICMP destination-unreachable messages are wanted as well.
        ///
        /// They are how a probe learns it was stopped in the path rather than
        /// answered, but an ICMP error carries no ports of its own - the probe
        /// it refers to is quoted in its payload - so admitting them means
        /// admitting *all* ICMP on every captured interface and matching it in
        /// userspace. Only a scan whose verdicts actually change on that
        /// evidence should pay for it.
        icmp_errors: bool,
    },
    /// UDP service probes (DNS / mDNS) and their replies, over IPv4.
    UdpResolve,
    /// ICMP echo requests and the replies and errors they draw, over both
    /// address families.
    ///
    /// The kind a scan uses to ask a host something its TCP stack cannot be made
    /// to answer. A host with no open and no closed port still answers a ping,
    /// and what it puts in the reply is a property of the same stack.
    IcmpEcho {
        /// The identifier every echo in the scan carries, and so the one its
        /// replies carry back.
        ///
        /// RFC 792 and RFC 4443 §4.2 both require a reply to echo the
        /// identifier and sequence back unchanged, which is the only thing that
        /// separates this scan's answers from every other ping on the host.
        /// Unlike a port it cannot be expressed in a kernel filter, since it
        /// sits past a header whose length is not fixed over IPv6. So it is
        /// matched in userspace and this field is what a caller matches against.
        identifier: u16,
    },
    /// SCTP port probes and the chunks they draw, over both address families.
    ///
    /// One kind for both techniques: an INIT and a COOKIE-ECHO are the same
    /// protocol from the same port, so the filter that narrows to one narrows to
    /// the other.
    Sctp {
        /// The port every probe in the scan leaves from, and so the port its
        /// answers come back to.
        ///
        /// One fixed port for the same reason [`UdpProbe`](Self::UdpProbe) uses
        /// one: it is what the kernel filter narrows on, and it is what the
        /// packet quoted inside an ICMP error is checked against.
        reply_port: u16,
    },
    /// Bare datagrams of one arbitrary IP protocol, and the ICMP messages they
    /// draw.
    ///
    /// What an [IP protocol scan](crate::scanner::strategy::protocols) sends. The
    /// number is the next-header value the probe goes out under, and it is what
    /// the scan is asking about rather than a way of reaching something.
    ///
    /// It does not narrow the filter, which is the same expression for every
    /// number, because there is nothing to narrow on. Most of the protocols
    /// worth asking about have no header this crate parses, no ports and no
    /// reply of their own; what answers a probe is the host's ICMP, and an ICMP
    /// message carries no field naming what provoked it beyond the packet it
    /// quotes. So the errors are admitted whole and matched against the
    /// quotation in userspace, the way [`UdpProbe`](Self::UdpProbe) already
    /// matches its own.
    IpProtocol {
        /// The next-header value the probes carry, and the protocol the scan is
        /// asking whether the host takes delivery of.
        number: u8,
    },
    /// UDP port probes and their ICMP unreachable / direct UDP replies.
    UdpProbe {
        /// The source port every probe in the scan is sent from, and so the
        /// destination port its direct replies come back to. Sending from one
        /// fixed port is what lets the kernel filter the UDP half down to this
        /// scan's own traffic; without it the only expressible filter is "all
        /// UDP", which on a busy host is mostly other people's packets.
        reply_port: u16,
    },
}

impl ProbeKind {
    /// The raw-socket transport type used for the send half.
    fn transport_type(self) -> TransportType {
        match self {
            ProbeKind::TcpSyn | ProbeKind::TcpProbe { .. } => TransportType::TcpLayer4,
            ProbeKind::UdpResolve | ProbeKind::UdpProbe { .. } => TransportType::UdpLayer4,
            ProbeKind::Sctp { .. } => TransportType::SctpLayer4,
            ProbeKind::IcmpEcho { .. } => TransportType::IcmpLayer4,
            ProbeKind::IpProtocol { number } => TransportType::IpProtocol(number),
        }
    }

    /// The IP protocol numbers this kind's probes are, one per address family,
    /// for a sender that writes the IP header itself.
    ///
    /// The raw-socket path never needs this - the kernel derives it from the
    /// socket's protocol - but a Layer-2 sender builds the header by hand and
    /// has nothing else to read it from. A wrong number here is invisible
    /// locally and fatal remotely: the datagram arrives and is handed to the
    /// wrong protocol handler, so it is simply never answered.
    pub(crate) fn ip_protocols(self) -> IpProtocols {
        match self {
            ProbeKind::TcpSyn | ProbeKind::TcpProbe { .. } => {
                IpProtocols::same(IpNextHeaderProtocols::Tcp)
            }
            ProbeKind::UdpResolve | ProbeKind::UdpProbe { .. } => {
                IpProtocols::same(IpNextHeaderProtocols::Udp)
            }
            ProbeKind::Sctp { .. } => IpProtocols::same(IpNextHeaderProtocols::Sctp),
            // The one kind whose two families are different protocols rather
            // than one protocol over two address sizes.
            ProbeKind::IcmpEcho { .. } => IpProtocols {
                v4: IpNextHeaderProtocols::Icmp,
                v6: IpNextHeaderProtocols::Icmpv6,
            },
            // The one kind whose number is the question rather than the means,
            // and so the one a caller chooses outright.
            ProbeKind::IpProtocol { number } => IpProtocols::same(IpNextHeaderProtocol(number)),
        }
    }

    /// The `libpcap`/`tcpdump` filter expression compiled into a kernel BPF
    /// program for the receive half. Narrow by design: only the replies a
    /// scan can act on ever reach userspace.
    fn filter(self) -> String {
        match self {
            // SYN+ACK (open) and RST (closed) both set at least one of the
            // SYN/RST flag bits; nothing else a SYN probe can elicit does.
            //
            // The two families are narrowed differently because only one of
            // them can be. `tcp[tcpflags]` is `proto[x]` indexing, and an IPv6
            // next-header chain puts the transport header at no fixed offset,
            // so libpcap cannot compile it - and does not say so. Written as one
            // unqualified `tcp`, the expression is silently restricted to IPv4
            // and every IPv6 frame is rejected at the EtherType, which is what
            // made routed IPv6 discovery and IPv6 SYN port scanning find nothing
            // whatsoever. Writing `ip6` in front of the same test does not help;
            // it fails to compile outright.
            //
            // So the IPv6 half is admitted unnarrowed and the flags are checked
            // in userspace instead. The cost is that every IPv6 TCP segment on
            // every captured interface is copied up, not only the two a probe
            // can draw: on a host with live IPv6 connections that is real
            // traffic, and it lands in the audit's `off-target` count where it
            // can be seen. It buys the only IPv6 receive path there is.
            ProbeKind::TcpSyn => {
                "(ip and tcp and (tcp[tcpflags] & (tcp-syn|tcp-rst)) != 0) or (ip6 and tcp)"
                    .to_string()
            }
            // Every reply to a probe of this kind is addressed back to the one
            // port the scan sends from, so that is the whole narrowing - and it
            // is a narrowing both families get, which the flag test above is
            // not. What reaches userspace is this scan's own traffic rather
            // than every segment that happens to carry a SYN or RST bit.
            //
            // The flags are checked in userspace instead. That is not a
            // concession: a segment answering the right port still has to be
            // one of the two answers a probe can draw, and has to carry back
            // the value the probe went out with.
            ProbeKind::TcpProbe {
                reply_port,
                icmp_errors,
            } => {
                // Both directions, not only the replies. The outbound half is
                // the scan watching its own probes leave, which is the only
                // thing that distinguishes a port that stayed quiet from one
                // whose probe the operating system took and threw away: macOS
                // does exactly that to a raw-socket write under load, returns
                // success, and leaves a scan reporting silence from a port it
                // never asked. It costs one captured frame per probe, all of it
                // this scan's own traffic.
                let tcp = format!("tcp and port {reply_port}");
                // An ICMP error names no ports of its own; the probe it refers
                // to is quoted in its payload, so this half cannot be narrowed
                // here and is matched in userspace.
                if icmp_errors {
                    format!("icmp or icmp6 or ({tcp})")
                } else {
                    tcp
                }
            }
            // DNS (53) and mDNS (5353) responses, by source port.
            ProbeKind::UdpResolve => "udp and (src port 53 or src port 5353)".to_string(),
            // A UDP probe draws two kinds of answer. A direct UDP reply comes
            // back to the port the scan sent from, so it narrows to exactly
            // this scan. An ICMP error carries no ports of its own - the probe
            // it refers to is quoted in its payload - so ICMP cannot be
            // narrowed here and is matched in userspace instead.
            ProbeKind::UdpProbe { reply_port } => {
                format!("icmp or icmp6 or (udp and dst port {reply_port})")
            }
            // The ICMP halves of the two filters above, and nothing else. A
            // protocol probe's answer is an ICMP message about it or no answer
            // at all, so this admits every error and reads the quotation in
            // userspace; see [`ProbeKind::IpProtocol`] for what that costs the
            // pass and why the cost is the protocol landscape rather than this
            // expression.
            ProbeKind::IpProtocol { .. } => "icmp or icmp6".to_string(),
            // The same shape as the UDP filter, and for the same reasons: every
            // answer an INIT can draw comes back to the one port the scan sends
            // from, and an ICMP error carries no ports of its own, so the error
            // half is admitted whole and matched against the quoted probe in
            // userspace.
            ProbeKind::Sctp { reply_port } => {
                format!("icmp or icmp6 or (sctp and dst port {reply_port})")
            }
            // Unnarrowed, and it has to be. The identifier that separates this
            // scan's replies from every other ping on the host sits four bytes
            // into the ICMP message, which is `proto[x]` indexing: expressible
            // over IPv4 and not over IPv6, whose next-header chain puts the
            // message at no fixed offset. Narrowing one family and not the other
            // would make the IPv6 half of every scan silently different from the
            // IPv4 half, which is the shape of defect that cost this crate its
            // whole IPv6 receive path once already. So both halves come up whole
            // and the identifier is matched in userspace.
            //
            // The errors are wanted as well as the replies: a host answering an
            // echo with "administratively prohibited" has said something, and it
            // did not come from the host's own stack.
            ProbeKind::IcmpEcho { .. } => "icmp or icmp6".to_string(),
        }
    }
}

/// Why one probe could not be put on the wire.
///
/// Two variants, because two things are worth telling apart and nothing else is.
/// [`Unsupported`](Self::Unsupported) is a fact about this transport that will
/// be just as true for the next probe, so retrying is pointless and a scan should
/// give up on the path. [`Refused`](Self::Refused) came from outside and may not
/// hold next time: a full send buffer clears, a route appears.
///
/// The refusal carries the operating system's own words rather than a
/// classification of them. "No route to host" and "Permission denied" call for
/// completely different responses from whoever is reading the report, and no
/// enum this crate could write would keep pace with what a kernel actually says.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum SendError {
    /// This host has no route to that address.
    ///
    /// Separated from [`Refused`](Self::Refused) because it is a fact about the
    /// *destination* rather than about this scanner or its socket, and the two
    /// call for opposite responses. A send path that will not work is a strategy
    /// that did not run, and a caller has to be told the scan covered less than
    /// it was asked to. An address with no route is ordinary: a dual-stack name
    /// on an IPv4-only network resolves to an AAAA nobody here can reach, and
    /// reporting that as a broken scan makes every such scan look partial.
    ///
    /// Still an error and still reported, the address having been asked about and
    /// not covered, but as something known about that address.
    #[error("{0}")]
    Unroutable(String),

    /// The host would not send the packet, in its own words.
    #[error("{0}")]
    Refused(String),

    /// This transport cannot express the probe it was handed, and will not be
    /// able to next time either.
    #[error("this transport cannot send that probe: {0}")]
    Unsupported(&'static str),
}

impl SendError {
    /// Classifies a failure from a lower layer, keeping its whole cause chain.
    ///
    /// Walks `source()` rather than a single message, so a wrapper naming which
    /// probe failed does not hide the operating system's own explanation
    /// underneath it. `thiserror`'s `#[error]` strings already interpolate their
    /// source, so the text is the whole chain.
    ///
    /// Reads the operating system's own error kind rather than matching on the
    /// text of its message, which differs per platform and per locale. Only the
    /// two unreachable kinds are singled out; everything else stays a refusal,
    /// including the ones that look similar: a full send buffer or a permission
    /// failure says nothing about whether the destination exists.
    pub(crate) fn from_io<E: std::error::Error + 'static>(error: E) -> Self {
        let unroutable = std::iter::successors(Some(&error as &dyn std::error::Error), |cause| {
            cause.source()
        })
        .any(|cause| {
            cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
                matches!(
                    io.kind(),
                    std::io::ErrorKind::HostUnreachable | std::io::ErrorKind::NetworkUnreachable
                )
            })
        });

        if unroutable {
            Self::Unroutable(error.to_string())
        } else {
            Self::Refused(error.to_string())
        }
    }

    /// Whether this failure is about the destination rather than about the
    /// sending host.
    ///
    /// What separates "the scan could not run" from "that address is not
    /// reachable from here", which are reported differently and should be.
    pub fn is_unroutable(&self) -> bool {
        matches!(self, Self::Unroutable(_))
    }
}

/// What a caller decides about the IP header carrying a probe, as opposed to
/// what the packet itself decides.
///
/// Addresses, protocol number, lengths and checksums all follow from the probe
/// and its destination, so a sender derives them. What is left is the handful of
/// header fields nothing downstream can infer, and today that is exactly one:
/// how far the probe may travel.
///
/// It is a value rather than a bare `u8` because it is the seam every remaining
/// per-probe header choice arrives through, whether fragmentation or IP options
/// or a deliberately wrong checksum, and each of those should widen this struct
/// rather than the signature of every sender in the crate a second time.
///
/// Both backends can honour it, by different means: the link-layer sender is
/// already building the header and simply writes the field, while the raw-socket
/// sender sets it on the socket before the send, under the lock that serialises
/// sends anyway. See [`raw::TransportSenderHandle::send_to`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Emission {
    /// How many hops the probe may cross before a router discards it and
    /// reports having done so.
    pub hop_limit: u8,
    /// The hardware address the frame claims to come from, or `None` for the
    /// sending interface's own. Only a self-built Ethernet frame can carry it,
    /// so an emission with this set cannot be sent over a raw socket. See
    /// [`requires_link_layer`](Self::requires_link_layer).
    pub source_mac: Option<MacAddr>,
    /// The largest each IP fragment this probe is split into may be, in bytes,
    /// or `None` to send it whole. Only a self-built Ethernet frame carries
    /// fragments this engine chose, for either address family. See
    /// [`requires_link_layer`](Self::requires_link_layer).
    pub fragment: Option<u16>,
}

impl Emission {
    /// What an ordinary probe wants: far enough for any path on the public
    /// internet. See [`ip::HOP_LIMIT_ROUTED`](crate::protocols::ip::HOP_LIMIT_ROUTED).
    pub const fn routed() -> Self {
        Self {
            hop_limit: crate::protocols::ip::HOP_LIMIT_ROUTED,
            source_mac: None,
            fragment: None,
        }
    }

    /// A probe built to die `hops` routers away, so that the router which
    /// discards it names itself in the error it must send back.
    ///
    /// The whole of how a path is measured. A hop limit of zero would be
    /// discarded by this host's own stack before it reached a wire, so it is
    /// raised to one, the first router, rather than silently sending nothing.
    pub const fn at_hop(hops: u8) -> Self {
        Self {
            hop_limit: if hops == 0 { 1 } else { hops },
            source_mac: None,
            fragment: None,
        }
    }

    /// The same emission with its hop limit replaced. Carries an evasion
    /// profile's chosen hop limit; path measurement sets its own with
    /// [`at_hop`](Self::at_hop) instead.
    #[must_use]
    pub const fn with_hop_limit(mut self, hop_limit: u8) -> Self {
        self.hop_limit = hop_limit;
        self
    }

    /// The same emission sent from a spoofed hardware address. Only a self-built
    /// Ethernet frame can carry it; see
    /// [`requires_link_layer`](Self::requires_link_layer).
    #[must_use]
    pub const fn with_source_mac(mut self, source_mac: MacAddr) -> Self {
        self.source_mac = Some(source_mac);
        self
    }

    /// The same emission split into IP fragments no larger than `mtu` bytes.
    /// Only a self-built Ethernet frame can carry the fragments, for either
    /// address family; see [`requires_link_layer`](Self::requires_link_layer).
    #[must_use]
    pub const fn with_fragment(mut self, mtu: u16) -> Self {
        self.fragment = Some(mtu);
        self
    }

    /// Whether this emission can only leave as a self-built Ethernet frame,
    /// because it sets a field a raw socket cannot place: a spoofed source
    /// hardware address, or fragments this engine chose rather than the kernel.
    #[must_use]
    pub const fn requires_link_layer(&self) -> bool {
        self.source_mac.is_some() || self.fragment.is_some()
    }
}

impl Default for Emission {
    fn default() -> Self {
        Self::routed()
    }
}

/// Sends an already-built Layer-4 `segment` to `dst`.
///
/// `src` is the source address the segment's checksum was computed against;
/// a raw-socket sender lets the kernel stamp it into the IP header, while a
/// link-layer sender uses it to build the header itself. `emission` is what the
/// caller decides about that header; see [`Emission`]. Implementations must be
/// safe to share across threads.
pub trait ProbeSender: Send + Sync {
    /// Emits one probe, or names why it did not leave.
    ///
    /// `zone` is the interface a link-local `dst` is valid on, and `None` for
    /// every address that identifies its host on its own. `fe80::1` names a
    /// different machine on every segment, so a sender given one without a zone
    /// has no destination it can reach.
    ///
    /// [`SendError::Unroutable`] says something about `dst` rather than about
    /// this sender: that address was asked about and not covered, while the
    /// sender itself is still working.
    fn send(
        &self,
        segment: &[u8],
        src: IpAddr,
        dst: IpAddr,
        zone: Option<u32>,
        emission: Emission,
    ) -> Result<(), SendError>;
}

/// The IP protocol number a kind's probes carry, per address family.
///
/// A pair rather than one value because [`ProbeKind::IcmpEcho`] is two
/// protocols: ICMP is next-header 1 and ICMPv6 is 58. Every other kind names the
/// same protocol twice, which [`same`](Self::same) says out loud rather than
/// leaving to a reader to notice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IpProtocols {
    /// What an IPv4 header carrying this kind's probes says it carries.
    pub v4: IpNextHeaderProtocol,
    /// What an IPv6 header carrying this kind's probes says it carries.
    pub v6: IpNextHeaderProtocol,
}

impl IpProtocols {
    /// One protocol under both families.
    pub const fn same(protocol: IpNextHeaderProtocol) -> Self {
        Self {
            v4: protocol,
            v6: protocol,
        }
    }

    /// The number to stamp into a header addressed to `destination`.
    pub const fn for_destination(self, destination: IpAddr) -> IpNextHeaderProtocol {
        match destination {
            IpAddr::V4(_) => self.v4,
            IpAddr::V6(_) => self.v6,
        }
    }
}

/// Why a probe transport could not be opened.
///
/// Named by the half that failed, because the two halves fail for different
/// reasons and only one of them has an alternative. A scan that cannot capture
/// has nowhere to hear an answer and is over; a scan that cannot open its send
/// socket may still have a link-layer path, which is what [`SendMode`] selects.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum TransportError {
    /// The receive half could not be started.
    #[error("the reply capture could not be started: {0}")]
    Capture(#[from] capture::CaptureError),

    /// The raw send socket could not be opened. Needs root, and on Windows raw
    /// TCP sends are blocked outright whatever the privileges.
    #[error("the raw send socket could not be opened: {0}")]
    RawSocket(String),

    /// Layer-2 sending was asked for and this host has nothing to send from,
    /// holding only tunnels or loopback. The raw-socket path works here.
    #[error("no Ethernet-capable interface for Layer-2 send: {0}")]
    NoEthernetInterface(String),
}

/// A borrowed Layer-4 segment presented as a `pnet` packet, so raw bytes can
/// be handed straight to a `TransportSender` without a copy or a typed
/// wrapper. The whole slice is the packet; it has no distinct payload of its
/// own as far as the transport is concerned.
struct RawSegment<'a>(&'a [u8]);

impl Packet for RawSegment<'_> {
    fn packet(&self) -> &[u8] {
        self.0
    }
    fn payload(&self) -> &[u8] {
        &[]
    }
}

/// The default sender: emits segments over a raw Layer-4 socket and lets the
/// kernel route them. Correct on Linux and macOS alike, for both on-link and
/// off-link destinations, with no ARP/NDP or gateway bookkeeping of its own.
pub struct RawIpSender {
    handle: TransportSenderHandle,
}

impl RawIpSender {
    fn open(kind: ProbeKind) -> Result<Self, TransportError> {
        raw::open_sender(kind.transport_type())
            .map(|handle| Self { handle })
            .map_err(|e| TransportError::RawSocket(format!("{e:#}")))
    }
}

impl ProbeSender for RawIpSender {
    fn send(
        &self,
        segment: &[u8],
        _src: IpAddr,
        dst: IpAddr,
        zone: Option<u32>,
        emission: Emission,
    ) -> Result<(), SendError> {
        // The kernel builds the IP header and the frame around it here, so a
        // field only a self-built frame can carry, such as a spoofed hardware
        // address, cannot be honoured. Refused with the reason rather than sent
        // without
        // it, so a scan that reports it spoofed did.
        if emission.requires_link_layer() {
            return Err(SendError::Unsupported(
                "this emission sets a field only a self-built Ethernet frame can carry",
            ));
        }
        self.handle
            .send_to(RawSegment(segment), dst, zone, emission.hop_limit)
            .map(|_| ())
            .map_err(SendError::from_io)
    }
}

/// Builds its own Ethernet frames, and falls back to the raw socket for the
/// destinations [`EthernetSender`] cannot frame: on-link IPv6 (no NDP),
/// loopback, and tunnels.
///
/// The macOS default. There the raw socket accepts a quarter of a large scan's
/// sends and drops them before the wire, where a self-built frame goes out. An
/// emission only a frame can carry is not retried through the socket, which
/// would send a different probe than the one asked for.
struct LinkLayerFirst {
    link: EthernetSender,
    socket: RawIpSender,
}

impl ProbeSender for LinkLayerFirst {
    fn send(
        &self,
        segment: &[u8],
        src: IpAddr,
        dst: IpAddr,
        zone: Option<u32>,
        emission: Emission,
    ) -> Result<(), SendError> {
        let framed = self.link.send(segment, src, dst, zone, emission);
        if framed.is_ok() || emission.requires_link_layer() {
            return framed;
        }
        self.socket.send(segment, src, dst, zone, emission)
    }
}

/// A sender that refuses to send. Paired with a capture for receive-only
/// transports (the DNS/mDNS resolver only listens), so no raw send socket is
/// opened just to be thrown away - and a stray send attempt fails loudly
/// rather than silently doing nothing.
struct NoopSender;

impl ProbeSender for NoopSender {
    fn send(
        &self,
        _segment: &[u8],
        _src: IpAddr,
        _dst: IpAddr,
        _zone: Option<u32>,
        _emission: Emission,
    ) -> Result<(), SendError> {
        Err(SendError::Unsupported("it is receive-only"))
    }
}

/// A probe transport: a swappable sender paired with a capture-fed receive
/// stream. Scanners hold one of these and depend only on [`ProbeTransport::tx`]
/// and [`ProbeTransport::rx`], never on how either is realized.
pub struct ProbeTransport {
    /// The send half. Boxed so the backend (raw socket today, Ethernet later)
    /// can vary without touching callers.
    pub tx: Box<dyn ProbeSender>,
    /// Parsed replies ([`capture::CapturedSegment`]), merged across every
    /// captured interface.
    pub rx: CaptureStream,
    /// Keeps the capture threads alive for this transport's lifetime, and holds
    /// the counters they publish.
    capture: CaptureGuard,
}

impl ProbeTransport {
    /// What the receive path's kernel buffers have done so far, summed over
    /// every interface this transport captures on.
    ///
    /// A scanner reports this alongside its own counters because the two answer
    /// different halves of the same question. The scanner knows how many replies
    /// it saw; only this knows how many arrived and were thrown away before it
    /// could. `None` for a transport with no capture behind it, so a synthetic
    /// receive stream never reports a clean receive path it never had.
    pub fn capture_counts(&self) -> Option<CaptureCounts> {
        self.capture.counts()
    }
    /// Opens a transport for `kind` with the platform-default send backend
    /// ([`SendMode::Auto`]).
    pub fn open(kind: ProbeKind) -> Result<Self, TransportError> {
        Self::open_with(kind, SendMode::Auto)
    }

    /// Opens a transport for `kind`, choosing the send backend per `mode`.
    ///
    /// All modes pair with a filtered `libpcap` capture on every currently-up
    /// interface. Capturing on all of them (loopback included) means a reply
    /// is caught whichever interface the kernel routed the probe out of - the
    /// egress path can differ per destination, especially with a VPN in play,
    /// so binding to a single guessed interface would silently miss replies.
    pub fn open_with(kind: ProbeKind, mode: SendMode) -> Result<Self, TransportError> {
        match mode {
            SendMode::Ethernet => Self::open_ethernet(kind),
            SendMode::RawSocket => Self::open_on(kind, &capturable_interfaces()),
            // Windows blocks raw-socket TCP sends; macOS accepts them and drops
            // a quarter silently. Elsewhere the raw socket reaches everything
            // without ARP. See [`LinkLayerFirst`].
            SendMode::Auto => {
                #[cfg(windows)]
                {
                    Self::open_ethernet(kind)
                }
                #[cfg(target_os = "macos")]
                {
                    Self::open_link_first(kind)
                }
                #[cfg(not(any(windows, target_os = "macos")))]
                {
                    Self::open_on(kind, &capturable_interfaces())
                }
            }
        }
    }

    /// [`open`](Self::open) against an explicit list of links.
    pub fn open_on(kind: ProbeKind, links: &[Zone]) -> Result<Self, TransportError> {
        let (rx, capture) = capture::segments(
            links,
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        let tx: Box<dyn ProbeSender> = Box::new(RawIpSender::open(kind)?);
        Ok(Self { tx, rx, capture })
    }

    /// A `LinkLayerFirst` transport: frames what it can, raw socket for the
    /// rest. The macOS default. A host with no Ethernet interface gets the
    /// plain raw-socket transport, which is all the fallback would do anyway.
    pub fn open_link_first(kind: ProbeKind) -> Result<Self, TransportError> {
        let Some(link) = EthernetSender::from_system(kind.ip_protocols()) else {
            return Self::open_on(kind, &capturable_interfaces());
        };
        let (rx, capture) = capture::segments(
            &capturable_interfaces(),
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        Ok(Self {
            tx: Box::new(LinkLayerFirst {
                link,
                socket: RawIpSender::open(kind)?,
            }),
            rx,
            capture,
        })
    }

    /// Opens a transport whose send half builds and emits Ethernet frames
    /// directly ([`EthernetSender`]) instead of using a raw socket.
    ///
    /// For Windows (where raw TCP sends are blocked) and for deliberately
    /// bypassing the host stack. Fails if the host has no Ethernet-capable
    /// interface - only a tunnel or loopback - in which case the raw-IP
    /// transport from [`open`](Self::open) is the correct choice.
    pub fn open_ethernet(kind: ProbeKind) -> Result<Self, TransportError> {
        let sender = EthernetSender::from_system(kind.ip_protocols()).ok_or_else(|| {
            TransportError::NoEthernetInterface(
                "the host has only tunnel or loopback interfaces".to_string(),
            )
        })?;
        let (rx, capture) = capture::segments(
            &capturable_interfaces(),
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        Ok(Self {
            tx: Box::new(sender),
            rx,
            capture,
        })
    }

    /// Opens a receive-only transport: a filtered capture on every up
    /// interface, with a sender that refuses to send.
    ///
    /// For consumers that only listen - the passive DNS/mDNS resolver never
    /// emits raw packets - so no raw send socket is opened. That drops an
    /// unnecessary privilege requirement and failure mode (a host that blocks
    /// raw sockets can still resolve hostnames).
    pub fn open_receiver(kind: ProbeKind) -> Result<Self, TransportError> {
        let (rx, capture) = capture::segments(
            &capturable_interfaces(),
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        Ok(Self {
            tx: Box::new(NoopSender),
            rx,
            capture,
        })
    }

    /// Builds a transport from an explicit sender and receive stream, opening
    /// no socket and no capture.
    ///
    /// This is the seam that lets a test stand a scanner up against a synthetic
    /// network: `tx` observes the probes the scanner emits, and whatever is
    /// pushed onto the sending half of `rx` arrives as though it had been
    /// captured off the wire. Because no capture threads exist, the transport
    /// holds an inert [`CaptureGuard`] and dropping it stops nothing.
    ///
    /// Requires the `test-support` feature outside this crate.
    #[cfg(any(test, feature = "test-support"))]
    pub fn from_parts(tx: Box<dyn ProbeSender>, rx: CaptureStream) -> Self {
        Self {
            tx,
            rx,
            capture: CaptureGuard::noop(),
        }
    }
}

/// The interfaces a capture should listen on: every interface that's up, and
/// loopback whether or not it admits to being.
///
/// Loopback needs naming separately because
/// [`is_up`](crate::system::interface::Link::is_up) wants a carrier as well as
/// an administrative flag, and loopback has no carrier to report - Linux leaves
/// its operational state `unknown` for the life of the machine. That conjunction
/// is the right question for deciding what to *probe out of*, which is what it
/// was written for; here the question is only what to listen on, and answering
/// the first one drops `lo`, so every localhost probe goes out and none is ever
/// heard back.
///
/// Each is named as a [`Zone`], carrying the index alongside the name. The
/// index costs nothing to keep here, the interface table having been read to find
/// the name, and it is what a finding scoped to a link needs, since a
/// link-local address names a different machine on every one of them.
fn capturable_interfaces() -> Vec<Zone> {
    crate::system::interface::interfaces()
        .into_iter()
        .filter(|link| link.is_up() || link.is_loopback())
        .map(|link| link.zone())
        .collect()
}

/// A record of one recorded send: `(segment, source, destination)`.
#[cfg(test)]
pub type SentProbe = (Vec<u8>, IpAddr, IpAddr);

/// A [`ProbeSender`] that records what it was asked to send instead of
/// touching a socket, so transport wiring and scanner logic can be exercised
/// without root. Available crate-wide under `cfg(test)`.
#[cfg(test)]
#[derive(Clone, Default)]
pub struct MockSender {
    /// Every probe handed to [`send`](ProbeSender::send), oldest first. Shared,
    /// so a clone of the sender given to a scanner reads the same list.
    pub sent: std::sync::Arc<std::sync::Mutex<Vec<SentProbe>>>,
}

#[cfg(test)]
impl ProbeSender for MockSender {
    fn send(
        &self,
        segment: &[u8],
        src: IpAddr,
        dst: IpAddr,
        _zone: Option<u32>,
        _emission: Emission,
    ) -> Result<(), SendError> {
        self.sent.lock().unwrap().push((segment.to_vec(), src, dst));
        Ok(())
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

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

    #[tokio::test]
    async fn transport_forwards_sends_and_delivers_replies() {
        use crate::transport::capture::CapturedSegment;
        use std::net::Ipv4Addr;

        let mock = MockSender::default();
        let recorded = mock.sent.clone();
        let (reply_tx, reply_rx) = tokio::sync::mpsc::channel(1024);
        let mut transport = ProbeTransport::from_parts(Box::new(mock), reply_rx);

        let src = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2));
        let dst = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
        transport
            .tx
            .send(&[0xAA, 0xBB], src, dst, None, Emission::routed())
            .unwrap();

        let sent = recorded.lock().unwrap().clone();
        assert_eq!(sent, vec![(vec![0xAA, 0xBB], src, dst)]);

        // A reply pushed onto the capture stream is observed on rx unchanged.
        let reply = CapturedSegment::synthetic(
            dst,
            pnet_packet::ip::IpNextHeaderProtocols::Udp,
            vec![1, 2, 3],
        );
        reply_tx.send(reply.clone()).await.unwrap();
        assert_eq!(transport.rx.recv().await, Some(reply));
    }

    /// The fallback is what keeps the macOS default from costing reach. The
    /// frame path cannot resolve an on-link IPv6 neighbour and has no route to
    /// loopback, and those destinations have to keep working: they were the
    /// reason the raw socket was the default everywhere.
    #[test]
    fn a_destination_the_frame_path_cannot_reach_goes_through_the_socket() {
        let refusing = RefusingSender(SendError::Unsupported("no NDP here"));
        let socket = MockSender::default();
        let sent = socket.sent.clone();

        let result = send_through_fallback(&refusing, &socket, Emission::routed());

        assert!(result.is_ok(), "the socket served it: {result:?}");
        assert_eq!(sent.lock().unwrap().len(), 1);
    }

    /// A probe carrying a field only a self-built frame can express is not
    /// retried through the socket. Sending it that way would put a different
    /// probe on the wire and report it as the one that was asked for.
    #[test]
    fn a_probe_only_a_frame_can_carry_is_never_retried_through_the_socket() {
        let refusing = RefusingSender(SendError::Refused("the link went down".to_string()));
        let socket = MockSender::default();
        let sent = socket.sent.clone();

        let spoofed = Emission {
            source_mac: Some(crate::model::mac::MacAddr::new(2, 0, 0, 0, 0, 1)),
            ..Emission::routed()
        };
        assert!(spoofed.requires_link_layer(), "test premise");

        let result = send_through_fallback(&refusing, &socket, spoofed);

        assert!(result.is_err(), "the refusal stands");
        assert!(
            sent.lock().unwrap().is_empty(),
            "and nothing went out the other way"
        );
    }

    /// A sender that always fails the same way, for exercising the fallback.
    struct RefusingSender(SendError);

    impl ProbeSender for RefusingSender {
        fn send(
            &self,
            _segment: &[u8],
            _src: IpAddr,
            _dst: IpAddr,
            _zone: Option<u32>,
            _emission: Emission,
        ) -> Result<(), SendError> {
            Err(match &self.0 {
                SendError::Unsupported(why) => SendError::Unsupported(why),
                SendError::Refused(why) => SendError::Refused(why.clone()),
                SendError::Unroutable(why) => SendError::Unroutable(why.clone()),
            })
        }
    }

    /// [`LinkLayerFirst::send`]'s rule, over two senders a test can drive.
    /// The type itself holds concrete backends, and what is worth testing is
    /// when it reaches for the second one.
    fn send_through_fallback(
        link: &dyn ProbeSender,
        socket: &dyn ProbeSender,
        emission: Emission,
    ) -> Result<(), SendError> {
        let src = IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, 1));
        let dst = IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, 9));
        let framed = link.send(&[0xAA], src, dst, None, emission);
        if framed.is_ok() || emission.requires_link_layer() {
            return framed;
        }
        socket.send(&[0xAA], src, dst, None, emission)
    }

    /// A Layer-2 sender writes the IP header itself and has nothing but this to
    /// read the protocol number from. Announcing a UDP probe as TCP is
    /// invisible locally and fatal remotely - the target's stack hands it to
    /// the wrong protocol handler, so it is simply never answered.
    #[test]
    fn every_probe_kind_carries_its_own_ip_protocol() {
        assert_eq!(
            ProbeKind::TcpSyn.ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Tcp)
        );
        assert_eq!(
            ProbeKind::TcpProbe {
                reply_port: 50_000,
                icmp_errors: true,
            }
            .ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Tcp)
        );
        assert_eq!(
            ProbeKind::UdpResolve.ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Udp)
        );
        assert_eq!(
            ProbeKind::UdpProbe { reply_port: 40_000 }.ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Udp)
        );
    }

    /// ICMP is the one kind whose families are different protocols, and the
    /// number is chosen by the destination rather than by the kind.
    ///
    /// Pinned because getting it wrong is silent: an ICMPv6 message announced as
    /// protocol 1 is delivered to a handler that will not recognise it, and the
    /// probe simply goes unanswered. A scan reading that as "the host did not
    /// reply" is wrong about the host.
    #[test]
    fn an_icmp_probe_names_a_different_protocol_per_family() {
        let protocols = ProbeKind::IcmpEcho { identifier: 1 }.ip_protocols();
        assert_eq!(protocols.v4, IpNextHeaderProtocols::Icmp);
        assert_eq!(protocols.v6, IpNextHeaderProtocols::Icmpv6);
        assert_eq!(
            protocols.for_destination(IpAddr::from([192, 0, 2, 1])),
            IpNextHeaderProtocols::Icmp
        );
        assert_eq!(
            protocols.for_destination("2001:db8::1".parse().unwrap()),
            IpNextHeaderProtocols::Icmpv6
        );
    }

    /// The ICMP filter admits both families whole.
    ///
    /// The echo identifier is what separates this scan's replies from every
    /// other ping on the host, and it cannot be expressed here: it sits past a
    /// header whose length is not fixed over IPv6. Narrowing the IPv4 half alone
    /// would leave the two families behaving differently for no reason a reader
    /// could see, which is exactly how this crate lost its IPv6 receive path
    /// once before.
    #[test]
    fn the_icmp_filter_admits_both_families() {
        assert_eq!(
            ProbeKind::IcmpEcho { identifier: 4242 }.filter(),
            "icmp or icmp6"
        );
    }

    /// The UDP filter must narrow direct replies to the scan's own source port,
    /// while leaving ICMP unnarrowed - an ICMP error carries no port to match on.
    #[test]
    fn udp_probe_filter_narrows_replies_to_the_scan_source_port() {
        let filter = ProbeKind::UdpProbe { reply_port: 54_321 }.filter();
        assert_eq!(filter, "icmp or icmp6 or (udp and dst port 54321)");
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Filter conformance
// ══════════════════════════════════════════════════════════════════════════════

/// What each [`ProbeKind`]'s filter actually admits, judged by `libpcap` rather
/// than by reading the expression.
///
/// These are the only tests in the crate that exercise the receive path's real
/// gatekeeper. Every scanner test drives a synthetic transport through
/// [`ProbeTransport::from_parts`], which opens no capture and therefore compiles
/// no filter: a reply pushed onto that stream arrives whatever the filter would
/// have done with it. So a scanner test can pass against a simulated network
/// while the same scan on a real one sees nothing at all, and the only way to
/// tell is to compile the expression and put a frame through it.
///
/// The evaluation is `libpcap`'s own `pcap_offline_filter` running the compiled
/// program - the same program the kernel is handed - over a frame built by this
/// crate's own packet builders. Nothing here re-implements a filter or a parser,
/// which is the point: an instrument that made the same assumptions as the code
/// it measures would confirm whatever the code already believed.
#[cfg(test)]
mod filter_conformance {
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

    use pnet_base::MacAddr;
    use pnet_packet::icmpv6::{Icmpv6Code, Icmpv6Types, MutableIcmpv6Packet};
    use pnet_packet::ip::IpNextHeaderProtocols;
    use pnet_packet::tcp::MutableTcpPacket;

    use super::ProbeKind;
    use crate::protocols::udp;
    use crate::transport::frame::{FrameSpec, build_ethernet_frame};

    const SRC_V4: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
    const DST_V4: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 20));
    const SRC_V6: IpAddr = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x10));
    const DST_V6: IpAddr = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x20));

    const SYN: u8 = 1 << 1;
    const RST: u8 = 1 << 2;
    const ACK: u8 = 1 << 4;

    const TCP_HDR_LEN: usize = 20;
    const ICMPV6_UNUSED_LEN: usize = 4;

    /// The single port a [`ProbeKind::TcpProbe`] scan sends from, and so the
    /// port its answers come back to.
    const SCAN_PORT: u16 = 50_000;

    /// Whether `filter`, compiled for an Ethernet link, admits `frame`.
    ///
    /// A dead capture is a compiler with no interface behind it, so this needs
    /// neither privileges nor a network.
    fn admits(filter: &str, frame: &[u8]) -> bool {
        let capture = pcap::Capture::dead(pcap::Linktype::ETHERNET)
            .expect("opening a dead capture for the Ethernet link type");
        let program = capture
            .compile(filter, true)
            .unwrap_or_else(|e| panic!("compiling `{filter}`: {e}"));
        program.filter(frame)
    }

    /// An Ethernet-framed TCP segment carrying `flags`, over whichever family
    /// `src` and `dst` are, addressed back to the port a scan sent from.
    fn tcp_frame(src: IpAddr, dst: IpAddr, flags: u8) -> Vec<u8> {
        tcp_frame_to(src, dst, flags, SCAN_PORT)
    }

    /// [`tcp_frame`] addressed to an explicit port, for the filters that narrow
    /// on one.
    fn tcp_frame_to(src: IpAddr, dst: IpAddr, flags: u8, dst_port: u16) -> Vec<u8> {
        let mut segment = vec![0u8; TCP_HDR_LEN];
        {
            let mut tcp = MutableTcpPacket::new(&mut segment).expect("TCP header buffer");
            tcp.set_source(443);
            tcp.set_destination(dst_port);
            tcp.set_data_offset((TCP_HDR_LEN / 4) as u8);
            tcp.set_flags(flags);
            tcp.set_window(1024);
        }
        frame(src, dst, IpNextHeaderProtocols::Tcp, &segment)
    }

    /// An Ethernet-framed UDP datagram between the given ports.
    fn udp_frame(src: IpAddr, dst: IpAddr, src_port: u16, dst_port: u16) -> Vec<u8> {
        let segment = udp::build_packet(src, dst, src_port, dst_port, vec![0u8; 4])
            .expect("building a UDP datagram");
        frame(src, dst, IpNextHeaderProtocols::Udp, &segment)
    }

    /// An Ethernet-framed SCTP packet between the given ports, carrying the
    /// chunk a probe draws back.
    fn sctp_frame(src: IpAddr, dst: IpAddr, src_port: u16, dst_port: u16) -> Vec<u8> {
        let packet = crate::protocols::sctp::build_init_probe(src_port, dst_port, 0xDEAD_BEEF);
        frame(src, dst, IpNextHeaderProtocols::Sctp, &packet)
    }

    /// An Ethernet-framed ICMPv6 destination-unreachable, the shape a UDP probe
    /// draws from a closed port over IPv6.
    fn icmpv6_error_frame(src: IpAddr, dst: IpAddr) -> Vec<u8> {
        let mut segment = vec![0u8; MutableIcmpv6Packet::minimum_packet_size() + ICMPV6_UNUSED_LEN];
        {
            let mut icmp = MutableIcmpv6Packet::new(&mut segment).expect("ICMPv6 header buffer");
            icmp.set_icmpv6_type(Icmpv6Types::DestinationUnreachable);
            icmp.set_icmpv6_code(Icmpv6Code(4));
        }
        frame(src, dst, IpNextHeaderProtocols::Icmpv6, &segment)
    }

    fn frame(
        src: IpAddr,
        dst: IpAddr,
        protocol: pnet_packet::ip::IpNextHeaderProtocol,
        segment: &[u8],
    ) -> Vec<u8> {
        build_ethernet_frame(
            &FrameSpec {
                src_mac: MacAddr::new(0x02, 0, 0, 0, 0, 0x02),
                dst_mac: MacAddr::new(0x02, 0, 0, 0, 0, 0x01),
                src,
                dst,
                protocol,
                hop_limit: crate::protocols::ip::HOP_LIMIT_ROUTED,
            },
            segment,
        )
        .expect("building an Ethernet frame")
    }

    /// The two send failures that call for opposite responses are told apart by
    /// the operating system's error kind, not by its wording.
    ///
    /// A message's text differs per platform and per locale, and matching on it
    /// is how a classification silently stops working on somebody else's
    /// machine. Only the two unreachable kinds are singled out: a full buffer or
    /// a permission failure says nothing about whether the destination exists,
    /// and treating either as unroutable would hide a scan that genuinely could
    /// not run.
    #[test]
    fn a_destination_with_no_route_is_not_a_broken_send_path() {
        use super::SendError;
        use std::io::{Error, ErrorKind};

        for kind in [ErrorKind::HostUnreachable, ErrorKind::NetworkUnreachable] {
            let error = SendError::from_io(Error::new(
                kind,
                "failed to send to 2001:db8::1: No route to host",
            ));
            assert!(error.is_unroutable(), "{kind:?} is about the destination");
            assert!(
                error.to_string().contains("2001:db8::1"),
                "the address survives the classification: {error}"
            );
        }

        for kind in [
            ErrorKind::PermissionDenied,
            ErrorKind::WouldBlock,
            ErrorKind::BrokenPipe,
        ] {
            let error = SendError::from_io(Error::new(kind, "nope"));
            assert!(
                !error.is_unroutable(),
                "{kind:?} is about this host, not the destination"
            );
        }
    }

    // ─── TCP SYN ─────────────────────────────────────────────────────────────

    #[test]
    fn the_syn_filter_admits_the_two_answers_a_syn_probe_draws_over_ipv4() {
        let filter = ProbeKind::TcpSyn.filter();

        assert!(
            admits(&filter, &tcp_frame(SRC_V4, DST_V4, SYN | ACK)),
            "a SYN+ACK is an open port and must reach the scanner"
        );
        assert!(
            admits(&filter, &tcp_frame(SRC_V4, DST_V4, RST | ACK)),
            "a RST is a closed port and must reach the scanner"
        );
    }

    /// The filter exists to keep unrelated traffic out of userspace, so an
    /// established connection's segments must not reach the scanner.
    #[test]
    fn the_syn_filter_rejects_established_traffic_over_ipv4() {
        assert!(!admits(
            &ProbeKind::TcpSyn.filter(),
            &tcp_frame(SRC_V4, DST_V4, ACK)
        ));
    }

    /// The gap this module was written to expose, and the assertion that says
    /// it is closed.
    ///
    /// `tcp[tcpflags]` is `proto[x]` indexing, which `libpcap` cannot compile
    /// over IPv6 - the next-header chain makes the offset non-constant. It does
    /// not report that; written unqualified it silently narrows the whole
    /// expression to IPv4, and the compiled program jumps straight to `ret #0`
    /// on EtherType `0x86dd`. Since the capture is the only receive path, that
    /// left routed IPv6 discovery and IPv6 SYN port scanning seeing no replies
    /// whatsoever.
    #[test]
    fn the_syn_filter_admits_the_same_answers_over_ipv6() {
        let filter = ProbeKind::TcpSyn.filter();

        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, SYN | ACK)));
        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, RST | ACK)));
    }

    /// What admitting the IPv6 half unnarrowed actually costs, stated as a
    /// property rather than discovered later in a packet count.
    ///
    /// An established IPv6 connection's segments reach userspace, where the
    /// IPv4 equivalent is dropped by the kernel. Nothing can be done about that
    /// at the filter - see [`libpcap_cannot_narrow_tcp_flags_over_ipv6`] - so
    /// the scanners re-check the flags themselves, and this test exists so that
    /// asymmetry is written down where the filter is, not inferred from a
    /// scanner three modules away.
    #[test]
    fn the_ipv6_half_of_the_syn_filter_is_not_narrowed_to_probe_replies() {
        let filter = ProbeKind::TcpSyn.filter();

        assert!(
            !admits(&filter, &tcp_frame(SRC_V4, DST_V4, ACK)),
            "the IPv4 half is narrowed by the kernel"
        );
        assert!(
            admits(&filter, &tcp_frame(SRC_V6, DST_V6, ACK)),
            "the IPv6 half cannot be, so userspace has to do it"
        );
    }

    /// Why the test above cannot be fixed by asking for IPv6 explicitly, and
    /// the constraint any replacement expression has to work around.
    ///
    /// This is the standing record of a `libpcap` limitation the engine has to
    /// design around rather than a choice it made. Should a future `libpcap`
    /// learn to index into IPv6, this test is what notices.
    #[test]
    fn libpcap_cannot_narrow_tcp_flags_over_ipv6() {
        let narrowed = "ip6 and tcp and (tcp[tcpflags] & (tcp-syn|tcp-rst)) != 0";
        let capture = pcap::Capture::dead(pcap::Linktype::ETHERNET).expect("dead capture");

        let admits_a_syn_ack = capture
            .compile(narrowed, true)
            .map(|program| program.filter(&tcp_frame(SRC_V6, DST_V6, SYN | ACK)))
            .unwrap_or(false);

        assert!(
            !admits_a_syn_ack,
            "libpcap now narrows TCP flags over IPv6; the split filter is no longer needed"
        );
    }

    // ─── TCP port probes ─────────────────────────────────────────────────────

    fn tcp_probe_filter(icmp_errors: bool) -> String {
        ProbeKind::TcpProbe {
            reply_port: SCAN_PORT,
            icmp_errors,
        }
        .filter()
    }

    /// Both answers a port probe can draw, over both families.
    #[test]
    fn the_tcp_probe_filter_admits_answers_addressed_to_the_scan() {
        let filter = tcp_probe_filter(false);

        for (src, dst) in [(SRC_V4, DST_V4), (SRC_V6, DST_V6)] {
            assert!(
                admits(&filter, &tcp_frame(src, dst, SYN | ACK)),
                "a SYN+ACK is an open port and must reach the scanner"
            );
            assert!(
                admits(&filter, &tcp_frame(src, dst, RST | ACK)),
                "a RST is an answer and must reach the scanner"
            );
        }
    }

    /// What narrowing on the scan's own port buys over narrowing on flags, and
    /// the reason a TCP port scan sends every probe from one port.
    ///
    /// A flag test cannot be compiled over IPv6 (see
    /// [`libpcap_cannot_narrow_tcp_flags_over_ipv6`]), so
    /// [`ProbeKind::TcpSyn`] admits every IPv6 TCP segment on every captured
    /// interface and sorts them out in userspace. A destination port compiles
    /// for both families, so this filter rejects the host's other conversations
    /// in the kernel over IPv6 exactly as it does over IPv4.
    #[test]
    fn the_tcp_probe_filter_rejects_traffic_addressed_elsewhere_over_both_families() {
        let filter = tcp_probe_filter(false);
        let elsewhere = SCAN_PORT + 1;

        for (src, dst) in [(SRC_V4, DST_V4), (SRC_V6, DST_V6)] {
            assert!(
                !admits(&filter, &tcp_frame_to(src, dst, RST | ACK, elsewhere)),
                "a segment to a port this scan never sent from is somebody else's"
            );
        }
    }

    /// What this filter narrows on is the conversation, not the flags, so a
    /// segment carrying neither of the two answers a probe can draw still
    /// reaches userspace if it is addressed to the scan's port.
    ///
    /// Stated here rather than left to be discovered in a packet count. The
    /// scan's port is drawn from the high ephemeral range precisely so nothing
    /// else on the host is holding a conversation on it, and the scanner
    /// re-checks the flags itself either way - so this costs a check per
    /// segment, not a wrong verdict.
    #[test]
    fn the_tcp_probe_filter_narrows_on_the_conversation_rather_than_the_flags() {
        let filter = tcp_probe_filter(false);

        assert!(admits(&filter, &tcp_frame(SRC_V4, DST_V4, ACK)));
        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, ACK)));
    }

    /// ICMP is admitted only when a technique's verdicts actually turn on it,
    /// because an ICMP error names no ports and so cannot be narrowed at all:
    /// asking for it means every ICMP packet on every captured interface is
    /// copied to userspace.
    #[test]
    fn the_tcp_probe_filter_admits_icmp_errors_only_when_asked() {
        let error = icmpv6_error_frame(SRC_V6, DST_V6);

        assert!(!admits(&tcp_probe_filter(false), &error));
        assert!(admits(&tcp_probe_filter(true), &error));
    }

    /// Asking for ICMP must not cost the answers the scan is actually waiting
    /// for, nor widen what it accepts on the TCP half.
    #[test]
    fn asking_for_icmp_changes_nothing_about_the_tcp_half() {
        let filter = tcp_probe_filter(true);

        assert!(admits(&filter, &tcp_frame(SRC_V6, DST_V6, RST | ACK)));
        assert!(!admits(
            &filter,
            &tcp_frame_to(SRC_V6, DST_V6, RST | ACK, SCAN_PORT + 1)
        ));
    }

    // ─── UDP ─────────────────────────────────────────────────────────────────

    /// The resolver's filter is family-agnostic, and has to stay that way: a
    /// DNS or mDNS answer over IPv6 names hosts just as well as one over IPv4.
    #[test]
    fn the_resolve_filter_admits_dns_answers_over_both_families() {
        let filter = ProbeKind::UdpResolve.filter();

        assert!(admits(&filter, &udp_frame(SRC_V4, DST_V4, 53, 40_000)));
        assert!(admits(&filter, &udp_frame(SRC_V6, DST_V6, 53, 40_000)));
        assert!(admits(&filter, &udp_frame(SRC_V6, DST_V6, 5353, 5353)));
        assert!(
            !admits(&filter, &udp_frame(SRC_V6, DST_V6, 12_345, 40_000)),
            "traffic from an unrelated source port is not an answer to anything"
        );
    }

    /// Both answers a UDP probe can draw, over both families. `icmp6` is what
    /// carries the IPv6 half here, and it is the reason UDP port scanning is the
    /// one raw path that already works over IPv6.
    #[test]
    fn the_udp_probe_filter_admits_direct_replies_and_icmp_errors_over_both_families() {
        const REPLY_PORT: u16 = 40_000;
        let filter = ProbeKind::UdpProbe {
            reply_port: REPLY_PORT,
        }
        .filter();

        assert!(admits(&filter, &udp_frame(SRC_V4, DST_V4, 53, REPLY_PORT)));
        assert!(admits(&filter, &udp_frame(SRC_V6, DST_V6, 53, REPLY_PORT)));
        assert!(admits(&filter, &icmpv6_error_frame(SRC_V6, DST_V6)));
        assert!(
            !admits(&filter, &udp_frame(SRC_V6, DST_V6, 53, REPLY_PORT + 1)),
            "a datagram to a port this scan never sent from is somebody else's"
        );
    }

    /// The SCTP filter, held to the same three claims the UDP one is: both
    /// families admitted, ICMP errors admitted whole, and somebody else's
    /// association kept out.
    ///
    /// `sctp` is a protocol keyword libpcap has to know for this to compile at
    /// all, and a filter that fails to compile is a scanner that reads nothing.
    #[test]
    fn the_sctp_filter_admits_answers_to_the_scan_over_both_families() {
        const REPLY_PORT: u16 = 40_000;
        let filter = ProbeKind::Sctp {
            reply_port: REPLY_PORT,
        }
        .filter();

        assert!(admits(
            &filter,
            &sctp_frame(SRC_V4, DST_V4, 2905, REPLY_PORT)
        ));
        assert!(admits(
            &filter,
            &sctp_frame(SRC_V6, DST_V6, 2905, REPLY_PORT)
        ));
        assert!(admits(&filter, &icmpv6_error_frame(SRC_V6, DST_V6)));
        assert!(
            !admits(&filter, &sctp_frame(SRC_V4, DST_V4, 2905, REPLY_PORT + 1)),
            "a packet to a port this scan never sent from belongs to somebody else"
        );
    }
}