zond-engine 0.18.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
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
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
// 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::IpNextHeaderProtocols;

use crate::model::capture::CaptureCounts;
use crate::model::ip::scoped::Zone;
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::Protocol;
use crate::system::interface::{Link, RoutedTargets};
use crate::transport::capture::{self, CaptureGuard, CaptureOptions, CaptureStream};
use crate::transport::kernel_neighbors::KernelNeighbors;
use crate::transport::link::{EthernetSender, LinkNeighbors};
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.
#[non_exhaustive]
#[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 Linux, which the kernel
    /// routes, ARPs, and fragments for us, and which works through VPN
    /// tunnels. Self-built Layer-2 Ethernet frames on Windows, where the OS
    /// blocks raw-socket TCP sends outright. Frames first with the socket
    /// behind them on macOS, where a large scan's raw sends are accepted and a
    /// quarter of them dropped before the wire, and where an unprivileged run
    /// has no socket to fall back to.
    #[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 tunnel-only destinations, or loopback anywhere but macOS, whose
    /// loopback interface takes a frame too.
    Ethernet,
}
impl SendMode {
    /// Every mode, in the order a front end should offer them.
    pub const ALL: &'static [Self] = &[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",
        }
    }

    /// Whether a transport this process opens in this mode reaches what a
    /// self-built frame cannot: loopback, this host's own addresses, a target
    /// the kernel routes through a tunnel, and an IPv6 neighbour.
    ///
    /// A raw socket reaches all of it, since the kernel carries the packet, and
    /// a frame reaches what has Ethernet in front of it. `Auto` is whichever
    /// this platform opens: the socket on Linux, frames alone on Windows, and on
    /// macOS frames with the socket behind them, which is there only for a
    /// process that may open one. An unprivileged run there with the BPF devices
    /// handed to its group has the frames and nothing behind them.
    pub(crate) fn reaches_past_frames(self) -> bool {
        match self {
            SendMode::RawSocket => true,
            SendMode::Ethernet => false,
            SendMode::Auto => {
                #[cfg(windows)]
                {
                    false
                }
                #[cfg(target_os = "macos")]
                {
                    crate::system::privilege::can_send_raw()
                }
                #[cfg(not(any(windows, target_os = "macos")))]
                {
                    true
                }
            }
        }
    }
}
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
            .iter()
            .copied()
            .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 kind in words, with its article, as a message names the traffic a
    /// transport was opened for: `a UDP probe`, `an ICMP echo`. The fields
    /// are left out, being which port or identifier the traffic is told apart
    /// by rather than what it is.
    pub(crate) const fn spoken(self) -> &'static str {
        match self {
            ProbeKind::TcpSyn => "a TCP SYN",
            ProbeKind::TcpProbe { .. } => "a TCP probe",
            ProbeKind::UdpResolve => "a UDP resolver",
            ProbeKind::IcmpEcho { .. } => "an ICMP echo",
            ProbeKind::Sctp { .. } => "an SCTP probe",
            ProbeKind::IpProtocol { .. } => "an IP protocol probe",
            ProbeKind::UdpProbe { .. } => "a UDP probe",
        }
    }

    /// The port a transport for this kind admits replies to, where the kind
    /// fixes one.
    const fn reply_port(self) -> Option<u16> {
        match self {
            ProbeKind::TcpProbe { reply_port, .. }
            | ProbeKind::UdpProbe { reply_port }
            | ProbeKind::Sctp { reply_port } => Some(reply_port),
            ProbeKind::TcpSyn
            | ProbeKind::UdpResolve
            | ProbeKind::IcmpEcho { .. }
            | ProbeKind::IpProtocol { .. } => None,
        }
    }

    /// Whether a transport opened for this kind hears the answers a port scan
    /// of `protocol` reads.
    ///
    /// A port scan over a transport that does not reads every answer as
    /// silence, and silence is a verdict, so the mismatch is refused where it
    /// would otherwise pass for a filtered network. Either TCP kind carries a
    /// TCP scan: both admit the resets and SYN+ACKs it reads. A UDP scan needs
    /// its own kind, since the resolver's admits name-service replies alone.
    pub(crate) const fn carries_port_scan(self, protocol: Protocol) -> bool {
        match protocol {
            Protocol::Tcp => matches!(self, ProbeKind::TcpSyn | ProbeKind::TcpProbe { .. }),
            Protocol::Udp => matches!(self, ProbeKind::UdpProbe { .. }),
            Protocol::Sctp => matches!(self, ProbeKind::Sctp { .. }),
        }
    }

    /// 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.0)
            }
            ProbeKind::UdpResolve | ProbeKind::UdpProbe { .. } => {
                IpProtocols::same(IpNextHeaderProtocols::Udp.0)
            }
            ProbeKind::Sctp { .. } => IpProtocols::same(IpNextHeaderProtocols::Sctp.0),
            // The one kind whose two families are different protocols rather
            // than one protocol over two address sizes.
            ProbeKind::IcmpEcho { .. } => IpProtocols {
                v4: IpNextHeaderProtocols::Icmp.0,
                v6: IpNextHeaderProtocols::Icmpv6.0,
            },
            // 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(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.
///
/// Split by whose fact the failure is, because each calls for a different
/// response. [`Unroutable`](Self::Unroutable) and
/// [`Unresolved`](Self::Unresolved) are facts about the destination: the
/// address was asked about and cannot be reached from here, and the sender is
/// still working. [`HeldDown`](Self::HeldDown) is one too, for as long as the
/// kernel holds it: asked again after that, the address may answer. [`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 this host and may not hold next time: a full send buffer clears.
/// [`is_unroutable`](Self::is_unroutable) is the test a scan reports by.
///
/// 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 neighbour this probe had to be framed to was asked for its hardware
    /// address and did not answer.
    ///
    /// A dead host on the local segment, or a gateway that is not there. Read
    /// as [`Unroutable`](Self::Unroutable) is, as a fact about the destination,
    /// and kept apart from it for the one reader that must not treat the two
    /// alike: a sender holding a second path. No route from one path says
    /// nothing about another, and is the reason to try it. An unanswered
    /// resolution is an answer about the destination itself, and a second path
    /// would only ask the same neighbour the same question again, at a pace and
    /// with a memory of its own that decide per probe whether it is accepted,
    /// queued or refused. See [`SendMode::Auto`] on macOS.
    #[error("{0}")]
    Unresolved(String),

    /// The kernel would not send to this neighbour because a resolution of it
    /// failed lately, and it will not ask again until a hold-down of its own
    /// has passed.
    ///
    /// What macOS says, as `EHOSTDOWN`, to every write to an on-link neighbour
    /// for twenty seconds, by default, after it has asked for the neighbour
    /// five times and heard nothing (`net.link.ether.inet.host_down_time` and
    /// `maxtries`); it asks at most once a second, and only when a write needs
    /// it. The write it gives up on is refused with `EHOSTUNREACH`, as is
    /// every write through a gateway it holds down, so this is the one refusal
    /// that names a hold-down. Linux keeps none: its sockets take every write
    /// to a neighbour it gave up on, and the write starts the asking over.
    ///
    /// A fact about the destination, as [`Unresolved`](Self::Unresolved) is,
    /// and kept apart from it because it answers a different question. That
    /// one is a resolution this sender asked for and waited out. This one is a
    /// kernel declining to ask, on the strength of a failure it remembers from
    /// whoever asked last, which may be another process, or a moment the
    /// neighbour was asleep and is no longer. The same question put after the
    /// hold-down is asked afresh.
    #[error("{0}")]
    HeldDown(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),

    /// This process, or the system, had no descriptor left to open what the
    /// send needed: a socket, or a link's handle for frames.
    ///
    /// A fact about this machine, as a [`Refused`](Self::Refused) is, and
    /// apart from it because it is the one whose words say the least: every
    /// layer the open passed through adds its own, around the one fact a
    /// reader can act on, which is the file limit.
    #[error("file limit reached")]
    OutOfDescriptors,
}

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
    /// 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.
    ///
    /// `EHOSTDOWN` has no [`ErrorKind`](std::io::ErrorKind) of its own and is
    /// read by number, as [`HeldDown`](Self::HeldDown). Read as a refusal, it
    /// would have a scan of one dead address report itself broken.
    pub(crate) fn from_io<E: std::error::Error + 'static>(error: E) -> Self {
        let chain = || {
            std::iter::successors(Some(&error as &dyn std::error::Error), |cause| {
                cause.source()
            })
            .filter_map(|cause| cause.downcast_ref::<std::io::Error>())
        };

        if chain().any(crate::system::descriptors::exhausted) {
            Self::OutOfDescriptors
        } else if chain().any(host_is_down) {
            Self::HeldDown(error.to_string())
        } else if chain().any(|io| {
            matches!(
                io.kind(),
                std::io::ErrorKind::HostUnreachable | std::io::ErrorKind::NetworkUnreachable
            )
        }) {
            Self::Unroutable(error.to_string())
        } else {
            Self::Refused(error.to_string())
        }
    }

    /// A probe not sent because the routing table gave no answer to the
    /// lookup of its source, in the words the lookup failed with.
    ///
    /// A refusal whatever those words are, never read by
    /// [`from_io`](Self::from_io): a lookup that failed says nothing about
    /// the destination, and an `EHOSTDOWN` read there would file the host as
    /// one whose neighbour did not answer.
    pub(crate) fn unanswered_route(error: &std::io::Error) -> Self {
        Self::Refused(format!("route lookup failed: {error}"))
    }

    /// Whether this failure is about the destination rather than about the
    /// sending host: no route to it, or no answer from the neighbour a route
    /// leads through, lately or just now.
    ///
    /// 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(_) | Self::Unresolved(_) | Self::HeldDown(_)
        )
    }
}

/// Whether `error` is the kernel's `EHOSTDOWN`: the next hop's address
/// resolution failed lately, and the kernel is refusing sends to it rather
/// than ask again yet. See [`SendError::HeldDown`].
pub(crate) fn host_is_down(error: &std::io::Error) -> bool {
    #[cfg(unix)]
    {
        error.raw_os_error() == Some(libc::EHOSTDOWN)
    }
    #[cfg(not(unix))]
    {
        let _ = error;
        false
    }
}

/// 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`.
#[non_exhaustive]
#[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: u8,
    /// What an IPv6 header carrying this kind's probes says it carries.
    pub v6: u8,
}

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

    /// The number to stamp into a header addressed to `destination`.
    pub const fn for_destination(self, destination: IpAddr) -> u8 {
        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_from(RawSegment(segment), src, 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) and
/// tunnels. Loopback it frames, to the loopback interface.
///
/// 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.
///
/// Two failures are final rather than a reason to try the socket. An emission
/// only a frame can carry would leave the socket as a different probe than the
/// one asked for. And a neighbour that did not answer its address resolution
/// ([`SendError::Unresolved`]) was reachable by a frame and asked: the socket
/// would hand the kernel the same question about the same neighbour, and the
/// kernel answers it in its own time. macOS takes the first few writes while it
/// asks and discards them later, then refuses the rest for twenty seconds once
/// it has given up, so a port's verdict would record where the kernel was in
/// that cycle when its probe left. Refused here, every probe to the address is
/// refused alike, and the scan reads one absent host.
///
/// Generic over its two senders so the rule is tested on this type rather
/// than on a copy of it; the transport only ever builds the one pairing.
struct LinkLayerFirst<L = EthernetSender, S = RawIpSender> {
    link: L,
    /// [`None`] when this process may inject frames but not open a raw socket,
    /// which is an unprivileged run on macOS with the BPF devices handed to a
    /// group. The fallback is what goes missing, not the scan: a destination
    /// with Ethernet in front of it is reached by the frame either way, as is
    /// loopback, and only tunnel-only addresses and IPv6 neighbours needed the
    /// socket.
    socket: Option<S>,
}

impl<L: ProbeSender, S: ProbeSender> ProbeSender for LinkLayerFirst<L, S> {
    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);
        let final_answer = match &framed {
            Ok(()) | Err(SendError::Unresolved(_)) => true,
            Err(_) => emission.requires_link_layer(),
        };
        if final_answer {
            return framed;
        }
        match &self.socket {
            Some(socket) => socket.send(segment, src, dst, zone, emission),
            // The frame's own error rather than one about a missing socket,
            // because it is the reason this destination went unreached.
            None => framed,
        }
    }
}

/// 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.
#[non_exhaustive]
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,
    /// Where the send half's address resolution stands, for a scan that holds
    /// a host's probes while its neighbour is asked for. See [`NeighborWatch`].
    /// `None` where a neighbour that does not answer is refused at the send,
    /// with nothing to read beforehand: a raw socket on macOS.
    ///
    /// Boxed so the watch's locks sit behind a pointer rather than inside the
    /// transport, whose auto traits are public and would otherwise carry them.
    neighbors: Option<Box<NeighborWatch>>,
    /// The kind this transport was opened for, which decides what its capture
    /// admits and so what a scan over it can hear. `None` for one built from
    /// parts, whose receive stream carries whatever is pushed onto it. See
    /// [`reply_port`](Self::reply_port) and
    /// [`mismatched_for`](Self::mismatched_for).
    kind: Option<ProbeKind>,
}

/// Where the address resolution a transport's sends depend on stands, read by
/// a scan before it hands a probe over.
///
/// Two kinds, because who asks for a neighbour decides what a scan can see of
/// it and when the asking starts.
pub(crate) enum NeighborWatch {
    /// The kernel's own resolution, behind a raw socket on Linux. A write to a
    /// neighbour starts it, and the kernel says nothing to the socket of how
    /// it went; its table does. See [`KernelNeighbors`].
    Kernel(KernelNeighbors),
    /// A frame sender's own resolution. Asking where it stands starts it, and
    /// a send to a neighbour still being resolved waits for it. See
    /// [`LinkNeighbors`].
    Frames(LinkNeighbors),
}

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()
    }

    /// Where the address resolution this transport's sends wait on stands.
    /// See [`NeighborWatch`].
    pub(crate) fn neighbors(&self) -> Option<&NeighborWatch> {
        self.neighbors.as_deref()
    }

    /// The port this transport's capture admits replies to, where the kind it
    /// was opened for fixes one: [`ProbeKind::TcpProbe`], [`ProbeKind::UdpProbe`]
    /// and [`ProbeKind::Sctp`]. `None` for a kind that fixes none, and for a
    /// transport built from parts, whose receive stream carries whatever is
    /// pushed onto it.
    ///
    /// A scan over this transport sends from this port, whatever port it was
    /// handed beside it: its probes' answers come back to the port they left
    /// from, and an answer to any other is filtered out before the scan could
    /// read it. The port a transport was opened for is the one fact both halves
    /// act on, so it is kept here, where the capture that filters on it is.
    pub fn reply_port(&self) -> Option<u16> {
        self.kind.and_then(ProbeKind::reply_port)
    }

    /// The kind this transport was opened for, where its capture filters on
    /// one, if that kind cannot carry a port scan of `protocol`.
    ///
    /// A transport built from parts filters nothing, so it carries anything.
    pub(crate) fn mismatched_for(&self, protocol: Protocol) -> Option<ProbeKind> {
        self.kind.filter(|kind| !kind.carries_port_scan(protocol))
    }

    /// This transport, standing in for one opened for `kind`.
    #[cfg(test)]
    pub(crate) fn opened_for(mut self, kind: ProbeKind) -> Self {
        self.kind = Some(kind);
        self
    }

    /// This transport, reading `neighbors` as the kernel's neighbour table.
    #[cfg(test)]
    pub(crate) fn with_kernel_neighbors(mut self, neighbors: KernelNeighbors) -> Self {
        self.neighbors = Some(Box::new(NeighborWatch::Kernel(neighbors)));
        self
    }

    /// This transport, reading `neighbors` as its frame sender's resolutions.
    #[cfg(test)]
    pub(crate) fn with_link_neighbors(mut self, neighbors: LinkNeighbors) -> Self {
        self.neighbors = Some(Box::new(NeighborWatch::Frames(neighbors)));
        self
    }
    /// 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> {
        Self::open_capturing(kind, mode, &capturable_interfaces())
    }

    /// [`open_with`](Self::open_with), capturing on `links` alone.
    ///
    /// For a scan that knows where its targets are: each capture holds a
    /// device of the system's own, which on macOS is one of a fixed number of
    /// BPF devices every process shares, and a capture on a link no reply can
    /// arrive by holds one for nothing. See [`capture_links_toward`].
    pub(crate) fn open_capturing(
        kind: ProbeKind,
        mode: SendMode,
        links: &[Zone],
    ) -> Result<Self, TransportError> {
        match mode {
            SendMode::Ethernet => Self::open_ethernet_capturing(kind, links),
            SendMode::RawSocket => Self::open_on(kind, links),
            // 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_capturing(kind, links)
                }
                #[cfg(target_os = "macos")]
                {
                    Self::open_link_first_capturing(kind, links)
                }
                #[cfg(not(any(windows, target_os = "macos")))]
                {
                    Self::open_on(kind, links)
                }
            }
        }
    }

    /// [`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,
            neighbors: KernelNeighbors::from_system()
                .map(|table| Box::new(NeighborWatch::Kernel(table))),
            kind: Some(kind),
        })
    }

    /// 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> {
        Self::open_link_first_capturing(kind, &capturable_interfaces())
    }

    /// [`open_link_first`](Self::open_link_first), capturing on `links` alone.
    fn open_link_first_capturing(kind: ProbeKind, links: &[Zone]) -> Result<Self, TransportError> {
        let Some(link) = EthernetSender::from_system(kind.ip_protocols()) else {
            return Self::open_on(kind, links);
        };
        let (rx, capture) = capture::segments(
            links,
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        let neighbors = Some(Box::new(NeighborWatch::Frames(link.neighbors())));
        Ok(Self {
            tx: Box::new(LinkLayerFirst {
                link,
                // Not `?`: a process that may inject frames and not open a raw
                // socket still scans everything with Ethernet in front of it,
                // and refusing to open here would give that run connect
                // scanning with the link-layer path sitting unused.
                socket: RawIpSender::open(kind).ok(),
            }),
            rx,
            capture,
            neighbors,
            kind: Some(kind),
        })
    }

    /// 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> {
        Self::open_ethernet_capturing(kind, &capturable_interfaces())
    }

    /// [`open_ethernet`](Self::open_ethernet), capturing on `links` alone.
    pub(crate) fn open_ethernet_capturing(
        kind: ProbeKind,
        links: &[Zone],
    ) -> 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(
            links,
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        let neighbors = Some(Box::new(NeighborWatch::Frames(sender.neighbors())));
        Ok(Self {
            tx: Box::new(sender),
            rx,
            capture,
            neighbors,
            kind: Some(kind),
        })
    }

    /// 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> {
        Self::open_receiver_capturing(kind, &capturable_interfaces())
    }

    /// [`open_receiver`](Self::open_receiver), capturing on `links` alone.
    pub(crate) fn open_receiver_capturing(
        kind: ProbeKind,
        links: &[Zone],
    ) -> Result<Self, TransportError> {
        let (rx, capture) = capture::segments(
            links,
            &CaptureOptions::for_replies(kind.filter()),
            REPLY_QUEUE_DEPTH,
        )?;
        Ok(Self {
            tx: Box::new(NoopSender),
            rx,
            capture,
            neighbors: None,
            kind: Some(kind),
        })
    }

    /// 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(),
            neighbors: None,
            kind: None,
        }
    }

    /// [`from_parts`](Self::from_parts) with a capture already stopped, for a
    /// test of what a scanner makes of a receive path that went deaf.
    #[cfg(test)]
    pub(crate) fn from_parts_deaf(tx: Box<dyn ProbeSender>, rx: CaptureStream) -> Self {
        Self {
            tx,
            rx,
            capture: CaptureGuard::stopped_early(),
            neighbors: None,
            kind: None,
        }
    }
}

/// 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.
pub(crate) fn capturable_interfaces() -> Vec<Zone> {
    capturable(&crate::system::interface::interfaces_or_none())
}

/// [`capturable_interfaces`] among `links`.
fn capturable(links: &[Link]) -> Vec<Zone> {
    links
        .iter()
        .filter(|link| link.is_up() || link.is_loopback())
        .map(Link::zone)
        .collect()
}

/// The links a reply to a probe of `targets` can arrive by, sent from
/// `forced` where the scan pins its source: what a scan that knows its
/// targets captures on.
///
/// A reply comes back to the address its probe was sent from, so it arrives
/// by the link that holds that address. For a target on a segment this host
/// is on, that is the segment's link; for a routed one, the link holding the
/// source the routing table picks, which is the tunnel's own link where a VPN
/// carries it; for this host's own addresses and loopback's, loopback. A
/// pinned source is asked of both the pin and the routing table, since the
/// probe may still leave by the route while its answer comes back to the pin.
///
/// Every link that is up where the routing cannot say: an address with no
/// route, or a source no link holds. A capture on a link nothing arrives by
/// costs a device and nothing else, and one missing from the link a reply
/// does arrive by loses the reply, so the doubt is resolved toward listening.
/// So too for a plan with more addresses to route one at a time than
/// [`MAX_ENUMERABLE_ADDRESSES`]: its phases route each of them anyway, and
/// asking again here would double the one cost of planning that grows with
/// the plan.
///
/// [`MAX_ENUMERABLE_ADDRESSES`]: crate::system::interface::MAX_ENUMERABLE_ADDRESSES
///
/// Worth narrowing because each capture holds a device of the system's own:
/// on macOS one of a fixed pool of BPF devices every process shares, which a
/// few scans capturing on every link of a machine with dozens of them
/// exhaust.
pub(crate) fn capture_links_toward(targets: &IpSet, forced: &[IpAddr]) -> Vec<Zone> {
    use crate::system::interface::{
        MAX_ENUMERABLE_ADDRESSES, is_enumerable, map_ips_to_interfaces,
        map_ips_to_interfaces_forced,
    };

    let links = crate::system::interface::interfaces_or_none();
    // What the routing below would walk address by address: every IPv4
    // range, and the IPv6 ones small enough to walk at all.
    let mut routed_one_by_one = IpSet::new();
    for range in targets.v4() {
        routed_one_by_one.push_v4_range(*range);
    }
    for range in targets.v6().iter().filter(|range| is_enumerable(range)) {
        routed_one_by_one.push_v6_range(*range);
    }
    if routed_one_by_one.len_gross() > MAX_ENUMERABLE_ADDRESSES {
        return capturable(&links);
    }
    let mut routings = vec![map_ips_to_interfaces(targets.clone())];
    if !forced.is_empty() {
        routings.push(map_ips_to_interfaces_forced(targets.clone(), forced));
    }
    links_replies_reach(&links, &routings).unwrap_or_else(|| capturable(&links))
}

/// The links among `links` a reply to what `routings` planned arrives by, or
/// `None` where one of them cannot be named; see [`capture_links_toward`].
fn links_replies_reach(links: &[Link], routings: &[RoutedTargets]) -> Option<Vec<Zone>> {
    let loopback: Vec<&Link> = links.iter().filter(|link| link.is_loopback()).collect();
    let mut reached: Vec<Zone> = Vec::new();
    for routing in routings {
        reached.extend(routing.local.keys().map(Link::zone));
        for routed in &routing.routed {
            let holder = links.iter().find(|link| {
                link.addresses()
                    .iter()
                    .any(|held| held.address() == routed.source)
            })?;
            reached.push(holder.zone());
        }
        let unmapped_is_loopback =
            routing
                .unmapped
                .v4()
                .iter()
                .all(|range| range.start_addr().is_loopback() && range.end_addr().is_loopback())
                && routing.unmapped.v6().iter().all(|range| {
                    range.start_addr().is_loopback() && range.end_addr().is_loopback()
                });
        if !unmapped_is_loopback {
            return None;
        }
        if !routing.ours.is_empty() || !routing.unmapped.is_empty() {
            if loopback.is_empty() {
                return None;
            }
            reached.extend(loopback.iter().map(|link| link.zone()));
        }
    }
    reached.sort_by(|one, other| one.name().cmp(other.name()));
    reached.dedup();
    (!reached.is_empty()).then_some(reached)
}

/// 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::*;
    use crate::system::interface::LinkKind;

    /// A link named `name` holding `address`, of `kind`.
    fn holding(name: &str, index: u32, kind: LinkKind, address: &str) -> Link {
        use crate::system::interface::LinkAddress;
        let address: IpAddr = address.parse().expect("an address");
        Link::new(name, index)
            .with_kind(kind)
            .with_addresses(vec![LinkAddress::new(address, 24)])
    }

    /// Loopback, a wired segment, a VPN's tunnel, and a link no target is on.
    fn machine() -> Vec<Link> {
        vec![
            holding("lo0", 1, LinkKind::Loopback, "127.0.0.1"),
            holding("en0", 4, LinkKind::Wired, "192.0.2.10"),
            holding("utun4", 20, LinkKind::Virtual, "198.51.100.2"),
            holding("awdl0", 11, LinkKind::Wireless, "203.0.113.77"),
        ]
    }

    /// Each port scan is carried by the kinds whose capture admits its
    /// answers and by no other, and a transport built from parts, which
    /// filters nothing, carries every one.
    ///
    /// The UDP resolver's kind is the near miss: the same protocol, but a
    /// capture that admits name-service replies alone, so a UDP port scan over
    /// it would hear nothing.
    #[test]
    fn a_transport_carries_the_port_scans_its_capture_admits_answers_to() {
        use Protocol::{Sctp, Tcp, Udp};
        let tcp = ProbeKind::TcpProbe {
            reply_port: 40_000,
            icmp_errors: true,
        };
        let udp = ProbeKind::UdpProbe { reply_port: 40_000 };
        let sctp = ProbeKind::Sctp { reply_port: 40_000 };
        for (kind, carried) in [
            (ProbeKind::TcpSyn, &[Tcp][..]),
            (tcp, &[Tcp]),
            (udp, &[Udp]),
            (sctp, &[Sctp]),
            (ProbeKind::UdpResolve, &[]),
            (ProbeKind::IcmpEcho { identifier: 7 }, &[]),
            (ProbeKind::IpProtocol { number: 47 }, &[]),
        ] {
            for protocol in [Tcp, Udp, Sctp] {
                assert_eq!(
                    kind.carries_port_scan(protocol),
                    carried.contains(&protocol),
                    "{kind:?} for {protocol:?}"
                );
            }
        }

        let (_tx, rx) = tokio::sync::mpsc::channel(1);
        let parts = ProbeTransport::from_parts(Box::new(MockSender::default()), rx);
        assert!(
            [Tcp, Udp, Sctp]
                .iter()
                .all(|p| parts.mismatched_for(*p).is_none())
        );
        let opened = parts.opened_for(udp);
        assert_eq!(opened.reply_port(), Some(40_000));
        assert!(opened.mismatched_for(Tcp).is_some());
    }

    fn names(zones: Option<Vec<Zone>>) -> Option<Vec<String>> {
        zones.map(|zones| zones.iter().map(|zone| zone.name().to_owned()).collect())
    }

    /// **A scan captures only on the links a reply to it can arrive by.**
    ///
    /// Every capture holds a device, and on macOS the devices are a fixed
    /// pool every process shares: a scan capturing on each of a machine's
    /// dozens of links leaves a handful of scans to exhaust it. A reply comes
    /// back to its probe's source, so to the segment an on-link target is on,
    /// to the link holding a routed target's source, which is the tunnel's
    /// where a VPN carries the route, and over loopback for this host's own
    /// addresses.
    #[test]
    fn a_capture_listens_where_replies_to_its_targets_arrive() {
        let links = machine();
        let on = |routing: RoutedTargets| names(links_replies_reach(&links, &[routing]));

        let loopback = RoutedTargets {
            unmapped: "127.0.0.1".parse().expect("an address"),
            ..RoutedTargets::default()
        };
        assert_eq!(on(loopback), Some(vec!["lo0".to_owned()]));

        let mut local = std::collections::HashMap::new();
        local.insert(links[1].clone(), "192.0.2.0/24".parse().expect("a range"));
        let beside_a_vpn = RoutedTargets {
            local,
            routed: vec![crate::system::interface::RoutedTarget {
                target: "203.0.113.5".parse().expect("an address"),
                source: "198.51.100.2".parse().expect("an address"),
            }],
            ..RoutedTargets::default()
        };
        assert_eq!(
            on(beside_a_vpn),
            Some(vec!["en0".to_owned(), "utun4".to_owned()])
        );

        let ours = RoutedTargets {
            ours: "192.0.2.10".parse().expect("an address"),
            ..RoutedTargets::default()
        };
        assert_eq!(on(ours), Some(vec!["lo0".to_owned()]), "this host's own");
    }

    /// Where the routing cannot name the link a reply arrives by, a capture
    /// listens on every link, since one missing from that link loses the
    /// reply and one too many costs only a device.
    #[test]
    fn a_capture_whose_replies_the_routing_cannot_place_listens_everywhere() {
        let links = machine();
        let no_route = RoutedTargets {
            unmapped: "203.0.113.9".parse().expect("an address"),
            ..RoutedTargets::default()
        };
        assert_eq!(links_replies_reach(&links, &[no_route]), None);

        let unheld_source = RoutedTargets {
            routed: vec![crate::system::interface::RoutedTarget {
                target: "203.0.113.5".parse().expect("an address"),
                source: "198.51.100.99".parse().expect("an address"),
            }],
            ..RoutedTargets::default()
        };
        assert_eq!(links_replies_reach(&links, &[unheld_source]), None);
    }

    /// A raw socket reaches whatever the kernel carries and a frame what has
    /// Ethernet in front of it, on every platform. What `Auto` reaches belongs
    /// to the platform and, on macOS, to the process, so there it is checked
    /// against the process's own answer rather than asserted.
    #[test]
    fn a_socket_reaches_past_frames_and_a_frame_does_not() {
        assert!(SendMode::RawSocket.reaches_past_frames());
        assert!(!SendMode::Ethernet.reaches_past_frames());

        #[cfg(target_os = "macos")]
        assert_eq!(
            SendMode::Auto.reaches_past_frames(),
            crate::system::privilege::can_send_raw(),
            "frames first, and the socket behind them only for a process that may open one"
        );
        #[cfg(windows)]
        assert!(!SendMode::Auto.reaches_past_frames(), "frames alone");
        #[cfg(not(any(windows, target_os = "macos")))]
        assert!(SendMode::Auto.reaches_past_frames(), "the socket alone");
    }

    #[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(198, 51, 100, 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.0,
            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 or into a tunnel, 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() {
        for cannot in [
            SendError::Unsupported("no NDP here"),
            SendError::Unroutable("no Ethernet route from 198.51.100.1".to_string()),
        ] {
            let socket = MockSender::default();
            let sent = socket.sent.clone();
            let sender = LinkLayerFirst {
                link: RefusingSender(cannot),
                socket: Some(socket),
            };

            let result = send_one(&sender, 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 socket = MockSender::default();
        let sent = socket.sent.clone();
        let sender = LinkLayerFirst {
            link: RefusingSender(SendError::Refused("the link went down".to_string())),
            socket: Some(socket),
        };

        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_one(&sender, spoofed);

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

    /// A neighbour the frame path asked for and heard nothing from is not asked
    /// again through the kernel. The kernel would put the same question to the
    /// same neighbour and accept or refuse each probe by where it had got to,
    /// so the ports of one dead address would come back part silent and part
    /// unasked. The frame's answer stands, and it stands as a fact about the
    /// destination.
    #[test]
    fn a_neighbour_that_did_not_answer_is_not_asked_again_through_the_socket() {
        let socket = MockSender::default();
        let sent = socket.sent.clone();
        let sender = LinkLayerFirst {
            link: RefusingSender(SendError::Unresolved(
                "198.51.100.9 did not answer address resolution on en0".to_string(),
            )),
            socket: Some(socket),
        };

        let result = send_one(&sender, Emission::routed());

        assert!(
            matches!(result, Err(SendError::Unresolved(_))),
            "the frame's answer is the one reported: {result:?}"
        );
        assert!(
            result.as_ref().is_err_and(SendError::is_unroutable),
            "and it is read as the destination's, not this host's"
        );
        assert!(
            sent.lock().unwrap().is_empty(),
            "nothing was handed to the kernel"
        );
    }

    /// 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()),
                SendError::Unresolved(why) => SendError::Unresolved(why.clone()),
                SendError::HeldDown(why) => SendError::HeldDown(why.clone()),
                SendError::OutOfDescriptors => SendError::OutOfDescriptors,
            })
        }
    }

    /// One probe through `sender`, to an address the tests share.
    fn send_one(sender: &dyn ProbeSender, emission: Emission) -> Result<(), SendError> {
        let src = IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, 1));
        let dst = IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, 9));
        sender.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.0)
        );
        assert_eq!(
            ProbeKind::TcpProbe {
                reply_port: 50_000,
                icmp_errors: true,
            }
            .ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Tcp.0)
        );
        assert_eq!(
            ProbeKind::UdpResolve.ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Udp.0)
        );
        assert_eq!(
            ProbeKind::UdpProbe { reply_port: 40_000 }.ip_protocols(),
            IpProtocols::same(IpNextHeaderProtocols::Udp.0)
        );
    }

    /// 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.0);
        assert_eq!(protocols.v6, IpNextHeaderProtocols::Icmpv6.0);
        assert_eq!(
            protocols.for_destination(IpAddr::from([192, 0, 2, 1])),
            IpNextHeaderProtocols::Icmp.0
        );
        assert_eq!(
            protocols.for_destination("2001:db8::1".parse().unwrap()),
            IpNextHeaderProtocols::Icmpv6.0
        );
    }

    /// 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 crate::model::mac::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 {
        admits_on(pcap::Linktype::ETHERNET, filter, frame)
    }

    /// Whether `filter`, compiled for a link of type `link`, admits `frame`.
    fn admits_on(link: pcap::Linktype, filter: &str, frame: &[u8]) -> bool {
        let capture = pcap::Capture::dead(link)
            .unwrap_or_else(|e| panic!("opening a dead capture for {link:?}: {e}"));
        let program = capture
            .compile(filter, true)
            .unwrap_or_else(|e| panic!("compiling `{filter}` for {link:?}: {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: protocol.0,
                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"
            );
        }
    }

    /// The kernel's own word for a neighbour it gave up on lately is a fact
    /// about the destination, and named as the hold-down it is rather than as
    /// a resolution this sender waited out.
    ///
    /// macOS answers every probe to such a neighbour with `EHOSTDOWN` for as
    /// long as it remembers the failure, and `std` has no error kind for it, so
    /// it is the one case read by number. Read as a refusal it would file a
    /// dead address as a scanner that broke; read as an unanswered resolution,
    /// a failure from before the scan asked would stand as the scan's verdict.
    /// A full send buffer is the case that must stay a refusal beside it, as
    /// it is this host's.
    #[cfg(unix)]
    #[test]
    fn a_neighbour_the_kernel_gave_up_on_is_not_a_broken_send_path() {
        use super::SendError;
        use std::io::Error;

        let error = SendError::from_io(Error::from_raw_os_error(libc::EHOSTDOWN));
        assert!(
            matches!(error, SendError::HeldDown(_)),
            "the kernel's hold-down: {error:?}"
        );
        assert!(error.is_unroutable(), "and about the destination");

        let error = SendError::from_io(Error::from_raw_os_error(libc::ENOBUFS));
        assert!(!error.is_unroutable(), "a full buffer is this host's");
    }

    /// A send refused for want of a descriptor is named by the one fact a
    /// reader can act on, whatever layers it was opened through, rather than
    /// in the words each of them wrapped around it.
    #[cfg(unix)]
    #[test]
    fn a_send_refused_for_want_of_a_descriptor_says_the_file_limit() {
        use super::SendError;
        use std::io::Error;

        for code in [libc::EMFILE, libc::ENFILE] {
            let error = SendError::from_io(Error::from_raw_os_error(code));
            assert!(
                matches!(error, SendError::OutOfDescriptors),
                "{code}: {error:?}"
            );
            assert!(!error.is_unroutable(), "a fact about this machine");
            assert_eq!(error.to_string(), "file limit reached");
        }
    }

    // ─── 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"
        );
    }

    // ─── Cooked links ────────────────────────────────────────────────────────

    /// The data-link type `libpcap` opens a PPP link as, `DLT_LINUX_SLL`.
    const LINUX_SLL: pcap::Linktype = pcap::Linktype(113);

    /// `frame`, an Ethernet frame, as a PPP link captures the same packet: the
    /// Ethernet header replaced by the pseudo-header Linux writes there, laid
    /// out from `pcap/sll.h` and naming the same EtherType.
    fn as_cooked(frame: &[u8]) -> Vec<u8> {
        let (ethernet, packet) = frame.split_at(crate::protocols::sizes::ETH_HDR_LEN);
        let mut cooked = vec![
            0x00, 0x00, // packet type: addressed to this host
            0x02, 0x00, // hardware type: ARPHRD_PPP
            0x00, 0x00, // address length: a PPP link has none
            0, 0, 0, 0, 0, 0, 0, 0, // the address, unused
        ];
        cooked.extend_from_slice(&ethernet[12..14]);
        cooked.extend_from_slice(packet);
        cooked
    }

    /// Every filter judges a packet arriving over PPP as it judges the same
    /// packet arriving over Ethernet.
    ///
    /// A filter is compiled for the link it is opened on, and on a cooked link
    /// `libpcap` finds the protocol and the IP header at offsets of its own. An
    /// expression reaching below IP, through an `ether` qualifier or an offset
    /// counted from the start of the frame, would compile to something else
    /// there or fail to compile, and a scan through a PPP VPN would hear
    /// nothing through it. Only `DLT_LINUX_SLL` is compiled for, being what a
    /// capture of one named link comes up as.
    #[test]
    fn every_filter_judges_a_packet_on_a_cooked_link_as_it_does_on_ethernet() {
        const REPLY_PORT: u16 = 40_000;
        let kinds = [
            ProbeKind::TcpSyn,
            ProbeKind::TcpProbe {
                reply_port: SCAN_PORT,
                icmp_errors: false,
            },
            ProbeKind::TcpProbe {
                reply_port: SCAN_PORT,
                icmp_errors: true,
            },
            ProbeKind::UdpResolve,
            ProbeKind::UdpProbe {
                reply_port: REPLY_PORT,
            },
            ProbeKind::Sctp {
                reply_port: REPLY_PORT,
            },
            ProbeKind::IcmpEcho { identifier: 4242 },
            ProbeKind::IpProtocol { number: 47 },
        ];
        let frames = [
            tcp_frame(SRC_V4, DST_V4, SYN | ACK),
            tcp_frame(SRC_V6, DST_V6, SYN | ACK),
            tcp_frame(SRC_V4, DST_V4, ACK),
            tcp_frame(SRC_V6, DST_V6, ACK),
            tcp_frame_to(SRC_V4, DST_V4, RST | ACK, SCAN_PORT + 1),
            udp_frame(SRC_V4, DST_V4, 53, REPLY_PORT),
            udp_frame(SRC_V6, DST_V6, 53, REPLY_PORT),
            udp_frame(SRC_V6, DST_V6, 12_345, REPLY_PORT + 1),
            sctp_frame(SRC_V4, DST_V4, 2905, REPLY_PORT),
            sctp_frame(SRC_V6, DST_V6, 2905, REPLY_PORT),
            icmpv6_error_frame(SRC_V6, DST_V6),
        ];

        let (mut admitted, mut refused) = (0, 0);
        for kind in kinds {
            let filter = kind.filter();
            for frame in &frames {
                let over_ethernet = admits(&filter, frame);
                assert_eq!(
                    admits_on(LINUX_SLL, &filter, &as_cooked(frame)),
                    over_ethernet,
                    "`{filter}` judged a packet differently over PPP than over Ethernet"
                );
                if over_ethernet {
                    admitted += 1;
                } else {
                    refused += 1;
                }
            }
        }
        // Agreement means nothing if every verdict was the same one.
        assert!(
            admitted > 0 && refused > 0,
            "{admitted} admitted, {refused} refused"
        );
    }
}