zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
// 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

//! # Deciding what a scan will do, before it does any of it
//!
//! A plan is the set of strategies a scan intends to run, worked out from the
//! targets and the host's own network configuration, with nothing opened and
//! nothing sent. [`discover`](crate::scanner::discover) and
//! [`scan`](crate::scanner::scan) build one and immediately execute it. A caller
//! orchestrating their own scan can build one, look at it, change it, and run
//! the parts they want.
//!
//! ## Why planning is separated from running at all
//!
//! Deciding is where every interesting judgement in a scan lives. Which
//! interface reaches a target, whether a `/64` can be walked, whether a
//! link-local address without a zone can be probed at all, whether a sweep may
//! take leads from the host's neighbour table, which protocols still need an
//! unprivileged fallback: all of that is settled before a single socket is
//! opened, and none of it needs a socket to settle.
//!
//! Fused into the code that spawns tasks, those judgements are unreachable: they
//! cannot be inspected without running a scan, cannot be tested without a host
//! that happens to have the right interfaces, and cannot be adjusted at all.
//! Split out, a plan is a value. `zond --dry-run` is a plan printed instead of
//! run. A caller who wants to sweep two of their five links drops three steps
//! and runs the rest. A test asserts on what *would* happen against a
//! hand-written interface table.
//!
//! ## What a plan costs to build
//!
//! No packets and no sockets. Building one does read the machine's own
//! configuration, the interface list, the routing table, and for a sweep the
//! IPv6 neighbour table, because which strategy reaches a target is a fact
//! about this host and cannot be guessed. Those are ordinary reads of local
//! state, they open nothing, and they are the same reads
//! [`crate::system::interface`] performs for any caller.
//!
//! ## What a plan does not promise
//!
//! That every step will run. A step becomes a strategy through
//! [`DiscoveryStep::into_scanner`], and that is where sockets are opened and
//! where the environment gets its say: a capture that cannot be opened, an
//! interface that disappeared between planning and running. Those surface as a
//! [`StrategyError`] per step, and the scan continues with the rest. A plan is
//! what the engine means to do, not a guarantee about a machine it does not
//! control.

use std::collections::{BTreeSet, HashMap, HashSet};
use std::net::IpAddr;

use tokio::sync::mpsc::UnboundedSender;

use crate::config::limits;
use crate::config::{ProbeTuning, ZondConfig};
use crate::model::exclusion::Exclusions;
use crate::model::ip::range::{IpRange, Ipv6Range};
use crate::model::ip::scoped::ZoneMap;
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::Protocol;
use crate::model::technique::TcpScanTechnique;
use crate::report::ScannerKind;
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::connect::{
    ConnectPortScanner, ConnectScanner, ConnectUdpPortScanner,
};
use crate::scanner::strategy::local::{LocalScanner, Scope};
use crate::scanner::strategy::ports::{
    IdlePortScanner, SctpPortScanner, TcpPortScanner, UdpPortScanner,
};
use crate::scanner::strategy::routed::{RoutedScanner, SynPorts};
use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
use crate::system::interface::Link;
use crate::system::interface::{self, RoutedTarget};
use crate::system::neighbor_cache;
use crate::system::privilege::Privilege;
use crate::{counted, info, warn};

/// Something the scan will not do, decided at planning time.
///
/// A refusal is not a failure of the network and not an address that went
/// unanswered: it was never probed, and the reason is knowable before anything
/// is sent. It is carried out of the plan rather than dropped because the one
/// thing a scanner may never do is stay quiet about ground it did not cover: a
/// caller has to be able to tell "nothing is there" from "nobody looked", and
/// only one of those is visible in a host count.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct RefusedStep {
    /// The strategy that would have taken this work.
    pub scanner: ScannerKind,
    /// What cannot be done, and what the caller could write instead, in one
    /// short line: the ground, then the reason and any remedy in brief. The
    /// reasoning behind each refusal is on the function that builds it, not in
    /// the words a console prints.
    pub reason: String,
}

impl RefusedStep {
    /// The TCP half left undone because `technique` cannot be expressed without
    /// raw sockets.
    ///
    /// A connect scan completes handshakes, so it answers roughly the question
    /// a SYN scan asks. It cannot send a FIN, a flagless segment or a bare ACK,
    /// so it cannot answer what any of those were asked, and substituting it
    /// silently would hand back verdicts from a technique nobody chose.
    ///
    /// Written once because it is reached from two places, and they are not
    /// redundant: [`PortScanPlan::build`] refuses ahead of time when there are
    /// no raw sockets to be had, while the scan's own coverage check refuses
    /// after the fact when a raw socket was expected and would not open. Same
    /// cause, same words, two moments at which it becomes knowable.
    pub fn technique_needs_raw_sockets(technique: TcpScanTechnique) -> Self {
        Self {
            scanner: ScannerKind::for_raw_tcp(technique),
            reason: format!("tcp ports: {technique} scan needs raw sockets (sudo)"),
        }
    }

    /// SCTP ports were named by a scan with no raw sockets to probe them with.
    ///
    /// There is no unprivileged form of an INIT scan: the kernel offers no way
    /// to send a chunk and read the answer without an SCTP stack and an
    /// association, and an association is the one thing this scan avoids
    /// completing. So the ports are refused rather than answered by something
    /// that asked a different question.
    pub fn sctp_needs_raw_sockets() -> Self {
        Self {
            scanner: ScannerKind::SctpPort,
            reason: "sctp ports: init scan needs raw sockets (sudo)".to_string(),
        }
    }

    /// SCTP ports were named for a scan running as an idle scan, which probes
    /// through a third party and has no way to carry an INIT.
    ///
    /// The refusal is the point rather than a limitation. An INIT sent directly
    /// would leave this host's own address on the target, which is the one thing
    /// an idle scan exists to avoid.
    pub fn sctp_not_in_an_idle_scan() -> Self {
        Self {
            scanner: ScannerKind::SctpPort,
            reason: "sctp ports: not probed in an idle scan".to_string(),
        }
    }

    /// UDP ports were named for a scan running as an idle scan, for the reason
    /// [`sctp_not_in_an_idle_scan`](Self::sctp_not_in_an_idle_scan) gives:
    /// the zombie's counter moves only for the TCP segments it answers, so a
    /// datagram has no way to be read through it, and one sent directly would
    /// put this host's address on the target.
    pub fn udp_not_in_an_idle_scan() -> Self {
        Self {
            scanner: ScannerKind::UdpPort,
            reason: "udp ports: not probed in an idle scan".to_string(),
        }
    }

    /// The TCP half left undone on the targets a frames-only run cannot reach.
    ///
    /// [`technique_needs_raw_sockets`](Self::technique_needs_raw_sockets) for
    /// part of a scan: the process sends every other target the probe asked for,
    /// and these, which only the kernel can carry, get no connect standing in
    /// for a technique it does not express.
    pub(crate) fn technique_beyond_frames(technique: TcpScanTechnique, targets: u128) -> Self {
        Self {
            scanner: ScannerKind::for_raw_tcp(technique),
            reason: format!(
                "tcp ports on {}: {technique} scan needs a raw socket (sudo)",
                counted(targets, "target", "targets"),
            ),
        }
    }

    /// The SCTP ports on the targets a frames-only run cannot reach, for the
    /// reason [`sctp_needs_raw_sockets`](Self::sctp_needs_raw_sockets) gives.
    pub(crate) fn sctp_beyond_frames(targets: u128) -> Self {
        Self {
            scanner: ScannerKind::SctpPort,
            reason: format!(
                "sctp ports on {}: init scan needs a raw socket (sudo)",
                counted(targets, "target", "targets"),
            ),
        }
    }

    /// A pass that sends its own segments to a host, left undone on the hosts a
    /// frames-only run cannot reach.
    ///
    /// Nothing stands in for these passes: each reads something only a packet it
    /// built can ask, which is what a connect cannot send. `pass` names the pass
    /// the way a reader would.
    pub(crate) fn pass_beyond_frames(scanner: ScannerKind, pass: &str, hosts: u128) -> Self {
        Self {
            scanner,
            reason: format!(
                "{pass} on {}: needs a raw socket (sudo)",
                counted(hosts, "host", "hosts"),
            ),
        }
    }

    /// A pass that would send the target its own packets, asked for under an
    /// idle scan.
    ///
    /// An idle scan forges every probe from its zombie so the target never
    /// hears from this host; a pass that opens a connection to the target or
    /// sends it a probe from here is the one thing the technique exists to
    /// avoid. So a pass the caller asked for that would do it is refused rather
    /// than run in the open, on the same reasoning
    /// [`idle_needs_privilege`](Self::idle_needs_privilege) refuses the scan
    /// itself. `pass` names it the way a reader would, in as few words as name
    /// it, and `scanner` is the strategy the report files the refusal under.
    ///
    /// The words say what was not run and under what, as
    /// [`udp_not_in_an_idle_scan`](Self::udp_not_in_an_idle_scan)'s do, and
    /// not why: every pass declined here is declined for the one reason above.
    pub(crate) fn pass_not_in_an_idle_scan(scanner: ScannerKind, pass: &str) -> Self {
        Self {
            scanner,
            reason: format!("{pass}: not run in an idle scan"),
        }
    }

    /// An idle scan was asked for through a zombie the exclusions forbid.
    ///
    /// The scan reads the zombie's counter by probing it again and again, so
    /// running it would send an excluded address the most traffic of anything
    /// in the scan. There is no fallback, for the reason
    /// [`idle_needs_privilege`](Self::idle_needs_privilege) gives.
    pub(crate) fn idle_zombie_excluded(zombie: IpAddr) -> Self {
        Self {
            scanner: ScannerKind::Idle,
            reason: format!("idle scan: zombie {zombie} is excluded"),
        }
    }

    /// An idle scan was asked for without the privilege it needs.
    ///
    /// The forged source address of an idle scan's probe can only ride a
    /// self-built frame, which needs privilege. There is no
    /// fallback: scanning the target under this host's own address is the one
    /// thing an idle scan exists to avoid, so the whole of it is refused rather
    /// than run in the open.
    pub fn idle_needs_privilege() -> Self {
        Self {
            scanner: ScannerKind::Idle,
            reason: "idle scan: needs raw sockets (sudo)".to_owned(),
        }
    }

    /// A routed IPv6 range with more addresses than any strategy can walk.
    ///
    /// See [`MAX_ENUMERABLE_ADDRESSES`](crate::system::interface::MAX_ENUMERABLE_ADDRESSES)
    /// for why there is a ceiling at all.
    pub fn routed_range_not_enumerable(range: &Ipv6Range) -> Self {
        Self {
            scanner: ScannerKind::Routed,
            reason: format!(
                "{}: too large to walk (give addresses or a smaller prefix)",
                describe(range)
            ),
        }
    }

    /// A TCP sweep left with no port to ask, every one it would ask being
    /// excluded.
    ///
    /// Refused rather than run, since a sweep asking nothing reports every
    /// address it holds as silent when nothing was put to them. Whatever the
    /// sweep would have reached by TCP is left unasked, and a segment swept at
    /// the link layer is not affected. `scanner` is the sweep refused.
    pub(crate) fn every_discovery_port_excluded(scanner: ScannerKind) -> Self {
        Self {
            scanner,
            reason: "tcp liveness: every port it asks is excluded".to_owned(),
        }
    }

    /// A port target range with more addresses than a port scan can walk.
    ///
    /// Whatever the privilege: the multicast that sweeps a segment's `/64` in
    /// one packet asks who is there, not what each of them serves, so the
    /// remedy is the addresses a sweep found. `scanner` is the port strategy
    /// the phase runs under.
    pub(crate) fn port_range_not_enumerable(range: &Ipv6Range, scanner: ScannerKind) -> Self {
        Self {
            scanner,
            reason: format!(
                "{}: too large to walk (give addresses or a smaller prefix)",
                describe(range)
            ),
        }
    }

    /// The same range, refused by an unprivileged scan.
    ///
    /// Separate wording from [`routed_range_not_enumerable`](Self::routed_range_not_enumerable)
    /// because the remedy is different and it is the more useful half of the
    /// message: a range this size *is* reachable on the local segment with raw
    /// sockets, through the all-nodes echo, which sweeps a `/64` in one packet
    /// rather than walking it. A user told only "too large" would go and narrow
    /// a prefix that root would have covered whole.
    pub fn unprivileged_range_not_enumerable(range: &Ipv6Range) -> Self {
        Self {
            scanner: ScannerKind::Connect,
            reason: format!(
                "{}: too large to walk (sudo sweeps a segment)",
                describe(range)
            ),
        }
    }

    /// A port target that is link-local and names no interface.
    ///
    /// `fe80::1` names a different machine on every segment, and every interface
    /// holds an `fe80::/64`, so there is nothing to choose between them. Written
    /// with an interface, as `fe80::1%en0`, it names one, and the scan sends
    /// from that interface. The reason written out shows the target written
    /// with an interface this host has: up, able to broadcast and holding a
    /// link-local address, the one the default route leaves by first.
    ///
    /// [`RoutedTargets::ambiguous`](crate::system::interface::RoutedTargets)
    /// refuses the same target on the discovery path.
    pub fn link_local_port_target_needs_an_interface(range: &Ipv6Range) -> Self {
        let target = name(range);
        Self {
            scanner: ScannerKind::SynPort,
            reason: format!("{target}: {}", name_an_interface(range)),
        }
    }

    /// One link-local address given on two interfaces in a single scan.
    ///
    /// Each is a different machine, and a port scan records its verdicts under
    /// the address it probed, so the two sets of answers would land on one host
    /// with nothing to say which segment either came from.
    pub fn link_local_port_target_names_two_segments(range: &Ipv6Range) -> Self {
        let target = name(range);
        Self {
            scanner: ScannerKind::SynPort,
            reason: format!("{target}: named on two interfaces (scan one at a time)"),
        }
    }

    /// An on-link IPv6 range too large to walk, in a scan that will not sweep
    /// the segment it is on.
    ///
    /// The one range this engine can reach and declines to. A local segment is
    /// covered by the all-nodes solicitation, which is a single packet whatever
    /// the prefix length, so the remedy is a sweep rather than a smaller
    /// prefix. A [`Scope::Sweep`] step already sends that packet and refuses
    /// nothing.
    ///
    /// Walking it instead would fail silently: the address count overflows the
    /// deadline's target count, the sweep is budgeted as though it had no
    /// targets at all, and it stops a couple of thousand solicitations into a
    /// space of eighteen quintillion having reported the range covered.
    pub fn local_range_needs_a_sweep(range: &Ipv6Range) -> Self {
        Self {
            scanner: ScannerKind::Local,
            reason: format!(
                "{}: too large to walk (sweep the segment instead)",
                describe(range)
            ),
        }
    }
}

/// Takes the IPv6 ranges out of `targets` that are too large to probe one
/// address at a time, leaving the rest.
///
/// The same test the routed path applies, applied where the local path needed
/// it: [`is_enumerable`](interface::is_enumerable) asks it of a range rather
/// than of a set, so a set holding a `/64` and three literal addresses keeps
/// the three.
///
/// IPv4 is untouched, on the same reasoning that leaves it untouched
/// everywhere else: every IPv4 range is finite in a way a person can reason
/// about.
fn withhold_unwalkable(targets: &mut IpSet) -> Vec<Ipv6Range> {
    let unwalkable: Vec<Ipv6Range> = targets
        .v6()
        .iter()
        .filter(|range| !interface::is_enumerable(range))
        .copied()
        .collect();

    if unwalkable.is_empty() {
        return unwalkable;
    }

    let mut kept = IpSet::new();
    for range in targets.v4() {
        kept.push_v4_range(*range);
    }
    for range in targets.v6() {
        if interface::is_enumerable(range) {
            kept.push_v6_range(*range);
        }
    }
    kept.canonicalize();
    *targets = kept;

    unwalkable
}

impl From<RefusedStep> for crate::report::Refusal {
    /// The recorded form of a refusal a plan carries.
    ///
    /// One direction only. A plan's refusal knows how it was decided, and a
    /// recorded one is what a reader is handed afterwards; going back would mean
    /// inventing the decision from the words.
    fn from(step: RefusedStep) -> Self {
        Self::new(step.scanner, step.reason)
    }
}

/// A range as a person wrote it: one address when it covers one, and the span
/// otherwise.
fn name(range: &Ipv6Range) -> String {
    match range.start_addr() == range.end_addr() {
        true => range.start_addr().to_string(),
        false => format!("{}-{}", range.start_addr(), range.end_addr()),
    }
}

/// The opening both refusals above share: which range, and how big it is.
///
/// The size is quoted because it is the argument. "Too large" invites the reader
/// to disagree; "18446744073709551616 addresses" does not.
fn describe(range: &Ipv6Range) -> String {
    format!(
        "{}-{} is {} addresses",
        range.start_addr(),
        range.end_addr(),
        range.len()
    )
}

/// One strategy a discovery sweep intends to run.
///
/// Each variant names a way of reaching a target and the targets it was given.
/// Turning one into a running strategy is [`into_scanner`](Self::into_scanner);
/// until then it is inert.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DiscoveryStep {
    /// ARP and ICMPv6 across one interface's own segment, for targets that share
    /// it. The cheapest and most informative of the three: it is the only one
    /// that yields a MAC address, and the only one that can find a neighbour
    /// nobody named.
    Local {
        /// The interface to sweep from.
        interface: Box<Link>,
        /// The addresses on its segment. May be empty for a
        /// [`Scope::Sweep`], whose most important probe is addressed to nobody.
        targets: IpSet,
        /// Whether this sweep may find hosts nobody asked about.
        scope: Scope,
    },
    /// Raw TCP SYN to targets reached through a gateway, each already paired
    /// with the source address the host would route it from.
    Routed {
        /// The destinations, with their source addresses.
        targets: Vec<RoutedTarget>,
        /// The ports every target is asked about. The common five unless
        /// [`DiscoveryPlan::asking_tcp`] said otherwise.
        ports: SynPorts,
    },
    /// Raw SCTP INIT to the same routed targets, for a scan whose ports name
    /// SCTP.
    ///
    /// Runs beside [`Routed`](Self::Routed) rather than instead of it. A host
    /// answers whichever transport reaches it, and one that answers only SCTP is
    /// reported down by a SYN sweep and never has its ports probed at all, since
    /// the port phase covers what discovery found.
    RoutedSctp {
        /// The destinations, with their source addresses.
        targets: Vec<RoutedTarget>,
        /// The port every INIT is aimed at.
        port: u16,
    },
    /// Ordinary TCP connect attempts, for targets with no route and no segment:
    /// loopback, or anything the OS declined to resolve. Needs no privileges.
    ///
    /// For a process whose raw strategies send frames and nothing else, also
    /// whatever a frame cannot reach, which the scan moves here from the steps
    /// that would have framed it.
    Connect {
        /// The addresses to try.
        targets: IpSet,
        /// The ports every address is asked about, the same set a routed step
        /// asks. The common five unless [`DiscoveryPlan::asking_tcp`] said
        /// otherwise.
        ports: SynPorts,
    },
}

impl DiscoveryStep {
    /// Which strategy this step becomes.
    pub fn kind(&self) -> ScannerKind {
        match self {
            Self::Local { .. } => ScannerKind::Local,
            Self::Routed { .. } => ScannerKind::Routed,
            Self::RoutedSctp { .. } => ScannerKind::RoutedSctp,
            Self::Connect { .. } => ScannerKind::Connect,
        }
    }

    /// How many addresses this step covers.
    ///
    /// Zero is meaningful rather than empty: a [`Scope::Sweep`] step with no
    /// addresses still sends the all-nodes solicitation its whole segment may
    /// answer.
    pub fn target_count(&self) -> u128 {
        match self {
            Self::Local { targets, .. } | Self::Connect { targets, .. } => targets.len(),
            Self::Routed { targets, .. } | Self::RoutedSctp { targets, .. } => {
                targets.len() as u128
            }
        }
    }

    /// Opens whatever this step needs and hands back the strategy to run.
    ///
    /// This is where the plan stops being free. A local step opens a
    /// link-layer channel on its interface; a routed step opens a raw transport
    /// and a capture. Either can fail on an environment the plan could not see,
    /// and that is a [`StrategyError`] rather than a panic, so a caller can
    /// record it and carry on with the steps that did build.
    ///
    /// `dns_tx` is where a strategy posts addresses worth a reverse lookup;
    /// pass `None` to do no hostname resolution.
    pub fn into_scanner(
        self,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        tuning: ProbeTuning,
    ) -> Result<Box<dyn HostScanner>, StrategyError> {
        match self {
            Self::Local {
                interface,
                targets,
                scope,
            } => Ok(Box::new(LocalScanner::new(
                *interface,
                targets,
                ctx,
                dns_tx,
                scope,
                tuning.retry,
            )?)),
            Self::Routed { targets, ports } => Ok(Box::new(RoutedScanner::over_tcp(
                targets, ctx, dns_tx, tuning, ports,
            )?)),
            Self::RoutedSctp { targets, port } => Ok(Box::new(RoutedScanner::over_sctp(
                targets, ctx, dns_tx, tuning, port,
            )?)),
            Self::Connect { targets, ports } => Ok(Box::new(ConnectScanner::asking(
                targets,
                ctx,
                &tuning.evasion,
                ports,
            ))),
        }
    }
}

/// What a discovery sweep intends to do.
///
/// Build one with [`build`](Self::build), read it, change it, run it. See the
/// [module documentation](self) for why this is a value rather than a function
/// call.
#[derive(Debug, Clone)]
pub struct DiscoveryPlan {
    steps: Vec<DiscoveryStep>,
    refusals: Vec<RefusedStep>,
    ours: IpSet,
    /// The neighbours this host's routing table refuses, left to the connect
    /// step rather than asked by frame.
    refused_by_route: IpSet,
    /// The neighbour-table candidates the exclusions kept from a sweep.
    withheld: IpSet,
}

impl DiscoveryPlan {
    /// Works out which strategies would cover `targets`, opening nothing.
    ///
    /// `scope` decides whether the sweep may go beyond what it was given.
    /// [`Scope::Sweep`] earns a step for the link even when no address mapped to
    /// it, its all-nodes echo is one packet the whole segment may answer, and
    /// takes candidate addresses from the host's IPv6 neighbour table, which is
    /// the only source the engine has for an IPv6 address nobody named.
    /// [`Scope::Targeted`] does neither: probing addresses nobody asked about is
    /// defensible for `lan` and surprising for a scan of one named address.
    ///
    /// `exclusions` is what a sweep's own discoveries are held to. The target
    /// list has already been withheld against them by the time it arrives here,
    /// in `withhold_targets`, before anything is opened. A sweep then adds
    /// addresses the list never had, from the host's neighbour table, and those
    /// were never subtracted from anything. `seed_from_neighbor_table` is where
    /// they arrive.
    ///
    /// `forced` pins the source addresses off-link targets are probed from,
    /// empty for a scan that let the routing table choose.
    pub fn build(targets: IpSet, scope: Scope, exclusions: &Exclusions, forced: &[IpAddr]) -> Self {
        let mut steps = Vec::new();
        let mut refusals = Vec::new();
        let mut refused_by_route = IpSet::new();

        let interface::RoutedTargets {
            mut local,
            routed,
            mut unmapped,
            ours,
            ambiguous,
            unenumerable,
        } = interface::map_ips_to_interfaces_forced(targets, forced);

        // A link-local target naming no interface. Refused rather than guessed
        // at: every interface has an `fe80::/64`, so probing the first one that
        // matches would scan an arbitrary segment and report the address absent
        // when it is present on another.
        for range in &ambiguous {
            refusals.push(RefusedStep {
                scanner: ScannerKind::Local,
                reason: format!("{}: {}", range.start_addr(), name_an_interface(range)),
            });
        }

        // Ranges no strategy can take. A routed IPv6 prefix cannot be walked
        // (see `MAX_ENUMERABLE_ADDRESSES`), and with no discovery strategy that
        // searches a scope instead of a list, saying so is the whole of what
        // the engine can honestly do with one.
        for range in &unenumerable {
            refusals.push(RefusedStep::routed_range_not_enumerable(range));
        }

        // A sweep may probe addresses nobody named, so it may also take leads
        // from the host itself. A targeted run may not.
        let mut withheld = IpSet::new();
        if matches!(scope, Scope::Sweep) {
            include_swept_link(&mut local);
            withheld = seed_from_neighbor_table(&mut local, exclusions);
        }

        for (interface, mut targets) in local {
            // An on-link range too large to walk is dropped here rather than
            // handed on. `map_ips_to_interfaces` keeps such a range whole,
            // because the strategy for a segment is the all-nodes solicitation
            // and that is one packet whatever the prefix length - but the
            // solicitation is a sweep's, and the walk below it is what a
            // targeted run has. See `local_range_needs_a_sweep`.
            for range in withhold_unwalkable(&mut targets) {
                match scope {
                    // Covered: the sweep sends the one packet the whole segment
                    // answers, so nothing is lost by not walking the prefix.
                    Scope::Sweep => info!(
                        verbosity = 1,
                        "{} is swept by solicitation rather than walked",
                        describe(&range)
                    ),
                    Scope::Targeted => {
                        refusals.push(RefusedStep::local_range_needs_a_sweep(&range))
                    }
                }
            }

            // A neighbour this host's routing table refuses is not asked by
            // frame, which would step around the table, and is left to the
            // connect step, whose connect the kernel refuses as it refuses
            // every other program's, and which files the address as one
            // nothing reaches. The port scan refuses it the same way; see
            // `SourceResolver::resolve`.
            let refused = interface::refused_neighbours(&interface, &targets);
            if !refused.is_empty() {
                targets.subtract(&refused);
                for address in refused.iter() {
                    unmapped.insert(address);
                    refused_by_route.insert(address);
                }
                info!(
                    verbosity = 1,
                    "{} on {} refused by a route, not asked by frame",
                    counted(refused.len(), "address", "addresses"),
                    interface.name()
                );
            }

            // A sweep's link earns a step whether or not any address mapped to
            // it. A targeted run has nothing to send without targets.
            if targets.is_empty() && matches!(scope, Scope::Targeted) {
                continue;
            }
            // Said here, once, because this is where it is decided. The lookup
            // that found the link answers whoever asks, and is asked more than
            // once a run.
            if matches!(scope, Scope::Sweep) {
                info!(
                    verbosity = 1,
                    "sweeping {}: {}",
                    interface.name(),
                    match targets.len() {
                        0 => "IPv6 neighbours only, having no IPv4 range to walk".to_string(),
                        count => counted(count, "address", "addresses"),
                    }
                );
            }
            steps.push(DiscoveryStep::Local {
                interface: Box::new(interface),
                targets,
                scope,
            });
        }

        if !routed.is_empty() {
            steps.push(DiscoveryStep::Routed {
                targets: routed,
                ports: SynPorts::common(),
            });
        }

        if !unmapped.is_empty() {
            steps.push(DiscoveryStep::Connect {
                targets: unmapped,
                ports: SynPorts::common(),
            });
        }

        Self {
            steps,
            refusals,
            ours,
            refused_by_route,
            withheld,
        }
    }

    /// The addresses from this host's IPv6 neighbour table that a plan
    /// [built](Self::build) from the same arguments would take as candidates
    /// for its sweep and the exclusions keep from it, read from the same
    /// tables without planning anything or saying anything.
    ///
    /// A scan counts these among the addresses its policy withheld, beside
    /// the targets it names, so a caller stating that count before the scan
    /// runs has them to add. Empty for [`Scope::Targeted`], which takes no
    /// candidates. A plan like this one is how a run holding raw sockets or
    /// the link layer sweeps; a run without either takes no candidates and so
    /// withholds none.
    pub fn withheld_neighbours(
        targets: IpSet,
        scope: Scope,
        exclusions: &Exclusions,
        forced: &[IpAddr],
    ) -> IpSet {
        if !matches!(scope, Scope::Sweep) {
            return IpSet::new();
        }
        let mut local = interface::map_ips_to_interfaces_forced(targets, forced).local;
        include_swept_link(&mut local);
        let table = neighbor_cache::ipv6_neighbors();
        let machines = machines_named(exclusions, &table);
        let mut withheld = IpSet::new();
        for intf in local.keys() {
            for candidate in candidates_on(intf, &table, exclusions, &machines) {
                if candidate.withheld {
                    withheld.insert_range(candidate.range);
                }
            }
        }
        withheld.canonicalize();
        withheld
    }

    /// The neighbours this host's routing table refuses, which the plan left
    /// to the connect step rather than asking by frame; see
    /// [`refused_neighbours`](interface::refused_neighbours).
    pub(crate) fn refused_by_route(&self) -> &IpSet {
        &self.refused_by_route
    }

    /// The neighbour-table candidates the exclusions kept from this plan's
    /// sweep, which its phase counts among the addresses its policy withheld;
    /// see [`withheld_neighbours`](Self::withheld_neighbours).
    pub(crate) fn withheld(&self) -> &IpSet {
        &self.withheld
    }

    /// Adds an SCTP sweep beside every routed step, asking `port`.
    ///
    /// Apart from [`build`](Self::build) for the reason
    /// [`PortScanPlan::cover_sctp`] is: what decides it is the
    /// port specification, which belongs to the targets and not to the addresses
    /// this plan was built from. A caller that never mentions SCTP sweeps with a
    /// SYN alone and opens no second socket.
    ///
    /// Only the routed steps gain one. A local segment is swept at the link
    /// layer, where ARP and neighbour discovery answer whatever the host speaks
    /// above them, and an unprivileged connect step has no raw socket to send an
    /// INIT through.
    pub fn also_over_sctp(&mut self, port: u16) {
        let sctp: Vec<DiscoveryStep> = self
            .steps
            .iter()
            .filter_map(|step| match step {
                DiscoveryStep::Routed { targets, .. } => Some(DiscoveryStep::RoutedSctp {
                    targets: targets.clone(),
                    port,
                }),
                _ => None,
            })
            .collect();
        self.steps.extend(sctp);
    }

    /// Asks every routed and connect target about `ports` in place of the
    /// common five.
    ///
    /// Apart from [`build`](Self::build) for the reason
    /// [`also_over_sctp`](Self::also_over_sctp) is: the ports a port scan is
    /// about belong to its targets, not to the addresses this plan was built
    /// from. A port scan's liveness pass passes [`SynPorts::for_scan`], so a
    /// host that drops a SYN to anything it does not serve is still asked about
    /// the ports the scan is about to ask it.
    ///
    /// The routed and the connect steps change alike, so which of the two
    /// reaches an address decides nothing about which ports it is asked on.
    /// A segment is swept at the link layer, where a host answers ARP and
    /// neighbour discovery whatever it filters above them, and is left as it
    /// was.
    ///
    /// An empty set takes the routed and connect steps out and refuses each,
    /// which is what a sweep whose every port was excluded comes to; see
    /// `RefusedStep::every_discovery_port_excluded`.
    pub fn asking_tcp(&mut self, ports: SynPorts) {
        if ports.is_empty() {
            let refusals = &mut self.refusals;
            self.steps.retain(|step| match step {
                DiscoveryStep::Routed { .. } | DiscoveryStep::Connect { .. } => {
                    refusals.push(RefusedStep::every_discovery_port_excluded(step.kind()));
                    false
                }
                _ => true,
            });
            return;
        }
        for step in &mut self.steps {
            if let DiscoveryStep::Routed { ports: asked, .. }
            | DiscoveryStep::Connect { ports: asked, .. } = step
            {
                *asked = ports;
            }
        }
    }

    /// Takes `targets` out of every step that sends its own packets, and returns
    /// what was taken.
    ///
    /// For a process whose raw strategies put frames on the wire and hold
    /// nothing behind them. A frame reaches what has Ethernet in front of it;
    /// `targets` is the rest, as
    /// [`beyond_frames`](crate::system::interface::beyond_frames) worked it out
    /// for the segment sweep. Left in a routed step, a target the kernel routes
    /// through a tunnel is sent a frame out of the wrong interface, and loopback
    /// no frame at all.
    ///
    /// A step left with nothing to send is dropped, except a sweep's local step
    /// on a link that carries frames: its most important probe is addressed to
    /// nobody, and it still has a segment to send it on. The connect step is
    /// left alone, since connect is not a frame.
    pub(crate) fn withhold(&mut self, targets: &IpSet) -> IpSet {
        let mut taken = IpSet::new();
        if targets.is_empty() {
            return taken;
        }

        for step in &mut self.steps {
            match step {
                DiscoveryStep::Local { targets: held, .. } => {
                    let mut kept = held.clone();
                    kept.subtract(targets);
                    // What the subtraction removed, which is the part of this
                    // step's targets the set named.
                    let mut gone = held.clone();
                    gone.subtract(&kept);
                    for range in gone.v4() {
                        taken.push_v4_range(*range);
                    }
                    for range in gone.v6() {
                        taken.push_v6_range(*range);
                    }
                    *held = kept;
                }
                DiscoveryStep::Routed { targets: held, .. }
                | DiscoveryStep::RoutedSctp { targets: held, .. } => held.retain(|routed| {
                    let out = targets.contains(&routed.target);
                    if out {
                        taken.insert(routed.target);
                    }
                    !out
                }),
                DiscoveryStep::Connect { .. } => {}
            }
        }

        self.steps.retain(|step| match step {
            DiscoveryStep::Local {
                interface,
                targets,
                scope,
            } => {
                !targets.is_empty() || (matches!(scope, Scope::Sweep) && interface.carries_frames())
            }
            DiscoveryStep::Routed { targets, .. } | DiscoveryStep::RoutedSctp { targets, .. } => {
                !targets.is_empty()
            }
            DiscoveryStep::Connect { .. } => true,
        });

        taken.canonicalize();
        taken
    }

    /// [`withhold`](Self::withhold)s `targets` and hands what was taken to the
    /// connect step, adding one where the plan has none. Returns what moved.
    ///
    /// Connect is how an unprivileged sweep reaches a target, and so how a
    /// frames-only one reaches what its frames cannot.
    pub(crate) fn connect_instead(&mut self, targets: &IpSet) -> IpSet {
        let moved = self.withhold(targets);
        if moved.is_empty() {
            return moved;
        }

        let existing = self.steps.iter_mut().find_map(|step| match step {
            DiscoveryStep::Connect { targets, .. } => Some(targets),
            _ => None,
        });
        match existing {
            Some(held) => {
                for range in moved.v4() {
                    held.push_v4_range(*range);
                }
                for range in moved.v6() {
                    held.push_v6_range(*range);
                }
                held.canonicalize();
            }
            // Asking what the routed steps ask, since these are addresses a
            // routed step would have swept had a frame reached them.
            None => {
                let ports = self
                    .steps
                    .iter()
                    .find_map(|step| match step {
                        DiscoveryStep::Routed { ports, .. } => Some(*ports),
                        _ => None,
                    })
                    .unwrap_or_else(SynPorts::common);
                self.steps.push(DiscoveryStep::Connect {
                    targets: moved.clone(),
                    ports,
                });
            }
        }
        moved
    }

    /// The strategies this plan would run.
    pub fn steps(&self) -> &[DiscoveryStep] {
        &self.steps
    }

    /// The strategies this plan would run, to drop or reorder before running it.
    pub fn steps_mut(&mut self) -> &mut Vec<DiscoveryStep> {
        &mut self.steps
    }

    /// Ground this plan will not cover, and why.
    /// The targets that are this host's own addresses.
    ///
    /// Up by construction and covered by no step, because no strategy can
    /// establish one: the kernel routes traffic for an address this host holds
    /// through loopback, so a probe never reaches the link and nothing on the
    /// link answers for it. Were these handed to a strategy, scanning a machine
    /// by its own LAN address would report it down while `ping` to the same
    /// address succeeds.
    ///
    /// A caller running the plan itself records these up rather than probing
    /// them; [`orchestrator`](crate::scanner) does.
    pub fn ours(&self) -> &IpSet {
        &self.ours
    }

    /// Ground this plan will not cover, and why.
    pub fn refusals(&self) -> &[RefusedStep] {
        &self.refusals
    }

    /// Takes the steps out, leaving the plan empty.
    pub fn into_steps(self) -> Vec<DiscoveryStep> {
        self.steps
    }
}

/// One strategy a port scan intends to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PortScanStep {
    /// Raw TCP probes classified from a single exchange, without completing a
    /// handshake. Needs raw sockets.
    RawTcp {
        /// Which flags the probe carries, and so which question it asks.
        technique: TcpScanTechnique,
    },
    /// Raw UDP probes, classified from a direct reply or an ICMP unreachable.
    /// Needs raw sockets.
    RawUdp,
    /// Raw SCTP INIT probes, classified from the chunk that answers. Needs raw
    /// sockets, and has no unprivileged counterpart.
    RawSctp,
    /// A full TCP connect per target. Needs no privileges, and answers roughly
    /// the question a SYN scan asks.
    ConnectTcp,
    /// An unprivileged UDP probe.
    ConnectUdp,
    /// The idle (zombie) TCP scan: port states read off a third party's IP-ID
    /// counter, so the target is never addressed under this host's own address.
    /// Needs the self-built frame a forged source requires.
    Idle {
        /// The zombie whose counter is the side channel.
        zombie: IpAddr,
        /// The port on the zombie to read the counter from, or `None` for the
        /// scanner's default.
        zombie_port: Option<u16>,
    },
}

impl PortScanStep {
    /// Which strategy this step becomes.
    ///
    /// The raw TCP name depends on the technique, because
    /// [`ScannerKind::SynPort`] means a half-open connection attempt was made
    /// and the flag probes make none. [`ScannerKind::for_raw_tcp`] is where
    /// that rule lives, so a step and the scanner it builds cannot disagree.
    pub fn kind(&self) -> ScannerKind {
        match self {
            Self::RawTcp { technique } => ScannerKind::for_raw_tcp(*technique),
            Self::RawUdp => ScannerKind::UdpPort,
            Self::RawSctp => ScannerKind::SctpPort,
            Self::ConnectTcp => ScannerKind::Connect,
            Self::ConnectUdp => ScannerKind::ConnectUdp,
            Self::Idle { .. } => ScannerKind::Idle,
        }
    }

    /// The transport protocol this step probes.
    pub fn protocol(&self) -> Protocol {
        match self {
            Self::RawTcp { .. } | Self::ConnectTcp | Self::Idle { .. } => Protocol::Tcp,
            Self::RawUdp | Self::ConnectUdp => Protocol::Udp,
            Self::RawSctp => Protocol::Sctp,
        }
    }

    /// Whether this step needs raw sockets.
    ///
    /// Asked after a scan is assembled, to decide whether host enrichment is
    /// worth running: ARP, ICMPv6 and raw TCP are what yield a MAC and a round
    /// trip, and the connect fallbacks yield neither.
    ///
    /// A property of the step rather than of its [`kind`](Self::kind), because
    /// the two answer different questions. Read off the name instead, this
    /// would be wrong for every raw technique not called `syn_port`.
    pub fn is_raw(&self) -> bool {
        matches!(self, Self::RawTcp { .. } | Self::RawUdp | Self::RawSctp)
    }

    /// Opens whatever this step needs and hands back the strategy to run.
    ///
    /// `target_count` sizes the probe ledger; a raw scanner uses it to reserve
    /// correlation state up front rather than growing it under load.
    ///
    /// `zones` names the interface each of the scan's link-local targets was
    /// given on, which is where both families of scanner get the scope id they
    /// send under. It is empty for a scan that named none.
    pub fn into_scanner(
        self,
        ctx: ScanContext,
        target_count: usize,
        tuning: ProbeTuning,
        zones: ZoneMap,
    ) -> Result<Box<dyn PortScanner>, StrategyError> {
        match self {
            Self::RawTcp { technique } => Ok(Box::new(TcpPortScanner::new(
                interface::SourceResolver::from_system()
                    .with_zones(zones)
                    .with_forced(tuning.send_source.clone()),
                ctx,
                technique,
                target_count,
                tuning,
            )?)),
            Self::RawUdp => Ok(Box::new(UdpPortScanner::new(
                interface::SourceResolver::from_system()
                    .with_zones(zones)
                    .with_forced(tuning.send_source.clone()),
                ctx,
                target_count,
                tuning,
            )?)),
            Self::RawSctp => Ok(Box::new(SctpPortScanner::new(
                interface::SourceResolver::from_system()
                    .with_zones(zones)
                    .with_forced(tuning.send_source.clone()),
                ctx,
                target_count,
                tuning,
            )?)),
            Self::ConnectTcp => Ok(Box::new(
                ConnectPortScanner::new(
                    ctx,
                    limits::CONNECT_CONCURRENCY,
                    tuning.service_detection,
                    &tuning.evasion,
                )
                .with_zones(zones),
            )),
            Self::ConnectUdp => Ok(Box::new(
                ConnectUdpPortScanner::with_detection(
                    ctx,
                    limits::CONNECT_CONCURRENCY,
                    &tuning.evasion,
                    tuning.service_detection,
                )
                .with_zones(zones),
            )),
            Self::Idle {
                zombie,
                zombie_port,
            } => Ok(Box::new(IdlePortScanner::new(
                ctx,
                zombie,
                zombie_port,
                tuning,
            )?)),
        }
    }
}

/// What a port scan intends to do.
#[derive(Debug, Clone)]
pub struct PortScanPlan {
    steps: Vec<PortScanStep>,
    refusals: Vec<RefusedStep>,
    /// The protocol each of `refusals` leaves unprobed, kept beside them
    /// because a refusal is words and the scan has to act on it too: a target
    /// of a refused protocol still reaches the router, and has to be counted
    /// there as what the plan declined rather than as work a scanner lost.
    refused: Vec<Protocol>,
    technique: TcpScanTechnique,
    /// Whether this is an idle scan, whether or not its idle step survived.
    ///
    /// Kept apart from the steps because a refused idle scan has no idle step,
    /// and is still an idle scan: what the targets name on another transport is
    /// refused as one, rather than planned as the direct probe the caller chose
    /// an idle scan to avoid sending. Read from the steps instead, a privileged
    /// run through an excluded zombie would plan the target's SCTP ports as a
    /// direct probe from this host's own address.
    idle: bool,
}

impl PortScanPlan {
    /// Works out which strategies would probe the requested ports, opening
    /// nothing.
    ///
    /// `privilege` is which sockets the scan would run with. It is a parameter
    /// rather than something read here so a caller can plan for a privilege
    /// level they do not currently hold: asking "what would a root scan do?"
    /// is a reasonable question and needs no root to answer.
    ///
    /// ## The fallback is decided per protocol, not per scan
    ///
    /// A host can be able to build one raw scanner and not the other: the TCP
    /// scanner needs a raw TCP socket, the UDP scanner a raw UDP one, and a
    /// sandbox can permit one and refuse the other. A protocol left with no
    /// strategy at all is not a degraded scan but a silent one: nothing would
    /// route those targets anywhere, so they would never be probed and never be
    /// reported.
    ///
    /// ## A connect fallback substitutes for a SYN scan and for nothing else
    ///
    /// It completes handshakes, so it answers roughly the question a SYN scan
    /// asks. It cannot send a FIN, a flagless segment or a bare ACK, so it
    /// cannot answer what any of those were asked. Where the caller chose one of
    /// those and raw sockets are unavailable, the TCP half is refused and left
    /// undone: worse for the caller, and honest, where a silent substitution
    /// would hand back verdicts from a technique they did not choose with no
    /// field in the report saying so.
    pub fn build(cfg: &ZondConfig, privilege: Privilege) -> Self {
        let mut plan = Self {
            steps: Vec::new(),
            refusals: Vec::new(),
            refused: Vec::new(),
            technique: cfg.tcp_technique,
            idle: cfg.idle_scan.is_some(),
        };

        // An idle scan replaces the ordinary port scan wholesale. It is TCP-only
        // by nature, a UDP port has no counter to be read through, and probing
        // one directly would announce the scanner the technique exists to hide,
        // so no step covers UDP. The refusal that says so waits for the targets
        // to name a UDP port; see `cover_udp`.
        if let Some(idle) = &cfg.idle_scan {
            // Asked first: a policy refusal holds whatever the privilege, and
            // telling somebody to find root for a scan that would be refused
            // anyway sends them the wrong way. The zombie is named in settings
            // rather than in the target list, so nothing else withholds it.
            if cfg.exclusions.excludes(&idle.zombie) {
                plan.refuse(
                    Protocol::Tcp,
                    RefusedStep::idle_zombie_excluded(idle.zombie),
                );
            } else if privilege.is_raw() {
                plan.steps.push(PortScanStep::Idle {
                    zombie: idle.zombie,
                    zombie_port: idle.zombie_port,
                });
            } else {
                plan.refuse(Protocol::Tcp, RefusedStep::idle_needs_privilege());
            }
            return plan;
        }

        // Raw scanning needs both the privilege and an address to probe from.
        let raw = Self::raw_scanning(privilege);
        if privilege.is_raw() && !raw {
            warn!("no usable network interface found; using TCP connect fallback");
        }

        // The TCP step alone. UDP is added by [`cover_udp`] when the targets
        // name a UDP port, the way SCTP is by [`cover_sctp`]: a step built here
        // whatever the targets name would open a UDP scanner on every TCP-only
        // scan, which probes nothing and reports an empty audit for a transport
        // nobody asked about.
        if raw {
            plan.steps.push(PortScanStep::RawTcp {
                technique: cfg.tcp_technique,
            });
        } else if cfg.tcp_technique.has_connect_fallback() {
            plan.steps.push(PortScanStep::ConnectTcp);
        } else {
            plan.refuse(
                Protocol::Tcp,
                RefusedStep::technique_needs_raw_sockets(cfg.tcp_technique),
            );
        }

        plan
    }

    /// Whether this host can raw-scan: it holds the privilege and has an address
    /// to probe from. The decision [`build`](Self::build) makes for the TCP
    /// step, read again where the UDP step is added so the two agree.
    fn raw_scanning(privilege: Privilege) -> bool {
        privilege.is_raw() && interface::SourceResolver::from_system().has_sources()
    }

    /// Records that `protocol` will not be probed, and the refusal that says
    /// why.
    fn refuse(&mut self, protocol: Protocol, refusal: RefusedStep) {
        self.refusals.push(refusal);
        self.refused.push(protocol);
    }

    /// The TCP technique this plan was built for.
    ///
    /// Kept because it outlives the steps: if a raw step fails to open, whether
    /// a connect scanner may stand in for it depends on which question the
    /// technique asks, and by then the step is gone.
    pub fn technique(&self) -> TcpScanTechnique {
        self.technique
    }

    /// The strategies this plan would run.
    pub fn steps(&self) -> &[PortScanStep] {
        &self.steps
    }

    /// The strategies this plan would run, to drop or reorder before running it.
    pub fn steps_mut(&mut self) -> &mut Vec<PortScanStep> {
        &mut self.steps
    }

    /// Ports this plan will not probe, and why.
    pub fn refusals(&self) -> &[RefusedStep] {
        &self.refusals
    }

    /// Takes the steps out, leaving the plan empty.
    pub fn into_steps(self) -> Vec<PortScanStep> {
        self.steps
    }

    /// Adds the step that probes SCTP, or the refusal that says why it could
    /// not be added.
    ///
    /// Apart from [`build`](Self::build) because what decides it is not in the
    /// configuration. SCTP ports are named in a target's port specification,
    /// which the plan is built before reading, and no default port list holds
    /// one: a scan that never mentions SCTP opens no socket for it, where a step
    /// added unconditionally would cost every privileged run a raw socket and a
    /// capture for a transport nobody asked about.
    ///
    /// Called with the same `privilege` the plan was built for.
    pub fn cover_sctp(&mut self, privilege: Privilege) {
        if self.idle {
            self.refuse(Protocol::Sctp, RefusedStep::sctp_not_in_an_idle_scan());
            return;
        }

        // The same two conditions raw scanning is planned under in `build`:
        // the privilege, and an address to send from.
        if privilege.is_raw() && interface::SourceResolver::from_system().has_sources() {
            self.steps.push(PortScanStep::RawSctp);
        } else {
            self.refuse(Protocol::Sctp, RefusedStep::sctp_needs_raw_sockets());
        }
    }

    /// Adds the step that probes UDP, or the refusal that says why it could not
    /// be added.
    ///
    /// Apart from [`build`](Self::build) for the reason [`cover_sctp`](Self::cover_sctp)
    /// is: whether a UDP port was named is in the targets, which the plan is
    /// built before reading. A step added there whatever the targets name would
    /// open a UDP scanner on every TCP-only scan, to probe nothing and report an
    /// empty audit; and an idle scan of TCP ports alone would carry a UDP
    /// refusal about ground nobody asked for. Called only when the targets name
    /// a UDP port, it adds the connect or raw step the run's privilege calls
    /// for, or, under an idle scan whose counter carries no datagram, the
    /// refusal that says the port goes unprobed.
    ///
    /// Called with the same `privilege` the plan was built for, so the UDP step
    /// is raw exactly where the TCP step is.
    pub fn cover_udp(&mut self, privilege: Privilege) {
        if self.covers(Protocol::Udp) {
            return;
        }
        if self.idle {
            self.refuse(Protocol::Udp, RefusedStep::udp_not_in_an_idle_scan());
        } else if Self::raw_scanning(privilege) {
            self.steps.push(PortScanStep::RawUdp);
        } else {
            self.steps.push(PortScanStep::ConnectUdp);
        }
    }

    /// Whether one of [`refusals`](Self::refusals) leaves `protocol`
    /// unprobed.
    ///
    /// Not the same question as [`covers`](Self::covers) answered in the
    /// negative. A protocol no step covers and no refusal names is one the
    /// plan left out without saying so, and the scan reports its targets as
    /// lost; one a refusal names has already been reported, and its targets
    /// are what that refusal is about.
    pub(crate) fn refuses(&self, protocol: Protocol) -> bool {
        self.refused.contains(&protocol)
    }

    /// Whether any step covers `protocol`.
    ///
    /// Read after a caller has edited [`steps_mut`](Self::steps_mut): a plan
    /// with nothing for a protocol probes none of its ports and reports none of
    /// them, which is silence rather than a finding.
    pub fn covers(&self, protocol: Protocol) -> bool {
        self.steps.iter().any(|step| step.protocol() == protocol)
    }
}

/// Makes sure the link a sweep is about is among the links to be scanned, even
/// when no address mapped to it.
///
/// Mapping targets to interfaces can only ever produce interfaces some target
/// named, and the whole point of a sweep is the probe that names nobody. A link
/// addressed only in IPv6 resolves to no target list at all, a `/64` cannot be
/// enumerated and there is no IPv4 range to walk, so it maps to nothing, no
/// step is built for it, and the all-nodes echo that would have found its entire
/// segment is never sent. The scan reports an empty network and looks like it
/// worked.
///
/// Matching by name rather than by value: `map_ips_to_interfaces` and this both
/// read the platform's interface list, but a `NetworkInterface` compares on
/// every field, and being wrong here means scanning one link twice.
fn include_swept_link(local: &mut HashMap<Link, IpSet>) {
    let Some(link) = interface::lan_link() else {
        return;
    };

    if local.keys().any(|intf| intf.name() == link.link.name()) {
        return;
    }

    local.insert(link.link, IpSet::new());
}

/// Adds the addresses in this host's IPv6 neighbour table to the targets of
/// whichever interface each belongs to.
///
/// This is the only source the engine has for an IPv6 address nobody named. A
/// neighbor solicitation is the mandatory probe, and it can only be aimed at an
/// address someone already holds; the all-nodes echo produces addresses but is
/// optional to answer and draws only link-local ones, since it goes out from a
/// link-local source. The operating system's own table has been accumulating
/// both for as long as the machine has been running, at no cost in packets: on
/// the segment this was written against it holds fifteen global and unique-local
/// addresses the engine could not otherwise learn at all.
///
/// Three exclusions, each for its own reason:
///
/// - **Other interfaces' entries.** A neighbour on `en1` is not reachable
///   through `en0`, and the entry says which it belongs to.
/// - **This host's own addresses.** The table lists them too, and a scan that
///   reported the machine running it as a discovered neighbour would be wrong in
///   a way nobody would think to check.
/// - **Loopback and the unspecified address**, which name nothing on a segment.
///
/// Nothing seeded here is treated as a discovered host. Every entry is an
/// address that answered *once*, from a table that goes stale, so each becomes a
/// probe like any other and earns its place in the report by answering now.
///
/// Returns the candidates `exclusions` kept from the sweep, which the phase
/// counts among the addresses its policy withheld.
fn seed_from_neighbor_table(local: &mut HashMap<Link, IpSet>, exclusions: &Exclusions) -> IpSet {
    let table = neighbor_cache::ipv6_neighbors();
    if table.is_empty() {
        return IpSet::new();
    }
    let machines = machines_named(exclusions, &table);
    seed_from_neighbor_table_with(local, &table, exclusions, &machines)
}

/// The machines `exclusions` name, by hardware address, read off both
/// neighbour tables, `v6_table` among them: an excluded IPv4 address is tied
/// to its machine's IPv6 ones by nothing but the hardware address they share.
fn machines_named(
    exclusions: &Exclusions,
    v6_table: &[neighbor_cache::Neighbor],
) -> BTreeSet<MacAddr> {
    if exclusions.is_empty() {
        return BTreeSet::new();
    }
    let v4 = neighbor_cache::ipv4_neighbors();
    exclusions.hardware_in(v4.iter().chain(v6_table).map(|entry| (entry.ip, entry.mac)))
}

/// [`seed_from_neighbor_table`] against an explicit table, so the exclusions can
/// be tested without a host that happens to have the right neighbours.
///
/// `machines` are the hardware addresses of the machines the exclusions name,
/// and an entry answering from one is held to the policy as its excluded
/// address is; see [`Exclusions::hardware_in`].
fn seed_from_neighbor_table_with(
    local: &mut HashMap<Link, IpSet>,
    table: &[neighbor_cache::Neighbor],
    exclusions: &Exclusions,
    machines: &BTreeSet<MacAddr>,
) -> IpSet {
    let mut withheld = IpSet::new();
    for (intf, targets) in local.iter_mut() {
        let mut seeded = 0usize;
        for candidate in candidates_on(intf, table, exclusions, machines) {
            // **The policy, not one of this function's own three filters.**
            //
            // `withhold_targets` subtracts excluded addresses from the list
            // before anything is opened, and that is the whole of the send-side
            // guarantee — but it can only subtract what the list had. These
            // addresses were never in it: they come from the host's own
            // neighbour table, which is exactly the case `Exclusions` names when
            // it says an exclusion that holds for the list and not for what the
            // sweep discovers is worse than no exclusion at all.
            //
            // Without this a swept segment would send a unicast solicitation to
            // an address somebody had been told would not be probed.
            // `write_host` would then drop the finding, so the *report* would
            // stay clean and the packet would still go out — which is the half
            // of the promise that cannot be checked from the report afterwards.
            if candidate.withheld {
                info!(
                    verbosity = 2,
                    "neighbour {} is excluded, so it is not taken as a candidate",
                    candidate.address
                );
                withheld.insert_range(candidate.range);
                continue;
            }
            targets.insert_range(candidate.range);
            seeded += 1;
        }

        if seeded > 0 {
            targets.canonicalize();
            info!(
                verbosity = 1,
                "took {} from the neighbour table as candidates on {}",
                counted(seeded as u128, "IPv6 address", "IPv6 addresses"),
                intf.name()
            );
        }
    }
    withheld.canonicalize();
    withheld
}

/// One neighbour-table address a sweep of a link would take as a candidate.
struct Candidate {
    /// The address as the table lists it.
    address: IpAddr,
    /// What a sweep probes for it: the address, with the link's interface
    /// where the address is link-local.
    range: IpRange,
    /// Whether the exclusions keep it from the sweep: they name it, or it is
    /// listed under the hardware of a machine they name.
    withheld: bool,
}

/// The neighbour-table candidates on `intf`, in table order, each with
/// whether `exclusions` keep it from a sweep; see [`candidates_for`] for which
/// entries are candidates at all.
fn candidates_on(
    intf: &Link,
    table: &[neighbor_cache::Neighbor],
    exclusions: &Exclusions,
    machines: &BTreeSet<MacAddr>,
) -> Vec<Candidate> {
    let tied: HashSet<IpAddr> = table
        .iter()
        .filter(|entry| entry.mac.is_some_and(|mac| machines.contains(&mac)))
        .map(|entry| entry.ip)
        .collect();
    candidates_for(intf, table)
        .into_iter()
        .filter_map(|address| {
            let IpAddr::V6(v6) = address else {
                return None;
            };
            // The zone matters for exactly the addresses that cannot be probed
            // without one, and is dropped for the rest for the reason
            // `ScopedIp` drops it: the same global address through two
            // interfaces is one address, not two.
            let zone = v6.is_unicast_link_local().then_some(intf.index());
            let range = IpRange::V6(Ipv6Range::scoped(v6, v6, zone).ok()?);
            Some(Candidate {
                address,
                range,
                withheld: exclusions.excludes(&address) || tied.contains(&address),
            })
        })
        .collect()
}

/// The neighbour-table addresses worth probing on `intf`, in table order.
fn candidates_for(link: &Link, table: &[neighbor_cache::Neighbor]) -> Vec<IpAddr> {
    let own: std::collections::HashSet<IpAddr> =
        link.addresses().iter().map(|held| held.address()).collect();

    table
        .iter()
        .filter(|entry| entry.interface_index == link.index())
        .filter(|entry| !own.contains(&entry.ip))
        .filter(|entry| match entry.ip {
            IpAddr::V6(addr) => !addr.is_loopback() && !addr.is_unspecified(),
            IpAddr::V4(_) => false,
        })
        .map(|entry| entry.ip)
        .collect()
}

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

/// The remedy for a link-local target that names no interface: the target
/// written with an interface this host has, from its own table.
///
/// An example rather than an instruction, because the one thing a reader
/// cannot tell from "name the interface" is how, and a name they do not have,
/// such as another platform's first Ethernet port, sends them to find out.
/// Where the host has no link to suggest, the instruction alone.
fn name_an_interface(range: &Ipv6Range) -> String {
    match link_local_example(&crate::system::interface::interfaces_or_none()) {
        Some(link) => format!(
            "link-local, name the interface ({}%{})",
            range.start_addr(),
            link.name()
        ),
        None => "link-local, name the interface".to_owned(),
    }
}

/// The link a link-local target is most likely meant on: one that is up, can
/// broadcast and holds a link-local address of its own, which is a segment
/// `fe80::/64` means something on. The one the default route leaves by is
/// preferred, being where this host meets the network it is on; otherwise the
/// first, in the order the system lists them.
fn link_local_example(links: &[Link]) -> Option<&Link> {
    let segment = |link: &&Link| {
        link.is_up()
            && link.is_broadcast()
            && !link.is_loopback()
            && link
                .ipv6()
                .any(|(address, _)| address.is_unicast_link_local())
    };
    links
        .iter()
        .filter(segment)
        .find(|link| link.carries_default_route())
        .or_else(|| links.iter().find(segment))
}

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

    /// **The link-local hint names an interface this host has**, one that is
    /// up, broadcasts and holds a link-local address, the default route's
    /// first, and suggests none where the host has no such link. A name taken
    /// from another platform, `en0` on a Linux host, is one the reader does
    /// not have.
    #[test]
    fn the_link_local_hint_names_an_interface_this_host_has() {
        use crate::system::interface::{Addressing, LinkAddress};
        use std::net::Ipv6Addr;

        let link_local =
            LinkAddress::new(IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)), 64);
        let global = LinkAddress::new(
            IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)),
            64,
        );
        let link = |name: &str, addresses: Vec<LinkAddress>| {
            Link::new(name, 1)
                .with_link_up(true)
                .with_addressing(Addressing::Broadcast)
                .with_addresses(addresses)
        };

        let links = [
            link("tun0", vec![link_local]).with_addressing(Addressing::PointToPoint),
            link("eth1", vec![global]),
            link("eth2", vec![link_local]).with_link_up(false),
            link("eth0", vec![link_local]),
            link("wlan0", vec![link_local]).with_default_route(true),
        ];
        assert_eq!(link_local_example(&links).map(Link::name), Some("wlan0"));
        assert_eq!(
            link_local_example(&links[..4]).map(Link::name),
            Some("eth0")
        );
        assert!(link_local_example(&links[..3]).is_none());
    }

    /// The port a raw TCP scanner built here probes from. Its transport sends
    /// nothing, so which one does not matter.
    const SRC_PORT: u16 = 54_321;

    fn v6(addr: &str) -> IpAddr {
        addr.parse().unwrap()
    }

    fn interface_with(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
        use crate::system::interface::LinkAddress;
        Link::new(name, index).with_addresses(
            own.into_iter()
                .map(|ip| LinkAddress::new(ip, if ip.is_ipv4() { 24 } else { 64 }))
                .collect(),
        )
    }

    fn entry(ip: &str, index: u32) -> neighbor_cache::Neighbor {
        neighbor_cache::Neighbor {
            ip: v6(ip),
            mac: None,
            interface_index: index,
        }
    }

    /// A link a frame can be put on, as against `interface_with`'s bare one.
    fn framed(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
        interface_with(index, name, own)
            .with_mac(crate::model::mac::MacAddr::new(0x02, 0, 0, 0, 0, 0x10))
    }

    fn set_of(addresses: &[&str]) -> IpSet {
        let mut set = IpSet::new();
        for address in addresses {
            set.insert(v6(address));
        }
        set
    }

    /// What a frames-only sweep cannot reach leaves the steps that would have
    /// framed it and joins the connect step, which is how an unprivileged
    /// sweep reaches it. A local step left empty goes with it; one still
    /// holding a neighbour a frame reaches stays.
    #[test]
    fn what_a_frame_cannot_reach_moves_to_the_connect_step() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![
                DiscoveryStep::Local {
                    interface: Box::new(interface_with(20, "utun9", vec![v6("198.51.100.2")])),
                    targets: set_of(&["198.51.100.7"]),
                    scope: Scope::Targeted,
                },
                DiscoveryStep::Local {
                    interface: Box::new(framed(4, "en0", vec![v6("192.0.2.10")])),
                    targets: set_of(&["192.0.2.50"]),
                    scope: Scope::Targeted,
                },
                DiscoveryStep::Routed {
                    targets: vec![
                        RoutedTarget {
                            target: v6("203.0.113.23"),
                            source: v6("198.51.100.2"),
                        },
                        RoutedTarget {
                            target: v6("203.0.113.9"),
                            source: v6("192.0.2.10"),
                        },
                    ],
                    ports: SynPorts::common(),
                },
            ],
            refusals: Vec::new(),
        };

        let moved = plan.connect_instead(&set_of(&["198.51.100.7", "203.0.113.23"]));

        assert_eq!(moved.len(), 2);
        let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
        assert_eq!(
            kinds,
            vec![
                ScannerKind::Local,
                ScannerKind::Routed,
                ScannerKind::Connect
            ],
            "the tunnel's local step is gone and a connect step has arrived"
        );
        match &plan.steps()[1] {
            DiscoveryStep::Routed { targets, .. } => {
                assert_eq!(targets.len(), 1);
                assert_eq!(targets[0].target, v6("203.0.113.9"));
            }
            other => panic!("expected the routed step, found {other:?}"),
        }
        match &plan.steps()[2] {
            DiscoveryStep::Connect { targets, .. } => assert_eq!(*targets, moved),
            other => panic!("expected the connect step, found {other:?}"),
        }
    }

    /// A sweep's own link keeps its step with nothing left to address, since
    /// its most important probe is addressed to nobody. A link that carries no
    /// frames has no such probe to send, and goes.
    #[test]
    fn a_sweeps_step_stays_on_a_framed_link_and_goes_on_a_tunnel() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![
                DiscoveryStep::Local {
                    interface: Box::new(framed(4, "en0", vec![v6("192.0.2.10")])),
                    targets: set_of(&["192.0.2.50"]),
                    scope: Scope::Sweep,
                },
                DiscoveryStep::Local {
                    interface: Box::new(interface_with(20, "utun9", vec![v6("198.51.100.2")])),
                    targets: set_of(&["198.51.100.7"]),
                    scope: Scope::Sweep,
                },
            ],
            refusals: Vec::new(),
        };

        plan.withhold(&set_of(&["192.0.2.50", "198.51.100.7"]));

        assert_eq!(plan.steps().len(), 1);
        match &plan.steps()[0] {
            DiscoveryStep::Local {
                interface, targets, ..
            } => {
                assert_eq!(interface.name(), "en0");
                assert!(targets.is_empty());
            }
            other => panic!("expected the sweep's own step, found {other:?}"),
        }
    }

    /// Withholding is about frames, and a connect step sends none: what it
    /// already holds stays, and nothing new arrives in it.
    #[test]
    fn withholding_leaves_the_connect_step_as_it_was() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![DiscoveryStep::Connect {
                targets: set_of(&["127.0.0.1"]),
                ports: SynPorts::common(),
            }],
            refusals: Vec::new(),
        };

        let taken = plan.withhold(&set_of(&["127.0.0.1"]));

        assert!(taken.is_empty(), "nothing was taken from a frame step");
        match &plan.steps()[0] {
            DiscoveryStep::Connect { targets, .. } => assert_eq!(*targets, set_of(&["127.0.0.1"])),
            other => panic!("expected the connect step, found {other:?}"),
        }
    }

    /// A port scan's liveness pass asks its routed targets about the scan's
    /// own ports, and a plan built for a sweep asks the common five until told
    /// otherwise.
    #[test]
    fn the_routed_steps_ask_the_ports_they_are_given() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![DiscoveryStep::Routed {
                targets: vec![RoutedTarget {
                    target: v6("198.51.100.1"),
                    source: v6("192.0.2.9"),
                }],
                ports: SynPorts::common(),
            }],
            refusals: Vec::new(),
        };
        let scan = SynPorts::for_scan(&"8443".try_into().expect("a port specification"));

        plan.asking_tcp(scan);

        assert!(matches!(
            plan.steps(),
            [DiscoveryStep::Routed { ports, .. }] if *ports == scan
        ));
    }

    /// The addresses a plan reaches by connect are asked the ports its routed
    /// addresses are. Asked fewer, a host behind a filter that serves only a
    /// port the scan names is found when a frame reaches it and missed when
    /// only a connect does, loopback and tunnels on every run and everything
    /// on an unprivileged one.
    #[test]
    fn the_connect_step_asks_the_ports_the_routed_steps_are_given() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![
                DiscoveryStep::Routed {
                    targets: vec![RoutedTarget {
                        target: v6("198.51.100.1"),
                        source: v6("192.0.2.9"),
                    }],
                    ports: SynPorts::common(),
                },
                DiscoveryStep::Connect {
                    targets: set_of(&["127.0.0.1"]),
                    ports: SynPorts::common(),
                },
            ],
            refusals: Vec::new(),
        };
        let scan = SynPorts::for_scan(&"8443".try_into().expect("a port specification"));

        plan.asking_tcp(scan);

        assert!(
            matches!(
                plan.steps(),
                [DiscoveryStep::Routed { .. }, DiscoveryStep::Connect { ports, .. }] if *ports == scan
            ),
            "the connect step asks {:?}",
            plan.steps()
        );
    }

    /// A plan whose every TCP port is excluded refuses its routed and connect
    /// steps rather than running them asking nothing.
    ///
    /// A sweep asking no port files every address it holds as silent, which
    /// reads as hosts that are not there when nothing was put to them. The
    /// refusal is what says why those addresses went unasked.
    #[test]
    fn a_plan_left_no_tcp_port_refuses_its_tcp_steps() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![
                DiscoveryStep::Routed {
                    targets: vec![RoutedTarget {
                        target: v6("198.51.100.1"),
                        source: v6("192.0.2.9"),
                    }],
                    ports: SynPorts::common(),
                },
                DiscoveryStep::Connect {
                    targets: set_of(&["127.0.0.1"]),
                    ports: SynPorts::common(),
                },
            ],
            refusals: Vec::new(),
        };
        let everything = "1-65535".try_into().expect("a port specification");

        plan.asking_tcp(SynPorts::common().excluding(&everything));

        assert!(plan.steps().is_empty(), "left {:?}", plan.steps());
        let refused: Vec<ScannerKind> = plan.refusals().iter().map(|r| r.scanner).collect();
        assert_eq!(refused, [ScannerKind::Routed, ScannerKind::Connect]);
    }

    /// And a connect step made after the ports were chosen, for what a frame
    /// cannot reach, asks them too: the order a caller edits a plan in decides
    /// nothing about which ports an address is asked on.
    #[test]
    fn a_connect_step_made_for_what_frames_miss_asks_the_routed_ports() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![DiscoveryStep::Routed {
                targets: vec![
                    RoutedTarget {
                        target: v6("198.51.100.1"),
                        source: v6("192.0.2.9"),
                    },
                    RoutedTarget {
                        target: v6("198.51.100.2"),
                        source: v6("192.0.2.9"),
                    },
                ],
                ports: SynPorts::common(),
            }],
            refusals: Vec::new(),
        };
        let scan = SynPorts::for_scan(&"8443".try_into().expect("a port specification"));

        plan.asking_tcp(scan);
        plan.connect_instead(&set_of(&["198.51.100.2"]));

        assert!(
            matches!(
                plan.steps(),
                [DiscoveryStep::Routed { .. }, DiscoveryStep::Connect { ports, .. }] if *ports == scan
            ),
            "the connect step asks {:?}",
            plan.steps()
        );
    }

    /// An SCTP sweep runs beside each routed step and nowhere else: a segment
    /// is swept at the link layer, where ARP and neighbour discovery answer
    /// whatever the host speaks above them, and a connect step has no raw
    /// socket to send an INIT through.
    #[test]
    fn an_sctp_sweep_is_added_to_the_routed_steps_alone() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            refused_by_route: IpSet::new(),
            withheld: IpSet::new(),
            steps: vec![
                DiscoveryStep::Routed {
                    targets: vec![RoutedTarget {
                        target: v6("192.0.2.1"),
                        source: v6("192.0.2.9"),
                    }],
                    ports: SynPorts::common(),
                },
                DiscoveryStep::Connect {
                    targets: IpSet::new(),
                    ports: SynPorts::common(),
                },
            ],
            refusals: Vec::new(),
        };

        plan.also_over_sctp(3868);

        let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
        assert_eq!(
            kinds,
            vec![
                ScannerKind::Routed,
                ScannerKind::Connect,
                ScannerKind::RoutedSctp
            ]
        );
        assert!(matches!(
            plan.steps().last(),
            Some(DiscoveryStep::RoutedSctp { port: 3868, .. })
        ));
    }

    /// SCTP has no unprivileged form at all, so a scan that named SCTP ports
    /// without raw sockets is told those ports went unprobed rather than being
    /// handed a strategy that asked a different question.
    #[test]
    fn sctp_without_raw_sockets_is_refused_rather_than_substituted() {
        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
        plan.cover_sctp(Privilege::Connect);

        assert!(!plan.covers(Protocol::Sctp));
        assert!(
            plan.refusals()
                .iter()
                .any(|refusal| refusal.scanner == ScannerKind::SctpPort),
            "the sctp ports went unprobed and nothing in the report said so"
        );
    }

    /// An idle scan reads a third party's counter and has no way to carry an
    /// INIT. Sending one directly would leave this host's address on the target,
    /// which is the one thing the technique exists to avoid, so the ports are
    /// refused with that as the reason.
    #[test]
    fn an_idle_scan_refuses_sctp_rather_than_probing_it_directly() {
        let cfg = ZondConfig {
            idle_scan: Some(crate::config::IdleScan::new(v6("192.0.2.9"))),
            ..ZondConfig::default()
        };
        let mut plan = PortScanPlan::build(&cfg, Privilege::Raw);
        plan.cover_sctp(Privilege::Raw);

        assert!(!plan.covers(Protocol::Sctp));
        let refusal = plan
            .refusals()
            .iter()
            .find(|refusal| refusal.scanner == ScannerKind::SctpPort)
            .expect("the sctp ports are accounted for");
        assert!(
            refusal.reason.contains("idle"),
            "the reason names something other than the idle scan: {}",
            refusal.reason
        );
    }

    /// A zombie the operator excluded is not scanned through. The idle scan
    /// reads its counter by sending it SYN+ACKs again and again, so naming it
    /// in a scan's settings would otherwise probe an address somebody was told
    /// would be left alone, and nothing in the target list could withhold it.
    ///
    /// Refused rather than replaced: probing the target directly instead would
    /// put this host's own address on it, which an idle scan exists to avoid,
    /// so no TCP port is planned at all.
    #[test]
    fn an_idle_scan_through_an_excluded_zombie_is_refused() {
        let zombie = v6("192.0.2.9");
        let mut forbidden = IpSet::new();
        forbidden.insert(zombie);
        let cfg = ZondConfig {
            idle_scan: Some(crate::config::IdleScan::new(zombie)),
            exclusions: Exclusions::new(forbidden),
            ..ZondConfig::default()
        };

        let plan = PortScanPlan::build(&cfg, Privilege::Raw);

        assert!(
            !plan
                .steps()
                .iter()
                .any(|step| matches!(step, PortScanStep::Idle { .. })),
            "an idle step would probe the excluded zombie"
        );
        assert!(
            !plan.covers(Protocol::Tcp),
            "and nothing stands in for it by probing the target directly"
        );
        let refusal = plan
            .refusals()
            .iter()
            .find(|refusal| refusal.scanner == ScannerKind::Idle)
            .expect("the refused scan is accounted for");
        assert!(
            refusal.reason.contains("192.0.2.9") && refusal.reason.contains("excluded"),
            "the reason names the zombie and the exclusion: {}",
            refusal.reason
        );
    }

    /// An idle scan the plan refused is still an idle scan, and what it names
    /// on other transports is refused as one. Neither SCTP nor UDP can be read
    /// through a zombie's counter, and a privileged plan that forgot the scan
    /// was an idle one once its idle step was gone would probe the target's
    /// SCTP ports from this host's own address: the one thing the caller chose
    /// an idle scan to avoid, done to the target the moment the zombie is
    /// excluded.
    #[test]
    fn a_refused_idle_scan_probes_no_other_transport_directly() {
        let zombie = v6("192.0.2.9");
        let mut forbidden = IpSet::new();
        forbidden.insert(zombie);
        let cfg = ZondConfig {
            idle_scan: Some(crate::config::IdleScan::new(zombie)),
            exclusions: Exclusions::new(forbidden),
            ..ZondConfig::default()
        };

        for privilege in [Privilege::Raw, Privilege::Connect] {
            let mut plan = PortScanPlan::build(&cfg, privilege);
            plan.cover_sctp(privilege);
            plan.cover_udp(privilege);

            assert!(
                plan.steps().is_empty(),
                "{privilege:?}: nothing is probed directly: {:?}",
                plan.steps()
            );
            for protocol in [Protocol::Sctp, Protocol::Udp] {
                assert!(plan.refuses(protocol), "{privilege:?}: {protocol:?}");
            }
            let reasons: Vec<&str> = plan.refusals().iter().map(|r| r.reason.as_str()).collect();
            for transport in ["sctp", "udp"] {
                assert!(
                    reasons
                        .iter()
                        .any(|reason| reason.contains(transport) && reason.contains("idle scan")),
                    "{privilege:?}: {transport} is refused as an idle scan's: {reasons:?}"
                );
            }
        }
    }

    /// An ordinary scan plans no UDP step until the targets are found to name a
    /// UDP port, so a TCP-only scan opens no UDP scanner to probe nothing.
    #[test]
    fn a_udp_step_is_planned_only_when_the_targets_name_udp() {
        for privilege in [Privilege::Raw, Privilege::Connect] {
            let plan = PortScanPlan::build(&ZondConfig::default(), privilege);
            assert!(
                !plan.covers(Protocol::Udp),
                "{privilege:?}: a plan built before the targets are read names no UDP step, so \
                 a TCP-only scan opens no UDP scanner to probe nothing"
            );
        }

        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
        plan.cover_udp(Privilege::Connect);
        assert!(plan.covers(Protocol::Udp) && !plan.refuses(Protocol::Udp));
        assert!(plan.refusals().is_empty());
    }

    fn v6_set(cidr: &str) -> IpSet {
        crate::model::parse::ip::to_set(&[cidr], None, None).expect("a range")
    }

    /// A `/64` on the local segment is eighteen quintillion addresses, and the
    /// walk is what a targeted run does with a local range. It is withheld
    /// before a scanner is built from it, because the alternative was measured
    /// and is worse than useless: the count overflows `usize`, the sweep is
    /// budgeted as though it had no targets, and it stops two thousand
    /// solicitations in having reported the prefix covered.
    #[test]
    fn a_local_prefix_too_large_to_walk_is_withheld_from_the_targets() {
        let mut targets = v6_set("2001:db8:1:1::/64");
        assert_eq!(targets.len(), 1u128 << 64, "a /64, kept whole to here");

        let withheld = withhold_unwalkable(&mut targets);

        assert_eq!(withheld.len(), 1, "the prefix is taken out");
        assert!(targets.is_empty(), "and nothing is left to walk");
    }

    /// Asked of a range and not of a set, so a prefix beside three literal
    /// addresses costs the prefix and not the three.
    #[test]
    fn withholding_a_prefix_keeps_the_addresses_named_beside_it() {
        let mut targets = crate::model::parse::ip::to_set(
            &["2001:db8:1:1::/64", "2001:db8:2::1", "192.0.2.7"],
            None,
            None,
        )
        .expect("a mixed set");

        let withheld = withhold_unwalkable(&mut targets);

        assert_eq!(withheld.len(), 1);
        assert_eq!(targets.len(), 2, "the literal and the IPv4 address survive");
    }

    /// A range small enough to walk is left exactly as it was, so the ordinary
    /// case pays nothing.
    #[test]
    fn a_walkable_prefix_is_untouched() {
        let mut targets = v6_set("2001:db8::/120");
        let before = targets.len();

        assert!(withhold_unwalkable(&mut targets).is_empty());
        assert_eq!(targets.len(), before);
    }

    /// The three entries that must never become targets, each wrong in its own
    /// way: another interface's neighbour is not reachable through this one,
    /// this host would be reported as a discovered neighbour of itself, and
    /// loopback names nothing on a segment.
    #[test]
    fn seeding_skips_other_interfaces_our_own_addresses_and_loopback() {
        let own = v6("2001:db8::50");
        let intf = interface_with(7, "en0", vec![own]);
        let table = vec![
            entry("2001:db8::aa", 7),
            entry("fe80::bb", 7),
            entry("2001:db8::cc", 9),
            entry("2001:db8::50", 7),
            entry("::1", 7),
        ];

        let seeded = candidates_for(&intf, &table);

        assert_eq!(seeded, vec![v6("2001:db8::aa"), v6("fe80::bb")]);
    }

    /// A link-local candidate carries the interface it came from, because it
    /// cannot be probed without one. A global address does not, for the reason
    /// `ScopedIp` drops it: the same address through two interfaces is one
    /// address.
    #[test]
    fn a_seeded_link_local_keeps_its_interface_and_a_global_does_not() {
        let intf = interface_with(7, "en0", Vec::new());
        let table = vec![entry("fe80::bb", 7), entry("2001:db8::aa", 7)];
        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);

        seed_from_neighbor_table_with(&mut local, &table, &Exclusions::none(), &BTreeSet::new());

        let targets = local.into_values().next().unwrap();
        let zones: Vec<Option<u32>> = targets.v6().iter().map(|range| range.zone()).collect();
        assert!(
            zones.contains(&Some(7)),
            "the link-local needs its interface"
        );
        assert!(
            zones.contains(&None),
            "the global address needs no interface"
        );
    }

    /// An unprivileged plan still covers both protocols. A protocol with no step
    /// is not a degraded scan but a silent one: nothing routes those targets, so
    /// they are never probed and never reported.
    #[test]
    fn an_unprivileged_plan_covers_both_protocols() {
        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
        plan.cover_udp(Privilege::Connect);

        assert!(plan.covers(Protocol::Tcp));
        assert!(plan.covers(Protocol::Udp));
        assert!(plan.refusals().is_empty());
    }

    /// A connect scan substitutes for a SYN scan and for nothing else. Asked for
    /// a technique it cannot express, an unprivileged plan has to leave the TCP
    /// half out and say why - a silent substitution would promise verdicts from
    /// a technique nobody chose, with no field in the report saying so.
    #[test]
    fn a_technique_the_fallback_cannot_express_is_refused_at_planning_time() {
        let cfg = ZondConfig {
            tcp_technique: TcpScanTechnique::Fin,
            ..ZondConfig::default()
        };
        let mut plan = PortScanPlan::build(&cfg, Privilege::Connect);
        plan.cover_udp(Privilege::Connect);

        assert!(
            !plan.covers(Protocol::Tcp),
            "a connect scan cannot send a FIN and must not plan to"
        );
        assert!(plan.covers(Protocol::Udp), "the UDP half is unaffected");

        assert_eq!(plan.refusals().len(), 1, "the caller has to be told");
        assert_eq!(plan.refusals()[0].scanner, ScannerKind::TcpPort);
        assert!(
            plan.refusals()[0].reason.contains("fin"),
            "the refusal has to name the technique: {}",
            plan.refusals()[0].reason
        );
        assert!(
            plan.refuses(Protocol::Tcp) && !plan.refuses(Protocol::Udp),
            "and which protocol it leaves unprobed, for the router to count"
        );
    }

    /// A step and the scanner it becomes have to answer to the same name, or a
    /// failure lands in the report under one strategy and the same scanner's
    /// later failures under another.
    ///
    /// [`ScannerKind::SynPort`] is the one that matters. It is documented to
    /// mean a half-open connection attempt was made, and a plan that called
    /// every raw TCP step by that name would attribute a FIN scan's socket
    /// failure to `syn_port` when no SYN was ever sent.
    #[test]
    fn a_step_reports_under_the_same_name_as_the_scanner_it_builds() {
        use crate::scanner::session::ScanSession;
        use crate::scanner::strategy::ports::TcpPortScanner;
        use crate::transport::probe::{Emission, ProbeSender, ProbeTransport, SendError};

        struct Unsendable;
        impl ProbeSender for Unsendable {
            fn send(
                &self,
                _: &[u8],
                _: IpAddr,
                _: IpAddr,
                _: Option<u32>,
                _emission: Emission,
            ) -> Result<(), SendError> {
                Ok(())
            }
        }

        let (_session, ctx) = ScanSession::new();
        for &technique in TcpScanTechnique::ALL {
            let (_tx, rx) = tokio::sync::mpsc::channel(1024);
            let scanner = TcpPortScanner::with_transport(
                interface::SourceResolver::from_links(&[]),
                ctx.clone(),
                technique,
                ProbeTransport::from_parts(Box::new(Unsendable), rx),
                1,
                SRC_PORT,
            );

            assert_eq!(
                PortScanStep::RawTcp { technique }.kind(),
                scanner.kind(),
                "a {technique} step and its scanner disagree about what to call themselves"
            );
        }
    }

    /// Host enrichment runs beside a raw scan because the raw paths are what
    /// yield a MAC and an RTT. Which technique the raw TCP scanner carries has
    /// no bearing on that, so every one of them has to count as raw.
    #[test]
    fn every_raw_step_is_recognisable_as_one() {
        for &technique in TcpScanTechnique::ALL {
            assert!(PortScanStep::RawTcp { technique }.is_raw(), "{technique}");
        }
        assert!(PortScanStep::RawUdp.is_raw());
        assert!(!PortScanStep::ConnectTcp.is_raw());
        assert!(!PortScanStep::ConnectUdp.is_raw());
    }

    /// The technique outlives the steps, because whether a connect scanner may
    /// stand in for a raw one that failed to open is a question asked after the
    /// step is gone.
    #[test]
    fn a_plan_remembers_the_technique_it_was_built_for() {
        let cfg = ZondConfig {
            tcp_technique: TcpScanTechnique::Ack,
            ..ZondConfig::default()
        };
        assert_eq!(
            PortScanPlan::build(&cfg, Privilege::Connect).technique(),
            TcpScanTechnique::Ack
        );
    }

    /// A plan is a value a caller may edit, and editing it changes what would
    /// run. The guard against editing it into silence is `covers`.
    #[test]
    fn dropping_a_step_is_visible_in_what_the_plan_covers() {
        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
        plan.steps_mut()
            .retain(|step| step.protocol() != Protocol::Udp);

        assert!(plan.covers(Protocol::Tcp));
        assert!(!plan.covers(Protocol::Udp));
    }

    /// **A sweep takes no candidate from the machine an exclusion names.** An
    /// excluded IPv4 address and the IPv6 addresses the same machine holds
    /// share nothing but the hardware address the neighbour tables list them
    /// under, and a sweep that took those from the table solicited the
    /// machine the operator excluded, at an address the policy never named.
    ///
    /// What the sweep kept back is handed on, since the phase counts it among
    /// what its policy withheld.
    #[test]
    fn a_swept_plan_takes_no_candidate_from_an_excluded_machine() {
        let machine = MacAddr::new(0x02, 0, 0, 0, 0, 0x30);
        let other = MacAddr::new(0x02, 0, 0, 0, 0, 0x31);
        let at = |ip: &str, mac| neighbor_cache::Neighbor {
            mac: Some(mac),
            ..entry(ip, 7)
        };
        let v4 = neighbor_cache::Neighbor {
            ip: "192.0.2.30".parse().expect("literal"),
            mac: Some(machine),
            interface_index: 7,
        };
        let v6_table = vec![at("2001:db8::30", machine), at("2001:db8::31", other)];

        let mut forbidden = IpSet::new();
        forbidden.insert(v4.ip);
        let exclusions = Exclusions::new(forbidden);
        let mut both = vec![v4];
        both.extend(v6_table.iter().cloned());
        let machines = exclusions.hardware_in(both.iter().map(|entry| (entry.ip, entry.mac)));

        let intf = interface_with(7, "en0", Vec::new());
        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);
        let withheld = seed_from_neighbor_table_with(&mut local, &v6_table, &exclusions, &machines);

        let targets = local.into_values().next().expect("the one interface");
        assert!(
            !targets.contains(&v6("2001:db8::30")),
            "the excluded machine's IPv6 address became a target"
        );
        assert_eq!(
            withheld.iter().collect::<Vec<_>>(),
            vec![v6("2001:db8::30")],
            "what the sweep kept back went uncounted"
        );
        assert!(
            targets.contains(&v6("2001:db8::31")),
            "and its neighbour did"
        );
    }

    /// **A sweep does not take an excluded neighbour as a candidate.**
    ///
    /// The target list is withheld against the exclusions before a plan is
    /// built, and that is the whole of the send-side guarantee — but a sweep
    /// adds addresses the list never had, from the host's own neighbour table,
    /// and those were never subtracted from anything. `Exclusions` names exactly
    /// this case: an exclusion that holds for the list and not for what the
    /// sweep discovers is worse than no exclusion at all.
    ///
    /// The recording gate at `write_host` would drop the finding, so the report
    /// stays clean either way. What it cannot undo is the packet, and that is
    /// the half of the promise a reader cannot check afterwards.
    #[test]
    fn a_swept_plan_does_not_take_an_excluded_neighbour_as_a_candidate() {
        let intf = interface_with(7, "en0", Vec::new());
        let table = vec![entry("2001:db8::aa", 7), entry("2001:dead::bb", 7)];
        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);

        let mut forbidden = IpSet::new();
        forbidden.insert_range("2001:db8::/64".parse().expect("a valid range"));
        seed_from_neighbor_table_with(
            &mut local,
            &table,
            &Exclusions::new(forbidden),
            &BTreeSet::new(),
        );

        let targets = local.into_values().next().expect("the one interface");
        let carried: Vec<std::net::Ipv6Addr> = targets
            .v6()
            .iter()
            .map(|range| range.start_addr())
            .collect();

        assert!(
            !carried.contains(&"2001:db8::aa".parse().expect("literal")),
            "an excluded neighbour must not become a target"
        );
        assert!(
            carried.contains(&"2001:dead::bb".parse().expect("literal")),
            "and everything else still is"
        );
    }
}