zond-engine 0.16.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
// 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

//! # TCP Port Probing
//!
//! Implements the privileged TCP half of [`crate::scanner::scan`]. It probes
//! specific `(address, port)` pairs with raw TCP segments and classifies each
//! one by whether and how it responds, rather than completing a full TCP
//! handshake per port the way the unprivileged fallback in
//! [`crate::scanner::strategy::connect`] must.
//!
//! Which segment goes out, and what an answer to it proves, is
//! [`TcpScanTechnique`]'s business - this drives the same loop whichever of the
//! six is chosen. Everything that makes a scan work rather than merely run is
//! shared across them: retransmission, the in-flight ceiling, the adaptive
//! deadline, source selection, and the rule that silence is only a verdict once
//! a probe has spent its whole budget on it. That last one is what separates
//! observing a firewall from assuming one, and it is the same discipline
//! whether the technique reads silence as filtered or as open-filtered.
//!
//! ## Tying a reply to its probe
//!
//! Every probe in a scan leaves from one source port, chosen when the scanner is
//! built, and that port is the scan's identity on the wire: the kernel's capture
//! filter admits the segments addressed to it and drops the rest of the host's
//! TCP traffic, over both address families ([`ProbeKind::TcpProbe`]). It is a
//! boundary the scanner re-checks rather than relies on, since a transport can
//! be built with no filter behind it at all.
//!
//! Which *attempt* a reply answers is a separate question, and the probe's nonce
//! settles it: each attempt carries a fresh one, and a conformant stack echoes
//! it back ([`tcp::echoed_nonce`]). That is what lets a reply arriving after a
//! retry has already gone out still name the attempt it belongs to, and so yield
//! a round trip that is real rather than one measured against the wrong packet.
//!
//! An ICMP error is correlated the same way, through the copy of the probe it
//! quotes rather than through its own header - so an error relayed by a router
//! still points at the host the probe was aimed at. See
//! [`icmp_error`].

use std::net::IpAddr;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use pnet_packet::ip::IpNextHeaderProtocols;
use tokio::sync::mpsc;

use crate::config::OsDetection;
use crate::config::ProbeTuning;
use crate::config::ServiceDetection;
use crate::evasion::SegmentShaping;
use crate::fingerprint::os;
use crate::journal::settle::Outcome;
use crate::logging::error;
use crate::model::capture::IpObservation;
use crate::model::host::{HostStatus, StatusProtocol, StatusReason};
use crate::model::port::discovery::{Discovery as PortDiscovery, ScanResponse};
use crate::model::port::{PortState, Protocol};
use crate::model::target::PlannedTarget;
use crate::model::technique::{TcpReply, TcpScanTechnique};
use crate::protocols::tcp;
use crate::report::ScannerKind;
use crate::scanner::service;
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::{PortScanner, StrategyError};
use crate::success;
use crate::system::interface::SourceResolver;
use crate::transport::capture::CapturedSegment;
use crate::transport::probe::{Emission, ProbeKind, ProbeSender, ProbeTransport};

// Port scanning and routed discovery send the same kind of raw TCP probe over
// the same kind of network path, so they share one adaptive-deadline profile
// rather than keeping two copies in step. They do *not* share a retry schedule:
// a sweep's probes are lost to what the path is doing, and a port scan's to the
// burst it is itself making at one stack. See `PORT_RETRY_POLICY`.
use super::PORT_RETRY_POLICY;
use super::{AuditLabels, CoreParts, ProbeTarget, RawPortScan, RawProbeScan};
use crate::scanner::strategy::icmp_error::{self, Unreachable};

/// What identifies one attempt of a probe on the wire.
///
/// The nonce alone, because the source port does not vary between attempts -
/// it identifies the *scan*, and is checked once against every reply rather than
/// per attempt. A fresh nonce per attempt is what makes a retried probe
/// measurable at all: TCP itself has to discard round-trip samples from
/// retransmissions because it cannot tell which transmission an
/// acknowledgement answers, and a scanner that varies the value the reply echoes
/// does not have that problem.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TcpToken {
    nonce: u32,
}

/// Probes specific `(address, port)` pairs with raw TCP segments, using
/// whichever [`TcpScanTechnique`] it was built for.
///
/// Unlike [`RoutedScanner`](crate::scanner::strategy::routed::RoutedScanner), which sends one SYN per host
/// purely to check for a pulse, this sends one per `(address, port)` pair it is
/// given and reports what each one revealed.
pub struct TcpPortScanner {
    /// Which segment each probe carries, and so what every answer means. Fixed
    /// for the life of the scan: a report that mixed techniques could not say
    /// which one produced a given verdict.
    technique: TcpScanTechnique,
    /// An arbitrary TCP flag byte to send in place of the technique's own, from
    /// [`EvasionProfile::flags`](crate::evasion::EvasionProfile::flags), or
    /// `None` to send the technique's. When set, every probe carries it and the
    /// verdict softens to reachable-or-silent, because an arbitrary combination
    /// has no open/closed meaning to read. See [`effective_flags`](Self::effective_flags).
    flags_override: Option<u8>,
    /// Everything a raw port scan carries and does regardless of protocol: the
    /// transport, the ledger, the deadline, the pacing and the stop conditions.
    /// What stays in this file is what a *TCP* probe is and what its answers
    /// prove.
    core: RawProbeScan<TcpToken>,

    /// How far this scan may go to identify the operating system behind a host.
    ///
    /// Read here because this is where the replies that carry a stack's shape
    /// arrive, and a SYN+ACK is the only segment that carries one. At
    /// [`OsDetection::Passive`] nothing extra is sent and nothing is timed
    /// differently: the reply was drawn to classify a port, and reading what else
    /// it says costs a parse.
    os_detection: OsDetection,

    /// How far the second identification pass may go over the ports this scan
    /// found open. Read here because this scanner owns that pass; see
    /// [`detect_services`](PortScanner::detect_services).
    service_detection: ServiceDetection,
}

impl TcpPortScanner {
    /// Builds a scanner that selects each probe's source via `resolver`, sized
    /// for a scan covering `target_count` `(address, port)` pairs.
    ///
    /// The scan's source port is drawn from the high ephemeral range, where it
    /// is unlikely to collide with a listening service on this host, and the
    /// transport's capture filter is built around it.
    pub fn new(
        resolver: SourceResolver,
        ctx: ScanContext,
        technique: TcpScanTechnique,
        target_count: usize,
        tuning: ProbeTuning,
    ) -> Result<Self, StrategyError> {
        let src_port: u16 = tuning
            .evasion
            .source_port_or(rand::random_range(50_000..u16::MAX));
        let flags_override = tuning.evasion.flags;
        let transport = ProbeTransport::open_with(
            ProbeKind::TcpProbe {
                reply_port: src_port,
                // An arbitrary flag combination reads its verdict off ICMP the
                // way a flag-probe technique does, silence upgrades to filtered
                // when an error names the filter, so it asks for errors too.
                icmp_errors: technique.reads_icmp_errors()
                    || flags_override.is_some()
                    || tuning.icmp_evidence,
            },
            tuning.evasion.effective_send_mode(tuning.send_mode),
        )?;

        Ok(Self::build(
            Self::core(resolver, ctx, transport, &tuning, src_port, target_count),
            technique,
            flags_override,
            tuning.os_detection,
            tuning.service_detection,
        ))
    }

    /// Builds a scanner around an already-opened transport, so the caller
    /// decides how probes reach the wire and where replies come from.
    ///
    /// Paired with a synthetic transport (`ProbeTransport::from_parts`, behind
    /// the `test-support` feature) this is the seam that lets probe and reply
    /// correlation be driven against a simulated network rather than a real
    /// one, with no privileges and no interface.
    ///
    /// The source port is chosen here rather than passed in, unlike
    /// [`UdpPortScanner::with_transport`](super::UdpPortScanner::with_transport):
    /// a TCP reply is addressed back to whatever port the probe came from, so a
    /// simulated network answers correctly without being told, where a
    /// synthesized ICMP error has to be built around a port the test knows.
    pub fn with_transport(
        resolver: SourceResolver,
        ctx: ScanContext,
        technique: TcpScanTechnique,
        transport: ProbeTransport,
        target_count: usize,
    ) -> Self {
        let tuning = ProbeTuning::default();
        Self::build(
            Self::core(
                resolver,
                ctx,
                transport,
                &tuning,
                rand::random_range(50_000..u16::MAX),
                target_count,
            ),
            technique,
            None,
            OsDetection::default(),
            ServiceDetection::default(),
        )
    }

    /// The common constructor.
    ///
    /// Takes a finished core so the two public constructors share one place that
    /// knows how a raw scan is set up, and adds only what a TCP scan decides for
    /// itself.
    fn build(
        core: RawProbeScan<TcpToken>,
        technique: TcpScanTechnique,
        flags_override: Option<u8>,
        os_detection: OsDetection,
        service_detection: ServiceDetection,
    ) -> Self {
        Self {
            technique,
            flags_override,
            os_detection,
            service_detection,
            core,
        }
    }

    /// The core a TCP port scan runs on.
    ///
    /// The pace it must outlive is the slowest its congestion window may settle
    /// at, which is the retry floor stretched by the window's own floor.
    fn core(
        resolver: SourceResolver,
        ctx: ScanContext,
        transport: ProbeTransport,
        tuning: &ProbeTuning,
        src_port: u16,
        target_count: usize,
    ) -> RawProbeScan<TcpToken> {
        let retry = PORT_RETRY_POLICY.configured(tuning.retry);
        let rate = super::super::raw::rate_within(
            tuning.max_probe_rate,
            tuning.min_probe_rate,
            super::TCP_PORT_RATE_CEILING,
        );

        RawProbeScan::new(CoreParts {
            resolver,
            ctx,
            transport,
            tuning,
            src_port,
            target_count,
            retry,
            rate,
            deadline: super::super::raw::DEADLINE_CONFIG,
            pace: retry.min_rto / super::TCP_PORT_WINDOW.floor,
            window: super::TCP_PORT_WINDOW,
            max_unresolved: super::TCP_PORT_UNRESOLVED,
        })
    }

    /// Matches a TCP segment against an outstanding probe and, if it answers
    /// one, classifies it and records the port's state.
    fn handle_tcp_reply(&mut self, captured: &CapturedSegment, now: Instant) {
        let (ip, bytes) = (captured.source, &captured.bytes);
        let Ok(tcp_packet) = tcp::parse(bytes) else {
            self.core.audit.record_off_target();
            return;
        };

        // This scan's own probe leaving, witnessed rather than read as a reply.
        // The destination check keeps a src==dst port collision reading as the
        // reply it is.
        if tcp_packet.source_port() == self.core.src_port
            && tcp_packet.destination_port() != self.core.src_port
        {
            self.witness_probe(captured, &tcp_packet);
            return;
        }

        // A segment addressed anywhere but this scan's own port answered
        // somebody else's conversation. The capture filter already narrows to
        // it, but that is a performance boundary rather than a guarantee - a
        // transport can be built with no filter at all - and this is the only
        // thing making the reply ours.
        if tcp_packet.destination_port() != self.core.src_port {
            self.core.audit.record_off_target();
            return;
        }

        let Some(reply) = tcp::classify_probe_response(&tcp_packet) else {
            self.core.audit.record_off_target();
            return;
        };
        // An arbitrary flag combination has no open/closed meaning to read, so
        // any reply this scan's own probe drew proves only that the port is
        // reachable. A named technique reads its defined verdict instead, and a
        // segment it could not have provoked, a SYN+ACK answering an ACK scan,
        // say, is somebody else's traffic on this scan's port and resolves
        // nothing.
        let state = if self.arbitrary_flags() {
            PortState::Unfiltered
        } else {
            match self.technique.verdict(reply) {
                Some(state) => state,
                None => return,
            }
        };

        // Which attempt the segment claims to be answering. The ledger checks it
        // against every attempt still live for this port, so a reply to an
        // earlier attempt that arrives after a retry has gone out is still
        // recognized - and names which attempt it answered, so the round trip it
        // yields is the real one.
        let token = TcpToken {
            nonce: tcp::echoed_nonce_with_flags(
                self.effective_flags(),
                &tcp_packet,
                self.core.shaping.padding.unwrap_or(0),
            ),
        };
        let key = (ip, tcp_packet.source_port());
        self.resolve_probe(
            key,
            Some(token),
            state,
            Answer {
                drawn_by: Some(reply),
                sender: None,
                // The header this function already had in hand, for the reason
                // the hop counter is kept at all: it costs nothing to read and
                // there is no second chance to read it.
                ttl: captured.observation.map(IpObservation::remaining_hops),
            },
            now,
        );

        self.identify_stack(ip, state, captured);
    }

    /// Marks the probe this outbound segment carries as seen on the wire,
    /// ignoring a frame it cannot match to a live probe.
    fn witness_probe(&mut self, captured: &CapturedSegment, probe: &tcp::Segment<'_>) {
        let Some(destination) = captured.destination else {
            return;
        };
        let token = TcpToken {
            nonce: tcp::sent_nonce_with_flags(self.effective_flags(), probe),
        };
        if self
            .core
            .ledger
            .witness(&(destination, probe.destination_port()), &token)
        {
            self.core.audit.record_witnessed_send();
        }
    }

    /// Reads what the reply that just resolved a port says about the machine
    /// behind it, and files it against the host.
    ///
    /// After the port verdict, and not able to change
    /// it. Identifying an operating system is a secondary reading of a reply
    /// drawn for another purpose, and a defect here must not be able to cost a
    /// port its state.
    ///
    /// Only a SYN+ACK is read. A reset carries no TCP options at all whatever the
    /// probe offered, and the corpus holds no rule that could be matched against
    /// one: the single reset feature that looks promising is not usable, since
    /// the same labelled devices answered two scanners on one segment with
    /// opposite values.
    fn identify_stack(&self, ip: IpAddr, state: PortState, captured: &CapturedSegment) {
        // `None` means this segment never had an IP header to read - a synthetic
        // receive stream - rather than that nothing notable was in one.
        let Some(observation) = captured.observation else {
            return;
        };

        // Before the detection gate. The hop counter is not an
        // identification and costs nothing to keep - it arrived in a header this
        // function already had in hand - while what needs it later is a
        // traceroute, which is a separate setting entirely. Gated with the OS
        // reading, a scan asking for a path without asking for a fingerprint
        // would have to re-obtain by probe a number it had already been told.
        self.core.ctx.update_host(ip, |host| {
            host.record_hop_counter(observation.remaining_hops())
        });

        if !self.os_detection.is_enabled() || state != PortState::Open {
            return;
        }
        let Some(stack) = os::classify_reply(observation, &captured.bytes) else {
            return;
        };

        self.core.ctx.update_host(ip, |host| {
            // The stack reading, handed to the one place that knows what else
            // a host implies about itself. This scanner's contribution is the
            // observation it just took; the rule that a host's own hardware and
            // name are always weighed beside it belongs to `identify`.
            os::identify(host, [stack.as_evidence()]);
        });
    }

    /// Reads an ICMP error as a verdict on the probe it quotes.
    ///
    /// The quotation is what makes this attributable at all, and it is checked
    /// as strictly as a TCP reply: it has to be a TCP segment, sent from this
    /// scan's own port, aimed at a probe still outstanding. What it cannot
    /// always carry is *which attempt* - eight quoted bytes reach the sequence
    /// number and no further - so for a technique whose nonce lives in the
    /// acknowledgement field, a sender quoting only the minimum names the probe
    /// by its ports alone. That is enough for a host unreachable, which settles
    /// no port and is filed only while the probe is outstanding. It is not
    /// enough for a refusal, which would settle one: a refusal that cannot name
    /// the attempt retires nothing, and the port takes whatever its own retry
    /// schedule concludes.
    fn handle_icmp_error(&mut self, reply: &CapturedSegment, now: Instant) {
        let Some(error) = icmp_error::parse(reply) else {
            return;
        };
        if error.quoted.protocol != IpNextHeaderProtocols::Tcp {
            return;
        }

        let Some(quoted) = tcp::quoted_probe(error.quoted.payload) else {
            return;
        };
        if quoted.source != self.core.src_port {
            return;
        }

        let key = (error.quoted.destination, quoted.destination);
        let token = tcp::quoted_nonce_with_flags(self.effective_flags(), &quoted)
            .map(|nonce| TcpToken { nonce });

        match error.reason {
            // Nobody could reach the address at all, so the message carries no
            // verdict on the port it happened to quote. The probe is left
            // outstanding to retire on its own schedule like any other
            // unanswered one.
            Unreachable::Host => {
                self.core.record_host_down(&key, token, reply.source);
            }
            // Everything else is a refusal, and for a TCP probe all three read
            // the same way. An administrative prohibition says so outright. A
            // *port* unreachable would mean a closed port had it answered a UDP
            // probe, but no TCP stack emits one - so something in the path
            // rejected the probe on the host's behalf, which is a filter and
            // not a closed port. A *protocol* unreachable would mean a host with
            // no TCP stack at all, which is not a closed port either; it is read
            // for what it is by the pass that asks about protocols on purpose.
            //
            // A refusal names a port, so unlike a host unreachable it has to
            // name the *attempt* as well. Four of the six techniques put their
            // nonce in the sequence number, which is inside the eight bytes RFC
            // 792 guarantees, so an error about one of those carries it however
            // stingy the sender. The two that use the acknowledgement field -
            // and Maimon, which carries ACK - need twelve quoted bytes, and a
            // sender offering only the minimum leaves `token` as `None`.
            //
            // Resolving on that would be resolving on the ports alone, which
            // anybody who knows this scan's source port can supply. For an ACK
            // or window scan it would reach the verdict silence reaches, costing
            // only a suppressed retry and an invented `IcmpProhibited`. For a
            // Maimon scan it would cost the verdict: `OpenFiltered` would become
            // `Filtered`, and an open port would be dismissed.
            //
            // So an unattributable refusal retires nothing, and the port takes
            // whatever its own retry schedule concludes. See the SCTP scanner,
            // which reaches the same rule from the other direction: an INIT's
            // nonce is *never* inside the guaranteed eight.
            Unreachable::Port | Unreachable::Prohibited | Unreachable::Protocol
                if token.is_none() =>
            {
                self.core.audit.record_reply_without_rtt();
            }
            Unreachable::Port | Unreachable::Prohibited | Unreachable::Protocol => {
                self.resolve_probe(
                    key,
                    token,
                    PortState::Filtered,
                    Answer {
                        drawn_by: None,
                        sender: Some(reply.source),
                        // The error's own hop counter, which is the distance to
                        // whatever refused the probe rather than to the target.
                        // That is the useful reading: a refusal from nearer than
                        // the host is a middlebox answering on its behalf.
                        ttl: reply.observation.map(IpObservation::remaining_hops),
                    },
                    now,
                );
            }
        }
    }

    /// Retires one outstanding probe with the state its reply established,
    /// crediting whatever round trip the ledger is willing to vouch for.
    ///
    /// `token` names the attempt that was answered, or `None` where the reply
    /// could not say. A reply matching no live attempt resolves nothing: it is a
    /// stray or spoofed segment, a duplicate of one already acted on, or an
    /// answer to a probe already written off.
    fn resolve_probe(
        &mut self,
        key: ProbeTarget,
        token: Option<TcpToken>,
        state: PortState,
        answer: Answer,
        now: Instant,
    ) {
        let Some(resolution) = self.core.ledger.resolve(&key, token, now) else {
            // A reply matching no live attempt: a stray or spoofed segment, a
            // duplicate of one already acted on, or an answer to a probe already
            // written off. It proves something is there and yields no sample.
            self.core.audit.record_reply_without_rtt();
            return;
        };

        let rtt = resolution.rtt;
        self.core.record_answer(&resolution);
        self.record_port_answered_by(key.0, key.1, state, answer, rtt);
        // The target spoke: the only outcome that settles positively.
        self.settle(Outcome::Answered {
            position: resolution.payload,
        });
    }

    /// Which protocol a host verdict from this scan is credited to.
    ///
    /// [`StatusProtocol::TcpSyn`] keeps its one meaning, so a report naming it
    /// always describes a half-open connection attempt. Every other
    /// technique credits [`StatusProtocol::Tcp`], with the probe that drew the
    /// answer named in the reason's details.
    const fn status_protocol(&self) -> StatusProtocol {
        match self.technique {
            TcpScanTechnique::Syn => StatusProtocol::TcpSyn,
            _ => StatusProtocol::Tcp,
        }
    }

    /// The TCP flag byte every probe carries: the arbitrary override when a
    /// profile set one, otherwise the technique's own combination.
    fn effective_flags(&self) -> u8 {
        self.flags_override
            .unwrap_or_else(|| tcp::probe_flags(self.technique))
    }

    /// Whether this scan sends an arbitrary flag combination, so a reply says
    /// only that the port is reachable and silence means open-filtered: the
    /// softer reading an arbitrary combination licenses, in place of the
    /// technique's defined open/closed verdict.
    const fn arbitrary_flags(&self) -> bool {
        self.flags_override.is_some()
    }
}

impl RawPortScan for TcpPortScanner {
    type Token = TcpToken;

    fn core(&self) -> &RawProbeScan<TcpToken> {
        &self.core
    }

    fn core_mut(&mut self) -> &mut RawProbeScan<TcpToken> {
        &mut self.core
    }

    fn protocol(&self) -> Protocol {
        Protocol::Tcp
    }

    /// What silence means here is the technique's to say: a firewall for the
    /// two probes any live stack would have answered, an open port or a
    /// firewall for the four an open port is required to ignore.
    fn silence_means(&self) -> PortState {
        if self.arbitrary_flags() {
            // Silence to an arbitrary combination is either a drop or an open
            // port that ignored it, the open-filtered of the flag-probe family:
            // never the plain filtered a SYN's silence would earn.
            PortState::OpenFiltered
        } else {
            self.technique.silence_means()
        }
    }

    /// "unanswered" rather than either verdict, because which one silence
    /// produces depends on the technique and the message is about probes that
    /// never left at all.
    fn audit_labels(&self) -> AuditLabels {
        AuditLabels {
            tag: "tcp-port",
            silence: "unanswered",
        }
    }

    /// Sends one probe at `(ip, port)` and records the attempt.
    ///
    /// Nothing about the probe is kept between attempts and none of it needs to
    /// be: the packet is built afresh from the target, which is both cheaper
    /// than buffering it and required, since every attempt must carry its own
    /// nonce.
    /// Routes one captured reply to whichever half of the classification can
    /// read it.
    ///
    /// ICMP only reaches here for a technique that asked for it; see
    /// [`TcpScanTechnique::reads_icmp_errors`].
    fn handle_reply(&mut self, reply: &CapturedSegment, now: Instant) {
        match reply.protocol {
            IpNextHeaderProtocols::Tcp => self.handle_tcp_reply(reply, now),
            _ => self.handle_icmp_error(reply, now),
        }
    }

    /// Files a port verdict and whatever the reply that produced it proves about
    /// the host.
    ///
    /// `sender` is the address the reply actually came from, or `None` when the
    /// verdict came from a spent attempt budget rather than from a packet. It
    /// matters because an ICMP error names two addresses - the hop that
    /// generated it and the destination of the datagram it quotes - and they are
    /// different claims:
    ///
    /// - **The target answered.** Any segment the host sent proves it is up, and
    ///   that includes the ones negative about the port. A RST is the clearest
    ///   case: it is the technique's evidence *against* a listener and evidence
    ///   *for* a live stack at the same time, and it is the row most easily
    ///   forgotten because the port verdict reads negative while the host
    ///   verdict does not.
    /// - **A middlebox rejected the probe by policy.** Something is enforcing a
    ///   perimeter around this address, which is [`HostStatus::Filtered`] -
    ///   materially different from an address nothing answers for.
    /// - **Nothing answered.** A verdict reached from silence records nothing.
    ///   Silence is not evidence about a host, and promoting it would make
    ///   `is_alive()` true for a host that has never sent a packet.
    fn record_port(&mut self, ip: IpAddr, port_num: u16, state: PortState, sender: Option<IpAddr>) {
        // The shared loop reaches a verdict from a spent budget rather than from
        // a packet, so it has no reply to name. Everything a reply *did* draw
        // goes through the fuller form below.
        self.record_port_answered_by(
            ip,
            port_num,
            state,
            Answer {
                sender,
                ..Answer::default()
            },
            None,
        );
    }

    /// One send, first attempt or retry. `position` is `Some` only for a probe
    /// that has never gone out, since the ledger keeps it thereafter.
    fn send(&mut self, ip: IpAddr, port: u16, position: Option<u64>, now: Instant) {
        let Some(src_addr) = self.core.resolver.resolve(ip) else {
            error!(verbosity = 2, "no route to {ip}; skipping {ip}:{port}");
            return;
        };

        // Whether this send takes a slot in the congestion window. A retry does
        // not: the slot went back when the question it repeats ran out of
        // round-trip budget. The ledger is what knows, since it is what holds
        // the probe between attempts.
        let first_attempt = !self.core.ledger.contains(&(ip, port));

        let token = send_tcp_probe(
            self.core.transport.tx.as_ref(),
            self.technique,
            self.effective_flags(),
            self.core.src_port,
            src_addr,
            ip,
            self.core.resolver.zone_of(ip),
            port,
            self.core.emission,
            self.core.shaping,
            &self.core.decoys,
            &mut self.core.send_failure,
        );
        self.core.record_send(ip, token.is_some(), first_attempt);

        if let Some(token) = token {
            match position {
                Some(position) => self.core.ledger.arm(ip, (ip, port), token, position, now),
                None => self.core.ledger.rearm(ip, (ip, port), token, now),
            }
        }
    }
}

impl TcpPortScanner {
    /// [`record_port`](RawPortScan::record_port), also saying what the reply
    /// that produced the verdict was and what it carried.
    ///
    /// Kept off the shared trait because it is a TCP concept: the UDP scanner
    /// implements the same trait and has no notion of a segment's flags, and
    /// widening the shared signature to carry one would put a protocol's
    /// vocabulary into the machinery both protocols share.
    fn record_port_answered_by(
        &mut self,
        ip: IpAddr,
        port_num: u16,
        state: PortState,
        answer: Answer,
        rtt: Option<Duration>,
    ) {
        let Answer {
            drawn_by, sender, ..
        } = answer;

        let port = crate::fingerprint::baseline_port(port_num, Protocol::Tcp, state);

        // The packet that settled it, written down rather than merely acted on.
        // The classification below already knows which reply arrived, it is
        // what decides the verdict, and without this record a reader would have
        // the word `filtered` and no way to learn whether a firewall said so or
        // nothing came back. The two are different findings.
        let port = match port_evidence(state, drawn_by, sender, ip) {
            Some(reason) => {
                let mut discovery = PortDiscovery::new(reason);
                if let Some(rtt) = rtt {
                    discovery = discovery.with_rtt(rtt);
                }
                if let Some(ttl) = answer.ttl {
                    discovery = discovery.with_ttl(ttl);
                }
                port.with_discovery(discovery)
            }
            None => port,
        };
        let evidence = match (state, sender) {
            // Three routes to an open port, told apart. A handshake is the peer
            // accepting the connection; a challenge ACK is the peer saying it is
            // *already* half-open on one, which only a listener can be; a reset
            // is a window scan reading the listening socket's own window off a
            // refusal. Same verdict, materially different evidence, and a report
            // that called any of the three a handshake would be describing a
            // packet nobody sent.
            (PortState::Open, _) => Some((
                HostStatus::Up,
                match drawn_by {
                    Some(TcpReply::Rst { .. }) => {
                        StatusReason::new(self.status_protocol(), rst_evidence(self.technique))
                    }
                    Some(TcpReply::ChallengeAck) => StatusReason::new(
                        StatusProtocol::TcpSyn,
                        "challenge ack from a probed port, so a listener holds it half-open",
                    ),
                    _ => StatusReason::new(StatusProtocol::TcpSyn, "syn-ack from a probed port"),
                },
            )),
            // Both verdicts a RST can produce: closed for the techniques that
            // read it as an absent listener, unfiltered for the ACK scan, which
            // reads it as a probe that arrived.
            (PortState::Closed | PortState::Unfiltered, _) => Some((
                HostStatus::Up,
                StatusReason::new(self.status_protocol(), rst_evidence(self.technique)),
            )),
            (PortState::Filtered, Some(sender)) if sender == ip => Some((
                HostStatus::Up,
                StatusReason::new(
                    StatusProtocol::IcmpUnreachable,
                    "unreachable for a probed port, from the host",
                ),
            )),
            (PortState::Filtered, Some(sender)) => Some((
                HostStatus::Filtered,
                StatusReason::new(
                    StatusProtocol::IcmpUnreachable,
                    "unreachable for a probed port, from the path",
                )
                .from_source(sender),
            )),
            _ => None,
        };

        self.core.ctx.update_host(ip, |host| {
            host.add_port(port);
            if let Some((status, reason)) = evidence {
                host.record_evidence(status, reason);
            }
        });
    }
}

/// What the reply that settled a port was, past the verdict it produced.
///
/// Three facts that arrive together, travel together and are read together, so
/// they are one value rather than three parameters threaded side by side. Every
/// one of them is `None` for a port nothing answered, which is the case the
/// sweep settles on its own schedule.
#[derive(Debug, Clone, Copy, Default)]
struct Answer {
    /// Which segment produced the verdict, where a TCP reply did.
    drawn_by: Option<TcpReply>,
    /// Who sent it, where that was not the target itself.
    sender: Option<IpAddr>,
    /// The hop counter as it arrived: an IPv4 TTL or an IPv6 hop limit.
    ///
    /// Not the value the sender wrote. Every router on the path decrements
    /// it, so what is recorded is the initial value less the distance, which is
    /// what makes it worth keeping per port: a reply whose count disagrees with
    /// the host's other replies did not come from where the others did. See
    /// [`IpObservation::remaining_hops`](crate::model::capture::IpObservation::remaining_hops).
    ttl: Option<u8>,
}

/// Which packet settled a port, in the vocabulary a report records.
///
/// The port-level mirror of the host evidence above, and drawn from the same
/// two facts: the verdict, and the reply that produced it. Kept apart because
/// they answer different questions, that one says why the *host* is believed
/// alive, this says why the *port* is in the state it is.
///
/// A [`PortState::Filtered`] port whose attempts ran out records
/// [`ScanResponse::NoResponse`], because that word alone does not say whether a
/// filter answered or nothing did. [`PortState::OpenFiltered`] says silence on
/// its own face and is left as it is: the flag-probe techniques come back full
/// of it, and a packet recorded against every one would be the verdict written
/// twice.
///
/// `None` where the verdict and the reply that produced it name no packet
/// between them.
fn port_evidence(
    state: PortState,
    drawn_by: Option<TcpReply>,
    sender: Option<IpAddr>,
    target: IpAddr,
) -> Option<ScanResponse> {
    match (state, drawn_by, sender) {
        // A window scan reaches an open port by the reset every other technique
        // reads as a refusal, so the packet named here is the one that arrived.
        (PortState::Open, Some(TcpReply::Rst { .. }), _) => Some(ScanResponse::TcpRst),
        // A challenge ACK is a listener saying it is already half-open, which
        // only a listener can be. Same segment family as a handshake, and the
        // report records both as the SYN/ACK path they are.
        (PortState::Open, _, _) => Some(ScanResponse::TcpSynAck),
        (PortState::Closed | PortState::Unfiltered, _, _) => Some(ScanResponse::TcpRst),
        // An unreachable from the target is the target's own policy; one from
        // the path is somebody else's. Both are prohibitions, and which address
        // sent it is kept on the host's evidence rather than restated here.
        (PortState::Filtered, _, Some(from)) => Some(match from == target {
            true => ScanResponse::IcmpProhibited,
            false => ScanResponse::IcmpUnreachable,
        }),
        (PortState::Filtered, None, None) => Some(ScanResponse::NoResponse),
        _ => None,
    }
}

/// What a RST proves, said in the terms of the probe that drew it.
///
/// Static strings rather than a formatted technique name, because
/// [`StatusReason`] holds its details in an `Arc<str>` precisely so thousands of
/// ports reporting the same rationale cost one allocation between them.
const fn rst_evidence(technique: TcpScanTechnique) -> &'static str {
    match technique {
        TcpScanTechnique::Syn => "rst from a probed port",
        TcpScanTechnique::Fin => "rst to a fin probe",
        TcpScanTechnique::Null => "rst to a flagless probe",
        TcpScanTechnique::Xmas => "rst to a fin-psh-urg probe",
        TcpScanTechnique::Maimon => "rst to a fin-ack probe",
        TcpScanTechnique::Ack => "rst to an ack probe",
        TcpScanTechnique::Window => "rst to an ack probe, read for its window",
    }
}

/// Sends one probe of `technique` from `src_port` at `dst_addr:dst_port` and
/// returns the token it went out carrying, so a later reply can be recognized as
/// answering this attempt.
///
/// The nonce is drawn fresh here rather than by the caller, because it is the
/// one thing that must never be repeated between attempts: two probes carrying
/// the same nonce are indistinguishable in their replies, and a round trip
/// measured against the wrong one is worse than no measurement.
///
/// `reason` receives the failure when there is one, so a scan whose probes never
/// reached the wire can say why in its report rather than only in a log line. A
/// probe that was never sent and a probe nobody answered are indistinguishable
/// in a port count and could hardly be more different in what they mean.
#[allow(clippy::too_many_arguments)]
fn send_tcp_probe(
    sender: &dyn ProbeSender,
    technique: TcpScanTechnique,
    flags: u8,
    src_port: u16,
    src_addr: IpAddr,
    dst_addr: IpAddr,
    dst_zone: Option<u32>,
    dst_port: u16,
    emission: Emission,
    shaping: SegmentShaping,
    decoys: &[IpAddr],
    reason: &mut Option<String>,
) -> Option<TcpToken> {
    let nonce: u32 = rand::random();

    let packet = match tcp::build_probe_with_flags(
        flags,
        src_addr,
        dst_addr,
        src_port,
        dst_port,
        nonce,
        shaping.padding,
        shaping.bad_tcp_checksum,
    ) {
        Ok(packet) => packet,
        Err(e) => {
            error!(
                verbosity = 2,
                "failed to create {technique} probe for {dst_addr}:{dst_port}: {e}"
            );
            return None;
        }
    };

    // A decoy from each address of the target's own family: its own port and
    // nonce, the same technique and shaping, so it is an equal-looking probe and
    // none of them is the odd one out.
    let decoy_packets: Vec<(IpAddr, Vec<u8>)> = decoys
        .iter()
        .filter(|decoy| decoy.is_ipv4() == dst_addr.is_ipv4())
        .filter_map(|&decoy| {
            tcp::build_probe_with_flags(
                flags,
                decoy,
                dst_addr,
                rand::random_range(50_000..u16::MAX),
                dst_port,
                rand::random(),
                shaping.padding,
                shaping.bad_tcp_checksum,
            )
            .ok()
            .map(|packet| (decoy, packet))
        })
        .collect();

    match super::super::raw::emit_among_decoys(
        sender,
        dst_addr,
        dst_zone,
        emission,
        src_addr,
        &packet,
        &decoy_packets,
    ) {
        Ok(()) => {
            success!(
                verbosity = 2,
                "sent {technique} probe to {dst_addr}:{dst_port}"
            );
            Some(TcpToken { nonce })
        }
        Err(e) => {
            // `{e:#}` rather than `{e}`: the outer message says which probe
            // failed, and the chained cause is the operating system's own
            // explanation - "No route to host" and "Permission denied" call for
            // completely different responses, and the bare wrapper distinguishes
            // neither.
            // Once. A link that has stopped accepting sends refuses every
            // probe behind the one that noticed, and the same line seven
            // thousand times buries everything else the run had to say:
            // including the count, which is the number that actually matters and
            // which the audit reports on its own.
            if reason.is_none() {
                error!(
                    verbosity = 2,
                    "failed to send {technique} probe to {dst_addr}:{dst_port}: {e:#}"
                );
                *reason = Some(format!("{e:#}"));
            }
            None
        }
    }
}

#[async_trait]
impl PortScanner for TcpPortScanner {
    /// Names the strategy the way a report has to read it.
    ///
    /// A SYN scan keeps [`ScannerKind::SynPort`], which is what every report
    /// this engine has ever written called it and what consumers already parse.
    /// The flag-probe techniques are a different question asked of the same
    /// scanner, and calling their failures `syn_port` would be a plain untruth;
    /// which of them ran is in the phase's settings.
    ///
    /// The rule itself lives on [`ScannerKind::for_raw_tcp`], because
    /// [`PortScanStep`](crate::scanner::plan::PortScanStep) has to reach the
    /// same answer when it attributes a socket that would not open.
    fn kind(&self) -> ScannerKind {
        ScannerKind::for_raw_tcp(self.technique)
    }

    fn supported_protocols(&self) -> Vec<Protocol> {
        vec![Protocol::Tcp]
    }

    /// Consumes `targets`, sending one probe for each TCP one, retrying the
    /// ones that go unanswered, and classifying every reply, until each probe
    /// has been resolved or has spent its attempts. UDP and SCTP targets are
    /// skipped, since this scanner does not support them. Anything still
    /// outstanding when the loop ends takes the verdict this technique reads
    /// silence as.
    ///
    /// New targets are admitted only while the congestion window has room, and
    /// retries are serviced before new targets are taken, since a retry is an
    /// obligation the scan already owns. The window is what paces the scan and
    /// what it discovers about each target's capacity; see
    /// `TCP_PORT_WINDOW`.
    async fn scan(&mut self, targets: mpsc::Receiver<PlannedTarget>) -> Result<(), StrategyError> {
        super::drive(self, targets).await;
        Ok(())
    }

    /// Fingerprints every open port the scan found. The raw exchange that
    /// classified each port never opened a connection, so this second pass makes
    /// one per open port and runs the shared fingerprint engine over it.
    ///
    /// Needs no branch on the technique. Only a SYN or a window scan reports a
    /// port [`PortState::Open`] (see [`TcpScanTechnique::finds_open_ports`]), so
    /// after any other one this finds nothing to identify and returns
    /// immediately - the data already guarantees what a condition here would
    /// have enforced. After a window scan it runs, and a port whose openness
    /// rests on a reset's window is the one most worth putting a connection to.
    async fn detect_services(&mut self, ctx: &ScanContext) {
        service::detect(ctx, self.service_detection, Protocol::Tcp).await;
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::target::Target;
    use std::net::Ipv4Addr;
    use std::time::Duration;

    use pnet_packet::icmp::destination_unreachable::{
        DestinationUnreachablePacket, IcmpCodes, MutableDestinationUnreachablePacket,
    };
    use pnet_packet::icmp::{IcmpCode, IcmpTypes};
    use pnet_packet::tcp::MutableTcpPacket;

    use crate::protocols::ip;
    use crate::scanner::session::ScanSession;
    use crate::transport::probe::{MockSender, ProbeTransport};

    const SYN: u8 = 1 << 1;
    const RST: u8 = 1 << 2;
    const PSH: u8 = 1 << 3;
    const ACK: u8 = 1 << 4;
    const TARGET: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 200));
    /// This host's address on [`on_link_interface`], which its probes leave from.
    const LOCAL: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 50);
    const LOCAL_IP: IpAddr = IpAddr::V4(LOCAL);
    /// A router between here and [`TARGET`], which reports errors under its own
    /// address rather than the target's.
    const ROUTER: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));

    /// An interface whose /24 contains [`TARGET`], so source resolution
    /// answers on-link without a kernel route probe.
    fn on_link_interface() -> crate::system::interface::Link {
        use crate::system::interface::{Link, LinkAddress};
        use std::net::{Ipv4Addr, Ipv6Addr};
        Link::new("test0", 0).with_addresses(vec![
            LinkAddress::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50)), 24),
            LinkAddress::new(
                IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 50)),
                64,
            ),
        ])
    }

    /// Builds a bare 20-byte TCP segment as a captured reply arrives, once the
    /// link and IP headers are stripped: from `from_port` on the target, back to
    /// `to_port` here, echoing the probe's nonce the way a stack answering
    /// `technique` would.
    ///
    /// The echo rule is written out from RFC 793 §3.4 rather than taken from
    /// [`tcp::echoed_nonce`], so a wrong rule in the engine fails these tests
    /// instead of agreeing with itself. A probe carrying ACK hands the reset its
    /// sequence number; otherwise the reset acknowledges the probe's sequence
    /// number plus the octet a FIN or SYN occupies, which is why a flagless
    /// probe is acknowledged unchanged.
    fn segment_to(
        from_port: u16,
        to_port: u16,
        technique: TcpScanTechnique,
        token: TcpToken,
        flags: u8,
    ) -> Vec<u8> {
        let mut buf = vec![0u8; 20];
        let mut tcp = MutableTcpPacket::new(&mut buf).unwrap();
        tcp.set_source(from_port);
        tcp.set_destination(to_port);
        tcp.set_data_offset(5);
        tcp.set_flags(flags);

        match technique {
            TcpScanTechnique::Maimon | TcpScanTechnique::Ack | TcpScanTechnique::Window => {
                tcp.set_sequence(token.nonce)
            }
            TcpScanTechnique::Null => tcp.set_acknowledgement(token.nonce),
            _ => tcp.set_acknowledgement(token.nonce.wrapping_add(1)),
        }
        buf
    }

    /// [`segment_to`] addressed where a real answer would arrive: the one port
    /// this scan sends from.
    fn tcp_segment(
        scanner: &TcpPortScanner,
        from_port: u16,
        token: TcpToken,
        flags: u8,
    ) -> Vec<u8> {
        segment_to(
            from_port,
            scanner.core.src_port,
            scanner.technique,
            token,
            flags,
        )
    }

    /// The probes a [`MockSender`] recorded, shared with the scanner under test.
    type SentProbes = std::sync::Arc<std::sync::Mutex<Vec<crate::transport::probe::SentProbe>>>;

    /// A sender that refuses everything, which is what an interface whose queue
    /// has filled or whose neighbour will not resolve looks like from up here.
    struct RefusingSender;

    impl crate::transport::probe::ProbeSender for RefusingSender {
        fn send(
            &self,
            _segment: &[u8],
            _src: IpAddr,
            _dst: IpAddr,
            _zone: Option<u32>,
            _emission: Emission,
        ) -> Result<(), crate::transport::probe::SendError> {
            Err(crate::transport::probe::SendError::Refused(
                "no route to host".to_string(),
            ))
        }
    }

    /// A SYN scanner wired to a recording [`MockSender`] and an idle capture
    /// stream, plus the session store to assert against and the probe log to
    /// read tokens back out of.
    fn scanner_with_mock() -> (TcpPortScanner, ScanSession, SentProbes) {
        scanner_for(TcpScanTechnique::Syn)
    }

    /// [`scanner_with_mock`] for an explicit technique.
    fn scanner_for(technique: TcpScanTechnique) -> (TcpPortScanner, ScanSession, SentProbes) {
        let (session, ctx) = ScanSession::new();
        let (_reply_tx, reply_rx) = tokio::sync::mpsc::channel(1024);
        let sender = MockSender::default();
        let sent = sender.sent.clone();
        let transport = ProbeTransport::from_parts(Box::new(sender), reply_rx);
        let resolver = SourceResolver::from_links(&[on_link_interface()]);
        let scanner = TcpPortScanner::with_transport(resolver, ctx, technique, transport, 8);
        (scanner, session, sent)
    }

    /// Sends a probe to `TARGET:port` and returns the token it went out
    /// carrying, so a matching reply can be synthesized.
    ///
    /// The token is read back off the recording sender rather than out of the
    /// scanner, so what a test answers is what actually reached the wire.
    fn probe(scanner: &mut TcpPortScanner, sent: &SentProbes, port: u16) -> TcpToken {
        let before = sent.lock().unwrap().len();
        scanner.send_probe(PlannedTarget::new(
            u64::from(port),
            Target {
                ip: TARGET,
                port,
                protocol: Protocol::Tcp,
            },
        ));

        let sent = sent.lock().unwrap();
        let (segment, _, _) = sent.get(before).expect("probe reached the wire");
        token_of(scanner.technique, segment)
    }

    /// The nonce a recorded probe went out carrying, read from whichever field
    /// its technique writes it to.
    fn token_of(technique: TcpScanTechnique, segment: &[u8]) -> TcpToken {
        let tcp = tcp::parse(segment).expect("probe is a TCP segment");
        TcpToken {
            nonce: match technique {
                TcpScanTechnique::Maimon | TcpScanTechnique::Ack | TcpScanTechnique::Window => {
                    tcp.acknowledgement()
                }
                _ => tcp.sequence(),
            },
        }
    }

    /// The token the most recent probe went out carrying.
    fn last_probe(technique: TcpScanTechnique, sent: &SentProbes) -> TcpToken {
        let sent = sent.lock().unwrap();
        let (segment, _, _) = sent.last().expect("a probe reached the wire");
        token_of(technique, segment)
    }

    fn port_state(session: &ScanSession, port: u16) -> Option<PortState> {
        session
            .hosts()
            .get(TARGET)
            .and_then(|h| h.ports().find(|p| p.number() == port).map(|p| p.state()))
    }

    /// The packet that settled a port is written down, with the hop counter the
    /// header carried.
    ///
    /// The scanner knows which reply arrived, it is what decides the verdict,
    /// and one that acted on it and threw it away would leave a reader the word
    /// `open` and no account of it, and no way at all to tell a `filtered` a
    /// firewall produced from a `filtered` nothing answered.
    #[test]
    fn an_answered_port_records_the_packet_that_settled_it() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 80);

        let reply = tcp_segment(&scanner, 80, token, SYN | ACK);
        scanner.handle_tcp_reply(&captured_with_ttl(reply, 58), Instant::now());

        let discovery = port_discovery(&session, 80).expect("the port carries its evidence");
        assert_eq!(discovery.reason(), &ScanResponse::TcpSynAck);
        assert_eq!(
            discovery.ttl(),
            Some(58),
            "the hop counter the reply arrived under was not kept"
        );
    }

    /// A reset is recorded as the reset it was, not as the absence of a reply.
    #[test]
    fn a_refused_port_records_the_reset_rather_than_a_silence() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 81);

        let reply = tcp_segment(&scanner, 81, token, RST | ACK);
        scanner.handle_tcp_reply(&captured_with_ttl(reply, 64), Instant::now());

        let discovery = port_discovery(&session, 81).expect("the port carries its evidence");
        assert_eq!(discovery.reason(), &ScanResponse::TcpRst);
        assert_eq!(discovery.ttl(), Some(64));
    }

    /// A synthetic reply has no header to read, and nothing is invented for it.
    ///
    /// The hop counter is the one field here that can only come off a wire, and
    /// a default stamped in its place would be a measurement nobody took.
    #[test]
    fn a_reply_with_no_header_behind_it_claims_no_hop_counter() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 80);

        let reply = tcp_segment(&scanner, 80, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply),
            Instant::now(),
        );

        let discovery = port_discovery(&session, 80).expect("the port carries its evidence");
        assert_eq!(discovery.reason(), &ScanResponse::TcpSynAck);
        assert_eq!(discovery.ttl(), None);
    }

    /// A probe this machine would not send leaves the port on the host saying
    /// nothing was established, rather than leaving it off.
    ///
    /// A link that stops accepting sends refuses every probe behind the one that
    /// noticed, so ports left off would go nowhere at all: not filtered, not
    /// unknown, absent, while the audit counted thousands of failed sends beside
    /// a host that looked cleanly scanned. That is the shortfall a reader cannot
    /// see, and it is the same one `resolve_unasked` closes for the targets
    /// still in the queue.
    #[test]
    fn a_probe_the_sender_refused_leaves_the_port_unasked() {
        let (session, ctx) = ScanSession::new();
        let (_reply_tx, reply_rx) = tokio::sync::mpsc::channel(1024);
        let transport = ProbeTransport::from_parts(Box::new(RefusingSender), reply_rx);
        let resolver = SourceResolver::from_links(&[on_link_interface()]);
        let mut scanner =
            TcpPortScanner::with_transport(resolver, ctx, TcpScanTechnique::Syn, transport, 8);

        scanner.send_probe(PlannedTarget::new(
            80,
            Target {
                ip: TARGET,
                port: 80,
                protocol: Protocol::Tcp,
            },
        ));

        assert_eq!(
            port_state(&session, 80),
            Some(PortState::Unasked),
            "a port whose probe never left this machine went missing from the host"
        );
        assert!(
            !scanner.core.ledger.contains(&(TARGET, 80)),
            "a probe that never went out must not be waiting for an answer"
        );
    }

    /// A port nothing answered records the silence, which is an answer of its
    /// own. Leaving the evidence off would give a verdict no account of itself,
    /// and a reader could not tell that from a report where the account was
    /// dropped.
    #[test]
    fn an_unanswered_port_records_the_silence() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);

        scanner.record_port(TARGET, 80, PortState::Filtered, None);

        assert_eq!(port_state(&session, 80), Some(PortState::Filtered));

        let discovery = port_discovery(&session, 80).expect("the silence is evidence too");
        assert_eq!(discovery.reason(), &ScanResponse::NoResponse);
        assert_eq!(discovery.rtt(), None, "nothing arrived to be timed");
        assert_eq!(discovery.ttl(), None, "and nothing carried a hop count");
    }

    /// A refusal that did arrive is still told apart from a silence, which is
    /// the whole reason either is written down.
    #[test]
    fn a_refusal_is_not_recorded_as_a_silence() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 81);

        scanner.record_port(TARGET, 81, PortState::Filtered, Some(TARGET));

        let discovery = port_discovery(&session, 81).expect("the refusal is evidence");
        assert_eq!(discovery.reason(), &ScanResponse::IcmpProhibited);
    }

    /// A TCP reply carrying `bytes`, as it would have arrived under a header
    /// whose hop counter reads `ttl`.
    fn captured_with_ttl(bytes: Vec<u8>, ttl: u8) -> CapturedSegment {
        CapturedSegment {
            received_at: Instant::now(),
            source: TARGET,
            destination: None,
            protocol: IpNextHeaderProtocols::Tcp,
            bytes,
            observation: Some(IpObservation::V4(crate::model::capture::Ipv4Observation {
                ttl,
                identification: 0,
                dont_fragment: true,
                more_fragments: false,
                dscp: 0,
                ecn: 0,
            })),
            source_mac: None,
        }
    }

    /// One of this scan's own probes as the capture hands it back, which is
    /// what a transport admitting both directions delivers.
    fn own_probe_leaving(bytes: Vec<u8>) -> CapturedSegment {
        CapturedSegment {
            received_at: Instant::now(),
            source: IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2)),
            destination: Some(TARGET),
            protocol: IpNextHeaderProtocols::Tcp,
            bytes,
            observation: None,
            source_mac: None,
        }
    }

    /// The bytes of the probe the recording sender was last handed.
    fn last_sent(sent: &SentProbes) -> Vec<u8> {
        sent.lock().unwrap().last().expect("a probe").0.clone()
    }

    /// A probe seen on the wire is witnessed, and the port still waits for an
    /// answer rather than being resolved by the sighting.
    #[test]
    fn a_probe_seen_leaving_is_witnessed_against_its_own_attempt() {
        let (mut scanner, _session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);
        assert!(
            !scanner.core.audit.witnesses_its_sends(),
            "nothing has been seen yet"
        );

        scanner.handle_reply(&own_probe_leaving(last_sent(&sent)), Instant::now());

        assert_eq!(scanner.core.audit.sends_witnessed(), 1);
        assert!(
            scanner.core.ledger.contains(&(TARGET, 80)),
            "a sighting is not an answer, and must not settle the port"
        );
    }

    /// One frame captured on a bridge and its member underneath is one probe
    /// seen twice, counted once.
    #[test]
    fn the_same_probe_seen_twice_is_witnessed_once() {
        let (mut scanner, _session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);
        let frame = last_sent(&sent);

        scanner.handle_reply(&own_probe_leaving(frame.clone()), Instant::now());
        scanner.handle_reply(&own_probe_leaving(frame), Instant::now());

        assert_eq!(scanner.core.audit.sends_witnessed(), 1);
    }

    /// A segment on this scan's port carrying no live nonce is someone else's
    /// traffic, and witnesses nothing.
    #[test]
    fn a_stranger_on_the_scans_own_port_witnesses_nothing() {
        let (mut scanner, _session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);

        let mut frame = last_sent(&sent);
        // A different nonce: the same shape of segment, from another probe.
        frame[4] ^= 0xFF;

        scanner.handle_reply(&own_probe_leaving(frame), Instant::now());

        assert_eq!(scanner.core.audit.sends_witnessed(), 0);
        assert_eq!(scanner.core.audit.segments_off_target, 0);
    }

    /// The evidence recorded against one of the target's ports.
    fn port_discovery(
        session: &ScanSession,
        port: u16,
    ) -> Option<crate::model::port::discovery::Discovery> {
        session
            .hosts()
            .get(TARGET)?
            .ports()
            .find_map(|probed| (probed.number() == port).then(|| probed.discovery().cloned()))?
    }

    #[test]
    fn syn_ack_matching_probe_is_open() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 80);

        let reply = tcp_segment(&scanner, 80, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 80), Some(PortState::Open));
        assert!(!scanner.core.ledger.contains(&(TARGET, 80)));
    }

    #[test]
    fn rst_matching_probe_is_closed() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 81);

        let reply = tcp_segment(&scanner, 81, token, RST | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 81), Some(PortState::Closed));
    }

    /// An arbitrary flag override softens the verdict to reachable-or-silent,
    /// where the underlying technique would read open or closed.
    ///
    /// SYN+PSH is span-one like a SYN, so the harness's own echo rule still
    /// applies and the answer resolves. A version that read the override's reply
    /// through the technique's verdict would call this reset closed, and one that
    /// left silence to the technique would call it plain filtered: both untrue
    /// of a combination that carries no open/closed meaning.
    #[test]
    fn an_arbitrary_flag_combination_reads_reachable_not_open_or_closed() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Syn);
        scanner.flags_override = Some(SYN | PSH);

        let token = probe(&mut scanner, &sent, 80);
        let reply = tcp_segment(&scanner, 80, token, RST | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply),
            Instant::now(),
        );

        assert_eq!(
            port_state(&session, 80),
            Some(PortState::Unfiltered),
            "a reply to an arbitrary combination proves only reachability"
        );
        assert_eq!(
            scanner.silence_means(),
            PortState::OpenFiltered,
            "and its silence is open-filtered, not a SYN's plain filtered"
        );
    }

    #[test]
    fn reply_carrying_the_wrong_nonce_is_ignored() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 82);

        // Acknowledges a value this scan never sent: a stray or spoofed
        // segment, not a reply to our probe.
        let stray = TcpToken {
            nonce: token.nonce.wrapping_add(999),
        };
        let reply = tcp_segment(&scanner, 82, stray, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 82), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 82)));
    }

    /// The scan's source port is where its answers arrive. A segment carrying
    /// the right nonce but addressed to another port on this host belongs to
    /// somebody else's conversation, and the capture that would normally have
    /// dropped it does not exist on a synthetic transport.
    #[test]
    fn reply_addressed_to_another_port_on_this_host_is_ignored() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 83);

        let elsewhere = scanner.core.src_port.wrapping_add(1);
        let reply = segment_to(83, elsewhere, scanner.technique, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 83), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 83)));
    }

    #[test]
    fn reply_for_unprobed_port_is_ignored() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 80);

        // Same host, but a port we never probed.
        let reply = tcp_segment(&scanner, 1234, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 1234), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 80)));
    }

    #[test]
    fn unanswered_probes_resolve_as_filtered() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 443);

        scanner.resolve_remaining();

        assert_eq!(port_state(&session, 443), Some(PortState::Filtered));
        assert!(scanner.core.ledger.is_empty());
    }

    // ── Techniques ─────────────────────────────────────────────────────────

    /// The same RST, three verdicts. Getting this table wrong reports a firewall
    /// map as a list of closed ports, or the reverse.
    #[test]
    fn a_rst_is_read_according_to_the_probe_that_drew_it() {
        for (technique, expected) in [
            (TcpScanTechnique::Syn, PortState::Closed),
            (TcpScanTechnique::Fin, PortState::Closed),
            (TcpScanTechnique::Null, PortState::Closed),
            (TcpScanTechnique::Xmas, PortState::Closed),
            (TcpScanTechnique::Maimon, PortState::Closed),
            (TcpScanTechnique::Ack, PortState::Unfiltered),
            // The helper builds a reset with no window set, which is what a
            // stack with nothing behind the port announces.
            (TcpScanTechnique::Window, PortState::Closed),
        ] {
            let (mut scanner, session, sent) = scanner_for(technique);
            let token = probe(&mut scanner, &sent, 80);

            let reply = tcp_segment(&scanner, 80, token, RST | ACK);
            scanner.handle_tcp_reply(
                &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
                Instant::now(),
            );

            assert_eq!(port_state(&session, 80), Some(expected), "{technique}");
        }
    }

    /// A RST is negative about the port and positive about the host, whichever
    /// probe drew it: the row most easily forgotten, since the two verdicts
    /// point opposite ways.
    #[test]
    fn a_rst_proves_the_host_is_up_whatever_it_says_about_the_port() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        let token = probe(&mut scanner, &sent, 80);

        let reply = tcp_segment(&scanner, 80, token, RST | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        let host = session.hosts().get(TARGET).expect("host recorded");
        assert!(host.status().is_up());
    }

    /// The window scan's whole claim, end to end: the reset every other
    /// technique reads as a refusal announces the listening socket's own window,
    /// and the port that announced one is open. The zero-window half is in the
    /// table above.
    ///
    /// The evidence matters as much as the verdict here. This open port was
    /// found by a reset, and a report crediting it to a handshake would be
    /// naming a segment the scan never drew.
    #[test]
    fn a_window_scan_reads_an_open_port_out_of_a_reset() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Window);
        let token = probe(&mut scanner, &sent, 80);

        let mut reply = tcp_segment(&scanner, 80, token, RST | ACK);
        MutableTcpPacket::new(&mut reply)
            .expect("the reply is a TCP segment")
            .set_window(8192);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 80), Some(PortState::Open));

        let host = session.hosts().get(TARGET).expect("host recorded");
        assert!(host.status().is_up());
        assert!(
            host.reasons().iter().all(|reason| reason
                .details
                .as_deref()
                .is_some_and(|details| details.contains("rst"))),
            "an open port drawn by a reset was credited to a handshake"
        );
    }

    /// Nothing but a SYN can provoke a SYN+ACK, so one arriving mid-FIN-scan
    /// answered something else and must not be read as an open port.
    #[test]
    fn a_syn_ack_resolves_nothing_for_a_flag_probe() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        let token = probe(&mut scanner, &sent, 80);

        let reply = tcp_segment(&scanner, 80, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 80), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 80)));
    }

    /// What silence means is the other half of the difference between the
    /// families: a SYN or an ACK any live stack would have answered, a flag
    /// probe an open port is required to ignore.
    #[test]
    fn silence_is_filtered_or_open_filtered_by_technique() {
        for (technique, expected) in [
            (TcpScanTechnique::Syn, PortState::Filtered),
            (TcpScanTechnique::Ack, PortState::Filtered),
            (TcpScanTechnique::Window, PortState::Filtered),
            (TcpScanTechnique::Fin, PortState::OpenFiltered),
            (TcpScanTechnique::Null, PortState::OpenFiltered),
            (TcpScanTechnique::Xmas, PortState::OpenFiltered),
            (TcpScanTechnique::Maimon, PortState::OpenFiltered),
        ] {
            let (mut scanner, session, sent) = scanner_for(technique);
            probe(&mut scanner, &sent, 443);

            scanner.resolve_remaining();

            assert_eq!(port_state(&session, 443), Some(expected), "{technique}");
        }
    }

    /// Silence records nothing about the host, whichever verdict it produces.
    /// Promoting it would make `is_alive()` true for a host that has never sent
    /// a packet.
    #[test]
    fn an_unanswered_probe_says_nothing_about_the_host() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Xmas);
        probe(&mut scanner, &sent, 443);

        scanner.resolve_remaining();

        let host = session.hosts().get(TARGET).expect("the port was recorded");
        assert!(!host.status().is_up());
    }

    /// A flag-probe scan and a SYN scan are different strategies as far as a
    /// report is concerned, even though one scanner runs both.
    #[test]
    fn the_reported_strategy_names_the_probe_that_was_sent() {
        assert_eq!(
            scanner_for(TcpScanTechnique::Syn).0.kind(),
            ScannerKind::SynPort
        );
        assert_eq!(
            scanner_for(TcpScanTechnique::Fin).0.kind(),
            ScannerKind::TcpPort
        );
    }

    // ── ICMP errors ────────────────────────────────────────────────────────

    /// An ICMP error as the capture would deliver it, quoting `quoted` back.
    fn icmp_error_quoting(code: IcmpCode, quoted: &[u8], from: IpAddr) -> CapturedSegment {
        let quotation = quote(quoted);
        let mut bytes =
            vec![0u8; DestinationUnreachablePacket::minimum_packet_size() + quotation.len()];
        let mut packet = MutableDestinationUnreachablePacket::new(&mut bytes).unwrap();
        packet.set_icmp_type(IcmpTypes::DestinationUnreachable);
        packet.set_icmp_code(code);
        packet.set_payload(&quotation);

        CapturedSegment::synthetic(from, IpNextHeaderProtocols::Icmp, bytes)
    }

    /// The probe under the IP header a router would have echoed back with it.
    fn quote(probe: &[u8]) -> Vec<u8> {
        let header = ip::build_ipv4_header(
            LOCAL,
            match TARGET {
                IpAddr::V4(v4) => v4,
                IpAddr::V6(_) => unreachable!("the fixture is v4"),
            },
            probe.len() as u16,
            IpNextHeaderProtocols::Tcp,
            ip::HOP_LIMIT_ROUTED,
        )
        .unwrap();
        header.into_iter().chain(probe.iter().copied()).collect()
    }

    /// The most recent probe exactly as it left, for an error to quote.
    fn last_probe_bytes(sent: &SentProbes) -> Vec<u8> {
        let sent = sent.lock().unwrap();
        sent.last().expect("a probe reached the wire").0.clone()
    }

    /// The near-miss that separates the two scanners: an ICMP *port* unreachable
    /// means a closed port when it answers a UDP probe, and cannot mean that
    /// here - no TCP stack emits one - so something in the path rejected the
    /// probe, which is filtered.
    #[test]
    fn a_port_unreachable_about_a_tcp_probe_is_filtered_not_closed() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);

        let error = icmp_error_quoting(
            IcmpCodes::DestinationPortUnreachable,
            &last_probe_bytes(&sent),
            ROUTER,
        );
        scanner.handle_reply(&error, Instant::now());

        assert_eq!(port_state(&session, 80), Some(PortState::Filtered));
        assert!(scanner.core.ledger.is_empty());
    }

    /// The verdict a flag probe cannot reach from silence, and the whole reason
    /// these techniques ask for ICMP at all: `Filtered` where an unanswered
    /// probe would have said open-filtered.
    #[test]
    fn an_administrative_rejection_beats_the_silence_verdict() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Xmas);
        probe(&mut scanner, &sent, 80);

        let error = icmp_error_quoting(
            IcmpCodes::CommunicationAdministrativelyProhibited,
            &last_probe_bytes(&sent),
            ROUTER,
        );
        scanner.handle_reply(&error, Instant::now());

        assert_eq!(port_state(&session, 80), Some(PortState::Filtered));
        assert_ne!(port_state(&session, 80), Some(PortState::OpenFiltered));
    }

    /// A middlebox refusing on a host's behalf is not the host answering. The
    /// address is enforcing a perimeter, which is `Filtered`, and reading it as
    /// `Up` would credit a NAT's reply to the machine behind it.
    #[test]
    fn a_rejection_from_the_path_does_not_prove_the_host_is_up() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);

        let error = icmp_error_quoting(
            IcmpCodes::CommunicationAdministrativelyProhibited,
            &last_probe_bytes(&sent),
            ROUTER,
        );
        scanner.handle_reply(&error, Instant::now());

        let host = session.hosts().get(TARGET).expect("host recorded");
        assert_eq!(host.status(), HostStatus::Filtered);
    }

    /// The same message from the target itself is a host policing its own
    /// traffic, which is a host that exists.
    #[test]
    fn a_rejection_from_the_host_proves_it_is_up() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);

        let error = icmp_error_quoting(
            IcmpCodes::CommunicationAdministrativelyProhibited,
            &last_probe_bytes(&sent),
            TARGET,
        );
        scanner.handle_reply(&error, Instant::now());

        let host = session.hosts().get(TARGET).expect("host recorded");
        assert!(host.status().is_up());
    }

    /// A host unreachable reports on the address, not on the port that happened
    /// to be quoted - so the probe keeps its remaining attempts rather than
    /// taking a verdict the message does not support.
    #[test]
    fn a_host_unreachable_leaves_the_port_undecided() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);

        let error = icmp_error_quoting(
            IcmpCodes::DestinationHostUnreachable,
            &last_probe_bytes(&sent),
            ROUTER,
        );
        scanner.handle_reply(&error, Instant::now());

        assert_eq!(port_state(&session, 80), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 80)));
        assert_eq!(
            session.hosts().get(TARGET).map(|host| host.status()),
            Some(HostStatus::Down)
        );
    }

    /// An error quoting a datagram this scan never sent resolves nothing. The
    /// quoted source port is the only thing that makes it ours, and an ICMP
    /// filter cannot narrow on ports at all - so every ICMP packet on the host
    /// reaches this check.
    #[test]
    fn an_error_quoting_somebody_elses_probe_is_ignored() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);

        // Same shape, but sent from a port this scan never used.
        let theirs = tcp::build_probe(
            TcpScanTechnique::Fin,
            LOCAL_IP,
            TARGET,
            scanner.core.src_port.wrapping_add(1),
            80,
            0xABCD,
        )
        .unwrap();
        let error = icmp_error_quoting(
            IcmpCodes::CommunicationAdministrativelyProhibited,
            &theirs,
            ROUTER,
        );
        scanner.handle_reply(&error, Instant::now());

        assert_eq!(port_state(&session, 80), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 80)));
    }

    /// A SYN scan does not ask its capture for ICMP, so nothing here should
    /// depend on it - but a stray error must still resolve nothing rather than
    /// panic, since a shared interface can deliver one anyway.
    #[test]
    fn a_truncated_error_resolves_nothing() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);

        let mut error = icmp_error_quoting(
            IcmpCodes::DestinationPortUnreachable,
            &last_probe_bytes(&sent),
            ROUTER,
        );
        error.bytes.truncate(12);
        scanner.handle_reply(&error, Instant::now());

        assert_eq!(port_state(&session, 80), None);
        assert!(scanner.core.ledger.contains(&(TARGET, 80)));
    }

    #[test]
    fn non_tcp_targets_are_not_probed() {
        let (mut scanner, _session, _sent) = scanner_with_mock();
        scanner.send_probe(PlannedTarget::new(
            0,
            Target {
                ip: TARGET,
                port: 53,
                protocol: Protocol::Udp,
            },
        ));
        assert!(scanner.core.ledger.is_empty());
    }

    // ── Retransmission ─────────────────────────────────────────────────────

    /// An unanswered probe goes out again, and the port stays undecided in the
    /// meantime rather than being written off after one silence.
    #[test]
    fn an_unanswered_probe_is_sent_again() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);

        scanner.service_retries(Instant::now() + Duration::from_secs(1));

        assert_eq!(sent.lock().unwrap().len(), 2, "the probe was not retried");
        assert!(scanner.core.ledger.contains(&(TARGET, 80)));
        assert_eq!(port_state(&session, 80), None, "no verdict has been earned");
    }

    /// A port whose probes were never seen leaving is unasked, not filtered:
    /// silence from a question nobody heard is evidence of nothing.
    #[test]
    fn a_port_whose_probes_were_never_seen_leaving_is_unasked_not_filtered() {
        let (mut scanner, session, sent) = scanner_with_mock();

        // One port witnessed leaving so the run can see its egress; another not.
        probe(&mut scanner, &sent, 80);
        scanner.handle_reply(&own_probe_leaving(last_sent(&sent)), Instant::now());
        probe(&mut scanner, &sent, 443);

        let mut now = Instant::now();
        for _ in 0..PORT_RETRY_POLICY.max_attempts + 2 {
            now += Duration::from_secs(4);
            scanner.service_retries(now);
        }

        assert_eq!(
            port_state(&session, 443),
            Some(PortState::Unasked),
            "silence from a probe nobody saw leave is not a verdict"
        );
        assert_eq!(
            port_state(&session, 80),
            Some(PortState::Filtered),
            "and a probe that was watched leaving still earns one"
        );
    }

    /// A scan that witnesses no egress reads silence as filtered, as before.
    #[test]
    fn a_scan_that_witnesses_nothing_reads_silence_as_it_always_did() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 443);
        assert!(!scanner.core.audit.witnesses_its_sends(), "test premise");

        let mut now = Instant::now();
        for _ in 0..PORT_RETRY_POLICY.max_attempts + 2 {
            now += Duration::from_secs(4);
            scanner.service_retries(now);
        }

        assert_eq!(port_state(&session, 443), Some(PortState::Filtered));
    }

    /// Filtered is what exhausting the budget means, and it takes the whole
    /// budget to get there.
    #[test]
    fn a_port_is_filtered_only_once_every_attempt_is_spent() {
        let (mut scanner, session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);

        let mut now = Instant::now();
        for _ in 0..PORT_RETRY_POLICY.max_attempts + 2 {
            now += Duration::from_secs(4);
            scanner.service_retries(now);
        }

        assert_eq!(port_state(&session, 80), Some(PortState::Filtered));
        assert_eq!(
            sent.lock().unwrap().len(),
            usize::from(PORT_RETRY_POLICY.max_attempts),
        );
        assert!(scanner.core.ledger.is_empty());
    }

    /// An answered probe must not be resent: a retry after a verdict is pure
    /// traffic, and on a wide scan it multiplies.
    #[test]
    fn an_answered_probe_is_never_retried() {
        let (mut scanner, _session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 80);
        let reply = tcp_segment(&scanner, 80, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        scanner.service_retries(Instant::now() + Duration::from_secs(10));

        assert_eq!(sent.lock().unwrap().len(), 1);
    }

    /// Each attempt carries its own nonce, so a reply to the first arriving
    /// after the second has gone out is still a reply. Matching only the newest
    /// attempt would discard it and report an open port filtered.
    #[test]
    fn a_reply_to_a_superseded_attempt_still_resolves_the_port() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let first = probe(&mut scanner, &sent, 80);

        scanner.service_retries(Instant::now() + Duration::from_secs(1));
        let second = last_probe(scanner.technique, &sent);
        assert_ne!(
            first.nonce, second.nonce,
            "each attempt needs its own identity"
        );

        let reply = tcp_segment(&scanner, 80, first, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        assert_eq!(port_state(&session, 80), Some(PortState::Open));
    }

    /// The other half of that identity, and the one this scan does *not* vary:
    /// every attempt leaves from the port the capture filter was built around,
    /// so a retry's answer arrives where the scan is listening rather than
    /// somewhere the kernel has already dropped.
    #[test]
    fn every_attempt_leaves_from_the_scans_own_port() {
        let (mut scanner, _session, sent) = scanner_with_mock();
        probe(&mut scanner, &sent, 80);
        scanner.service_retries(Instant::now() + Duration::from_secs(1));

        let ports: Vec<u16> = sent
            .lock()
            .unwrap()
            .iter()
            .map(|(segment, _, _)| tcp::parse(segment).unwrap().source_port())
            .collect();

        assert_eq!(ports.len(), 2, "the probe was not retried");
        assert!(
            ports.iter().all(|port| *port == scanner.core.src_port),
            "probes left from {ports:?}, not from {}",
            scanner.core.src_port
        );
    }

    /// Two answers, one port: the second finds nothing outstanding and is
    /// dropped, so it cannot be credited as a second observation.
    #[test]
    fn a_duplicate_reply_resolves_nothing_further() {
        let (mut scanner, session, sent) = scanner_with_mock();
        let token = probe(&mut scanner, &sent, 80);

        let reply = tcp_segment(&scanner, 80, token, SYN | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, reply.clone()),
            Instant::now(),
        );

        let host = session.hosts().get(TARGET).expect("host recorded");
        assert_eq!(host.ports().filter(|p| p.number() == 80).count(), 1);
    }

    /// The scan has to outlive the schedule it commits each probe to, or ports
    /// are written off having never been fully asked.
    #[test]
    fn the_scan_budget_covers_the_whole_retry_schedule() {
        let lifetime = PORT_RETRY_POLICY.worst_case_probe_lifetime();
        let budget = crate::scanner::strategy::raw::DEADLINE_CONFIG
            .allowing_for(lifetime)
            .max_budget
            .for_target_count(1);

        assert!(
            budget > lifetime,
            "a {budget:?} scan cannot finish a {lifetime:?} probe"
        );
    }

    /// An ICMP error built by hand rather than from a probe this scan sent:
    /// the sender chooses the quoted destination, the quoted port and how much
    /// of the header to include.
    fn forged_host_unreachable(
        dst: Ipv4Addr,
        src_port: u16,
        dst_port: u16,
        header_bytes: usize,
    ) -> CapturedSegment {
        let mut tcp_header = vec![0u8; 20];
        tcp_header[0..2].copy_from_slice(&src_port.to_be_bytes());
        tcp_header[2..4].copy_from_slice(&dst_port.to_be_bytes());
        tcp_header[4..8].copy_from_slice(&0xDEAD_BEEFu32.to_be_bytes());
        tcp_header.truncate(header_bytes);

        let ip_header = ip::build_ipv4_header(
            LOCAL,
            dst,
            tcp_header.len() as u16,
            IpNextHeaderProtocols::Tcp,
            ip::HOP_LIMIT_ROUTED,
        )
        .expect("an IPv4 header");
        let quotation: Vec<u8> = ip_header.into_iter().chain(tcp_header).collect();

        let mut bytes =
            vec![0u8; DestinationUnreachablePacket::minimum_packet_size() + quotation.len()];
        let mut packet =
            MutableDestinationUnreachablePacket::new(&mut bytes).expect("an ICMP buffer");
        packet.set_icmp_type(IcmpTypes::DestinationUnreachable);
        packet.set_icmp_code(IcmpCodes::DestinationHostUnreachable);
        packet.set_payload(&quotation);

        CapturedSegment::synthetic(ROUTER, IpNextHeaderProtocols::Icmp, bytes)
    }

    const TARGET_V4: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 200);

    /// **An address this scan never probed is not a host this scan may report.**
    ///
    /// `write_host` creates the record it is handed, so without this check an
    /// unreachable naming a destination of the sender's choosing would invent a
    /// host and file it down. Nothing about the message establishes that the
    /// scan had ever addressed that address at all.
    #[test]
    fn an_unreachable_naming_an_unprobed_address_records_no_host() {
        let (mut scanner, session, _sent) = scanner_for(TcpScanTechnique::Fin);
        let never = Ipv4Addr::new(203, 0, 113, 77);
        let src = scanner.core.src_port;

        scanner.handle_reply(&forged_host_unreachable(never, src, 443, 8), Instant::now());

        assert_eq!(session.hosts().len(), 0, "no host may be invented");
        assert!(session.hosts().get(IpAddr::V4(never)).is_none());
    }

    /// A host that *was* probed still may not be filed down on the word of an
    /// error quoting a port nobody asked about.
    ///
    /// The distinction this protects is the one `HostStatus` is ordered by:
    /// `Unknown` says nothing was heard, and `Down` says an intermediary
    /// answered for the address. A hardened host that silently drops traffic is
    /// the first and must not be reported as the second.
    #[test]
    fn an_unreachable_quoting_an_unprobed_port_does_not_file_the_host_down() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);
        let src = scanner.core.src_port;

        scanner.handle_reply(
            &forged_host_unreachable(TARGET_V4, src, 9999, 8),
            Instant::now(),
        );

        assert_ne!(
            session.hosts().get(TARGET).map(|host| host.status()),
            Some(HostStatus::Down),
            "port 9999 was never probed, so this error is about nothing this scan sent"
        );
    }

    /// A host proved up keeps its status — the promotion rule already saw to
    /// that — but it must not collect the unreachable as a reason either.
    ///
    /// The reasons are the evidence trail, kept because "reachability is a claim
    /// someone will want to check". An unreachable filed against a host that
    /// answered for itself is a claim that cannot be checked, because it is not
    /// true.
    #[test]
    fn a_live_host_does_not_collect_a_forged_unreachable_as_a_reason() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        let token = probe(&mut scanner, &sent, 80);
        let rst = tcp_segment(&scanner, 80, token, RST | ACK);
        scanner.handle_tcp_reply(
            &CapturedSegment::synthetic(TARGET, IpNextHeaderProtocols::Tcp, rst),
            Instant::now(),
        );

        let before = session
            .hosts()
            .get(TARGET)
            .map(|host| host.reasons().len())
            .expect("the host answered");
        let src = scanner.core.src_port;

        scanner.handle_reply(
            &forged_host_unreachable(TARGET_V4, src, 80, 8),
            Instant::now(),
        );

        let host = session.hosts().get(TARGET).expect("still recorded");
        assert!(host.status().is_up(), "the promotion rule holds");
        assert_eq!(
            host.reasons().len(),
            before,
            "an unreachable this scan cannot attribute adds no evidence"
        );
    }

    /// And the honest case still works: a router quoting a probe that really
    /// went out files the host down, which is what the check must not cost.
    #[test]
    fn an_unreachable_quoting_a_real_probe_still_files_the_host_down() {
        let (mut scanner, session, sent) = scanner_for(TcpScanTechnique::Fin);
        probe(&mut scanner, &sent, 80);

        let error = icmp_error_quoting(
            IcmpCodes::DestinationHostUnreachable,
            &last_probe_bytes(&sent),
            ROUTER,
        );
        scanner.handle_reply(&error, Instant::now());

        assert_eq!(
            session.hosts().get(TARGET).map(|host| host.status()),
            Some(HostStatus::Down)
        );
        assert!(
            scanner.core.ledger.contains(&(TARGET, 80)),
            "and the port keeps its remaining attempts"
        );
    }

    /// **A refusal that cannot name the attempt retires nothing.**
    ///
    /// The acknowledgement field sits at offset eight, past what RFC 792
    /// guarantees an ICMP error will quote, so a sender offering only the
    /// minimum names an ack-field technique's probe by its ports and nothing
    /// else. The ports are in every packet this scan sends.
    #[test]
    fn a_refusal_quoting_too_little_to_name_the_attempt_resolves_no_port() {
        for technique in [
            TcpScanTechnique::Ack,
            TcpScanTechnique::Window,
            TcpScanTechnique::Maimon,
        ] {
            let (mut scanner, session, sent) = scanner_for(technique);
            probe(&mut scanner, &sent, 80);

            // The probe as it left, cut to the eight bytes and no further.
            let whole = last_probe_bytes(&sent);
            let error = icmp_error_quoting(
                IcmpCodes::CommunicationAdministrativelyProhibited,
                &whole[..8],
                ROUTER,
            );
            scanner.handle_reply(&error, Instant::now());

            assert_eq!(
                port_state(&session, 80),
                None,
                "{technique:?}: an eight-byte quotation named no attempt"
            );
            assert!(
                scanner.core.ledger.contains(&(TARGET, 80)),
                "{technique:?}: and the probe keeps its remaining attempts"
            );
        }
    }

    /// The four techniques whose nonce is the sequence number are unaffected:
    /// it is inside the guaranteed eight, so a minimal quotation still names
    /// the attempt and still resolves the port.
    #[test]
    fn a_sequence_nonce_technique_still_resolves_on_the_guaranteed_eight() {
        for technique in [
            TcpScanTechnique::Syn,
            TcpScanTechnique::Fin,
            TcpScanTechnique::Null,
            TcpScanTechnique::Xmas,
        ] {
            let (mut scanner, session, sent) = scanner_for(technique);
            probe(&mut scanner, &sent, 80);

            let whole = last_probe_bytes(&sent);
            let error = icmp_error_quoting(
                IcmpCodes::CommunicationAdministrativelyProhibited,
                &whole[..8],
                ROUTER,
            );
            scanner.handle_reply(&error, Instant::now());

            assert_eq!(
                port_state(&session, 80),
                Some(PortState::Filtered),
                "{technique:?}: the sequence number is inside the guaranteed eight"
            );
        }
    }
}