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
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
// 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

//! # Local Area Network Scanner
//!
//! Discovers hosts on the same physical network segment by sending ARP requests
//! (IPv4) and ICMPv6 all-nodes solicitations (IPv6), then listening for replies.
//! Recognizing those replies is left to the `discovery` module, so adding a
//! new discovery mechanism does not mean touching the receive loop.
//!
//! The two probes are repeated on different terms, because they ask different
//! questions. An ARP request is put to one address, answered once, and retired
//! by that answer, so it is retransmitted through the shared
//! `ProbeLedger` like every other
//! probe in the engine. The solicitation is put to the whole segment and
//! answered by whoever is listening, so it is simply repeated a few times and
//! given a window to be answered in.
//!
//! This scanner requires root privileges. It builds and intercepts raw Ethernet
//! frames directly, bypassing the operating system's own IP stack.

mod ipv6;
mod probes;

use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::{Duration, Instant};

use crate::model::mac::MacAddr;
use crate::protocols::ethernet::Frame;
use async_trait::async_trait;
use tokio::sync::mpsc::UnboundedSender;
use tokio::time::Interval;

use crate::config::RetryConfig;
use crate::info;
use crate::journal::settle::{Outcome, Settled};
use crate::logging::error;
use crate::model::host::telemetry::RttSource;
use crate::model::host::{HostStatus, NetworkRole, StatusProtocol, StatusReason};
use crate::model::ip::scoped::Zone;
use crate::model::ip::set::IpSet;
use crate::protocols::{self as protocol, ethernet};
use crate::report::ScannerKind;
use crate::report::{Attachment, AttachmentSource, StopReason};
use crate::scanner::dispatcher::WalkOrder;
use crate::scanner::pacing::deadline::{AdaptiveDeadline, AdaptiveDeadlineConfig};
use crate::scanner::pacing::retry::{ProbeLedger, RetryPolicy};
use crate::scanner::pacing::timer::ScanBudget;
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::sweep::HostSweep;
use crate::scanner::strategy::{HostScanner, StrategyError};
use crate::system::interface::{self, Link};
use crate::transport::capture::CapturedFrame;
use crate::transport::channel::{self, EthernetHandle};
use crate::transport::frame::LinkType;
use crate::transport::neighbor;

use crate::scanner::strategy::frames::{self, DiscoveryProtocol, ProtocolMatch, Reading};
use ipv6::Ipv6Discovery;

/// What a local sweep's capture admits, as a `libpcap` filter expression.
///
/// The union of what every [`DiscoveryProtocol`] declares it reads, plus the one
/// thing the sweep reads without one. Derived rather than written down, so that
/// adding a protocol widens the capture by the same edit that adds the reader.
/// see [`DiscoveryProtocol::capture_clause`] for why that is not a convenience.
///
/// Receiving the whole segment and rejecting the surplus in userspace would, on
/// a busy link, copy every frame on the wire to discard almost all of it.
///
/// 802.1Q-tagged frames are not admitted, and that loses nothing: the frame
/// reader below takes the EtherType from its fixed offset, so a tagged frame
/// would read as an unsupported EtherType and be rejected a layer up anyway.
///
/// One expression, where a listener's filter is a set of alternatives each
/// link takes what it can of. A listener reads whatever a link carries, so a
/// tunnel that cannot express the Ethernet clauses still has TCP worth
/// hearing. A sweep sends Ethernet frames and reads every answer from an
/// Ethernet header, so a link without one would take the IP clauses, hear
/// nothing it can read, and report an empty segment; as one expression the
/// Ethernet clauses refuse such a link instead, which is what the sweep
/// needs. See [`CaptureFilter`](crate::transport::capture::CaptureFilter).
fn sweep_filter() -> String {
    let mut clauses: Vec<&'static str> = frames::sweep_protocols()
        .iter()
        .map(|protocol| protocol.capture_clause())
        .collect();

    clauses.extend(ABSORBED_CLAUSES);

    // Several protocols share a clause, the three IPv6 readers are all
    // `icmp6`, and a filter repeating it would compile to the same program
    // while reading as though it meant something.
    clauses.sort_unstable();
    clauses.dedup();

    clauses.join(" or ")
}

/// The clauses for the readers that conclude no liveness, and so have no
/// [`DiscoveryProtocol`] to declare them.
///
/// Every protocol in [`frames::sweep_protocols`] exists to conclude that a
/// host is present. These three do not, and each declines for its
/// own reason:
///
/// - **mDNS** (`absorb_mdns`) reads a name off the segment and credits nobody
///   with being there for it, because every laptop and printer on a link
///   answers mDNS and the announcer is often not the machine being announced.
/// - **LLDP** and **CDP** (`absorb_announcement`) are equipment describing
///   *itself*, and what they establish is where **this** machine is plugged in:
///   a fact about the phase rather than about any host in it. See
///   [`Attachment`].
///
/// A fourth reader of this kind needs a clause here, and nothing will say so:
/// the derivation above covers only the protocols that conclude liveness.
///
/// The CDP clause matches the group address rather than the protocol, because
/// CDP rides 802.3 framing and has no EtherType to match on. That address also
/// carries VTP, DTP and PAgP, which the reader declines: a small surplus, and
/// the alternative is reaching past a header whose length BPF cannot express.
const ABSORBED_CLAUSES: [&str; 3] = [
    "(udp port 5353)",
    "(ether proto 0x88cc)",
    "(ether dst 01:00:0c:cc:cc:cc)",
];

/// Outstanding ARP requests and the schedule they are retried on.
///
/// The attempt token is `()`: consecutive requests for one address are
/// identical on the wire, so a reply cannot say which of them it answers. The
/// ledger applies Karn's rule on that basis and declines to measure a round trip
/// it cannot attribute.
///
/// The all-nodes solicitation is not in here. It is one multicast
/// packet that every neighbour may answer, so it has no single outcome to
/// resolve and nothing to retire; the scanner times it separately.
type Ledger = ProbeLedger<IpAddr, ()>;

/// How an ARP request is retransmitted.
///
/// ARP is lost on a busy segment considerably more often than its reputation
/// suggests - requests are broadcast, and a switch under load drops broadcast
/// before anything else - and a sweep that never asks twice simply reports the
/// hosts it missed as absent.
///
/// Until the segment has answered anything, an address is asked on the
/// kernel's schedule: three requests a second apart, and silent only once the
/// third has gone unanswered for a second, which is the evidence the kernel
/// takes before it calls a neighbour failed, and the evidence the frame
/// path's own address resolution takes before a port scan's probe gives up on
/// one. Judged sooner, a neighbour the port scans would resolve is written off
/// here, and one answering in more than the sweep's patience answers after the
/// process that asked has gone, into the capture of whichever process asks
/// next, so one run finds it and the next does not.
///
/// Once the segment has answered, the round trip it answered in governs: a
/// wired neighbour answers in well under a millisecond, the floor takes over
/// almost at once, and the silent addresses of a segment that answers are
/// settled in a fraction of a second. So the second of patience is paid by a
/// sweep that hears nothing, which is the sweep that has nothing faster to go
/// on.
///
/// No silent-host rule, because there would be nothing for it to do: each
/// address here is probed once, so no host ever accumulates the exhausted
/// probes that rule counts.
const RETRY_POLICY: RetryPolicy = RetryPolicy::new(
    3,
    Duration::from_secs(1),
    Duration::from_millis(25),
    Duration::from_secs(1),
    2.0,
    0.2,
    None,
);

/// How many machines may declare what they are before this scanner knows which
/// hosts they are.
///
/// One bound on what the segment can make this process hold. A router
/// advertisement and a DHCP reply are unsolicited traffic, so unlike every
/// other record here this one grows from frames nobody asked for, and a
/// neighbour sending them under a new hardware address each time would
/// otherwise grow it without limit.
///
/// Sixty-four is past any segment that has this many routers and DHCP servers
/// on it, and small enough that reaching the cap costs nothing worth measuring.
/// Past it, a declaration from a machine still unknown is dropped like any other
/// off-target frame: it is a claim about a host this scan has not found.
const MAX_DECLARING_MACS: usize = 64;

/// Why a captured frame is not a discovery finding.
///
/// Not a failure of the scanner: a promiscuous capture sees the whole segment's
/// traffic, so most of what arrives is somebody else's and rejecting it is the
/// normal case rather than an error. These are named rather than lumped into one
/// `None` because which check rejected a frame is the first thing worth knowing
/// when a host that should have been found was not.
///
/// Kept apart from [`StrategyError`], which is about a strategy that could not
/// run at all.
#[derive(Debug, thiserror::Error)]
pub(crate) enum FrameRejected {
    #[error("unmapped RTT source: {0}")]
    UnmappedRttSource(IpAddr),
    #[error("packet originated from this host")]
    SelfSourcedPacket,
    #[error("{0} is not in the scanned range")]
    AddressOutOfRange(IpAddr),
    #[error("the frame came off a link that prepends no Ethernet header")]
    UnreadableLink,
    /// The bytes did not hold the headers they were read for.
    ///
    /// A promiscuous capture admits whatever the filter let through, so a frame
    /// that stops mid-header is an ordinary arrival rather than a fault. Named
    /// with the parser's own reason, since which header ran out is the thing
    /// worth knowing.
    #[error("{0}")]
    Malformed(#[from] crate::protocols::error::PacketError),
}

/// How long a discovery sweep runs and how it adapts. The base and per-target
/// budgets scale with the number of targets, while the silence floor, silence
/// ceiling, and jitter multiplier bound how far the tolerance for network
/// silence can stretch in response to recent round-trip times. These starting
/// values assume a local segment, where round trips are usually well under a
/// millisecond.
///
/// The hard ceiling bounds only a range small enough that nothing else does.
/// This scanner paces its own sends at [`SEND_INTERVAL`], so a sweep needs at
/// least that interval per address per attempt simply to emit its probes, and
/// a ceiling below that stops it mid-send, invisibly: an address never probed
/// is indistinguishable from one with nothing on it. So the sweep raises the
/// ceiling to what its range and its schedule need; see [`deadline_for`].
const DEADLINE_CONFIG: AdaptiveDeadlineConfig = AdaptiveDeadlineConfig::new(
    ScanBudget::new(
        Duration::from_millis(2_000),
        Duration::from_millis(20),
        Duration::from_secs(120),
    ),
    ScanBudget::new(
        Duration::from_millis(800),
        Duration::from_millis(7),
        Duration::from_millis(5_000),
    ),
    Duration::from_millis(250),
    Duration::from_millis(2_000),
    4.0,
    20,
);

/// How long to leave between probes.
///
/// Slowing this down measurably raises the share of *first* attempts that get
/// answered on a wireless segment, where both of this scanner's first-attempt
/// probes are group-addressed and group-addressed frames are the expensive
/// case. It is not slowed down anyway: a first attempt that goes
/// unanswered is recovered by [`RETRY_POLICY`], so the gain is a better
/// *attributed* round trip on a few hosts rather than more hosts, and it is
/// bought at several times the scan duration: the send phase drags the
/// adaptive deadline along behind it, so the cost compounds rather than adds.
///
/// Two cautions from the last attempt, for whoever revisits it: the run-to-run
/// variance on a segment of sleeping
/// wireless devices is large enough to swamp small differences, so arms are
/// only comparable within one block; and the number to judge it on is hosts
/// found and hosts timed *per second of scan*, not first-attempt rate.
const SEND_INTERVAL: Duration = Duration::from_micros(1000);

/// The deadline a sweep of `target_count` addresses runs under when its ARP
/// requests are retried on `retry`.
///
/// It has to outlive two things the sweep commits to, and it is derived from
/// both rather than left to [`DEADLINE_CONFIG`]'s ceiling, which a large
/// enough range outgrows invisibly.
fn deadline_for(target_count: usize, retry: &RetryPolicy) -> AdaptiveDeadlineConfig {
    // The schedule it commits each probe to, or addresses are given up on
    // having never been fully asked. The longer of the two schedules, because
    // the sweep has to outlive whichever probe it commits to last. Sized from
    // ARP alone, it ends while solicitations are still legitimately
    // outstanding, which is the shape of the bug `ipv6::NDP_RETRY_POLICY`
    // exists to fix, arriving one layer up. Each is taken at its longest,
    // every attempt at its ceiling, since a segment that answered slowly times
    // its silent addresses from what it heard, up to the ceiling on every
    // attempt, the first included.
    let probe_lifetime = retry
        .longest_probe_lifetime()
        .max(ipv6::NDP_RETRY_POLICY.longest_probe_lifetime());

    // And its own pacing, or it stops mid-send. Every frame leaves through one
    // ticker at `SEND_INTERVAL`, a repeat as much as a first attempt, so an
    // address nothing answers costs an interval per attempt, and a range costs
    // that many times its size. Handed over as a pace per address, which
    // raises the ceiling to cover the range rather than leave it to clamp it.
    let attempts = retry.max_attempts.max(ipv6::NDP_RETRY_POLICY.max_attempts);
    DEADLINE_CONFIG
        .allowing_for(probe_lifetime)
        .allowing_pace_of(SEND_INTERVAL * u32::from(attempts), target_count)
}

/// How much of the segment a [`LocalScanner`] run touches.
///
/// Non-exhaustive: "everything here" and "only what was named" are the two a scan
/// needs today, and neither is an argument that there is no third.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    /// Probe every address in range and record every responder, including
    /// IPv6-only neighbors found through an all-nodes solicitation. Used by
    /// `discover`, whose job is to find whatever is on the segment.
    Sweep,
    /// Probe only the given target addresses and record only those. No all-nodes
    /// solicitation is sent, so scanning one host never lights up its neighbors.
    /// Used by `scan`, where the targets are already known.
    Targeted,
}

/// The addressing identity this scanner uses to speak on its interface,
/// resolved once at construction time and never changed afterward.
struct SourceIdentity {
    mac: MacAddr,
    ipv4: Option<Ipv4Addr>,
    link_local_ipv6: Option<Ipv6Addr>,
    /// The interface itself, which this scanner is the only kind that knows.
    ///
    /// Every neighbour it finds was reached across this one segment, so every
    /// link-local address it records is valid on this interface and no other.
    /// Recording that alongside the host is what makes those addresses usable
    /// by the phases that come after discovery; see
    /// [`ScopedIp`](crate::model::ip::scoped::ScopedIp).
    zone: Zone,
}

impl SourceIdentity {
    /// How the store keys a neighbour this scanner found.
    ///
    /// The interface belongs in the key, not only on the record. Every
    /// address here was read off one segment, and a link-local one is valid on
    /// that segment alone: `fe80::1` on `en0` and `fe80::1` on `en1` are two
    /// machines. Keyed by the bare address they would be one entry, and the
    /// second sweep to find one would fold its neighbour's hardware address,
    /// roles and round trips into the first's record.
    ///
    /// [`ScopedIp::scoped`](crate::model::ip::scoped::ScopedIp::scoped) drops
    /// the zone from every address that does not need one, so this is the plain
    /// address for an IPv4 neighbour and for a global IPv6 one, which is right,
    /// since a machine reachable at a global address is the same machine
    /// through whichever interface it answered.
    fn key_for(&self, addr: std::net::IpAddr) -> crate::model::ip::scoped::ScopedIp {
        crate::model::ip::scoped::ScopedIp::scoped(addr, self.zone.clone())
    }
    /// Picks the addresses this scanner will present as its own when probing
    /// `ip_set` from `intf`.
    ///
    /// For IPv4, it prefers an address in the same subnet as the targets being
    /// scanned and otherwise falls back to the interface's first non-loopback
    /// address. For IPv6, it uses the interface's link-local address when it has
    /// one, since that is what the ICMPv6 all-nodes probe is sent from.
    fn resolve(link: &Link, ip_set: &IpSet) -> Result<Self, StrategyError> {
        let mac = link.mac().ok_or_else(|| StrategyError::Interface {
            interface: link.name().to_owned(),
            reason: "it has no MAC address, and every probe here is an Ethernet frame",
        })?;

        let mut ipv4 = None;
        for held in link.addresses() {
            let IpAddr::V4(address) = held.address() else {
                continue;
            };
            if ipv4.is_none() && !address.is_loopback() {
                ipv4 = Some(address);
            }
            // An address on the same segment as the targets beats one that
            // merely exists: a probe sourced from the wrong subnet is answered
            // to somewhere this scanner is not listening.
            if ip_set
                .v4()
                .iter()
                .any(|range| held.contains(&IpAddr::V4(range.start_addr())))
            {
                ipv4 = Some(address);
                break;
            }
        }

        let link_local_ipv6 = link
            .ipv6()
            .map(|(address, _)| address)
            .find(Ipv6Addr::is_unicast_link_local);

        Ok(Self {
            mac,
            ipv4,
            link_local_ipv6,
            zone: link.zone(),
        })
    }
}

/// What a solicited reply proves about the probe it answers.
///
/// The two are separate because either can be missing on its own. An address
/// asked more than once names the send it settles but not the interval, and one
/// answered through the single confirmation an overheard address gets is timed
/// with no send of this scan's to retire.
struct ProbeCorrelation {
    /// The round trip, where one can be attributed to this reply.
    rtt: Option<(Duration, RttSource)>,
    /// Which of this address's sends the reply retires, where the ledger can
    /// say.
    answered_attempt: Option<u8>,
}

/// What one turn of the send ticker put on the wire.
///
/// Only whether the packet iterator is empty matters to the loop: everything
/// else is a frame sent, whether a first attempt, a repeat, or a question put
/// to the whole segment.
enum Dispatched {
    /// A frame, of whichever kind was owed first.
    Sent,
    /// The iterator is empty, so every address the sweep was handed has been
    /// asked at least once.
    Drained,
    /// Nothing was due, which is what an already-drained iterator looks like
    /// on a tick with no repeat behind it.
    Nothing,
}

/// Finds the hosts sharing one Ethernet segment, asking IPv4 addresses by ARP
/// and the IPv6 half of the segment by all-nodes solicitation.
///
/// Frames are built and read directly rather than through this host's IP
/// stack, so a run takes root and reaches only the segment its [`Link`] is
/// attached to. What a given reply proves is left to the `DiscoveryProtocol`
/// implementations in `frames`, and [`Scope`] decides whether a run probes
/// the whole segment or only the addresses it was handed.
pub struct LocalScanner {
    /// Shared state (host store, event channel, abort signal) for the scan
    /// this explorer is part of.
    ctx: ScanContext,
    /// The addresses being probed for aliveness.
    ip_set: IpSet,
    /// The address this scanner presents as its own when probing.
    identity: SourceIdentity,
    /// Raw Ethernet capture used to send probe packets and receive replies.
    eth_handle: EthernetHandle,
    /// Governs how long this sweep keeps running, adapting to observed
    /// round-trip times.
    deadline: AdaptiveDeadline,
    /// Wire formats this scanner recognizes as discovery replies, tried in
    /// order against every received frame.
    protocols: Vec<Box<dyn DiscoveryProtocol>>,
    /// The outstanding ARP requests, the retry queue, what has answered and
    /// the run's counters, shared with the two routed sweeps.
    ///
    /// The neighbour-discovery schedule is `ipv6`'s own and is serviced through
    /// [`HostSweep::service_second_ledger`]: one link, two populations, and a
    /// mains-powered router answers a solicitation in five milliseconds where a
    /// phone asleep on wifi takes four hundred.
    sweep: HostSweep<()>,
    /// Where to forward newly discovered addresses for hostname
    /// resolution, if enabled.
    dns_tx: Option<UnboundedSender<IpAddr>>,
    /// Maps each MAC seen back to the first address observed from it, so a
    /// host reachable at more than one address is recorded once.
    mac_to_ip: HashMap<MacAddr, IpAddr>,
    /// What a machine said it is, held until this scanner knows which host that
    /// machine is.
    ///
    /// The two segment-wide questions are answered from an address the scan was
    /// never asked about, a router advertises from its link-local, a DHCP
    /// server may sit outside the range, so on a targeted run the answer
    /// arrives before, and often instead of, anything that identifies its
    /// sender. Held by MAC rather than dropped, and applied the moment that MAC
    /// answers a probe of ours.
    ///
    /// This is what keeps a targeted run targeted. Nothing here creates a
    /// host or adds an address: a declaration only ever lands on a record the
    /// scan built by asking, so a run handed one address still reports one
    /// host: with, if it happens to be the router, the fact that it routes.
    ///
    /// Bounded by [`MAX_DECLARING_MACS`], unlike `mac_to_ip`, which only ever
    /// grows from replies to probes this scanner sent. This grows from traffic
    /// nobody solicited.
    declared: HashMap<MacAddr, HashSet<NetworkRole>>,
    /// Whether to sweep the segment or probe only the given targets.
    scope: Scope,
    /// Why the first frame that could not be put on the wire failed, if any did.
    ///
    /// The count alone cannot separate a link that refused every write from a
    /// scanner that could not build a packet, and those call for opposite
    /// responses. Kept as the first cause rather than all of them: a segment
    /// that refuses one write refuses the next few hundred for the same reason,
    /// and a report carrying that reason three hundred times says nothing the
    /// first one did not.
    send_failure: Option<String>,
    /// What this sweep has asked the IPv6 half of the segment, and what it is
    /// still waiting to hear back.
    ///
    /// A `/64` cannot be walked the way an IPv4 range can, so nothing about the
    /// ARP half carries over: the probes are different, the retry schedule is
    /// different, and an advertisement cannot say which attempt it answers. That
    /// mechanism keeps its own state rather than sharing this struct's, and the
    /// reasoning behind its timing lives with it.
    ipv6: Ipv6Discovery,
    /// The prefixes the link holds, which say whether an overheard address is
    /// one the routing table's refusal can be read for; see
    /// [`confirm`](Self::confirm).
    prefixes: interface::OnLinkTable,
    /// How the routing table is asked whether it refuses an overheard
    /// address: [`interface::refuses_neighbour`], or, in a test, a table
    /// refusing as no host the test runs on does.
    refuses: fn(IpAddr) -> bool,
}

#[async_trait]
impl HostScanner for LocalScanner {
    fn kind(&self) -> ScannerKind {
        ScannerKind::Local
    }

    async fn discover_hosts(&mut self) -> Result<(), StrategyError> {
        // Every reply records its sender's hardware address, and the first
        // loads the manufacturer database; see the call.
        crate::model::mac::load_vendors().await;
        // The sweep's time runs from here. Loading that database takes
        // hundreds of milliseconds, seconds on a loaded machine, and a caller
        // may build the scanner well before it runs it; charged to the sweep,
        // either spends its minimum runtime and its silence before the first
        // frame is read, and whatever the segment says first is read as
        // arriving after the sweep concluded nothing more would.
        self.deadline.start();
        let mut packet_iter = probes::eth_packet_iter(
            &self.identity.mac,
            &self.identity.ipv4,
            &self.identity.link_local_ipv6,
            &self.ip_set,
            WalkOrder::of(&self.ip_set, &self.ctx).as_ref(),
        );

        // The first all-nodes echo is owed immediately, so it goes out at the
        // head of the sweep rather than behind every ARP request. It is the one
        // probe that reaches an IPv6 neighbour holding no address anybody could
        // have guessed, and the sooner it is asked the more of its response
        // window falls inside the scan.
        if matches!(self.scope, Scope::Sweep) && self.identity.link_local_ipv6.is_some() {
            self.ipv6.arm_solicitation(Instant::now());

            // Recorded where the probe is armed, because this is the one
            // condition under which the phase covers the whole link rather than
            // the addresses it was handed. A host found here holds an address
            // no target set named, and without this the record cannot say it
            // was looked for.
            self.ctx.record_sweep(self.identity.zone.clone());
        }

        // Asked on every local run, sweep or not, and answered by a class of
        // machine rather than by an address: neither question can be put to a
        // target, and a scan of a segment that does not ask them reports the
        // segment without the two machines it is built around.
        //
        // This is not the sweep's reach in disguise. A sweep may *record* a
        // host nobody named; a targeted run still may not, and does not: an
        // answer from an address outside the target set is read for what its
        // sender said it is and for nothing else. See
        // [`note_declaration`](Self::note_declaration).
        self.solicit_routers();
        self.ask_for_configuration();

        let mut sending_finished = false;
        let mut send_interval: Interval = tokio::time::interval(SEND_INTERVAL);
        // Without this, an interval that went unpolled while the loop waited on
        // replies hands back every tick it missed at once, and the pacing this
        // ticker exists to impose evaporates exactly when the queue is longest.
        send_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

        // The loop yields why it stopped, so the audit cannot report a reason
        // the code never actually took.
        let reason = loop {
            let now = Instant::now();
            // Answers already waiting first, so one that arrived before its
            // probe came due settles it before the timer can retire it; see
            // the port scans' `read_waiting_replies`.
            self.read_waiting_frames();
            // Both schedules, and a sweep settles: it was asked whether an
            // address is there and has asked as many times as it may.
            self.sweep.service_retries(&self.ctx, now);
            self.sweep
                .service_second_ledger(&self.ctx, self.ipv6.ledger_mut(), now);

            if let Some(reason) = self.stop_reason(now, sending_finished) {
                break reason;
            }

            // Anything left to put on the wire, whether a first attempt or a
            // repeat, goes through the same paced ticker.
            let sending = !sending_finished
                || !self.sweep.retries.is_empty()
                || self.ipv6.confirmations_pending()
                || self.ipv6.solicitation().is_due(now);
            let idle_delay = self.tick_delay(now);

            tokio::select! {
                pkt = self.eth_handle.rx.recv() => {
                    match pkt {
                        Some(frame) => {
                            self.sweep.audit.record_segment();
                            // The moment the capture took the frame, not the
                            // moment this loop reached it. See
                            // `CapturedFrame::received_at`.
                            _ = self.process_eth_packet(&frame, frame.received_at);
                        }
                        None => break StopReason::StreamClosed,
                    }
                }

                _ = send_interval.tick(), if sending => {
                    let now = Instant::now();
                    match self.send_next(&mut packet_iter, sending_finished, now) {
                        Dispatched::Drained => sending_finished = true,
                        Dispatched::Sent | Dispatched::Nothing => {}
                    }
                }

                _ = tokio::time::sleep(idle_delay), if !sending => {}
            }
        };

        // What the iterator still holds was never asked. Built into frames to
        // be read, which is work only a sweep cut short pays for, and the
        // one reading that names the addresses rather than counting them.
        let unasked: Vec<IpAddr> = if sending_finished {
            Vec::new()
        } else {
            packet_iter.map(|(_, ip)| ip).collect()
        };
        self.report_outcome(reason, &unasked);
        Ok(())
    }
}

impl LocalScanner {
    /// A sweep for `ip_set` across the segment `link` is attached to, over a
    /// capture this constructor opens on that interface.
    ///
    /// `scope` decides whether the whole segment is invited to answer or only
    /// the addresses given are asked. Whatever is found is written to `ctx`,
    /// and each address goes to `dns_tx` for a reverse lookup unless that is
    /// `None`. `retry` scales how often an unanswered ARP request is repeated,
    /// and with it how long the sweep is prepared to run.
    ///
    /// Fails when the capture cannot be opened, and when `link` has no MAC
    /// address to send from.
    pub fn new(
        link: Link,
        ip_set: IpSet,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        scope: Scope,
        retry: RetryConfig,
    ) -> Result<Self, StrategyError> {
        let eth_handle: EthernetHandle = channel::start_capture(&link, &sweep_filter())?;
        Self::build(
            link,
            ip_set,
            ctx,
            dns_tx,
            scope,
            eth_handle,
            RETRY_POLICY.configured(retry),
        )
    }

    /// Builds a scanner around an already-opened Ethernet channel, so the caller
    /// decides how frames reach the wire and where replies come from.
    ///
    /// The addressing identity is still resolved from `intf`, since a probe has
    /// to be sent from some MAC and address, but nothing here touches the
    /// interface itself.
    ///
    /// This is the constructor for a caller orchestrating their own scan, who
    /// has opened a channel on the interface they mean rather than letting
    /// [`new`](Self::new) choose. Paired with a synthetic channel
    /// (`EthernetHandle::from_parts`, behind the `test-support` feature) and a
    /// hand-built [`Link`], it is also the seam
    /// that lets ARP and
    /// NDP discovery be driven against a simulated segment with no privileges.
    pub fn with_handle(
        link: Link,
        ip_set: IpSet,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        scope: Scope,
        eth_handle: EthernetHandle,
    ) -> Result<Self, StrategyError> {
        Self::build(link, ip_set, ctx, dns_tx, scope, eth_handle, RETRY_POLICY)
    }

    /// The common constructor, taking the retry schedule as an argument because
    /// the sweep's own deadline is derived from it and so has to be settled
    /// before anything is built.
    #[allow(clippy::too_many_arguments)]
    fn build(
        link: Link,
        ip_set: IpSet,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        scope: Scope,
        eth_handle: EthernetHandle,
        retry: RetryPolicy,
    ) -> Result<Self, StrategyError> {
        let identity = SourceIdentity::resolve(&link, &ip_set)?;

        // Saturating, not truncating. An address count is a `u128` and a `/64`
        // is exactly `usize::MAX + 1`, so the plain cast would turn the largest
        // possible sweep into a target count of zero and hand it the smallest
        // possible budget. `ScanBudget::unclamped` saturates its own cast for
        // the same reason one layer down.
        let target_count = usize::try_from(ip_set.len()).unwrap_or(usize::MAX);
        let deadline = AdaptiveDeadline::new(deadline_for(target_count, &retry), target_count);

        Ok(Self {
            ctx,
            ip_set,
            identity,
            eth_handle,
            deadline,
            protocols: frames::sweep_protocols(),
            sweep: HostSweep::new(Ledger::new(retry, target_count)),
            dns_tx,
            mac_to_ip: HashMap::new(),
            declared: HashMap::new(),
            scope,
            ipv6: Ipv6Discovery::new(target_count),
            send_failure: None,
            prefixes: interface::OnLinkTable::from_links(std::slice::from_ref(&link)),
            refuses: interface::refuses_neighbour,
        })
    }

    /// Reads every frame already waiting in the capture stream, without
    /// waiting for more, bounded by what is queued on entry.
    ///
    /// A loop held up past a timeout wakes to the answer and the expired timer
    /// at once. Read in the other order, an address's last attempt is spent
    /// before the answer to it is seen, and the answer finds no probe to time:
    /// the host is recorded unmeasured, and its address settled as asked and
    /// unanswered by a sweep that holds its answer.
    fn read_waiting_frames(&mut self) {
        let waiting = self.eth_handle.rx.len();
        for _ in 0..waiting {
            let Ok(frame) = self.eth_handle.rx.try_recv() else {
                // Empty after all, or closed, which the `select!` reads as
                // the stream ending.
                return;
            };
            self.sweep.audit.record_segment();
            _ = self.process_eth_packet(&frame, frame.received_at);
        }
    }

    /// Why the loop should stop, if it should.
    ///
    /// A run somebody aborted, or whose wall-clock budget ran out, is reported
    /// as such whatever state the sweep was in, because the caller stopped it
    /// rather than the sweep stopping itself. Otherwise the reason says
    /// whether the sweep finished, which is the caller's next question.
    ///
    /// A sweep that has sent every first attempt and holds nothing
    /// outstanding has asked every address as often as its schedule allows,
    /// and stops as [`AttemptsSpent`](StopReason::AttemptsSpent) once the
    /// segment has been quiet for its silence tolerance, or its hard deadline
    /// passes first. It goes on listening that long, where the routed sweep
    /// stops at once, but no probe of its own is waiting any more. Only a
    /// sweep stopped with something unsent or outstanding is cut short, and
    /// only that one reads [`DeadlineExpired`](StopReason::DeadlineExpired).
    fn stop_reason(&self, now: Instant, sending_finished: bool) -> Option<StopReason> {
        if let Some(cause) = self.ctx.handle.stopped() {
            return Some(cause.into());
        }
        if sending_finished && self.all_targets_responded() {
            return Some(StopReason::AllResponded);
        }
        // Silence is only evidence once nothing is outstanding: with probes
        // still waiting on their timers, quiet is what the retry schedule
        // expects rather than a sign the segment has gone quiet.
        let spent = sending_finished && self.idle(now);
        if self.deadline.hard_deadline_passed() {
            return Some(if spent {
                StopReason::AttemptsSpent
            } else {
                StopReason::DeadlineExpired
            });
        }
        if spent && self.deadline.has_expired() {
            return Some(StopReason::AttemptsSpent);
        }

        None
    }

    /// Puts the next frame this sweep owes on the wire, and says which kind it
    /// was.
    ///
    /// Repeats first: an address already asked once is an obligation this sweep
    /// owns, where the next new address is only work it intends to do. The two
    /// IPv6 schedules are ahead of first attempts for the same reason, each
    /// having a due time to keep.
    fn send_next(
        &mut self,
        packet_iter: &mut probes::PacketIter,
        sending_finished: bool,
        now: Instant,
    ) -> Dispatched {
        if let Some(target) = self.next_live_retry() {
            self.send_probe(target, now);
            Dispatched::Sent
        } else if let Some(target) = self.ipv6.next_confirmation() {
            self.send_confirmation(target, now);
            Dispatched::Sent
        } else if self.ipv6.solicitation().is_due(now) {
            self.send_solicitation(now);
            Dispatched::Sent
        } else if !sending_finished {
            match packet_iter.next() {
                Some((packet, ip)) => {
                    // Armed only if the frame left. A probe nobody sent
                    // must not run out of attempts and earn a verdict, and
                    // the failure the sweep reports on its way out is about
                    // exactly these addresses.
                    if self.emit(&packet, "first attempt") {
                        self.record_probe(ip, Instant::now());
                    }
                    Dispatched::Sent
                }
                None => Dispatched::Drained,
            }
        } else {
            Dispatched::Nothing
        }
    }

    /// What the sweep leaves behind once the loop has stopped: the addresses it
    /// never settled, the questions that went unanswered, the frames that never
    /// left, and the counters a later phase reads.
    ///
    /// `unasked` is every address the sweep never sent a first attempt to.
    fn report_outcome(&mut self, reason: StopReason, unasked: &[IpAddr]) {
        // What the sweep did not earn a verdict for, so a resumed one asks again
        // rather than skipping it. None of these carries a position: a probe
        // still mid-schedule was cut off rather than spent, and one the iterator
        // still held was never sent.
        let interrupted = self.sweep.ledger.drain_unresolved();
        self.ctx
            .record_address_outcomes(Outcome::Interrupted, interrupted.len() as u64);
        self.ctx
            .record_address_outcomes(Outcome::Unasked, unasked.len() as u64);

        // Addresses never asked leave the result narrower than the caller asked
        // for, which is what a failure says, and the number is the part a
        // reader can act on. Only where the sweep stopped itself, as the routed
        // sweep decides it: a caller who aborted the scan or set its budget
        // knows why it ended.
        if !unasked.is_empty() && !matches!(reason, StopReason::Aborted | StopReason::TimedOut) {
            self.ctx.record_failure(
                ScannerKind::Local,
                format!(
                    "{} of {} addresses on {} were never asked: {reason} with them \
                     still queued",
                    unasked.len(),
                    self.ip_set.len(),
                    self.identity.zone,
                ),
            );
        }

        // What the confirmations bought, which is only visible from here. An
        // entry still in the map is a solicitation that went out and was never
        // answered, and the difference between "none were sent" and "none came
        // back" is the difference between a bug here and a segment full of
        // devices that decline to answer a direct question.
        if self.ipv6.unanswered_confirmations() > 0 {
            info!(
                verbosity = 2,
                "{} of the addresses asked about directly never answered",
                self.ipv6.unanswered_confirmations()
            );
        }

        // A sweep whose frames never left is not a sweep that found nothing, and
        // the difference is invisible in every number a caller reads. Reported
        // once with a count and the first cause rather than once per probe, as
        // the routed paths do.
        //
        // This covers every frame the sweep emits, which is what makes it worth
        // having: while the first attempts bypassed the audit, the one path that
        // sends a frame per target could fail entirely and this stayed silent.
        if self.sweep.audit.sends_failed > 0 {
            self.ctx.record_failure(
                ScannerKind::Local,
                format!(
                    "{} of {} frames never reached {}, so those addresses are \
                     reported absent without having been asked: {}",
                    self.sweep.audit.sends_failed,
                    self.sweep.audit.sends_attempted,
                    self.identity.zone,
                    self.send_failure.as_deref().unwrap_or("cause unrecorded"),
                ),
            );
        }

        // What the kernel discarded before this scanner could read it. A frame
        // lost there is indistinguishable from a host that never answered, so a
        // sweep finding fewer hosts than the segment holds can be attributed to
        // loss rather than guessed at. `None` only for a synthetic stream,
        // which has no kernel buffer to have overflowed.
        let capture = self.eth_handle.capture_counts();
        let targets = self.ip_set.len();
        self.sweep.report(
            &self.ctx,
            "local-discovery",
            ScannerKind::Local,
            targets,
            reason,
            capture,
        );
    }

    /// Puts one frame on the segment and records what actually happened to it.
    ///
    /// Every send in this scanner goes through here, and that is the point.
    /// The audit's counters are only worth reading if they cover every frame,
    /// and a second send path is how they stop doing that: were the sweep's own
    /// first attempts to go out beside this one, uncounted, `sends_attempted`
    /// would describe the retries and nothing else while reading like a total.
    ///
    /// [`FrameSink::send_frame`](crate::transport::capture::FrameSink::send_frame)
    /// reports whether the frame left, and an error is the only way it did not.
    /// Every way a frame can fail to leave, no buffer to write into or a write
    /// that failed, means the same thing to every caller, which is why this
    /// says it once. Reading only whether the *packet built* would leave
    /// `sends_failed` making a claim about this code where a caller reads it as
    /// a claim about the link.
    fn emit(&mut self, packet: &[u8], what: &str) -> bool {
        match self.eth_handle.tx.send_frame(packet) {
            Ok(()) => {
                self.sweep.audit.record_send(true);
                true
            }
            Err(reason) => {
                self.sweep.audit.record_send(false);
                self.send_failure
                    .get_or_insert_with(|| format!("{what}: {reason}"));
                false
            }
        }
    }

    /// Notes that a probe for `ip` has just gone out.
    ///
    /// Everything the packet iterator emits is one address's own probe, to be
    /// repeated and eventually given up on. The all-nodes echo is not among
    /// them: it belongs to [`Solicitation`](ipv6::Solicitation), which records
    /// its own sends because it has to remember the token each one carried.
    fn record_probe(&mut self, ip: IpAddr, now: Instant) {
        if ip.is_ipv6() {
            self.ipv6.record_asked(ip, now);
        } else {
            self.sweep.ledger.arm(ip, ip, (), (), now);
        }
    }

    /// Queues a solicitation for an IPv6 address that turned up without one
    /// having been sent.
    ///
    /// Most IPv6 neighbours are found this way rather than by being asked. A
    /// segment carries a constant traffic of advertisements - neighbours
    /// resolving each other, announcing a new address, answering somebody else's
    /// question - and a promiscuous capture sees all of it. That is real evidence
    /// the host is there, and it is the mechanism behind most of what a sweep
    /// reports, but it is evidence of a conversation we were not part of: there
    /// is no probe of ours to measure against, so the host arrives with no round
    /// trip and no proof it is answering *now* rather than having answered
    /// somebody a moment ago.
    ///
    /// Asking directly costs one packet and settles both. The address came from
    /// the wire seconds ago, so unlike a neighbour-table entry it is almost
    /// certainly still live, and a solicitation to it is answered by the host
    /// itself rather than overheard.
    ///
    /// Bounded by [`solicited`](ipv6::Ipv6Discovery::solicited), so an address
    /// is asked about once however often it advertises itself.
    ///
    /// The one place a lead becomes a probe, and so where the exclusions are
    /// asked about it. Every caller hands over an address the target list never
    /// held, so withholding the list never reached it.
    fn confirm(&mut self, address: IpAddr) {
        if !address.is_ipv6()
            || !matches!(self.scope, Scope::Sweep)
            || self.identity.link_local_ipv6.is_none()
        {
            return;
        }

        if !self.ctx.may_probe(&address) {
            info!(
                verbosity = 2,
                "{address} was overheard and is excluded, so it is not asked about"
            );
            return;
        }
        // Nor one this host's routing table refuses, which the sweep's own
        // targets were withheld for before it started; see
        // `interface::refused_neighbours`. Only an address inside a prefix the
        // link holds is put to the table, as only such targets of the sweep's
        // own are. For one of those the table's answer is the connected route
        // unless a route of the host's policy overrides it, so a refusal is
        // that policy. For any other the table answers about a path through a
        // router, which the solicitation does not take: a host with no route
        // there, a machine with no IPv6 beyond its links among them, would
        // read every neighbour announcing an address from another prefix as
        // refused, and a phone named only by its mDNS announcements would not
        // be found. A link-local address is on no prefix the table can
        // answer for either: it is on this segment by definition, and without
        // its zone Linux refuses the lookup as an invalid argument, the
        // answer a blackhole route gives.
        let on_a_prefix = self.prefixes.source_for(address).is_some();
        if on_a_prefix && (self.refuses)(address) {
            info!(
                verbosity = 2,
                "{address} was overheard and a route refuses it, so it is not asked about"
            );
            return;
        }

        // Queued rather than sent here, so a confirmation leaves on the same
        // paced ticker every other probe does.
        self.ipv6.note_overheard(address);
    }

    /// Sends the one solicitation an overheard address gets, and notes when.
    fn send_confirmation(&mut self, target: IpAddr, now: Instant) {
        let (IpAddr::V6(target_v6), Some(source_v6)) = (target, self.identity.link_local_ipv6)
        else {
            return;
        };

        let packet =
            protocol::ndp::build_neighbor_solicitation(self.identity.mac, source_v6, target_v6);
        self.emit(&packet, "confirming solicitation");
        self.ipv6.record_confirmation_sent(target, now);
        info!(
            verbosity = 2,
            "asked {target} directly, having only overheard it"
        );
    }

    /// Asks every router on the segment to say so, once, at the head of a
    /// sweep.
    ///
    /// One packet for a question nothing else on the segment answers. A router
    /// advertises itself unprompted on a timer measured in minutes, which
    /// outlasts any sweep, so without asking the engine finds the segment's
    /// routers only by luck. The reply is an ordinary advertisement claimed by
    /// [`RouterAdvertProtocol`](frames::RouterAdvertProtocol), so the router
    /// arrives as a host in the same breath as being named one.
    ///
    /// Sent on any local run, unlike the all-nodes echo. The rule that keeps a
    /// targeted run targeted is about what may be *recorded*, and it is
    /// enforced where records are made: an answer from an address nobody asked
    /// about is read for the role its sender claims and never becomes a host.
    /// The echo has no such reading, everything it draws is a new address,
    /// which is why it stays behind the sweep.
    ///
    /// Not repeated. A lost solicitation costs the *unsolicited* route to this
    /// finding, not the finding: a router that answers any of the scan's
    /// ordinary neighbour solicitations declares itself in the R flag of the
    /// reply, and every address the sweep asks about is asked more than once.
    fn solicit_routers(&mut self) {
        let Some(link_local) = self.identity.link_local_ipv6 else {
            return;
        };

        let packet = protocol::ndp::build_router_solicitation(self.identity.mac, link_local);
        self.emit(&packet, "router solicitation");
    }

    /// Asks the segment which machine configures it, once.
    ///
    /// A `DHCPINFORM`, which asks for configuration without asking for an
    /// address, so every server on the link answers and none of them reserves
    /// anything for a client that will never appear. See
    /// [`dhcp`](crate::protocols::dhcp) for why this is a broadcast rather than
    /// a port probe.
    ///
    /// Broadcast, and therefore seen by every device on the segment, which is
    /// the same reach an ARP request has, and a scan of a range sends one of
    /// those per address in it. Sent on any local run, on the same terms as the
    /// router solicitation: what a targeted run may record is enforced where
    /// records are made, not by declining to ask.
    ///
    /// The one run this is disproportionate for is a scan of a single address,
    /// where it triples a discovery phase that would otherwise put one ARP
    /// request on the wire. It is still two frames, on a segment this machine
    /// is already on.
    ///
    /// The answer comes back to this host's address, and is read off the
    /// segment by [`DhcpProtocol`](frames::DhcpProtocol) rather than through a
    /// socket: binding UDP/68 is a privilege this scanner already has a better
    /// use for, and the capture sees the reply either way.
    fn ask_for_configuration(&mut self) {
        let Some(source) = self.identity.ipv4 else {
            return;
        };

        let packet = protocol::dhcp::build_inform(self.identity.mac, source);
        self.emit(&packet, "dhcp inform");
    }

    /// Sends the all-nodes solicitation again.
    ///
    /// Unlike an ARP request this is never retired by an answer, so it is simply
    /// repeated a fixed number of times: a neighbour that missed the last one,
    /// or was asleep when it arrived, gets another chance to hear it.
    fn send_solicitation(&mut self, now: Instant) {
        let Some(link_local) = self.identity.link_local_ipv6 else {
            return;
        };

        let packet = protocol::icmp::build_all_nodes_echo_request_v6(
            self.identity.mac,
            link_local,
            self.ipv6.solicitation().identifier,
            self.ipv6.solicitation().next_sequence(),
        );
        self.emit(&packet, "all-nodes solicitation");
        self.ipv6.record_solicitation_sent(now);
    }

    /// The first queued retry whose probe is still outstanding, taken off the
    /// queue.
    ///
    /// One whose probe has left its ledger was answered while it waited, and
    /// is dropped: sending it asks a question nothing is waiting on, and
    /// arming it would start its address a fresh schedule after its verdict.
    fn next_live_retry(&mut self) -> Option<IpAddr> {
        while let Some(target) = self.sweep.retries.pop_front() {
            let outstanding = if target.is_ipv6() {
                self.ipv6.ledger_mut().contains(&target)
            } else {
                self.sweep.ledger.contains(&target)
            };
            if outstanding {
                return Some(target);
            }
        }
        None
    }

    /// Rebuilds and sends a queued retry for `target`, whichever kind its
    /// address calls for: an ARP request over IPv4, a neighbor solicitation
    /// over IPv6.
    ///
    /// Nothing about either is kept between attempts, because nothing needs to
    /// be: the frame is a function of this scanner's identity and the address
    /// being asked about, and rebuilding it is cheaper than holding a copy per
    /// outstanding probe.
    ///
    /// The probe's clock stopped while the retry was queued and restarts here
    /// on the ledger that scheduled it: from the send, or from now for a frame
    /// that did not leave, whose attempt stays charged so the address still
    /// runs out of attempts on schedule. See
    /// [`HostSweep::retries`](crate::scanner::strategy::sweep::HostSweep::retries).
    fn send_probe(&mut self, target: IpAddr, now: Instant) {
        let packet = match target {
            IpAddr::V4(target_v4) => self
                .identity
                .ipv4
                .map(|source| protocol::arp::build_request(self.identity.mac, source, target_v4)),
            IpAddr::V6(target_v6) => self.identity.link_local_ipv6.map(|source| {
                protocol::ndp::build_neighbor_solicitation(self.identity.mac, source, target_v6)
            }),
        };

        let left = packet.is_some_and(|packet| self.emit(&packet, "probe"));
        let ledger = if target.is_ipv6() {
            self.ipv6.ledger_mut()
        } else {
            &mut self.sweep.ledger
        };
        if left {
            ledger.rearm(target, target, (), now);
        } else {
            ledger.resume(&target, now);
        }
    }

    /// Takes the IPv6 addresses an overheard mDNS message names as leads,
    /// returning whether the frame was one.
    ///
    /// A segment announces itself constantly and this scanner's capture is
    /// promiscuous, so these addresses already arrive here.
    /// The hostname resolver caches mDNS records too, but applies them to hosts
    /// *already in the store*: a record naming an address nothing has answered
    /// for goes nowhere there.
    ///
    /// They arrive as candidates, never as hosts. An mDNS record is a claim
    /// somebody else made, possibly some time ago and possibly about an address
    /// that has since moved: the same standing as a neighbour-table entry, and
    /// it earns its place in the report the same way, by answering a
    /// solicitation now. [`confirm`](Self::confirm) is that mechanism and
    /// already bounds itself to one solicitation per address.
    ///
    /// The sender is not credited either. A frame off the segment
    /// does prove its sender exists, but crediting a host to "was chatty on
    /// mDNS" attributes it to a mechanism that did not find it, which is the
    /// distinction [`Icmpv6EchoProtocol`](frames::Icmpv6EchoProtocol) is
    /// careful about for the same reason.
    ///
    /// Nothing is taken once the sweep has run its course. Each confirmation
    /// holds the run open for a reply, so a segment that keeps talking could
    /// otherwise keep extending it, and a lead that arrives after the sweep
    /// would have ended belongs to the next scan.
    /// Reads a switch's announcement of itself, where the frame is one.
    ///
    /// Returns whether the frame was an announcement, so the caller can stop
    /// reading it as something else.
    ///
    /// # Two findings, and only one of them is about a host
    ///
    /// Where this machine is plugged in is recorded unconditionally, as an
    /// [`Attachment`] on the phase. It is not a claim about a host in the
    /// report, it is a relation between this machine and somebody else's
    /// equipment, so the rule that keeps a targeted run targeted does not
    /// apply to it. A run handed one address still reports one host, and also
    /// says which switch port it was run from.
    ///
    /// What the sender is goes through `note_declaration` like any other
    /// overheard claim: filed against the announcing hardware address and
    /// applied only if that machine turns out to be one the scan found by
    /// asking. A switch usually holds no address on the segment it serves, so
    /// in the common case the claim is never applied to anything, and that is
    /// the correct outcome, not a loss. The switch's identity is in the
    /// attachment, where it belongs.
    ///
    /// # What an announcement is not evidence of
    ///
    /// That its sender is a switch. Anything on a link can emit one, and
    /// nothing here authenticates it. What the group address buys is a
    /// statement about *where*, conforming bridges constrain those addresses
    /// rather than forwarding them, and never about truthfulness. The role
    /// this files carries that caveat in its own documentation.
    fn absorb_announcement(
        &mut self,
        frame: &Frame<'_>,
        source_mac: MacAddr,
        captured: &CapturedFrame,
    ) -> bool {
        let mut attachment = Attachment::new(
            captured.zone.clone(),
            AttachmentSource::Lldp,
            captured.observed_at,
        );
        let mut roles: Vec<NetworkRole> = Vec::new();

        if let Some(advertisement) = protocol::lldp::parse(frame) {
            attachment = attachment.with_device_mac(source_mac);

            if let Some(name) = advertisement.system_name {
                attachment = attachment.with_device_name(name);
            }
            if let Some(protocol::lldp::Identifier::Text(port)) = advertisement.port_id {
                attachment = attachment.with_port(port);
            }
            if let Some(vlan) = advertisement.port_vlan {
                attachment = attachment.with_native_vlan(vlan);
            }
            if let Some(address) = advertisement.management_address {
                attachment = attachment.with_management_address(address);
            }
            if let Some(capabilities) = advertisement.capabilities {
                if capabilities.is_bridge() {
                    roles.push(NetworkRole::Switch);
                }
                if capabilities.is_router() {
                    roles.push(NetworkRole::Router);
                }
            }
        } else if let Some(announcement) = protocol::cdp::parse(frame) {
            attachment = Attachment::new(
                captured.zone.clone(),
                AttachmentSource::Cdp,
                captured.observed_at,
            )
            .with_device_mac(source_mac);

            if let Some(name) = announcement.device_id {
                attachment = attachment.with_device_name(name);
            }
            if let Some(port) = announcement.port_id {
                attachment = attachment.with_port(port);
            }
            if let Some(vlan) = announcement.native_vlan {
                attachment = attachment.with_native_vlan(vlan);
            }
            if let Some(address) = announcement.address {
                attachment = attachment.with_management_address(address);
            }
            if let Some(capabilities) = announcement.capabilities {
                if capabilities.is_switch() {
                    roles.push(NetworkRole::Switch);
                }
                if capabilities.is_router() {
                    roles.push(NetworkRole::Router);
                }
            }
        } else {
            return false;
        }

        info!(
            verbosity = 1,
            "{} says this machine is on {}{}",
            self.identity.zone,
            attachment.device_name().unwrap_or("an unnamed device"),
            match attachment.port() {
                Some(port) => format!(" port {port}"),
                None => String::new(),
            },
        );

        self.ctx.record_attachment(attachment);
        for role in roles {
            self.note_declaration(source_mac, role);
        }

        true
    }

    fn absorb_mdns(&mut self, frame: &Frame<'_>) -> bool {
        let Some(payload) = protocol::ip::udp_payload(frame, protocol::mdns::PORT) else {
            return false;
        };
        if self.deadline.has_expired() {
            return true;
        }

        let Ok(hosts) = protocol::mdns::extract_hosts(payload) else {
            return true;
        };

        for host in hosts {
            for ip in host.ips {
                if ip.is_ipv6() && !self.ipv6.is_solicited(&ip) {
                    info!(
                        verbosity = 2,
                        "mDNS named {ip} as {}, which nothing has answered for", host.hostname
                    );
                    self.confirm(ip);
                }
            }
        }

        true
    }

    /// Retires the probe for `address` from whichever ledger owns its family.
    fn resolve_probe(
        &mut self,
        address: &IpAddr,
        now: Instant,
    ) -> Option<crate::scanner::pacing::retry::Resolution> {
        if address.is_ipv6() {
            self.ipv6.resolve(address, now)
        } else {
            self.sweep.ledger.resolve(address, None, now)
        }
    }

    /// Whether an ARP frame is a reply sent to this scanner, the one kind that
    /// can answer the request it put to the frame's sender.
    ///
    /// A neighbour's own request, an announcement, and a reply to another
    /// machine that a promiscuous capture overhears all prove the sender is
    /// there, and none of them answers this scan's question. Taken as the
    /// answer, each would retire the request and time it from the moment it
    /// left to the moment somebody else's conversation happened to pass.
    ///
    /// A reply to this machine's address is taken as the answer to this
    /// scanner's request whoever on the machine asked. ARP carries no token,
    /// so a reply to a request another process sent a moment earlier, one
    /// that stopped waiting before its answer came, is indistinguishable on
    /// the wire from a reply to this one. Accepting it costs nothing in what
    /// the sweep reports, since the neighbour did answer for its address;
    /// what it can cost is a round trip timed short, which seeds the passes
    /// after this one short, and they retransmit early and measure the path
    /// for themselves. Refusing every reply that could be another's would
    /// refuse every reply. What keeps the case rare is the patience of
    /// [`RETRY_POLICY`]: a neighbour answering within it answers the process
    /// that asked.
    fn answers_our_request(&self, frame: &Frame<'_>) -> bool {
        frame.destination() == self.identity.mac
            && pnet_packet::arp::ArpPacket::new(frame.payload())
                .is_some_and(|arp| arp.get_operation() == pnet_packet::arp::ArpOperations::Reply)
    }

    /// Whether the sweep has nothing left to send and nothing left to wait for.
    fn idle(&self, now: Instant) -> bool {
        self.sweep.retries.is_empty() && self.sweep.ledger.is_empty() && self.ipv6.is_idle(now)
    }

    /// How long the loop may sleep once it has stopped sending: until the
    /// sweep's next checkpoint, until the next address is due to be asked again,
    /// or until the solicitation's schedule next needs attention - whichever
    /// comes first.
    fn tick_delay(&self, now: Instant) -> Duration {
        let mut delay = self.deadline.time_until_next_tick();
        for wakeup in [self.sweep.ledger.next_due(), self.ipv6.next_wakeup()]
            .into_iter()
            .flatten()
        {
            delay = delay.min(wakeup.saturating_duration_since(now));
        }
        delay
    }

    /// Validates an incoming frame, then handles a discovery reply in two steps:
    /// working out what it means, and recording that in shared scan state.
    fn process_eth_packet(
        &mut self,
        frame: &CapturedFrame,
        now: Instant,
    ) -> Result<(), FrameRejected> {
        // Every probe this sweep sends is an Ethernet frame and every reading it
        // takes starts from an Ethernet header, so a link that prepends
        // something else carries nothing this can read. `start_capture` refuses
        // such an interface outright; a synthetic stream is the only way one
        // reaches here, and reading its bytes as Ethernet would invent a source
        // address rather than fail.
        if frame.link != LinkType::Ethernet {
            self.sweep.audit.record_off_target();
            return Err(FrameRejected::UnreadableLink);
        }

        let eth_frame: Frame<'_> = ethernet::parse(&frame.bytes)?;

        let source_mac = eth_frame.source();
        if source_mac == self.identity.mac {
            self.sweep.audit.record_off_target();
            return Err(FrameRejected::SelfSourcedPacket);
        }

        // Before the address is read, because neither of these frames has one.
        // LLDP carries no IP header at all and CDP is not even an EtherType
        // protocol, so `source_address` refuses both, which is correct, and is
        // why they have to be taken out of the stream first.
        if self.absorb_announcement(&eth_frame, source_mac, frame) {
            return Ok(());
        }

        let source_addr: IpAddr = protocol::source_address(&eth_frame)?;

        if self.absorb_mdns(&eth_frame) {
            return Ok(());
        }

        let Some((reading, protocol)) = self.interpret_response(&eth_frame) else {
            // Common in promiscuous mode: traffic between other hosts, or
            // forwarded through a router. Not this scan's, and not a fault.
            self.sweep.audit.record_off_target();
            return Ok(());
        };

        // Which address this reply is *about*, which is not always where it came
        // from. A neighbor advertisement names its subject, and a host with
        // several addresses answers from whichever its stack prefers - so the
        // claim has to be read before the frame is judged, or a reply to a probe
        // this scan sent is discarded for naming an address nobody asked about.
        let subject = match reading.matched {
            ProtocolMatch::Solicited(Some(claimed)) => claimed,
            _ => source_addr,
        };

        // A targeted run records only its exact targets; a sweep records every
        // in-range IPv4 responder plus any IPv6 neighbor (linked by MAC).
        let out_of_range = match self.scope {
            Scope::Targeted => !self.ip_set.contains(&subject),
            Scope::Sweep => subject.is_ipv4() && !self.ip_set.contains(&subject),
        };
        if out_of_range {
            // Out of range and still worth reading, in the one case where the
            // frame says something about a machine rather than about an
            // address: a router advertising from its link-local, a DHCP server
            // answering from outside the range. The claim is filed against the
            // sender's hardware address and applied only if that machine turns
            // out to be one this scan asked about.
            if let Some(role) = reading.declared
                && self.note_declaration(source_mac, role)
            {
                return Ok(());
            }

            self.sweep.audit.record_off_target();
            return Err(FrameRejected::AddressOutOfRange(subject));
        }

        // An ARP frame names its sender's address and comes from its hardware
        // address, which is exactly what a sender framing a probe to that
        // address has to know. Handed on, so the passes after this sweep frame
        // their probes to the neighbour it heard rather than asking again by a
        // broadcast the neighbour may not hear in time.
        if protocol == StatusProtocol::Arp && subject.is_ipv4() {
            neighbor::learn_neighbor(self.identity.zone.name(), subject, source_mac);
        }

        if subject != source_addr {
            info!(
                verbosity = 2,
                "{subject} answered from {source_addr}, which is another of its addresses"
            );
        }

        // Which send the reply answered, where the wire can say. Set inside the
        // one arm that can know it rather than threaded through the match: the
        // all-nodes echo is timed against a request it names, but that request
        // was put to the whole segment and answers no address's own probe.
        let mut answered_attempt = None;

        // Every ARP frame proves its sender is there, and only a reply sent to
        // this scanner can answer the request it put; see `answers_our_request`.
        let matched = match reading.matched {
            ProtocolMatch::Solicited(_)
                if protocol == StatusProtocol::Arp && !self.answers_our_request(&eth_frame) =>
            {
                ProtocolMatch::Unsolicited
            }
            matched => matched,
        };

        let rtt = match matched {
            // `interpret_response` returns `None` rather than this, so the arm
            // exists only to satisfy the match.
            ProtocolMatch::Unhandled => return Ok(()),
            ProtocolMatch::Solicited(_) => {
                let correlated = self.correlate_rtt(subject, &protocol, now);
                answered_attempt = correlated.answered_attempt;
                correlated.rtt
            }
            // Proof of presence and of nothing else. A probe may well be
            // outstanding for this address, and it stays outstanding: this
            // message did not answer it, so retiring it here would credit our
            // question with somebody else's answer and time it from the moment
            // we asked.
            //
            // Asked directly instead, which is the same treatment an overheard
            // address gets, and the only way one of these senders is ever
            // measured. An IPv4 neighbour is not: its own request is still
            // outstanding and is what measures it.
            ProtocolMatch::Unsolicited => {
                self.confirm(subject);
                None
            }
            ProtocolMatch::AllNodes {
                identifier,
                sequence,
            } => self.match_solicitation(subject, identifier, sequence, now)?,
        };

        if self.ip_set.contains(&subject) {
            self.sweep.responded.insert(subject);
        }
        self.record_response(
            source_mac,
            subject,
            rtt,
            protocol.clone(),
            answered_attempt,
            reading.declared,
        );

        // The address the reply came *from* belongs to the same host and is just
        // as real, so it is recorded too - but only after the subject, which is
        // what keys the host. Filing it under an address the scan never asked
        // about is how a phone solicited at one address came back reported under
        // another.
        if subject != source_addr {
            // The declaration went in with the subject above, and both calls
            // reach the same record: a host is keyed by the MAC that answered,
            // whichever of its addresses this frame was about.
            self.record_response(source_mac, source_addr, None, protocol, None, None);
        }

        Ok(())
    }

    /// What a solicited reply from `subject` says about the send it answers:
    /// the round trip, and which attempt it retires.
    ///
    /// The two ways a round trip goes missing are worth telling apart out loud,
    /// because from the outside they look identical - a host with no latency
    /// beside it - and they call for opposite responses. One is a probe this
    /// scan never had outstanding, which means the reply answered somebody
    /// else's question or arrived after we gave up. The other is Karn's rule:
    /// the address was asked more than once, consecutive probes are identical
    /// on the wire, and the reply cannot say which it answers.
    ///
    /// An address with neither a probe nor a confirmation outstanding is asked
    /// directly on the way out, so the next reply from it can be measured.
    fn correlate_rtt(
        &mut self,
        subject: IpAddr,
        protocol: &StatusProtocol,
        now: Instant,
    ) -> ProbeCorrelation {
        match self.resolve_probe(&subject, now) {
            Some(resolution) => {
                if resolution.rtt.is_none() {
                    info!(
                        verbosity = 2,
                        "{subject} answered over {protocol:?} after {} attempts, so it is not timed{}",
                        resolution.attempts,
                        self.ipv6.since_first_asked(&subject, now)
                    );
                }
                ProbeCorrelation {
                    rtt: resolution.rtt.map(|rtt| (rtt, RttSource::Direct)),
                    answered_attempt: resolution.answered_attempt,
                }
            }
            // Not in the ledger, so either it answers the one confirmation an
            // overheard address gets - unambiguous, because there is only ever
            // one - or it is a neighbour talking to somebody else, which is
            // worth asking about directly.
            None => {
                let rtt = match self.ipv6.take_confirmation_rtt(&subject, now) {
                    Some(rtt) => Some((rtt, RttSource::Direct)),
                    None => {
                        info!(
                            verbosity = 2,
                            "{subject} answered over {protocol:?} with no probe of ours outstanding{}",
                            self.ipv6.since_first_asked(&subject, now)
                        );
                        self.confirm(subject);
                        None
                    }
                };
                ProbeCorrelation {
                    rtt,
                    answered_attempt: None,
                }
            }
        }
    }

    /// Which all-nodes echo request a reply answers, and how long that took.
    ///
    /// The echoed identifier and sequence name the request outright. That is
    /// what a neighbor advertisement can never do, and it is why this probe is
    /// timed at all: a neighbour that wakes in time for the third request is
    /// measured against the third rather than the first. Several neighbours
    /// answering the same request each get their own measurement from it,
    /// because a segment-wide question is not used up by whoever replies first.
    ///
    /// Reported as [`RttSource::SegmentWide`], because knowing *which* request
    /// was answered does not make the interval a clean round trip: a node
    /// answering the whole segment waits before it does, so this is an upper
    /// bound and is reported only by a host that produced nothing better.
    ///
    /// A token this scan never sent belongs to somebody else's ping, so it is
    /// not timed; a reply arriving when no request was ever sent is not an
    /// answer to one of ours at all, and the frame is rejected.
    fn match_solicitation(
        &self,
        subject: IpAddr,
        identifier: u16,
        sequence: u16,
        now: Instant,
    ) -> Result<Option<(Duration, RttSource)>, FrameRejected> {
        if self.ipv6.solicitation().nothing_sent() {
            return Err(FrameRejected::UnmappedRttSource(subject));
        }

        let rtt = match self.ipv6.solicitation().sent_at(identifier, sequence) {
            Some(sent_at) => Some((
                now.saturating_duration_since(sent_at),
                RttSource::SegmentWide,
            )),
            None => {
                info!(
                    verbosity = 2,
                    "{subject} answered an echo request that was not ours, so it is not timed"
                );
                None
            }
        };

        Ok(rtt)
    }

    /// Whether every target address has answered, which is a question only a
    /// [`Scope::Targeted`] run can ask.
    ///
    /// A sweep counts only in-range IPv4 addresses as responders, an IPv6
    /// neighbour found through the all-nodes echo was never in the range, so
    /// comparing that count against the whole target set asks whether the IPv4
    /// half is done and then stops the IPv6 half on the answer. On a wide range
    /// it never trips and the bug stays hidden; on a handful of addresses that
    /// all answer, the sweep exits with advertisements still in the receive
    /// queue.
    ///
    /// It is also the difference between a sweep of a link with no IPv4 at all
    /// and no sweep whatsoever: with an empty target set the comparison is
    /// `0 >= 0`, true on the first iteration, so the run ends before the echo it
    /// exists to send can be answered.
    fn all_targets_responded(&self) -> bool {
        matches!(self.scope, Scope::Targeted) && self.sweep.all_responded(self.ip_set.len())
    }

    /// Tries each configured [`DiscoveryProtocol`] against `frame` in turn.
    ///
    /// Returns the claiming protocol's verdict together with the evidence it
    /// counts as, or `None` when no protocol recognized the frame as a discovery
    /// response, or when one recognized it but failed to interpret it. Either
    /// way the frame carries no reliable information about who sent it and must
    /// not be attributed to any host. Seeing a frame that no protocol
    /// claims is common in promiscuous mode: it may be LAN traffic between other
    /// hosts, or traffic forwarded through a router rather than sent directly,
    /// whose Ethernet source is the router itself and not the host the IP packet
    /// originated from.
    fn interpret_response(&mut self, frame: &Frame<'_>) -> Option<(Reading, StatusProtocol)> {
        for protocol in &self.protocols {
            match protocol.interpret(frame) {
                Ok(Reading {
                    matched: ProtocolMatch::Unhandled,
                    ..
                }) => continue,
                Ok(reading) => return Some((reading, protocol.status_protocol())),
                Err(e) => {
                    error!(verbosity = 3, "failed to interpret discovery response: {e}");
                    return None;
                }
            }
        }

        None
    }

    /// Files what a machine said it is, against the hardware address that said
    /// it.
    ///
    /// Returns whether the claim was kept, which is the caller's answer to
    /// whether the frame was worth receiving.
    ///
    /// Applied immediately where the MAC is already on the roster, and held
    /// otherwise, because the order is not ours to choose: a router answers a
    /// solicitation within half a second (RFC 4861 §6.2.6) and the ARP request
    /// that will identify it leaves on a paced ticker some way into the sweep.
    /// Dropping the early half of that race is dropping the common case.
    ///
    /// Never creates a host and never records an address. A declaration is a
    /// claim about a machine, and the machine has to be one the scan found by
    /// asking before there is anything for the claim to attach to.
    fn note_declaration(&mut self, source_mac: MacAddr, role: NetworkRole) -> bool {
        if let Some(ip) = self.mac_to_ip.get(&source_mac).copied() {
            self.ctx.write_host(self.identity.key_for(ip), |host| {
                host.add_network_role(role);
                true
            });
            return true;
        }

        if self.declared.len() >= MAX_DECLARING_MACS && !self.declared.contains_key(&source_mac) {
            return false;
        }

        self.declared.entry(source_mac).or_default().insert(role);
        true
    }

    /// Applies a discovery response to shared scan state. It creates or updates
    /// the responding host, records what the reply proves about its liveness,
    /// feeds the adaptive deadline, and notifies both the scan's event channel
    /// and the hostname resolver of anything new.
    ///
    /// `protocol` is the evidence the claiming [`DiscoveryProtocol`] stands
    /// behind. Every frame reaching here came off the local segment with the
    /// host's own MAC as its Ethernet source, which is the strongest liveness
    /// evidence the engine can obtain: the host is provably present, so the
    /// status is [`HostStatus::Up`] regardless of which protocol claimed it and
    /// regardless of whether the reply could be timed.
    ///
    /// `rtt` carries what kind of question produced it, because the host is what
    /// ranks the two: a reply to a segment-wide probe is an upper bound rather
    /// than a round trip, and pooling it with a directed probe's answer is what
    /// reported a router that answers in 5 ms as answering in 37.
    ///
    /// `declared` is what the sender said it *is*, where the frame carried such
    /// a claim: the R flag on an advertisement, or an advertisement only a
    /// router sends. It is the host's own word rather than an inference of
    /// ours, which is why it is recorded here beside the liveness evidence and
    /// not derived later from what the record ended up holding.
    fn record_response(
        &mut self,
        source_mac: MacAddr,
        source_addr: IpAddr,
        rtt: Option<(Duration, RttSource)>,
        protocol: StatusProtocol,
        answered_attempt: Option<u8>,
        declared: Option<NetworkRole>,
    ) {
        // Whether *this scanner* has seen this device before, which is not the
        // same question as whether the store has a host at this address. In a
        // port-scan phase local discovery runs as enrichment beside the port
        // scanner, so the host usually exists already and `write_host` reports
        // nothing new - crediting the audit on that would report a sweep that
        // found nothing while its own log said a neighbour answered.
        //
        // Keyed on the MAC rather than the address because a device answering
        // at three addresses is one device found once, which is the unit the
        // roster and the audit both count in.
        let first_sighting = !self.mac_to_ip.contains_key(&source_mac);
        let primary_ip = *self.mac_to_ip.entry(source_mac).or_insert(source_addr);

        // Whatever this machine told the segment before this scan knew which
        // host it was. Taken out of the roster rather than left in it: the MAC
        // is on `mac_to_ip` from here on, so a later declaration is applied on
        // the spot.
        let held = self.declared.remove(&source_mac);

        // Host mutation only. `write_host` owns the guard, the drop-before-emit
        // ordering, and the event. `is_new_ip` is returned for the DNS decision
        // below, which runs after the guard is released, as does the deadline
        // bookkeeping.
        let mut is_new_ip = false;
        let zone = self.identity.zone.clone();
        let is_new_host = self
            .ctx
            .write_host(self.identity.key_for(primary_ip), |host| {
                // Every frame this scanner reads came off the one link it is
                // bound to, so a host it credits was observed through that
                // interface: whichever of its addresses answered first.
                //
                // **Set here rather than left to the key.** A host is born with
                // the zone its *key* carries, and a key carries one only where
                // the address needs it: a machine whose IPv4 answers before its
                // link-local is created unscoped, and left to the key its
                // link-local would then be reported bare. `fe80::aa` names a
                // different machine on every segment, so which of two addresses
                // replied first would decide whether the record was usable.
                // `set_zone` keeps the first it is given, so repeating this is
                // free.
                host.set_zone(zone.clone());

                // Recorded whether we just created the host or the port scanner
                // created it first, so enrichment order doesn't decide whether a MAC
                // is recorded. Repeating one already on record refreshes its
                // last-seen time, which is what `HardwareInfo` keeps them for.
                host.record_mac(source_mac);

                // The protocol name is the whole of the evidence here - a reply came
                // off the segment carrying this host's own MAC - so there is nothing
                // a details string would add that `arp` or `ndp` does not already
                // say.
                let was_up = host.status().is_up();
                host.record_evidence(HostStatus::Up, StatusReason::basic(protocol.clone()));

                let mut changed = rtt.is_some() || !was_up;
                for role in held.into_iter().flatten() {
                    changed |= host.add_network_role(role);
                }
                if let Some(role) = declared {
                    // A watcher told about this host before its sender said what it
                    // is has to hear the correction, so a role it did not carry is
                    // news in the same way a status change is. Repeating one is not:
                    // a router advertises on a timer.
                    changed |= host.add_network_role(role);
                }
                match rtt {
                    Some((rtt, RttSource::Direct)) => {
                        host.add_rtt_from(rtt, protocol.clone());
                    }
                    Some((rtt, RttSource::SegmentWide)) => {
                        host.add_segment_wide_rtt_from(rtt, protocol.clone());
                    }
                    Some((rtt, RttSource::FirstToNeighbour)) => {
                        host.add_first_to_neighbour_rtt_from(rtt, protocol.clone());
                    }
                    None => {}
                }

                is_new_ip = !host.ips().contains(&source_addr);
                // The rule for which address names a dual-stack host lives on the
                // host, not here: this scanner is one of several that learn a new
                // address for one, and a rule spread across their receive loops is
                // one each of them can disagree about.
                changed |= host.consider_primary_ip(source_addr) || is_new_ip;

                changed
            });
        // The address answered, which is a verdict this sweep earned however the
        // reply was timed and whether it was solicited or overheard. It is the
        // address that answered rather than the host's primary: a device
        // reachable at three addresses answered at this one. Settled once the
        // answer is stored; see `ScanContext::record_outcome`.
        self.ctx.settle_address(source_addr, Settled::Answered);

        if is_new_host {
            self.deadline.mark_activity();
        }
        if first_sighting {
            self.sweep.audit.record_host_found(answered_attempt);
        }
        if rtt.is_none() {
            // Alive, and no round trip to show for it: a reply to a probe this
            // scan no longer had outstanding, or one Karn's rule refuses to
            // time. Both are worth counting separately from the finding itself.
            self.sweep.audit.record_reply_without_rtt();
        }

        if let Some((rtt, source)) = rtt {
            // Named in the log, because several neighbours reporting the same
            // figure to the millisecond is a property of the probe rather than
            // of the network, and a reader who cannot tell the two kinds of
            // sample apart has no way to know that.
            let asked = match source {
                RttSource::Direct => "",
                RttSource::SegmentWide => " to the all-nodes echo",
                RttSource::FirstToNeighbour => " before it was resolved",
            };
            info!(
                incoming,
                verbosity = 2,
                "{source_addr} responded in {}ms{asked}",
                rtt.as_millis()
            );
            // Both kinds steer the deadline, which is asking a different
            // question from the one a reported latency answers: how long this
            // sweep should keep listening. A neighbour that takes 200 ms to
            // answer the segment is 200 ms this scan has to stay open for,
            // whatever inflated it.
            self.deadline.record_rtt(rtt);
        }

        if (is_new_host || is_new_ip)
            && let Some(tx) = &self.dns_tx
        {
            let _ = tx.send(source_addr);
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::mac::MacAddr;
    use crate::scanner::strategy::frames::tests::{
        LOCAL_MAC, PEER_MAC, advertisement_body, arp_reply_frame, arp_request_frame,
        dhcp_reply_frame, echo_reply_frame, mdns_frame, ndp_frame,
    };
    use std::net::{Ipv4Addr, Ipv6Addr};

    /// A sweep of a segment is given at least the time its own ticker needs to
    /// ask every address as often as its schedule says, however large the
    /// range: an address never asked looks exactly like one with nothing on
    /// it. The need is worked out from the numbers, a frame per address per
    /// attempt at [`SEND_INTERVAL`], rather than read from the sweep.
    #[test]
    fn a_segment_sweep_outlasts_the_time_its_ticker_needs_to_send_every_attempt() {
        const SLASH_16: usize = 1 << 16;
        let thorough = RetryConfig {
            effort: crate::config::ScanEffort::Thorough,
            ..RetryConfig::default()
        };

        for (case, retry, attempts) in [
            ("by default", RetryConfig::default(), 3),
            ("at thorough", thorough, 5),
        ] {
            let needed = SEND_INTERVAL * (SLASH_16 as u32) * attempts;
            let given = deadline_for(SLASH_16, &RETRY_POLICY.configured(retry))
                .max_budget
                .for_target_count(SLASH_16);
            assert!(
                given >= needed,
                "a /16 {case}: needs {needed:?} to send every attempt and is given {given:?}"
            );
        }
    }

    /// A segment sweep outlasts the schedule of the last address it asks, on
    /// whichever of its two ledgers that schedule is longer, with every
    /// attempt timed as long as measurement may make it.
    ///
    /// A segment that answered slowly, a wireless one of sleeping devices
    /// say, times its silent addresses at up to the retry ceiling on every
    /// attempt. Sized for an unmeasured schedule, the deadline stops a small
    /// sweep of it while its last address still has attempts to spend.
    #[test]
    fn a_segment_sweep_outlasts_a_probe_timed_at_the_ceiling_on_every_attempt() {
        let thorough = RetryConfig {
            effort: crate::config::ScanEffort::Thorough,
            ..RetryConfig::default()
        };
        for (case, retry) in [
            ("by default", RetryConfig::default()),
            ("at thorough", thorough),
        ] {
            let arp = RETRY_POLICY.configured(retry);
            let needed = arp
                .longest_probe_lifetime()
                .max(ipv6::NDP_RETRY_POLICY.longest_probe_lifetime());
            let given = deadline_for(1, &arp).max_budget.for_target_count(1);
            assert!(
                given >= needed,
                "one address {case}: its schedule at the ceiling takes {needed:?} \
                 and the sweep is given {given:?}"
            );
        }
    }

    /// A segment whose first neighbour's answer arrives while the sweep is
    /// asking the next one, and whose next send holds the sending thread for
    /// `stall`: the sweep stopped in its tracks with the answer already
    /// waiting for it.
    struct StalledAfterAnswering {
        stall: Duration,
        frames: tokio::sync::mpsc::Sender<CapturedFrame>,
        /// The first address asked about, whose answer is held for the next
        /// request.
        first: Option<Ipv4Addr>,
        answered: bool,
    }

    impl crate::transport::capture::FrameSink for StalledAfterAnswering {
        fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
            let asked = ethernet::parse(frame)
                .ok()
                .filter(|frame| frame.ethertype() == pnet_packet::ethernet::EtherTypes::Arp.0)
                .and_then(|frame| pnet_packet::arp::ArpPacket::owned(frame.payload().to_vec()))
                .map(|request| request.get_target_proto_addr());
            let Some(target) = asked.filter(|_| !self.answered) else {
                return Ok(());
            };
            let Some(first) = self.first else {
                self.first = Some(target);
                return Ok(());
            };
            self.answered = true;
            self.frames
                .try_send(CapturedFrame {
                    zone: Zone::new(7, "sim0"),
                    link: LinkType::Ethernet,
                    bytes: arp_reply_frame(first),
                    observed_at: std::time::SystemTime::now(),
                    received_at: Instant::now(),
                })
                .expect("room for the answer");
            std::thread::sleep(self.stall);
            Ok(())
        }
    }

    /// An answer that was waiting when its probe ran out of attempts still
    /// times its host, however late the loop gets round to either.
    ///
    /// A loop held up for longer than a timeout wakes to find both the answer
    /// and the expired timer. Serviced timer first, the address's one attempt
    /// is spent and the answer behind it finds no probe to be timed against,
    /// so the host is recorded unmeasured and its address settled as asked
    /// and unanswered.
    #[tokio::test(flavor = "current_thread")]
    async fn an_answer_waiting_when_its_probe_runs_out_still_times_the_host() {
        use crate::system::interface::LinkAddress;

        // Asked in address order, which a session told to walk no seed
        // keeps, so the answer is the first one's and the stall comes on
        // asking the second.
        let target = Ipv4Addr::new(192, 0, 2, 10);
        let silent = Ipv4Addr::new(192, 0, 2, 11);
        let (session, ctx) = crate::scanner::session::ScanSession::builder()
            .ordering(None)
            .build();
        let retry = RETRY_POLICY.configured(RetryConfig {
            max_attempts: std::num::NonZeroU8::new(1),
            ..RetryConfig::default()
        });
        let (frames, rx) = tokio::sync::mpsc::channel(16);
        // Longer than the longest first timeout an unmeasured address draws.
        let stall = retry.initial_rto.mul_f64(1.0 + retry.jitter) + Duration::from_millis(200);
        let handle = EthernetHandle::from_parts(
            Box::new(StalledAfterAnswering {
                stall,
                frames,
                first: None,
                answered: false,
            }),
            rx,
        );
        let link = Link::new("sim0", 7)
            .with_mac(LOCAL_MAC)
            .with_addresses(vec![LinkAddress::new(
                IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
                24,
            )]);
        let mut targets = IpSet::new();
        targets.insert(IpAddr::V4(target));
        targets.insert(IpAddr::V4(silent));
        let mut scanner =
            LocalScanner::build(link, targets, ctx, None, Scope::Targeted, handle, retry)
                .expect("a scanner over the simulated segment");

        scanner.discover_hosts().await.expect("the sweep runs");

        let host = session
            .hosts()
            .get(IpAddr::V4(target))
            .expect("the host answered and is not on record");
        assert!(
            host.min_rtt().is_some(),
            "the answer was read after its probe was written off"
        );
    }

    /// A neighbour that, asked for its address, first broadcasts a request of
    /// its own and answers the question it was asked `delay` later.
    struct AsksBeforeAnswering {
        delay: Duration,
        frames: tokio::sync::mpsc::Sender<CapturedFrame>,
        answered: bool,
    }

    impl AsksBeforeAnswering {
        fn captured(bytes: Vec<u8>, received_at: Instant) -> CapturedFrame {
            CapturedFrame {
                zone: Zone::new(7, "sim0"),
                link: LinkType::Ethernet,
                bytes,
                observed_at: std::time::SystemTime::now(),
                received_at,
            }
        }
    }

    impl crate::transport::capture::FrameSink for AsksBeforeAnswering {
        fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
            let asked = ethernet::parse(frame)
                .ok()
                .filter(|frame| frame.ethertype() == pnet_packet::ethernet::EtherTypes::Arp.0)
                .and_then(|frame| pnet_packet::arp::ArpPacket::owned(frame.payload().to_vec()))
                .map(|request| request.get_target_proto_addr());
            let Some(target) = asked.filter(|_| !self.answered) else {
                return Ok(());
            };
            self.answered = true;
            self.frames
                .try_send(Self::captured(arp_request_frame(target), Instant::now()))
                .expect("room for the neighbour's own request");
            let frames = self.frames.clone();
            let arrives = Instant::now() + self.delay;
            tokio::spawn(async move {
                tokio::time::sleep_until(arrives.into()).await;
                let _ = frames
                    .send(Self::captured(arp_reply_frame(target), arrives))
                    .await;
            });
            Ok(())
        }
    }

    /// A neighbour's own request, heard while the sweep's request to it is
    /// outstanding, proves it is there and times nothing: the neighbour is
    /// timed by its reply, where the sweep is still listening when it comes.
    ///
    /// Every ARP frame proves its sender present, and a neighbour that has
    /// just been asked often asks something itself before it answers. Taken
    /// as the answer, that request retires the sweep's and times the
    /// neighbour at the gap between the two, a round trip the passes after
    /// the sweep then time their own probes from.
    #[tokio::test(flavor = "current_thread")]
    async fn a_neighbours_own_request_does_not_answer_the_sweeps() {
        use crate::system::interface::LinkAddress;

        let target = Ipv4Addr::new(198, 51, 100, 2);
        let delay = Duration::from_millis(80);
        let (session, ctx) = crate::scanner::session::ScanSession::new();
        let (frames, rx) = tokio::sync::mpsc::channel(16);
        let handle = EthernetHandle::from_parts(
            Box::new(AsksBeforeAnswering {
                delay,
                frames,
                answered: false,
            }),
            rx,
        );
        let link = Link::new("sim0", 7)
            .with_mac(LOCAL_MAC)
            .with_addresses(vec![LinkAddress::new(
                IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)),
                24,
            )]);
        let mut targets = IpSet::new();
        targets.insert(IpAddr::V4(target));
        let mut scanner = LocalScanner::build(
            link,
            targets,
            ctx,
            None,
            Scope::Targeted,
            handle,
            RETRY_POLICY,
        )
        .expect("a scanner over the simulated segment");

        scanner.discover_hosts().await.expect("the sweep runs");

        let host = session
            .hosts()
            .get(IpAddr::V4(target))
            .expect("the neighbour answered and is not on record");
        assert!(
            host.min_rtt().is_none_or(|rtt| rtt >= delay),
            "a neighbour answering in {delay:?} was timed at {:?}",
            host.min_rtt()
        );
    }

    /// A table refusing as Linux's does when asked about a link-local address
    /// with no zone, and allowing everything else.
    fn refuses_as_linux_does(address: IpAddr) -> bool {
        crate::model::ip::scoped::ScopedIp::needs_zone(&address)
    }

    /// A table refusing every address it is asked about.
    fn refuses_everything(_: IpAddr) -> bool {
        true
    }

    /// A sweep over a simulated segment holding `192.0.2.1/24`, `fe80::1/64`
    /// and `2001:db8::1/64`, for a test that hands it overheard addresses.
    fn overhearing_scanner() -> LocalScanner {
        use crate::system::interface::LinkAddress;

        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        let (_frames, rx) = tokio::sync::mpsc::channel(16);
        let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let handle = EthernetHandle::from_parts(Box::new(Asked(asked)), rx);
        let link = Link::new("sim0", 7)
            .with_mac(LOCAL_MAC)
            .with_addresses(vec![
                LinkAddress::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)), 24),
                LinkAddress::new("fe80::1".parse().expect("an address"), 64),
                LinkAddress::new("2001:db8::1".parse().expect("an address"), 64),
            ]);
        let targets: IpSet = "192.0.2.0/30".parse().expect("a prefix");
        LocalScanner::build(link, targets, ctx, None, Scope::Sweep, handle, RETRY_POLICY)
            .expect("a scanner over the simulated segment")
    }

    /// **A link-local address the sweep overheard is asked about whatever the
    /// routing table would say of it without its zone, and one on a prefix
    /// the link holds that the table refuses is not.**
    ///
    /// Linux answers a route lookup for a link-local address with no zone
    /// as an invalid argument, the answer a blackhole route gives, so putting
    /// one to the table there reads every link-local neighbour as refused by
    /// policy. A phone that ignores the all-nodes echo and is named only by
    /// its mDNS announcements is then never asked, and never found.
    #[tokio::test(flavor = "current_thread")]
    async fn an_overheard_link_local_address_is_asked_whatever_the_table_says_without_a_zone() {
        let link_local: IpAddr = "fe80::2".parse().expect("an address");
        let on_link: IpAddr = "2001:db8::2".parse().expect("an address");
        let mut scanner = overhearing_scanner();

        scanner.refuses = refuses_as_linux_does;
        scanner.confirm(link_local);
        assert_eq!(
            scanner.ipv6.next_confirmation(),
            Some(link_local),
            "an overheard link-local neighbour was read as refused by a route"
        );

        scanner.refuses = refuses_everything;
        scanner.confirm(on_link);
        assert_eq!(
            scanner.ipv6.next_confirmation(),
            None,
            "an address the table refuses was asked about"
        );
    }

    /// **An overheard address on no prefix the link holds is asked about
    /// whatever the routing table says of it.**
    ///
    /// The table answers for such an address about a path through a router,
    /// which a solicitation on the segment does not take. A host with no
    /// route there, as a machine with no IPv6 beyond its links has none,
    /// would otherwise read every neighbour announcing an address from a
    /// prefix it does not hold as refused by policy, and never ask it.
    #[tokio::test(flavor = "current_thread")]
    async fn an_overheard_address_off_the_links_prefixes_is_asked_whatever_the_table_says() {
        let elsewhere: IpAddr = "2001:db8:1::2".parse().expect("an address");
        let mut scanner = overhearing_scanner();

        scanner.refuses = refuses_everything;
        scanner.confirm(elsewhere);
        assert_eq!(
            scanner.ipv6.next_confirmation(),
            Some(elsewhere),
            "an address off the link's prefixes was read as refused by a route"
        );
    }

    /// A segment that answers nothing and notes the address every ARP request
    /// it is sent asks about, in the order they leave.
    struct Asked(std::sync::Arc<std::sync::Mutex<Vec<IpAddr>>>);

    impl crate::transport::capture::FrameSink for Asked {
        fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
            let asked = ethernet::parse(frame)
                .ok()
                .filter(|frame| frame.ethertype() == pnet_packet::ethernet::EtherTypes::Arp.0)
                .and_then(|frame| pnet_packet::arp::ArpPacket::owned(frame.payload().to_vec()))
                .map(|request| request.get_target_proto_addr());
            if let Some(target) = asked {
                self.0.lock().expect("the log").push(IpAddr::V4(target));
            }
            Ok(())
        }
    }

    /// A seeded sweep asks the segment in the order the scan's seed names, the
    /// order a dispatched sweep streams the same plan in, rather than walking
    /// the range.
    ///
    /// A sweep across an address range in address order is the most
    /// recognisable thing a scanner puts on the wire, and the one a
    /// correlating sensor keys on.
    #[tokio::test(flavor = "current_thread")]
    async fn a_seeded_sweep_asks_in_the_order_the_seed_names() {
        use crate::model::ip::set::Positions;
        use crate::system::interface::LinkAddress;

        const SEED: u64 = 0x5EED;
        let targets: IpSet = "192.0.2.64/27".parse().expect("a prefix");
        let (_session, ctx) = crate::scanner::session::ScanSession::builder()
            .ordering(Some(SEED))
            .counting(Positions::of(&targets))
            .build();
        let mut walk = crate::scanner::dispatcher::dispatch_addresses_of(
            targets.clone(),
            1,
            Some(SEED),
            Some(std::sync::Arc::clone(&ctx.positions)),
            &ctx.handle,
        );
        let mut expected = Vec::new();
        while let Some(ip) = walk.recv().await {
            expected.push(ip);
        }
        assert_ne!(
            expected,
            targets.iter().collect::<Vec<_>>(),
            "the walk the seed names is not the range"
        );

        let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let (_frames, rx) = tokio::sync::mpsc::channel(16);
        let handle = EthernetHandle::from_parts(Box::new(Asked(std::sync::Arc::clone(&asked))), rx);
        let link = Link::new("sim0", 7)
            .with_mac(LOCAL_MAC)
            .with_addresses(vec![LinkAddress::new(
                IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
                24,
            )]);
        let retry = RETRY_POLICY.configured(RetryConfig {
            max_attempts: std::num::NonZeroU8::new(1),
            ..RetryConfig::default()
        });
        let mut scanner =
            LocalScanner::build(link, targets, ctx, None, Scope::Targeted, handle, retry)
                .expect("a scanner over the simulated segment");

        scanner.discover_hosts().await.expect("the sweep runs");

        assert_eq!(*asked.lock().expect("the log"), expected);
    }

    /// The sweep's capture narrows in the kernel, so a frame the filter does not
    /// admit is one no [`DiscoveryProtocol`] is ever offered, and it fails
    /// silently, because a protocol that is never called looks exactly like one
    /// that recognised nothing.
    ///
    /// Nothing else can catch it. The fake-LAN fixtures inject frames straight
    /// into the scanner through `EthernetHandle::from_parts`, so they bypass the
    /// capture entirely and would stay green against a filter that admitted
    /// nothing at all. This compiles the real expression with `libpcap` and runs
    /// it against real frames, which needs no interface and no privileges.
    #[test]
    fn the_sweep_filter_admits_every_frame_the_sweep_can_read() {
        let filter = super::sweep_filter();
        let program = pcap::Capture::dead(pcap::Linktype::ETHERNET)
            .expect("a dead capture")
            .compile(&filter, true)
            .unwrap_or_else(|e| panic!("the sweep filter `{filter}` does not compile: {e}"));

        // The two announcement frames need only their framing: the filter reads
        // the EtherType and the destination address, and what the sender put
        // behind them is the reader's business rather than the kernel's.
        let lldp = ethernet::build_header(
            PEER_MAC,
            MacAddr::new(0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E),
            crate::protocols::lldp::ETHERTYPE,
        );
        let cdp = {
            let group = crate::protocols::cdp::GROUP_ADDRESS;
            let mut bytes = group.octets().to_vec();
            bytes.extend_from_slice(&PEER_MAC.octets());
            // 802.3: a length rather than an EtherType, which is the whole
            // reason this clause matches the address instead.
            bytes.extend_from_slice(&[0x00, 0x20]);
            bytes.resize(60, 0);
            bytes
        };

        let readable: [(&str, Vec<u8>); 7] = [
            (
                "an ARP frame",
                arp_reply_frame(Ipv4Addr::new(198, 51, 100, 2)),
            ),
            (
                "a neighbour advertisement",
                ndp_frame(&advertisement_body(
                    Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2),
                    0,
                )),
            ),
            (
                "an echo reply",
                echo_reply_frame(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)),
            ),
            (
                "a DHCP server reply",
                dhcp_reply_frame(Ipv4Addr::new(192, 0, 2, 1), None),
            ),
            ("an mDNS response", mdns_frame()),
            ("an LLDP advertisement", lldp),
            ("a CDP announcement", cdp),
        ];

        for (what, frame) in readable {
            assert!(
                program.filter(&frame),
                "the sweep filter rejects {what}, so the sweep would never see one: {filter}"
            );
        }
    }

    /// A link with no Ethernet header refuses the sweep's filter whole rather
    /// than taking the part of it that it can express. The sweep reads every
    /// answer from an Ethernet header, so a capture opened there on the IP
    /// clauses alone would hear nothing it can read and report the segment
    /// empty; refused, the sweep says it cannot run on that link.
    #[test]
    fn a_link_without_ethernet_refuses_the_sweep_filter_whole() {
        /// `DLT_RAW`, how a WireGuard or IP-in-IP tunnel comes up.
        const RAW: i32 = 12;

        let filter = super::sweep_filter();
        let tunnel = pcap::Capture::dead(pcap::Linktype(RAW)).expect("a dead capture");

        assert!(
            tunnel.compile(&filter, true).is_err(),
            "a tunnel took the sweep filter: {filter}"
        );
    }

    /// The other half of the same rule. A filter that admitted everything would
    /// pass the test above while undoing the reason for having one: the sweep
    /// would go back to copying the whole segment into this process.
    #[test]
    fn the_sweep_filter_rejects_traffic_no_reader_asked_for() {
        let filter = super::sweep_filter();
        let program = pcap::Capture::dead(pcap::Linktype::ETHERNET)
            .expect("a dead capture")
            .compile(&filter, true)
            .expect("the sweep filter compiles");

        let ordinary_tcp = {
            let datagram = crate::protocols::craft::Packet::new()
                .push(crate::protocols::craft::Ipv4::new(
                    Ipv4Addr::new(192, 0, 2, 50),
                    Ipv4Addr::new(192, 0, 2, 60),
                ))
                .push(crate::protocols::craft::Udp::new(4444, 8080).with_payload(vec![0u8; 16]))
                .build()
                .expect("a test datagram");

            [
                ethernet::build_header(
                    PEER_MAC,
                    LOCAL_MAC,
                    pnet_packet::ethernet::EtherTypes::Ipv4.0,
                ),
                datagram,
            ]
            .concat()
        };

        assert!(
            !program.filter(&ordinary_tcp),
            "the sweep filter admits traffic between two other hosts on ports \
             nothing here reads, which is the copying it exists to avoid: {filter}"
        );
    }
}