zond-engine 0.17.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
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
// 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

//! # A scan while it is running
//!
//! The live half of what a scan produces. [`ScanReport`](crate::report) is the
//! record afterwards; everything here describes the present moment and keeps no
//! history.
//!
//! It comes in two halves that share one store, handed out by
//! [`ScanSession::new`]:
//!
//! - [`ScanSession`] is the reading half, for whoever asked for the scan: the
//!   hosts found so far ([`HostStore`]), the stream saying when that changed
//!   ([`ScanEvents`]), and the means to stop
//!   ([`ScanHandle`]).
//! - [`ScanContext`] is the writing half, for the strategies. Every scanner is
//!   built with one, and it is how findings, failures and probe counters enter
//!   the scan.
//!
//! ## Why the writing half is not just the map
//!
//! [`ScanContext::write_host`] is the single door a host finding goes through,
//! and that is what lets the ordering it depends on be written once. It takes
//! the store's guard, runs the caller's edit under it, drops the guard, and
//! only then announces the change, so the map is never locked across a channel
//! send. Handing a strategy the raw map instead would hand it that ordering to
//! get wrong, and would make the version of a third-party concurrency crate
//! part of this crate's semver.
//!
//! ## What a host is keyed by
//!
//! By the address it is reported under, carrying the interface that address was
//! read on where it needs one: a [`ScopedIp`]. For every IPv4 address and every
//! routable IPv6 one that is the bare address and nothing more, because a
//! machine reachable at a global address is the same machine through whichever
//! interface answered it.
//!
//! An IPv6 link-local is the exception, and it is why the key exists.
//! `fe80::1` names a different machine on every segment, so a host watching two
//! of them finds two neighbours under one number. Keyed by the bare address, the
//! second write would land on the first's entry, and one machine's hardware
//! address, roles and round trips would be folded into another machine's record.
//!
//! Three rules follow, and between them they are the whole of it:
//!
//! - **A host takes its link from its key.** [`ScanContext::write_host`] records
//!   the zone when it creates a host, so no scanner has to remember to.
//! - **A key read from the store writes back to the store.**
//!   [`ScanContext::host_addresses`] hands out keys, and a strategy that reads a
//!   host and writes a finding back carries the key rather than rebuilding one
//!   from the address it probed. A bare address written back would land in a
//!   second entry, and one host would become two, each holding half of what was
//!   found.
//! - **A bare link-local finds nothing.** [`HostStore::get`] answers `None` for
//!   one, because it is a question with more than one answer. Consumers get the
//!   whole key from [`ScanEvent::HostUpdated`], which is the path that matters:
//!   the event exists to be handed straight back to the store.
//!
//! ## Why a failure is written down twice
//!
//! Once to the event stream, for a consumer watching, and once to a log the
//! report drains at the end. An event nobody listens for is an event that never
//! happened: a caller that simply awaits the scan and reads the hosts would
//! otherwise have no way to learn that a strategy died, and "the network is
//! empty" and "the raw scanner never started" would be the same answer.

use dashmap::DashMap;
use std::collections::BTreeSet;
use std::net::IpAddr;
use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::broadcast;
use tokio::sync::broadcast::error::{RecvError, TryRecvError};
use tracing::error;

use crate::config::ServiceDetection;
use crate::detect::compute::DetectionRunRecord;
use crate::info;
use crate::journal::settle::{Outcome, Settled, Settlements};
use crate::model::exclusion::Exclusions;
use crate::model::host::Host;
use crate::model::ip::range::IpRange;
use crate::model::ip::scoped::{ScopedIp, Zone, ZoneMap};
use crate::model::ip::set::{IpSet, Positions};
use crate::model::port::Protocol;
use crate::report::ScannerKind;
use crate::report::{Attachment, AttachmentSource, ProbeStats, Refusal, ScannerFailure};
use crate::scanner::handle::ScanHandle;

/// What a scan is working on.
///
/// A scan is not one uniform stretch of work. The sweep settles its plan, and
/// then a tail of quite different jobs runs over what it found: identifying the
/// services behind the open ports, running detections against those services,
/// reading a stack for an operating system, tracing a path. The tail routinely
/// takes several times as long as the sweep did, so a caller measuring the plan
/// alone shows a finished bar for most of a run.
///
/// Each stage announces itself as it begins, through [`ScanEvent::StageChanged`],
/// and [`Progress::stage`] answers which one is current. Some know their own
/// size the moment they start, the set of ports they will work over having been
/// decided before any of it was probed; the rest report only that they are
/// running.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum Stage {
    /// Establishing which addresses are alive. Where every scan starts.
    #[default]
    Discovery,
    /// Classifying the ports of the hosts that answered.
    Ports,
    /// Identifying what is listening behind each open port.
    Services,
    /// Running the detection corpus over the services just identified.
    Detections,
    /// Asking what each TLS port accepts.
    Tls,
    /// Reading a stack, and asking what a host says about itself.
    Os,
    /// Tracing the path to each host.
    Traceroute,
    /// Reading a link, which ends when the caller says so rather than when the
    /// work runs out.
    Listening,
    /// The correlating and record keeping left once the probing is over.
    Finishing,
}

impl Stage {
    /// Every stage this build knows, in the order a scan runs them.
    ///
    /// Here for the reason [`ScanKind::ALL`](crate::report::ScanKind::ALL)
    /// gives: the enum is `#[non_exhaustive]`, so nothing outside this crate can
    /// match it exhaustively, and a front end that maps stages onto a protocol
    /// of its own has no other way to check that it covered them all. A variant
    /// added without a place in that protocol is a value this engine reports and
    /// no consumer can name.
    pub const ALL: [Stage; 9] = [
        Self::Discovery,
        Self::Ports,
        Self::Services,
        Self::Detections,
        Self::Tls,
        Self::Os,
        Self::Traceroute,
        Self::Listening,
        Self::Finishing,
    ];

    /// Its place in the atomic the tracker keeps.
    const fn code(self) -> u8 {
        match self {
            Stage::Discovery => 0,
            Stage::Ports => 1,
            Stage::Services => 2,
            Stage::Detections => 3,
            Stage::Tls => 4,
            Stage::Os => 5,
            Stage::Traceroute => 6,
            Stage::Listening => 7,
            Stage::Finishing => 8,
        }
    }

    /// The stage `code` stands for, and [`Discovery`](Stage::Discovery) for a
    /// number no stage claims, which is where a scan begins.
    const fn from_code(code: u8) -> Self {
        match code {
            1 => Stage::Ports,
            2 => Stage::Services,
            3 => Stage::Detections,
            4 => Stage::Tls,
            5 => Stage::Os,
            6 => Stage::Traceroute,
            7 => Stage::Listening,
            8 => Stage::Finishing,
            _ => Stage::Discovery,
        }
    }
}

impl std::fmt::Display for Stage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Stage::Discovery => "discovery",
            Stage::Ports => "ports",
            Stage::Services => "services",
            Stage::Detections => "detections",
            Stage::Tls => "tls",
            Stage::Os => "os",
            Stage::Traceroute => "traceroute",
            Stage::Listening => "listening",
            Stage::Finishing => "finishing",
        };

        f.write_str(name)
    }
}

/// Which stage a scan is in and how far through it.
///
/// Three atomics rather than one lock, because this is written from every
/// probing task and read eight times a second by whatever is drawing. The three
/// are not updated as a group, so a reader can catch a stage that has just
/// changed against a count that has not caught up. That costs one frame of a
/// progress line and is the reason this is not the thing a report is built from.
#[derive(Debug, Default)]
pub(crate) struct Stages {
    current: AtomicU8,
    done: AtomicU64,
    total: AtomicU64,
    /// The stages this scan expects to run, in the order it runs them.
    planned: Vec<Stage>,
    /// How many of those are behind it, which only ever grows.
    reached: AtomicUsize,
}

impl Stages {
    fn new(planned: Vec<Stage>) -> Self {
        Self {
            planned,
            ..Self::default()
        }
    }

    /// Where the scan stands across every stage it expects to run, as a
    /// position over a total.
    ///
    /// `within` is how far through the current stage it is, and the pair comes
    /// back scaled so both halves are whole numbers: a caller drawing a bar of a
    /// fixed number of cells divides in integers and gets cells and a percentage
    /// that agree.
    fn overall(&self, within: Option<(u64, u64)>) -> Option<(u64, u64)> {
        let stages = u64::try_from(self.planned.len()).ok().filter(|n| *n > 0)?;
        let reached = u64::try_from(self.reached.load(Ordering::Relaxed)).unwrap_or(0);

        // Past the last stage the scan expected: whatever it is doing now, the
        // work it was counting is behind it.
        let Some((done, total)) = within.filter(|_| self.planned.contains(&self.stage())) else {
            return Some((reached.min(stages), stages));
        };

        Some((reached * total + done.min(total), stages * total))
    }

    /// Moves to `stage`, answering whether that was a change worth announcing.
    ///
    /// Entering the stage already current adds to its total instead of starting
    /// it over, which is what service detection needs when it runs once per
    /// protocol.
    fn enter(&self, stage: Stage, total: Option<u64>) -> bool {
        let total = total.unwrap_or(0);

        // How many expected stages this one comes after, read from the order the
        // variants are declared in, which is the order a scan runs them. A stage
        // that was expected and had no work is stepped over rather than waited
        // for.
        let reached = self
            .planned
            .iter()
            .filter(|planned| planned.code() < stage.code())
            .count();
        self.reached.fetch_max(reached, Ordering::Relaxed);

        if self.current.swap(stage.code(), Ordering::Relaxed) == stage.code() {
            self.total.fetch_add(total, Ordering::Relaxed);
            return false;
        }

        self.done.store(0, Ordering::Relaxed);
        self.total.store(total, Ordering::Relaxed);
        true
    }

    fn advance(&self) {
        self.done.fetch_add(1, Ordering::Relaxed);
    }

    fn stage(&self) -> Stage {
        Stage::from_code(self.current.load(Ordering::Relaxed))
    }

    fn done(&self) -> u64 {
        self.done.load(Ordering::Relaxed)
    }

    fn total(&self) -> Option<u64> {
        match self.total.load(Ordering::Relaxed) {
            0 => None,
            total => Some(total),
        }
    }
}

/// Lightweight notifications for the status of an ongoing scan.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ScanEvent {
    /// Something was learned about the host at this address.
    ///
    /// The event carries only the address: a scan can emit
    /// thousands of these, and copying a whole [`Host`] into each one would cost
    /// more than the notification is worth. Read the current state back from
    /// [`ScanSession::hosts`], which is a single lookup and always up to date,
    /// where a host copied into an event is stale the moment the next probe
    /// answers.
    HostUpdated(ScopedIp),

    /// A scanning strategy failed to start or terminated abnormally. The scan
    /// continues with whatever strategies remain, so results may be incomplete
    /// rather than absent.
    ScannerFailed {
        /// The strategy that failed.
        scanner: ScannerKind,
        /// A human-readable description of the failure.
        reason: String,
    },

    /// The scan has moved on to another [`Stage`].
    ///
    /// A scan spends most of its time somewhere other than its plan, and this is
    /// what says where. Read [`ScanSession::progress`] for how far through the
    /// stage it is, on the same reasoning [`HostUpdated`](ScanEvent::HostUpdated)
    /// carries only an address: the figure moves far faster than the
    /// announcement does.
    StageChanged {
        /// What the scan is working on now.
        stage: Stage,
    },

    /// The stream ran ahead of this consumer, and `count` events were dropped
    /// to make room for newer ones.
    ///
    /// Delivered in the position the missing events would have had, so a
    /// consumer knows where its picture went incomplete rather than only that
    /// it did. [`ScanEvents`] says what the gap costs and what to do about it.
    EventsDropped {
        /// How many events were dropped.
        count: u64,
    },
}

/// What a scan has found so far, readable while it is still running.
///
/// A cheap, cloneable view of one shared store. Cloning it does not copy the
/// hosts; every clone reads the same live data, so a consumer can hand one to a
/// rendering task and keep another for itself.
///
/// Reads return owned snapshots. [`get`](Self::get) clones the host rather
/// than lending a reference into the map, because the alternative is a guard
/// held across whatever the caller does next, and a scanner writing to the same
/// key meanwhile is not a hypothetical, it is the normal case. A caller cannot
/// hold this wrong.
///
/// The concrete map behind it is not visible. It is an
/// implementation choice, and exposing it would make the version of a
/// third-party concurrency crate part of this crate's semver.
#[derive(Debug, Clone, Default)]
pub struct HostStore {
    inner: Arc<DashMap<ScopedIp, Host>>,
}

impl HostStore {
    fn new(inner: Arc<DashMap<ScopedIp, Host>>) -> Self {
        Self { inner }
    }

    /// The host recorded at `ip`, as it stands right now.
    ///
    /// Keyed by the address a scanner wrote it under, which for a host found at
    /// several addresses is whichever one it was first credited to. To look a
    /// host up by any of its addresses, search
    /// [`snapshot`](Self::snapshot) on [`Host::ips`].
    ///
    /// An IPv6 link-local needs the interface it was read on. `fe80::1`
    /// names a different machine on every segment, so a bare one names no host
    /// here and answers `None`; pass the [`ScopedIp`] the event carried. Every
    /// other address is its own whole key, and a plain [`IpAddr`] is accepted
    /// for exactly that reason.
    pub fn get(&self, ip: impl Into<ScopedIp>) -> Option<Host> {
        self.inner
            .get(&ip.into())
            .map(|entry| entry.value().clone())
    }

    /// Reads the host at `ip` without cloning it, if there is one.
    ///
    /// The live counterpart of [`get`](Self::get), and the one to reach for
    /// inside an event loop. A scan fires
    /// [`HostUpdated`](ScanEvent::HostUpdated) on every change, and a port scan
    /// changes a host once per port, so a consumer that answers each event with
    /// a [`get`](Self::get) clones a growing port map on every port of every
    /// host, which is quadratic in the size of the scan and invisible until the
    /// port count is large. Take what the event needs through this, and clone
    /// only once the answer is that the host is worth rendering.
    ///
    /// `read` runs under the store's own guard. It must not touch the store
    /// again, that deadlocks, and it should not block, since a scanner writing
    /// to the same host waits behind it.
    pub fn read<R>(&self, ip: impl Into<ScopedIp>, read: impl FnOnce(&Host) -> R) -> Option<R> {
        self.inner.get(&ip.into()).map(|entry| read(entry.value()))
    }

    /// Whether anything has been recorded at `ip`.
    ///
    /// Cheaper than [`get`](Self::get) when the host itself is not wanted, since
    /// nothing is cloned.
    pub fn contains(&self, ip: impl Into<ScopedIp>) -> bool {
        self.inner.contains_key(&ip.into())
    }

    /// How many hosts have been recorded.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Whether nothing has been recorded yet.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Every host recorded so far, ordered by the address each is keyed under.
    ///
    /// A point-in-time copy: the scan carries on writing, and this does not
    /// change afterwards. Ordered rather than in map order so two reads of the
    /// same data can be compared, for the reason
    /// [`ScanReport`](crate::report::ScanReport) orders its hosts.
    pub fn snapshot(&self) -> Vec<Host> {
        let mut hosts: Vec<Host> = self
            .inner
            .iter()
            .map(|entry| entry.value().clone())
            .collect();
        hosts.sort_by_cached_key(Host::scoped_ip);
        hosts
    }

    /// Puts a host in the store directly, replacing anything at that address.
    ///
    /// Test-only, and not how a scan records a finding, that is
    /// [`ScanContext::write_host`], which upserts, merges and announces the
    /// change. This exists for the tests that need a store already holding a
    /// particular host, standing in for the scanner that would have written it.
    #[cfg(test)]
    pub(crate) fn insert(&self, ip: impl Into<ScopedIp>, host: Host) {
        self.inner.insert(ip.into(), host);
    }
}

/// The live event stream of a scan.
///
/// Each event says that something changed; the detail is read back from the
/// [`HostStore`]. See [`ScanEvent`].
///
/// The stream is bounded, and the oldest events are the ones that go. It
/// holds [`CAPACITY`](Self::CAPACITY) events, and a scan that fills it
/// overwrites what has waited longest rather than growing or pausing. A caller
/// who never reads this costs the scan one fixed buffer, and a caller who reads
/// it slowly never holds the scan up.
///
/// A gap is announced where it happened. The read that follows one answers
/// [`ScanEvent::EventsDropped`], carrying how many events went missing, so a
/// consumer is never quietly out of date.
///
/// What a gap costs is the notice and not the finding. A dropped
/// [`HostUpdated`](ScanEvent::HostUpdated) named a host whose current state is
/// in the [`HostStore`], so the answer to a gap is to re-read the store rather
/// than to try to replay the stream. A dropped
/// [`ScannerFailed`](ScanEvent::ScannerFailed) still reaches the
/// [`ScanReport`](crate::report::ScanReport), which carries every failure
/// whether or not anybody was listening.
#[derive(Debug)]
pub struct ScanEvents {
    rx: broadcast::Receiver<ScanEvent>,
}

impl ScanEvents {
    /// How many events the stream holds for a consumer that has not caught up.
    ///
    /// The buffer is allocated when the scan starts, so an event stream costs
    /// the same whether or not anything reads it.
    pub const CAPACITY: usize = 1024;

    /// Waits for the next event. `None` once the scan has ended and every event
    /// it emitted has been taken, which is the definitive end of the stream.
    ///
    /// Falling behind is not an error here: a gap arrives as
    /// [`ScanEvent::EventsDropped`], in the position the missing events would
    /// have had, and the stream carries on with the oldest event it still
    /// holds.
    pub async fn recv(&mut self) -> Option<ScanEvent> {
        match self.rx.recv().await {
            Ok(event) => Some(event),
            Err(RecvError::Lagged(count)) => Some(ScanEvent::EventsDropped { count }),
            Err(RecvError::Closed) => None,
        }
    }

    /// The next event if one is already queued, without waiting.
    ///
    /// `None` covers both "nothing queued right now" and "the scan is over", so
    /// it drains a finished scan but cannot detect the end of a running one. Use
    /// [`recv`](Self::recv) for that. A gap reads the same way it does through
    /// [`recv`](Self::recv), as [`ScanEvent::EventsDropped`].
    pub fn try_recv(&mut self) -> Option<ScanEvent> {
        match self.rx.try_recv() {
            Ok(event) => Some(event),
            Err(TryRecvError::Lagged(count)) => Some(ScanEvent::EventsDropped { count }),
            Err(TryRecvError::Empty | TryRecvError::Closed) => None,
        }
    }
}

/// How far a scan has got through its plan.
///
/// A cheap, cloneable view of the counters the strategies settle their targets
/// against, so one can sit in a rendering task and be read as often as it
/// draws. A read is a pair of atomic loads and one short lock, never a walk of
/// the findings.
///
/// The two halves come from different places. [`settled`](Self::settled) counts
/// what the strategies have finished with, and it counts on every scan whether
/// or not the scan is journalled. [`planned`](Self::planned) is the size of the
/// plan, which a scan knows only where its targets can be numbered: an IPv6
/// range of a `/64` or wider cannot be, and a [`listen`](crate::listen) session
/// has no plan at all, having asked for nothing. Where the plan cannot be
/// counted, [`fraction`](Self::fraction) answers `None`, and a front end has a
/// running count to show in place of a bar.
///
/// A scan that runs to the end settles every target in its plan and the
/// fraction reaches 1.0. One stopped early leaves it short, which is the
/// accurate account of how much ground the run covered.
///
/// ```no_run
/// # fn example(session: &zond_engine::ScanSession) {
/// let progress = session.progress();
/// match progress.planned() {
///     Some(planned) => println!("{} of {planned} targets", progress.settled()),
///     None => println!("{} targets settled", progress.settled()),
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Progress {
    settlements: Arc<Settlements>,
    planned: Option<u64>,
    plan_stage: Stage,
    stages: Arc<Stages>,
}

impl Progress {
    fn new(
        settlements: Arc<Settlements>,
        planned: Option<u64>,
        plan_stage: Stage,
        stages: Arc<Stages>,
    ) -> Self {
        Self {
            settlements,
            planned,
            plan_stage,
            stages,
        }
    }

    /// What the scan is working on right now.
    pub fn stage(&self) -> Stage {
        self.stages.stage()
    }

    /// How many units of the current stage are finished.
    ///
    /// The unit is the stage's own: ports for [`Stage::Services`], detection
    /// runs for [`Stage::Detections`], TLS ports for [`Stage::Tls`]. Zero for a
    /// stage that does not count itself.
    ///
    /// A unit is counted once the stage is done with it, whatever it came to.
    /// One passed over before it began, because its host had spent its budget
    /// or the scan was stopped, is not, so a stage can end short of its total,
    /// and the shortfall is what it never asked.
    pub fn stage_done(&self) -> u64 {
        self.stages.done()
    }

    /// How many units the current stage holds, for one that knew its size when
    /// it began.
    pub fn stage_total(&self) -> Option<u64> {
        self.stages.total()
    }

    /// How many of the plan's targets the scan has finished with, counting
    /// those an earlier sitting settled and this one resumed past.
    ///
    /// A target is settled once no further probing could change its verdict: it
    /// answered, its retry budget was spent on silence, or its host was found
    /// down and no probe was owed. A target the scan stopped before reaching is
    /// not settled and is not counted here.
    pub fn settled(&self) -> u64 {
        self.settlements.settled_count()
    }

    /// How many targets the plan holds, or `None` for a plan whose targets
    /// cannot all be numbered.
    ///
    /// Fixed for the life of the scan. A resumed sitting reports the size of the
    /// whole job rather than what was left of it, so both halves of a fraction
    /// describe the same plan.
    pub const fn planned(&self) -> Option<u64> {
        self.planned
    }

    /// How many targets are still to settle, or `None` where the plan cannot be
    /// counted.
    pub fn remaining(&self) -> Option<u64> {
        self.planned
            .map(|planned| planned.saturating_sub(self.settled()))
    }

    /// How far through the current stage the scan is, from 0.0 to 1.0.
    ///
    /// A stage that counted itself answers for itself. The one the scan's plan
    /// was drawn for answers with what the plan has settled, which is what
    /// carries a resumed sitting's earlier work into the figure. Any other stage
    /// that never learned its size answers `None`, describing a stage running
    /// with no end in sight rather than one that has not started.
    ///
    /// A port scan's liveness pass is the interesting `None`: its plan counts
    /// address-and-port pairs and the pass settles none of them, so it reports
    /// that it is running rather than reporting nought percent of the wrong
    /// thing.
    ///
    /// An empty stage is complete, and one that somehow finishes more units than
    /// it counted reports 1.0 rather than overshooting.
    pub fn fraction(&self) -> Option<f64> {
        let (done, total) = self.counted()?;

        Some(ratio(done, total))
    }

    /// Where the scan stands across every stage it expects to run, as a position
    /// over a total.
    ///
    /// One figure for a whole run rather than one per stage, so a bar drawn from
    /// it fills once instead of refilling at every stage boundary. It only moves
    /// forward: a stage that was expected and turned out to have nothing to do
    /// is stepped over, which is why the figure can jump.
    ///
    /// The expected stages are a superset. Whether services, detections and TLS
    /// have anything to do depends on what the ports turn out to be, and none of
    /// that is knowable before the ports are read.
    ///
    /// `None` for a session that was never told which stages to expect. See
    /// [`SessionBuilder::staging`].
    pub fn overall(&self) -> Option<(u64, u64)> {
        self.stages.overall(self.counted())
    }

    /// The same reckoning as [`fraction`](Self::fraction), as the two figures it
    /// divides rather than the result.
    ///
    /// For a caller that would rather round the figures itself, or draw
    /// something a fraction cannot express. A bar of a fixed number of cells is
    /// the usual reason: dividing twice in integers keeps the cells and the
    /// percentage agreeing, where taking both off one `f64` can round a bar full
    /// beside a figure that reads 99%.
    pub fn counted(&self) -> Option<(u64, u64)> {
        match self.stage_total() {
            Some(total) => Some((self.stage_done(), total)),
            None if self.stage() == self.plan_stage => Some((self.settled(), self.planned?)),
            None => None,
        }
    }
}

/// `done` out of `total`, held between 0.0 and 1.0. Nothing to do is done.
fn ratio(done: u64, total: u64) -> f64 {
    if total == 0 {
        return 1.0;
    }

    (done as f64 / total as f64).min(1.0)
}

/// A handle to an active network scan: what it has found, what it is doing, and
/// the means to stop it.
///
/// Returned by [`discover`](crate::scanner::discover) and
/// [`scan`](crate::scanner::scan) alongside the
/// [`ScanTask`](crate::scanner::ScanTask) that resolves to the final report.
/// This is the live half of that pair: it describes the present moment and
/// keeps no history; the report is what answers a question asked afterwards.
///
/// ```no_run
/// # async fn example(mut session: zond_engine::ScanSession) {
/// use zond_engine::ScanEvent;
///
/// while let Some(event) = session.events().recv().await {
///     if let ScanEvent::HostUpdated(ip) = event
///         && let Some(host) = session.hosts().get(&ip)
///     {
///         println!("{host}");
///     }
/// }
/// # }
/// ```
pub struct ScanSession {
    store: HostStore,
    events: ScanEvents,
    handle: ScanHandle,
    progress: Progress,
}

impl ScanSession {
    /// What the scan has found so far.
    ///
    /// Once the scan is over this holds the hosts its report lists. While it
    /// runs it can hold more: a port scan that stood its probes in for a
    /// liveness pass files a record at every address it asks, and forgets the
    /// ones nothing answered when its ports are done, so an event naming such
    /// an address can find no host behind it by the time it is read. See
    /// [`ScanPhase::silent`](crate::report::ScanPhase::silent).
    pub fn hosts(&self) -> &HostStore {
        &self.store
    }

    /// The live event stream.
    ///
    /// Bounded: a consumer that reads it slowly, or not at all, loses the
    /// oldest events rather than accumulating them. See [`ScanEvents`].
    pub fn events(&mut self) -> &mut ScanEvents {
        &mut self.events
    }

    /// The control handle, which is how a scan is stopped early.
    pub fn handle(&self) -> &ScanHandle {
        &self.handle
    }

    /// How far the scan has got through its plan.
    ///
    /// Cloneable, so a caller rendering a scan elsewhere clones this rather than
    /// holding the session still. See [`Progress`].
    pub fn progress(&self) -> &Progress {
        &self.progress
    }

    /// Takes the session apart, for a caller that wants to watch the events from
    /// one task and read the hosts from another.
    ///
    /// [`HostStore`], [`ScanHandle`] and [`Progress`] are all cloneable and
    /// shareable, so this is only needed to move the event stream, which is not,
    /// there being exactly one of it.
    pub fn into_parts(self) -> (HostStore, ScanEvents, ScanHandle, Progress) {
        (self.store, self.events, self.handle, self.progress)
    }
}

/// Where an instrumented scanner leaves its counters for the final
/// [`ScanReport`](crate::report::ScanReport).
///
/// A scanner reports its audit as its receive loop exits, which is well before
/// the phase that spawned it knows the scan is over, and the strategy is
/// consumed by then. This is where those counters wait in the meantime.
#[derive(Debug, Default)]
pub(crate) struct ProbeStatsLog {
    entries: Mutex<Vec<ProbeStats>>,
}

impl ProbeStatsLog {
    fn push(&self, stats: ProbeStats) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.push(stats);
    }

    fn drain(&self) -> Vec<ProbeStats> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries)
    }

    fn snapshot(&self) -> Vec<ProbeStats> {
        self.entries
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }
}

/// Each open port's gathered responses, held from the service phase to the
/// detection phase for a passive [detection](crate::detect) to read.
///
/// The service phase already draws a first-contact banner and any probe replies
/// to name the service; rather than a later phase redrawing them, they are kept
/// here, keyed by port, and *taken* by the detection phase, so a response body
/// is held only across the two adjacent phases and freed as it is read, not
/// retained through the whole paced scan.
#[derive(Default)]
pub(crate) struct Responses {
    inner: DashMap<(ScopedIp, u16, Protocol), Vec<String>>,
}

impl Responses {
    /// Records what the service phase gathered for one port. An empty set is not
    /// stored: there is nothing for a detection to read, and a passive detection
    /// over no bytes has nothing to do.
    fn record(&self, ip: ScopedIp, number: u16, protocol: Protocol, banners: Vec<String>) {
        if !banners.is_empty() {
            self.inner.insert((ip, number, protocol), banners);
        }
    }

    /// Takes one port's gathered responses, removing them so the memory is freed
    /// as the detection phase reads it. Empty if the port drew nothing.
    fn take(&self, ip: &ScopedIp, number: u16, protocol: Protocol) -> Vec<String> {
        self.inner
            .remove(&(ip.clone(), number, protocol))
            .map(|(_, banners)| banners)
            .unwrap_or_default()
    }
}

/// The tapes of detection runs, captured as the detection phase produces them and
/// drained into the journal by the checkpoint task. A plain queue: unlike the
/// responses, a tape is never looked up by port, only appended once and taken in a
/// batch.
#[derive(Debug, Default)]
pub(crate) struct Tapes {
    inner: Mutex<Vec<DetectionRunRecord>>,
}

impl Tapes {
    /// Records one detection run's tape.
    pub(crate) fn record(&self, run: DetectionRunRecord) {
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push(run);
    }

    /// Takes every tape captured since the last call, freeing them as the journal
    /// writes them down.
    pub(crate) fn take(&self) -> Vec<DetectionRunRecord> {
        std::mem::take(
            &mut self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
    }
}

/// Ground a phase declined to cover, gathered as it is decided.
///
/// Kept apart from [`FailureLog`] for the reason [`Refusal`] gives: a strategy
/// that could not run means something went wrong, and a refusal means the scan
/// as written cannot answer part of what it was asked. Both narrow the result
/// and only one of them is a fault, so a reader who cannot tell them apart
/// learns to ignore both.
///
/// Ordered by insertion rather than sorted: the plan decides these in the order
/// it works through the targets, and that order is the one a reader following
/// the plan expects.
#[derive(Debug, Default)]
pub(crate) struct RefusalLog {
    entries: Mutex<Vec<Refusal>>,
}

impl RefusalLog {
    fn push(&self, refusal: Refusal) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        if !entries.contains(&refusal) {
            entries.push(refusal);
        }
    }

    fn drain(&self) -> Vec<Refusal> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries)
    }

    fn snapshot(&self) -> Vec<Refusal> {
        self.entries
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }
}

/// Addresses this host could not reach, gathered across a phase.
///
/// A set, so a target probed several times is named once, and ordered so two
/// runs of the same scan report them the same way.
///
/// Kept apart from [`FailureLog`] because the two are different findings. A
/// strategy that could not run means the scan covered less than it was asked
/// to and its result is partial; an unreachable address means that address is
/// not reachable from this machine, which is an ordinary fact about a
/// dual-stack name on a single-stack network and says nothing about the rest of
/// the scan.
#[derive(Debug, Default)]
pub(crate) struct UnroutableLog {
    entries: Mutex<std::collections::BTreeSet<IpAddr>>,
}

impl UnroutableLog {
    fn insert(&self, address: IpAddr) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(address);
    }

    fn contains(&self, address: IpAddr) -> bool {
        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.contains(&address)
    }

    fn drain(&self) -> Vec<IpAddr> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries).into_iter().collect()
    }
}

/// Addresses a discovery sweep was handed and reached no verdict on, gathered
/// across a phase.
///
/// The same shape as [`UnroutableLog`], and it answers the question a liveness
/// filter has to ask before it reads a missing host as a host that is not
/// there: whether anything asked.
#[derive(Debug, Default)]
pub(crate) struct UnsweptLog {
    entries: Mutex<std::collections::BTreeSet<IpAddr>>,
}

impl UnsweptLog {
    fn insert(&self, address: IpAddr) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(address);
    }

    fn snapshot(&self) -> Vec<IpAddr> {
        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.iter().copied().collect()
    }
}

/// Addresses whose ICMP errors a phase found rate-limited, gathered across
/// it.
///
/// The same shape as [`TimedOutLog`] and for a related purpose: the phase
/// qualifying what it covered. A set, so a host two scanners read the same
/// way is named once.
#[derive(Debug, Default)]
pub(crate) struct RateLimitedLog {
    entries: Mutex<std::collections::BTreeSet<IpAddr>>,
}

impl RateLimitedLog {
    fn insert(&self, address: IpAddr) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(address);
    }

    fn drain(&self) -> Vec<IpAddr> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries).into_iter().collect()
    }
}

/// Addresses whose own budget ran out, gathered across a phase.
///
/// The same shape as [`UnroutableLog`] and for a related purpose: both are the
/// phase saying what it did not finish covering, and neither is a fault. A set,
/// so a host left early by three passes is named once.
#[derive(Debug, Default)]
pub(crate) struct TimedOutLog {
    entries: Mutex<std::collections::BTreeSet<IpAddr>>,
}

impl TimedOutLog {
    fn insert(&self, address: IpAddr) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(address);
    }

    fn contains(&self, address: IpAddr) -> bool {
        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.contains(&address)
    }

    fn drain(&self) -> Vec<IpAddr> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries).into_iter().collect()
    }
}

/// Addresses a discovery pass asked as many times as its policy allows and
/// heard nothing from.
///
/// Read to tell a host found down from one the pass never reached a verdict
/// on. A port scan's port phase settles only the first as
/// [`Skipped`](crate::journal::settle::Outcome::Skipped), and every discovery
/// phase names the second in
/// [`ScanPhase::undecided`](crate::report::ScanPhase::undecided). A host
/// missing from the live set proves neither, since a pass that stopped early,
/// had no strategy for a range or was refused it leaves hosts out of that set
/// too.
///
/// Positive evidence rather than a list of what went wrong, so a way of failing
/// to ask that nobody thought to record still fails in the safe direction: the
/// host is asked again on a resume rather than written off.
///
/// One range per address until merged, so it is merged whenever what was added
/// since the last merge outgrows what that merge left. A pass walking a
/// permutation settles addresses far apart and merges little until it is
/// nearly done, which bounds this at one range per silent address and no more.
#[derive(Debug, Default)]
pub(crate) struct SilenceLog {
    entries: Mutex<Silence>,
}

/// The set behind [`SilenceLog`], and what decides when it is next merged.
#[derive(Debug, Default)]
struct Silence {
    set: IpSet,
    /// How many ranges the last merge left, which is what the next one waits
    /// for the additions to outgrow.
    merged: usize,
    added: usize,
}

impl SilenceLog {
    /// The fewest additions worth a merge, so a small pass is merged once, on
    /// the way out, rather than every few addresses.
    const MERGE_AFTER: usize = 4096;

    fn insert(&self, address: IpAddr) {
        let mut silence = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        silence.set.insert(address);
        silence.added += 1;
        if silence.added >= Self::MERGE_AFTER.max(silence.merged) {
            silence.set.canonicalize();
            silence.merged = silence.set.v4().len() + silence.set.v6().len();
            silence.added = 0;
        }
    }

    fn drain(&self) -> IpSet {
        let mut silence = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        let mut taken = std::mem::take(&mut *silence).set;
        taken.canonicalize();
        taken
    }
}

/// Addresses a raw phase reached by TCP connect, gathered across it.
///
/// Held as ranges rather than addresses, because what fills it is a whole group
/// a strategy was handed, and a tunnel's own subnet can be a `/23`. Merged on
/// the way out, so a range two strategies both reported is named once.
#[derive(Debug, Default)]
pub(crate) struct ConnectLog {
    entries: Mutex<IpSet>,
}

impl ConnectLog {
    fn extend(&self, targets: &IpSet) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        for range in targets.v4() {
            entries.push_v4_range(*range);
        }
        for range in targets.v6() {
            entries.push_v6_range(*range);
        }
    }

    fn drain(&self) -> Vec<IpRange> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        let mut taken = std::mem::take(&mut *entries);
        taken.canonicalize();
        let v4 = taken.v4().iter().copied().map(IpRange::V4);
        let v6 = taken.v6().iter().copied().map(IpRange::V6);
        v4.chain(v6).collect()
    }
}

/// When each host's wall-clock budget started, for a scan given one.
///
/// A host's clock starts on the first probe aimed at it rather than when the
/// phase did, because a shuffled scan of a wide range reaches an address
/// whenever it reaches it, and a budget counted from the start of the run would
/// give the last address in the plan no time at all.
///
/// `budget` is `None` for a scan that set no per-host bound, which is the
/// ordinary case: the map is then never written to, and every question about a
/// host is a read of an `Option` and nothing more.
///
/// ## What it costs
///
/// One instant per address the scan probes. That is bounded by the same thing
/// the host store is bounded by, and each entry here is a fraction of the
/// [`Host`] the store already keeps for the same address, so a scan that can
/// afford its own findings can afford to time them.
#[derive(Debug, Default)]
pub(crate) struct HostClocks {
    budget: Option<Duration>,
    started: DashMap<IpAddr, Instant>,
}

/// The shortest gap the scan keeps between two probes aimed at one host.
///
/// The companion to [`HostClocks`], built the same way and for the same reason:
/// a bound on one host is a property of the scan rather than of whichever pass
/// happens to be probing, so it lives on the context every pass already holds.
/// A copy per strategy would be no bound at all, since
/// [`max_probe_rate`](crate::config::ZondConfig::max_probe_rate) is handed to
/// each strategy undivided and two passes probing one address would each allow
/// the whole gap.
///
/// `minimum` is `None` for a scan that set none, which is the ordinary case: the
/// map is then never touched and every question is a read of an `Option`.
///
/// ## Deciding, not enforcing
///
/// This answers *when* and records *that*, in two calls a caller makes in that
/// order. It cannot enforce anything on its own, because what to do with a probe
/// it turns away is not its business: the raw port scanner has a queue to hold
/// one in, and the sweep would rather ask the next host and come back. Folding a
/// wait in here would make the decision for both of them, and inside a lock.
///
/// ## What it costs
///
/// One instant per address the scan probes, on the same reasoning
/// [`HostClocks`] gives for its own map. The two are deliberately not one type:
/// a budget is read once per target and starts a clock, a gap is read once per
/// *probe* and moves one, and merging them would put both writes behind
/// whichever question was asked first.
#[derive(Debug, Default)]
pub(crate) struct HostSpacing {
    minimum: Option<Duration>,
    last_sent: DashMap<IpAddr, Instant>,
}

impl HostSpacing {
    /// When `address` may next be probed, or `None` if it may be probed now.
    ///
    /// Reads only. A caller that goes on to send says so with
    /// [`sent`](Self::sent), and one that defers the probe leaves nothing
    /// behind, so a target turned away does not push its own next slot back.
    fn ready_at(&self, address: IpAddr, now: Instant) -> Option<Instant> {
        let minimum = self.minimum?;
        let last = *self.last_sent.get(&address)?;
        let ready = crate::scanner::pacing::timer::later(last, minimum);
        (ready > now).then_some(ready)
    }

    /// Records a probe leaving for `address`.
    ///
    /// Called after the send rather than before it, so a probe the kernel
    /// refused does not spend the host's slot. Nothing is stored for a scan that
    /// set no minimum: without one there is no question for the instant to
    /// answer.
    fn sent(&self, address: IpAddr, now: Instant) {
        if self.minimum.is_none() {
            return;
        }
        self.last_sent.insert(address, now);
    }
}

impl HostClocks {
    /// Whether `address` has used up its budget, starting its clock if this is
    /// the first time it has been asked about.
    ///
    /// Always false for a scan with no budget, without touching the map.
    fn expired(&self, address: IpAddr) -> bool {
        let Some(budget) = self.budget else {
            return false;
        };
        // Read before writing. Only the first probe aimed at a host takes the
        // shard's write lock; the thousand after it are reads, and this is
        // asked once per target on the send path.
        if let Some(started) = self.started.get(&address) {
            return started.elapsed() >= budget;
        }
        let started = *self.started.entry(address).or_insert_with(Instant::now);
        started.elapsed() >= budget
    }
}

/// The links a phase swept, gathered as its strategies run.
///
/// A sweep of a local segment reaches every host on the link, not only the
/// addresses it was handed: an all-nodes solicitation is one probe every IPv6
/// neighbour is required to answer. That is coverage, and there is no address
/// range that expresses it: a link is named by the interface it is on.
///
/// Keyed by interface name, so a link swept by two strategies is recorded once.
#[derive(Debug, Default)]
pub(crate) struct SweptLinks {
    entries: Mutex<std::collections::BTreeMap<String, Zone>>,
}

impl SweptLinks {
    fn insert(&self, zone: Zone) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(zone.name().to_owned(), zone);
    }

    fn drain(&self) -> Vec<Zone> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries).into_values().collect()
    }
}

/// The switch ports a phase found itself plugged into, gathered as its
/// strategies run.
///
/// Keyed by the link and the protocol the announcement came from, so a switch
/// re-announcing itself every thirty seconds, which is what they do, is
/// recorded once rather than once per frame. The *latest* announcement wins,
/// because the question is what this machine is plugged into now and a cable
/// somebody moved should not be reported as two attachments held at once.
///
/// A link answering on both LLDP and CDP keeps both: which
/// protocols a network speaks is itself a fact about what it is made of, and
/// the two carry different fields.
#[derive(Debug, Default)]
pub(crate) struct Attachments {
    entries: Mutex<std::collections::BTreeMap<(String, AttachmentSource), Attachment>>,
}

impl Attachments {
    fn insert(&self, attachment: Attachment) {
        let key = (attachment.link().name().to_owned(), attachment.source());
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(key, attachment);
    }

    fn drain(&self) -> Vec<Attachment> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries).into_values().collect()
    }
}

/// Every host in `store`, cloned, ordered by the address each is keyed under.
///
/// Ordered because the one production consumer writes these to disk: a
/// compaction whose record order came out of a concurrent map's iteration
/// writes a different file every time it runs over the same findings.
///
/// A free function rather than a method, because both halves of the session
/// need it and neither owns the other. `ScanContext` writes and `ScanProgress`
/// is the narrow view a journal gets, and the three readings they have in
/// common would otherwise be three copies.
fn snapshot_of(store: &DashMap<ScopedIp, Host>) -> Vec<Host> {
    let mut hosts: Vec<Host> = store.iter().map(|entry| entry.value().clone()).collect();
    hosts.sort_by_cached_key(Host::scoped_ip);
    hosts
}

/// The hosts `changed` has marked since it was last drained, with their current
/// state, dropping any the store no longer holds.
fn changed_since(store: &DashMap<ScopedIp, Host>, changed: &ChangedHosts) -> Vec<Host> {
    changed
        .drain()
        .into_iter()
        .filter_map(|key| store.get(&key).map(|host| host.clone()))
        .collect()
}

/// What a journal needs from a running scan, and nothing more.
///
/// See [`ScanContext::progress`] for why this exists rather than a context.
#[derive(Debug, Clone)]
pub struct ScanProgress {
    store: Arc<DashMap<ScopedIp, Host>>,
    changed: Arc<ChangedHosts>,
    settlements: Arc<Settlements>,
    failures: Arc<FailureLog>,
    tapes: Arc<Tapes>,
}

impl ScanProgress {
    /// How far the scan has got, and what became of what it did not settle.
    pub fn settlements(&self) -> &Settlements {
        &self.settlements
    }

    /// Takes the hosts whose findings have changed since this was last called.
    pub fn take_changed_hosts(&self) -> Vec<Host> {
        changed_since(&self.store, &self.changed)
    }

    /// Takes the detection tapes captured since this was last called, for the
    /// journal to write down.
    pub fn take_tapes(&self) -> Vec<DetectionRunRecord> {
        self.tapes.take()
    }

    /// Every host found so far, cloned, ordered by the address each is keyed
    /// under.
    ///
    /// Ordered because the one production consumer writes these to disk, and a
    /// compaction whose record order came out of a concurrent map's iteration
    /// writes a different file every time it runs over the same findings.
    pub fn hosts_snapshot(&self) -> Vec<Host> {
        snapshot_of(&self.store)
    }

    /// How many hosts have been found so far.
    pub fn host_count(&self) -> usize {
        self.store.len()
    }

    /// Files a failure to the report. Not to the event stream; see
    /// [`ScanContext::progress`].
    ///
    /// Logged under the strategy that is failing, as
    /// [`ScanContext::record_failure`] logs it, rather than under a fixed word:
    /// the checkpoint task is not the only thing that reaches the report this
    /// way, and a line saying `journal` for all of them would tell a reader less
    /// than the name it already has.
    pub fn record_failure(&self, scanner: ScannerKind, reason: String) {
        error!("{scanner:?} failed: {reason}");
        self.failures.push(ScannerFailure::new(scanner, reason));
    }
}

/// The hosts whose findings a journal has yet to record.
#[derive(Debug, Default)]
pub(crate) struct ChangedHosts {
    entries: Mutex<std::collections::BTreeSet<ScopedIp>>,
}

impl ChangedHosts {
    fn insert(&self, ip: ScopedIp) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.insert(ip);
    }

    fn drain(&self) -> Vec<ScopedIp> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries).into_iter().collect()
    }
}

/// Where strategy failures accumulate for the final
/// [`ScanReport`](crate::report::ScanReport).
///
/// [`ScanEvent::ScannerFailed`] tells a live consumer about a failure the moment
/// it happens, but an event nobody listens for is an event that never happened:
/// a caller that simply awaits the scan and reads the store at the end has no
/// way to learn that a strategy died. The log keeps the same failures somewhere
/// the report can reach them afterwards, so "the network is empty" and "the raw
/// scanner never started" stay distinguishable however the caller chose to
/// consume the scan.
///
/// A plain [`Mutex`] rather than a lock-free structure: failures are rare
/// enough that contention is not a consideration, and the lock is never held
/// across an await.
#[derive(Debug, Default)]
pub(crate) struct FailureLog {
    entries: Mutex<Vec<ScannerFailure>>,
}

impl FailureLog {
    fn push(&self, failure: ScannerFailure) {
        // A poisoned lock means another thread panicked mid-push. The scan's
        // findings are still worth reporting, so recover the entries rather than
        // propagating the panic into an unrelated scanner.
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        entries.push(failure);
    }

    fn drain(&self) -> Vec<ScannerFailure> {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        std::mem::take(&mut *entries)
    }

    fn snapshot(&self) -> Vec<ScannerFailure> {
        self.entries
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }
}

/// The shared, cloneable handles that every scanning strategy needs: somewhere to
/// write discovered hosts, somewhere to announce updates, a way to check for abort,
/// and somewhere to record its own failure.
///
/// Bundling these avoids passing (and cloning) the same arguments individually
/// at every scanner construction site.
/// Every field is `pub(crate)`. A scanner is built with one of these and writes
/// findings through [`write_host`](Self::write_host), which is where the
/// lock-then-announce ordering lives; handing a consumer the raw map and the raw
/// event sender would hand them that ordering to get wrong, and would pin the
/// concurrency crate behind the map into this crate's semver. What a consumer
/// reads is [`ScanSession`].
#[derive(Clone)]
pub struct ScanContext {
    pub(crate) handle: ScanHandle,
    pub(crate) store: Arc<DashMap<ScopedIp, Host>>,
    pub(crate) events_tx: broadcast::Sender<ScanEvent>,
    pub(crate) failures: Arc<FailureLog>,
    /// Ground this scan declined to cover before sending anything.
    pub(crate) refusals: Arc<RefusalLog>,
    pub(crate) probe_stats: Arc<ProbeStatsLog>,
    /// Addresses this host could not reach, so no probe was sent to them.
    pub(crate) unroutable: Arc<UnroutableLog>,
    /// Addresses the scan stopped working on because their budget ran out.
    pub(crate) timed_out: Arc<TimedOutLog>,
    /// Addresses whose ICMP errors the scan found rate-limited.
    pub(crate) icmp_rate_limited: Arc<RateLimitedLog>,
    /// Addresses a discovery sweep stopped before it reached a verdict on.
    pub(crate) unswept: Arc<UnsweptLog>,
    /// Addresses a raw phase reached by TCP connect instead.
    pub(crate) reached_by_connect: Arc<ConnectLog>,
    /// Addresses a discovery pass found silent, or that a port phase standing
    /// in for one asked on every port and heard nothing from.
    pub(crate) silent: Arc<SilenceLog>,
    /// Addresses a port phase standing in for a liveness pass heard nothing
    /// from without finishing asking them.
    pub(crate) undecided: Arc<SilenceLog>,
    /// Which stage's unit the plan, and so the settlements, are counted in.
    pub(crate) plan_stage: Stage,
    /// When each host's budget started, for a scan that set one.
    pub(crate) clocks: Arc<HostClocks>,
    pub(crate) spacing: Arc<HostSpacing>,
    /// The interface each of this scan's link-local targets was named on.
    ///
    /// A link-local address is not a key on its own, and a scanner addressing
    /// its targets one at a time holds a bare one. Completing the key from this
    /// is what keeps a port scan's verdicts on the same record as the sweep's
    /// hardware address, rather than beside it under a keyless `fe80::…`.
    ///
    /// Learned once the port phase knows which targets it kept, and empty for
    /// every scan that named no zone.
    pub(crate) zones: Arc<OnceLock<ZoneMap>>,
    pub(crate) swept_links: Arc<SweptLinks>,
    /// Where this machine turned out to be plugged in, as the equipment said.
    pub(crate) attachments: Arc<Attachments>,
    /// Addresses no finding may be recorded against.
    ///
    /// Behind an `Arc` because a context is cloned once per strategy and the
    /// policy is read, never written, by all of them.
    pub(crate) exclusions: Arc<Exclusions>,
    /// Which hosts have findings a journal has not written down yet.
    ///
    /// Marked on every write, which is *not* the condition that
    /// fires [`ScanEvent::HostUpdated`]. A watcher is told about novelty and a
    /// journal records state, and the two part company exactly where it matters:
    /// an enrichment pass adding evidence to a host already announced has
    /// nothing new to say and a great deal to write down.
    ///
    /// Bounded by the number of distinct hosts, which the store holds anyway.
    pub(crate) changed: Arc<ChangedHosts>,
    /// What the scan is working on, and how far through it.
    pub(crate) stages: Arc<Stages>,
    /// What became of each target, for a resume that must not skip one.
    ///
    /// Separate from the verdict a target receives: the engine gives an
    /// exhausted probe, an interrupted one and one never sent the same verdict
    /// on purpose. See [`journal::settle`](crate::journal::settle).
    pub(crate) settlements: Arc<Settlements>,
    /// How this scan numbers an address, when it is counted in addresses.
    ///
    /// Empty for a scan counted in something else, which is every port scan:
    /// its positions pair an address with a port and arrive on the target
    /// stream. A sweep has no such stream, a
    /// [`HostScanner`](crate::scanner::strategy::HostScanner) owns its targets,
    /// so the numbering travels here instead.
    ///
    /// Empty is what keeps the two apart. A port scan's liveness pass runs
    /// the discovery strategies against a port scan's context, and those
    /// strategies settle addresses. Numbering them against the port plan would
    /// advance its watermark over probes nobody sent, so a context that does not
    /// count addresses answers `None` to every address and nothing is recorded.
    pub(crate) positions: Arc<Positions>,
    /// The key the order this scan asks its targets in is a function of.
    ///
    /// [`None`] for a scan that walks its plan in order. Read by the dispatcher
    /// and by nothing else, since it decides what to ask next rather than
    /// anything about what an answer means.
    pub(crate) order_seed: Option<u64>,
    /// Each open port's gathered responses, kept from the service phase for the
    /// detection phase to hand a passive detection.
    pub(crate) responses: Arc<Responses>,
    /// The tapes of detection runs, captured for the journal to write down so a
    /// recorded scan can be replayed offline.
    pub(crate) tapes: Arc<Tapes>,
    /// The corpus the detection phase runs, the shipped one unless a caller set
    /// their own on the config. Cheap to clone: the compiled tiers sit behind
    /// `Arc`s.
    pub(crate) detections: crate::detect::Detections,
    /// The sources the scan forced, which decide where each connection it
    /// opens leaves from. Empty for a scan that forced none.
    pub(crate) forced: Arc<crate::transport::dial::ForcedSources>,
    /// The TCP ports this scan connects to and listens on and sends nothing;
    /// see [`listens_only`](Self::listens_only).
    pub(crate) listen_only: Arc<BTreeSet<u16>>,
}

impl ScanContext {
    /// Where a connection this scan opens to `target` leaves from.
    ///
    /// Asked by every phase that dials, once per destination, and handed to
    /// each connection it makes there, so a port the scan's probe reached from
    /// a forced source is spoken to from that source too.
    pub(crate) fn egress_toward(&self, target: IpAddr) -> crate::transport::dial::Egress {
        self.forced.toward(target)
    }

    /// Whether this scan may do no more than connect to `number` over
    /// `protocol` and read what it volunteers.
    ///
    /// Asked by every pass that would put bytes on a port: the service pass and
    /// the connect scanner's inline identification, through
    /// [`service_detection_on`](Self::service_detection_on), and the detection
    /// and TLS enumeration passes, which leave such a port alone. A pass that
    /// wrote to a port without asking would be the one that makes a printer
    /// print; see
    /// [`ZondConfig::listen_only_ports`](crate::config::ZondConfig::listen_only_ports).
    pub(crate) fn listens_only(&self, number: u16, protocol: Protocol) -> bool {
        protocol == Protocol::Tcp && self.listen_only.contains(&number)
    }

    /// How far identification goes on one port under a scan asking for
    /// `detection`: that far, or no further than listening on a port this scan
    /// [only listens on](Self::listens_only).
    ///
    /// A cap rather than a skip, because connecting and reading is safe on any
    /// port and names every service that greets on connect. Everything past
    /// [`ServiceDetection::Banner`] sends, a handshake's ClientHello and an
    /// analyzer's second connection as much as a probe.
    pub(crate) fn service_detection_on(
        &self,
        detection: ServiceDetection,
        number: u16,
        protocol: Protocol,
    ) -> ServiceDetection {
        if self.listens_only(number, protocol) {
            detection.min(ServiceDetection::Banner)
        } else {
            detection
        }
    }

    /// Records the responses the service phase gathered for one port, for the
    /// detection phase to hand a passive detection.
    pub(crate) fn record_responses(
        &self,
        ip: ScopedIp,
        number: u16,
        protocol: Protocol,
        banners: Vec<String>,
    ) {
        self.responses.record(ip, number, protocol, banners);
    }

    /// Takes a port's gathered responses, freeing them as the detection phase
    /// reads it.
    pub(crate) fn take_responses(
        &self,
        ip: &ScopedIp,
        number: u16,
        protocol: Protocol,
    ) -> Vec<String> {
        self.responses.take(ip, number, protocol)
    }

    /// Whether this scan may address a probe to `address`.
    ///
    /// The send-side half of what [`Exclusions`] promises, for the one kind of
    /// address the up-front withholding cannot reach: one a strategy learns while
    /// it runs. A segment sweep takes leads off the wire, from mDNS records and
    /// from advertisements nobody solicited, and asks each one directly. None of
    /// them was in the target list, so none was withheld from it, and
    /// [`write_host`](Self::write_host) sees only the answer: it can keep the
    /// report clean and cannot keep the question off the wire.
    ///
    /// Asked by whoever turns a learned address into a probe, at the moment it
    /// does. A target the caller named has already been withheld and need not
    /// ask again.
    pub fn may_probe(&self, address: &IpAddr) -> bool {
        !self.exclusions.excludes(address)
    }

    /// The single place a host finding enters the store.
    ///
    /// Upserts the host at `ip`, runs `edit` against it while the store guard is
    /// held, then releases that guard *before* emitting
    /// [`ScanEvent::HostUpdated`] - so the DashMap lock is never held across the
    /// channel send. That ordering rule lives here, once, rather than being
    /// re-spelled (and eventually mis-spelled) at each scanner. Returns `true` if
    /// this call created the host.
    ///
    /// `edit` returns whether the change is worth announcing: `true` emits the
    /// event, `false` suppresses it - e.g. a duplicate reply from an already
    /// known host that revealed nothing new. A newly created host is always
    /// announced, regardless of what `edit` returns.
    ///
    /// Anything a caller must do *without* the guard held - hostname resolution,
    /// adaptive-deadline bookkeeping - keys off the returned flag and runs after
    /// this call, so no scanner has to reason about guard lifetime itself.
    /// Callers that always want to announce their change use the
    /// [`update_host`](Self::update_host) shorthand.
    ///
    /// # Exclusions
    ///
    /// A key the scan's [`Exclusions`] forbid is dropped here: `edit` is not run,
    /// no host is created, no event is emitted, and this returns `false`. Every
    /// other address `edit` attaches to the host is held to the same policy once
    /// it has run, the sweep's later replies from the same machine, a merged
    /// sighting, an mDNS record's other addresses, so none of them reaches the
    /// report either, and none can become the address the host is reached at.
    /// Every router on the host's path is held to it too, whether the trace
    /// measured it or spliced it in from another host's trace: one the policy
    /// names keeps its distance and loses its address, for the reason
    /// [`Hop::withheld`](crate::model::host::Hop::withheld) gives. So is the
    /// router or firewall that sent second-hand evidence about the host, an
    /// ICMP unreachable above all: one the policy names leaves its evidence on
    /// the host and its address off it, for the reason
    /// [`EvidenceSource::Withheld`](crate::model::host::EvidenceSource::Withheld)
    /// gives.
    ///
    /// This is the enforcement that a subtraction from the target list cannot
    /// perform, and putting it here rather than at each scanner is deliberate.
    /// Every finding in the engine reaches the store through this function, so
    /// this one branch covers the ARP and neighbour-advertisement replies a
    /// sweep learns addresses from, the host's own neighbour table, the mDNS
    /// records, and, transitively, because they read the store to decide who to
    /// probe, the service, OS-series and SNMP phases that run afterwards. A
    /// scanner cannot forget to apply the policy, because a scanner is not where
    /// it is applied.
    ///
    /// A drop is logged rather than counted. The property worth checking is that
    /// no excluded address appears in the report, and a reader can confirm that
    /// against the ranges the report already records, which is a better
    /// guarantee than a number this engine reports about itself.
    pub fn write_host(
        &self,
        key: impl Into<ScopedIp>,
        edit: impl FnOnce(&mut Host) -> bool,
    ) -> bool {
        let key = self.key(key);
        let ip = key.addr();

        if self.exclusions.excludes(&ip) {
            // Ordinary on a sweep, which cannot address its all-nodes echo away
            // from an excluded neighbour, and worth a line either way: it is the
            // record that the gate did something, on the one path where a
            // caller may be surprised that there was anything for it to do.
            info!(
                verbosity = 2,
                "excluded address {ip} answered a probe it was not addressed; dropping the finding"
            );
            return false;
        }

        let mut is_new = false;
        let mut host = self.store.entry(key.clone()).or_insert_with(|| {
            is_new = true;
            let mut host = Host::new(ip);
            // The key carries the interface where the address needs one, so the
            // host is born knowing which link it is on rather than waiting for a
            // scanner to remember to say. `Host::set_zone` keeps the first zone
            // it is given, which is the right rule only if the first one is
            // right, and the key is the one thing here that cannot be wrong
            // about it, since it is what the host was looked up by.
            if let Some(zone) = key.zone() {
                host.set_zone(zone.clone());
            }
            host
        });
        let announce = edit(&mut host);
        // The key passed the gate above, and what the edit attached under it
        // has not been asked. The key's own address is among what is kept, so
        // the host never runs out of addresses here.
        if !self.exclusions.is_empty() {
            let keep = |address: &IpAddr| !self.exclusions.excludes(address);
            let before = host.ips().len();
            host.retain_ips(keep);
            if host.ips().len() < before {
                info!(
                    verbosity = 2,
                    "an excluded address arrived beside {ip}; leaving it off the host"
                );
            }
            if host.withhold_intermediaries(keep) {
                info!(
                    verbosity = 2,
                    "an excluded router answered for a probe to {ip}; withholding its address"
                );
            }
        }
        drop(host);

        // Marked whether or not the edit asked to be announced. `edit` was
        // handed a `&mut Host` and may have moved the record however it
        // answered, and a journal that missed that would give back a quieter
        // host than the scan found.
        //
        // **These are two questions, and one boolean cannot answer both.** What
        // a watcher is told is about novelty: a host already announced does not
        // need announcing again, which is why the echo probe answers `false`
        // for a host that was already up. What a journal writes is about state,
        // and that probe has just added an `icmp_echo` reason and a round trip
        // to it. Sharing the boolean would silently drop both from every
        // recorded scan.
        self.changed.insert(key.clone());

        if announce || is_new {
            let _ = self.events_tx.send(ScanEvent::HostUpdated(key));
        }
        is_new
    }

    /// Reads the host at `ip`, if there is one, without cloning it.
    ///
    /// The counterpart of [`write_host`](Self::write_host), and a closure for
    /// the same reason: the store's guard is held for the duration of `read`
    /// and released before this returns, so a caller cannot keep it across an
    /// await. Take what is needed out of the host and let the guard go.
    ///
    /// `read` must not touch this context again. The guard it runs under is the
    /// store's own, and reaching back into the store from inside it deadlocks.
    pub fn read_host<R>(
        &self,
        ip: impl Into<ScopedIp>,
        read: impl FnOnce(&Host) -> R,
    ) -> Option<R> {
        self.store
            .get(&self.key(ip))
            .map(|entry| read(entry.value()))
    }

    /// `ip` as this scan keys a host under.
    ///
    /// A key that already names its interface is kept as it is. One that needs
    /// an interface and has none is completed from the zones the scan named its
    /// targets on, so a finding recorded against a bare `fe80::…` reaches the
    /// host it belongs to. An address needing no zone passes straight through.
    fn key(&self, ip: impl Into<ScopedIp>) -> ScopedIp {
        let key = ip.into();
        match key.is_unusable() {
            true => self
                .zones
                .get()
                .map_or(key.clone(), |zones| zones.key(key.addr())),
            false => key,
        }
    }

    /// Records which interface each of this scan's link-local targets was named
    /// on. The first call decides; later ones are ignored.
    pub(crate) fn learn_zones(&self, zones: ZoneMap) {
        let _ = self.zones.set(zones);
    }

    /// Whether anything is recorded under `ip`.
    ///
    /// Cheaper than [`read_host`](Self::read_host) when the host itself is not
    /// wanted: nothing is cloned and no closure runs. The writing half's name
    /// for what [`HostStore::contains`] answers on the reading half, and named
    /// to match it: one question should not have two names across the pair.
    ///
    /// A question about the key, not about the machine. A host is reachable
    /// at every address it holds and is recorded under one of them, so this
    /// answers "is there a record here" and never "is this machine known".
    pub fn contains_host(&self, ip: &ScopedIp) -> bool {
        self.store.contains_key(&self.key(ip.clone()))
    }

    /// Every address a host is currently recorded under.
    ///
    /// A snapshot, so a caller may write to the store while walking it.
    /// [`write_host`](Self::write_host) takes the store's own lock, and holding
    /// an iterator over the map while calling it would deadlock against
    /// whichever shard the iterator is on.
    pub fn host_addresses(&self) -> Vec<ScopedIp> {
        self.store.iter().map(|entry| entry.key().clone()).collect()
    }

    /// The single place a strategy failure enters the record.
    ///
    /// Logs it, files it for the final report, and announces it to any live
    /// consumer - in that order, so the durable copy exists before the
    /// notification that might be dropped. A scan continues with whatever
    /// strategies remain, so this narrows a result rather than ending it.
    ///
    /// Public because a caller running strategies themselves has to be able to
    /// file what went wrong the same way the engine's own orchestration does; a
    /// custom strategy that could not would produce a report claiming a clean
    /// run over a scan that lost half its work.
    pub fn record_failure(&self, scanner: ScannerKind, reason: String) {
        error!("scanner {scanner:?} failed: {reason}");
        self.failures
            .push(ScannerFailure::new(scanner, reason.clone()));
        let _ = self
            .events_tx
            .send(ScanEvent::ScannerFailed { scanner, reason });
    }

    /// Where a strategy files work it began and could not finish because a
    /// budget it runs under ran out: a detection whose declared time or bytes
    /// were spent before its question was answered.
    ///
    /// Filed exactly as [`record_failure`](Self::record_failure) files, as a
    /// [`ScannerFailure`] and a [`ScanEvent::ScannerFailed`], because the report
    /// has one account of work that did not complete and a consumer reading it
    /// for coverage has to find this there. The run did cover less than it was
    /// asked to. What differs is the console. Nothing broke, so this is a
    /// warning in the caller's own words rather than an error announcing that
    /// the scanner failed: a reader told a scanner failed looks for a fault,
    /// and here there is none to find, only a target that cost more than the
    /// budget allowed.
    pub(crate) fn record_cut_short(&self, scanner: ScannerKind, reason: String) {
        crate::warn!("{reason}");
        self.failures
            .push(ScannerFailure::new(scanner, reason.clone()));
        let _ = self
            .events_tx
            .send(ScanEvent::ScannerFailed { scanner, reason });
    }

    /// The single place a refusal enters the record.
    ///
    /// Not a failure, and this is the difference. A refusal is the engine
    /// working out, before anything is sent, that part of what it was asked for
    /// has no strategy behind it: an SCTP port on a host with no raw sockets, a
    /// prefix too large to walk, a technique a connect scan cannot express.
    /// Nothing broke, so it is not announced on the event stream and no
    /// strategy is blamed. It reaches the report as its own kind of thing, and
    /// [`Refusal`] has the argument for why that matters.
    ///
    /// Filed once per distinct refusal. A plan that declines the same range on
    /// two links says it once, because a reader acts on the reason rather than
    /// on the count.
    ///
    /// Public for the reason [`record_failure`](Self::record_failure) is: a
    /// caller assembling their own scan decides their own coverage, and one who
    /// could not say what they declined would produce a report claiming to have
    /// covered ground nobody looked at.
    pub fn record_refusal(&self, refusal: Refusal) {
        info!(verbosity = 1, "not covered: {}", refusal.reason());
        self.refusals.push(refusal);
    }

    /// Takes the refusals recorded so far, leaving the log empty.
    pub(crate) fn take_refusals(&self) -> Vec<Refusal> {
        self.refusals.drain()
    }

    /// The refusals filed so far, left in place.
    ///
    /// The reading counterpart of [`record_refusal`](Self::record_refusal), on
    /// the same terms [`failures_snapshot`](Self::failures_snapshot) is for
    /// failures: a caller driving strategies themselves never reaches the phase
    /// that drains these into a report.
    pub fn refusals_snapshot(&self) -> Vec<Refusal> {
        self.refusals.snapshot()
    }

    /// Files what an instrumented scanner observed about its own run.
    ///
    /// Called once per scanner, as its receive loop exits. Unlike a failure this
    /// is not announced on the event stream: it describes the run rather than
    /// changing what the scan found, and a live consumer has nothing to do with
    /// it mid-scan.
    ///
    /// Public for the same reason [`record_failure`](Self::record_failure) is: a
    /// strategy somebody else wrote should be able to account for its own run,
    /// and a report is worth less when only the built-in strategies appear in
    /// its audit.
    pub fn record_probe_stats(&self, stats: ProbeStats) {
        self.probe_stats.push(stats);
    }

    /// Takes the probe counters recorded so far, leaving the log empty.
    pub(crate) fn take_probe_stats(&self) -> Vec<ProbeStats> {
        self.probe_stats.drain()
    }

    /// The probe counters filed so far, left in place.
    ///
    /// The reading counterpart of [`record_probe_stats`](Self::record_probe_stats),
    /// for a caller driving strategies themselves: they never reach the phase
    /// that drains these into a [`ScanReport`](crate::report::ScanReport),
    /// so this is how they read what a strategy filed. Non-destructive on
    /// purpose: draining is the report's privilege, and a caller who could do
    /// it would leave the report describing a scan that recorded nothing.
    pub fn probe_stats_snapshot(&self) -> Vec<ProbeStats> {
        self.probe_stats.snapshot()
    }

    /// Takes the failures recorded so far, leaving the log empty.
    ///
    /// Called once, when a phase assembles its report. Draining rather than
    /// copying means a context that outlives its phase cannot hand the same
    /// failure to a second one.
    pub(crate) fn take_failures(&self) -> Vec<ScannerFailure> {
        self.failures.drain()
    }

    /// Records that this host could not reach `address`, so no probe was sent
    /// to it: no route or source address led there, or the neighbour never
    /// answered address resolution.
    ///
    /// Not a failure and not an event: no strategy broke and nothing about the
    /// scan's standing changes. It is recorded because the address was asked
    /// about and not covered, and a report that omitted it would leave the
    /// caller to work out from a host count why one of their targets is missing.
    pub fn record_unroutable(&self, address: IpAddr) {
        self.unroutable.insert(address);
    }

    /// Records that a discovery sweep stopped before it reached a verdict on
    /// `address`: it was never asked, or it was still owed attempts.
    ///
    /// Neither is evidence that nothing is there. A sweep reports the host it
    /// found and says nothing about the one it did not, so without this an
    /// address the sweep never reached and one that answered nothing it was
    /// asked are the same absence, and a port scan's liveness filter would
    /// skip both.
    pub fn record_unswept(&self, address: IpAddr) {
        self.unswept.insert(address);
    }

    /// Every address a discovery sweep has recorded with
    /// [`record_unswept`](Self::record_unswept), in address order.
    ///
    /// Read rather than taken, since the phase that ran the sweep and the one
    /// that filters on its result are different readers of it.
    pub fn unswept(&self) -> Vec<IpAddr> {
        self.unswept.snapshot()
    }

    /// The unroutable addresses filed so far, taken.
    pub(crate) fn take_unroutable(&self) -> Vec<IpAddr> {
        self.unroutable.drain()
    }

    /// Whether `address` has been filed as unroutable in this phase, left in
    /// place.
    pub(crate) fn is_unroutable(&self, address: IpAddr) -> bool {
        self.unroutable.contains(address)
    }

    /// Whether `address` has been filed as left early by its own budget in this
    /// phase, left in place.
    ///
    /// Unlike [`host_expired`](Self::host_expired), which is asked before a
    /// probe and files the host the moment its budget is found spent, this
    /// reads what was filed and files nothing: a host whose clock runs out
    /// after its last probe was answered for in full.
    pub(crate) fn left_early(&self, address: IpAddr) -> bool {
        self.timed_out.contains(address)
    }

    /// Files the host records at `keys` as addresses a port phase standing in
    /// for its liveness pass asked on every port and heard nothing from, and
    /// forgets those records.
    ///
    /// The pass it stood in for would have found each address silent and made
    /// no host of it, and forgetting the record here is what keeps the live
    /// store and the report the phase closes into saying the same: a caller
    /// reading [`ScanSession::hosts`] after the scan sees the hosts the report
    /// lists. The addresses go where a discovery pass files its silence, which
    /// is what the phase's
    /// [`silent`](crate::report::ScanPhase::silent) list is read from.
    ///
    /// A record a journal already wrote down stays on disk; the report drops
    /// it on read-back by the same list.
    pub(crate) fn forget_silent(&self, keys: Vec<ScopedIp>) {
        for key in keys {
            self.silent.insert(key.addr());
            self.store.remove(&key);
        }
    }

    /// Files the host records at `keys` as addresses a port phase standing in
    /// for its liveness pass heard nothing from and did not finish asking, and
    /// forgets those records.
    ///
    /// The pass it stood in for would have reached no verdict on them either
    /// way: nothing answered, which is not a host found, and not every port
    /// was asked, which is not a silence. So no host is made of them, as the
    /// pass would have made none, and they are named where that pass names
    /// what it could not decide, the phase's
    /// [`undecided`](crate::report::ScanPhase::undecided) list. Their ports
    /// stay unsettled, so a resume asks them again.
    pub(crate) fn forget_undecided(&self, keys: Vec<ScopedIp>) {
        for key in keys {
            self.undecided.insert(key.addr());
            self.store.remove(&key);
        }
    }

    /// The addresses [`forget_undecided`](Self::forget_undecided) filed,
    /// merged and taken.
    pub(crate) fn take_undecided(&self) -> IpSet {
        self.undecided.drain()
    }

    /// Whether `address` has spent the per-host budget this scan was given,
    /// starting its clock on the first probe aimed at it.
    ///
    /// The one question every pass that probes a host asks before probing it
    /// again, and the only place the answer is filed: a host that answers true
    /// here for the first time is written into the phase's
    /// [`timed_out`](crate::report::ScanPhase::timed_out) list by this call, so
    /// no strategy can leave a host early without the report saying it did.
    ///
    /// Always false for a scan with no budget, which is what keeps this cheap
    /// enough to ask per target. See
    /// [`ZondConfig::host_timeout`](crate::config::ZondConfig::host_timeout).
    pub fn host_expired(&self, address: IpAddr) -> bool {
        if !self.clocks.expired(address) {
            return false;
        }
        self.timed_out.insert(address);
        true
    }

    /// When `address` may next be probed, or `None` if it may be probed now.
    ///
    /// The question every send site asks beside
    /// [`host_expired`](Self::host_expired), and the two are different in kind:
    /// an expired host is finished with and gets written into the phase's
    /// [`timed_out`](crate::report::ScanPhase::timed_out) list, while one asked
    /// too soon is fine and will be ready at the instant this returns.
    ///
    /// **A refusal here is not a verdict.** The probe has not been sent and the
    /// port has not been settled, so a caller that drops one on this answer
    /// reports a port nobody asked about as though the target had been silent.
    /// Hold it and send it at the instant returned, or file it
    /// [`Unasked`](crate::model::port::PortState::Unasked); a scanner with
    /// nowhere to hold one should be reading
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval)
    /// as a reason not to have taken the target off its queue yet.
    ///
    /// Always `None` for a scan that set no minimum, which is what keeps this
    /// cheap enough to ask once per probe rather than once per target. See
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval).
    pub fn host_ready_at(&self, address: IpAddr, now: Instant) -> Option<Instant> {
        self.spacing.ready_at(address, now)
    }

    /// Records a probe leaving for `address`, moving its next slot.
    ///
    /// Called after the send and only for one that reached the wire: a probe the
    /// kernel refused occupied nothing and must not spend the host's slot, on
    /// the same reasoning `RawProbeScan::record_send` gives for keeping it out
    /// of the congestion window.
    pub fn host_probed(&self, address: IpAddr, now: Instant) {
        self.spacing.sent(address, now);
    }

    /// The gap this scan keeps between two probes at one address, or `None`
    /// for a scan that set none. A scanner sizing its own deadline reads it,
    /// since every probe at one host waits it out in turn. See
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval).
    pub(crate) fn host_probe_interval(&self) -> Option<Duration> {
        self.spacing.minimum
    }

    /// The addresses left early so far, taken.
    pub(crate) fn take_timed_out(&self) -> Vec<IpAddr> {
        self.timed_out.drain()
    }

    /// Records that `address` rate-limited the ICMP errors a scanner reads
    /// its verdicts from, so the ports it had no allowance to answer for
    /// read as silent; see
    /// [`ScanPhase::icmp_rate_limited`](crate::report::ScanPhase::icmp_rate_limited).
    pub(crate) fn record_icmp_rate_limited(&self, address: IpAddr) {
        self.icmp_rate_limited.insert(address);
    }

    /// The addresses found rate-limiting their ICMP errors so far, taken.
    pub(crate) fn take_icmp_rate_limited(&self) -> Vec<IpAddr> {
        self.icmp_rate_limited.drain()
    }

    /// Records that `targets` were reached by TCP connect in a phase that held
    /// the privilege its raw strategies need.
    ///
    /// For a strategy that, inside a raw phase, reaches its targets the way an
    /// unprivileged one would: loopback in any raw phase, and whatever a
    /// process's self-built frames cannot reach when frames are all it has.
    /// What such a strategy finds is connect evidence, and the phase's privilege
    /// alone would present it as raw. Ignored by a phase recorded at
    /// [`Privilege::Connect`](crate::system::privilege::Privilege::Connect),
    /// which reached everything this way. See
    /// [`ScanPhase::reached_by_connect`](crate::report::ScanPhase::reached_by_connect).
    pub fn record_reached_by_connect(&self, targets: &IpSet) {
        self.reached_by_connect.extend(targets);
    }

    /// The addresses reached by connect so far, merged and taken.
    pub(crate) fn take_reached_by_connect(&self) -> Vec<IpRange> {
        self.reached_by_connect.drain()
    }

    /// Records that this phase swept a whole link, not merely the addresses on
    /// it that were named.
    ///
    /// Called by a strategy that put a probe on the segment which every host
    /// there is required to answer. What it buys is stated on
    /// [`TargetScope::links`](crate::report::TargetScope::links): a
    /// comparison can then tell a host that appeared on a link somebody was
    /// watching from one that turned up on ground nobody had covered.
    pub fn record_sweep(&self, zone: Zone) {
        self.swept_links.insert(zone);
    }

    /// Takes the links swept so far, leaving the log empty.
    pub(crate) fn take_swept_links(&self) -> Vec<Zone> {
        self.swept_links.drain()
    }

    /// Records which switch port this machine turned out to be plugged into.
    ///
    /// Called by whatever read an announcement off a link. see
    /// [`Attachment`] for why this is a fact
    /// about the phase rather than about any host in it. A device re-announcing
    /// itself replaces the previous reading for that link and protocol rather
    /// than adding to it.
    pub fn record_attachment(&self, attachment: Attachment) {
        self.attachments.insert(attachment);
    }

    /// Takes the attachments observed so far, leaving the log empty.
    pub(crate) fn take_attachments(&self) -> Vec<Attachment> {
        self.attachments.drain()
    }

    /// Records what became of one target, for a later resume.
    ///
    /// Not the same question as the verdict: a target reaches the store with a
    /// port state, and this says whether the scan *earned* it or assigned it
    /// because the run ended. See [`Outcome`].
    pub fn record_outcome(&self, outcome: Outcome) {
        self.settlements.record(outcome);
    }

    /// Announces the stage the scan has moved into, with how much work it holds
    /// where that is known before any of it is done.
    ///
    /// Entering the stage that is already current adds to its total rather than
    /// starting it over, so service detection running once per protocol reports
    /// one stage the size of both runs rather than two stages that each restart
    /// the count.
    pub fn enter_stage(&self, stage: Stage, total: Option<u64>) {
        if self.stages.enter(stage, total) {
            let _ = self.events_tx.send(ScanEvent::StageChanged { stage });
        }
    }

    /// Counts one unit of the current stage as finished.
    ///
    /// Called where the work completes rather than where it is handed out. A
    /// stage that submits into a pool has given out all of its work long before
    /// any of it is done, and counting the handing out would fill the bar while
    /// the pool was still draining.
    pub fn stage_advanced(&self) {
        self.stages.advance();
    }

    /// Records `count` targets ending the same way, for the outcomes that carry
    /// no position. See [`Settlements::record_many`].
    pub fn record_many_outcomes(&self, outcome: Outcome, count: u64) {
        self.settlements.record_many(outcome, count);
    }

    /// Records `count` addresses a sweep left unsettled the same way, where the
    /// scan's settlements are counted in addresses.
    ///
    /// A port scan's plan is counted in address-and-port pairs, and its
    /// liveness pass asks about addresses that plan does not number. Counted
    /// beside the port targets, three hundred addresses the pass never asked
    /// would read as three hundred port targets never asked, in a tally whose
    /// unit is the port target. The pass's own account of those addresses is
    /// its phase's [`undecided`](crate::report::ScanPhase::undecided) list, so
    /// nothing is lost by leaving them out here.
    pub(crate) fn record_address_outcomes(&self, outcome: Outcome, count: u64) {
        if self.plan_stage != Stage::Ports {
            self.settlements.record_many(outcome, count);
        }
    }

    /// Records what became of one address, in a scan counted in addresses.
    ///
    /// The position comes from the plan this scan is numbered in, which the
    /// caller does not need to know: a strategy knows it asked an address and
    /// what came back, and this turns that into a position a resume can skip.
    ///
    /// Nothing is settled in two cases, and both are correct. A scan not
    /// counted in addresses has no numbering, so a port scan's liveness pass
    /// settles nothing. And an address the plan does not name has no position:
    /// a sweep finds neighbours it was never asked about, and those are findings
    /// rather than plan targets. Either way the address is asked again on the
    /// next sitting, which is the direction this has to fail in.
    ///
    /// Silence is kept whichever of those holds, because two readers need it
    /// that a position cannot serve. The port phase after a liveness pass
    /// settles the ports of a host found down, and silence the pass asked for
    /// is what earns that; see [`Outcome::Skipped`]. And every discovery phase
    /// names the addresses it reached no verdict on, which is its scope less
    /// what answered and what was asked to exhaustion; see
    /// [`ScanPhase::undecided`](crate::report::ScanPhase::undecided).
    pub fn settle_address(&self, ip: IpAddr, settled: Settled) {
        if let Some(position) = self.positions.find(ip) {
            self.record_outcome(settled.at(position));
        }
        if settled == Settled::Exhausted {
            self.silent.insert(ip);
        }
    }

    /// The addresses a discovery pass asked as many times as its policy allows
    /// and heard nothing from, merged and taken.
    ///
    /// Only these may have their ports settled as
    /// [`Skipped`](crate::journal::settle::Outcome::Skipped), and only these
    /// keep an address out of a phase's
    /// [`undecided`](crate::report::ScanPhase::undecided) list without a host
    /// found at it. An address the pass never reached a verdict on is not
    /// here, whatever kept it from one. See
    /// [`Dispatcher::screened`](crate::scanner::dispatcher::Dispatcher::screened).
    pub(crate) fn take_silent(&self) -> IpSet {
        self.silent.drain()
    }

    /// How far the scan has got, and what became of what it did not settle.
    pub fn settlements(&self) -> &Settlements {
        &self.settlements
    }

    /// Seeds the store with hosts an earlier sitting found.
    ///
    /// Merged rather than inserted, so a host this sitting has already seen
    /// keeps both readings.
    ///
    /// Each restored host is announced, because to a caller watching the stream
    /// these hosts have just appeared. They are not marked as *changed*, though:
    /// they came from the journal, and writing them straight back would be work
    /// with nothing new in it.
    ///
    /// The exclusions this sitting was given apply to what comes back, address
    /// by address, as they do in [`write_host`](Self::write_host): this is the
    /// one other way into the store, and a scan interrupted before an exclusion
    /// was added carries the addresses it now forbids in its journal. A host
    /// loses each of those, and is restored under its best remaining address
    /// where the one it was recorded under is among them. Only a host with no
    /// address left that this sitting may report is left out. A router the
    /// policy names on a restored host's path keeps its distance and loses its
    /// address, and one that sent evidence about the host keeps the evidence
    /// and loses its address, as each would have in `write_host`.
    ///
    /// The journal itself is left alone. It is an honest record of a sitting
    /// that was allowed to make it, and rewriting history to match a policy that
    /// arrived later would be the wrong repair. What changes is only what this
    /// sitting is willing to say.
    pub fn restore_hosts(&self, hosts: &[Host]) {
        let keep = |address: &IpAddr| !self.exclusions.excludes(address);
        for host in hosts {
            let mut host = host.clone();
            if !host.retain_ips(keep) {
                info!(
                    verbosity = 2,
                    "every address of {} in the journal is excluded; leaving it out of this sitting",
                    host.primary_ip()
                );
                continue;
            }
            host.withhold_intermediaries(keep);

            let key = host.scoped_ip();
            match self.store.get_mut(&key) {
                Some(mut existing) => existing.merge(host),
                None => {
                    self.store.insert(key.clone(), host);
                }
            }
            let _ = self.events_tx.send(ScanEvent::HostUpdated(key));
        }
    }

    /// What a journal needs from a running scan.
    ///
    /// Not a [`ScanContext`]. A context carries the event
    /// sender, and a checkpoint task holding one would keep the event stream
    /// open after the scan had ended, so a caller watching that stream to know
    /// when to stop would wait forever for a scan that was already over, and the
    /// checkpoint task would wait for the caller to stop it. Neither moves.
    ///
    /// A failure recorded through this reaches the report but not the stream,
    /// which is right: a checkpoint that could not be written is a fact about
    /// the journal, not about a scanning strategy.
    pub fn progress(&self) -> ScanProgress {
        ScanProgress {
            store: Arc::clone(&self.store),
            changed: Arc::clone(&self.changed),
            settlements: Arc::clone(&self.settlements),
            failures: Arc::clone(&self.failures),
            tapes: Arc::clone(&self.tapes),
        }
    }

    /// Every host found so far, cloned, ordered by the address each is keyed
    /// under.
    ///
    /// For a journal compacting its findings, which needs the whole state rather
    /// than what changed recently. Ordered for the reason
    /// [`HostStore::snapshot`] is: the one consumer writes these to disk, and a
    /// compaction whose record order came out of a concurrent map's iteration
    /// writes a different file every time it runs over the same findings.
    pub fn hosts_snapshot(&self) -> Vec<Host> {
        let mut hosts: Vec<Host> = self
            .store
            .iter()
            .map(|entry| entry.value().clone())
            .collect();
        hosts.sort_by_cached_key(Host::scoped_ip);
        hosts
    }

    /// How many hosts have been found so far.
    pub fn host_count(&self) -> usize {
        self.store.len()
    }

    /// Takes the hosts whose findings have changed since this was last called,
    /// with their current state.
    ///
    /// For a journal writing findings down as a scan produces them. Draining
    /// rather than reading, so a host is written once per change rather than
    /// once per checkpoint for the rest of the run.
    pub fn take_changed_hosts(&self) -> Vec<Host> {
        changed_since(&self.store, &self.changed)
    }

    /// The strategy failures filed so far, left in place.
    ///
    /// The reading counterpart of [`record_failure`](Self::record_failure), and
    /// the same shape as
    /// [`probe_stats_snapshot`](Self::probe_stats_snapshot) for the same
    /// reason: a caller driving strategies themselves needs to see what went
    /// wrong without waiting for a phase to close, and a live event stream only
    /// answers for a consumer that happened to be listening.
    ///
    /// Non-destructive on purpose. Draining belongs to
    /// [`PhaseRecorder::finish`](crate::scanner::recorder::PhaseRecorder::finish),
    /// and a caller who could do it here would leave the report claiming a
    /// clean run over a scan that lost work.
    pub fn failures_snapshot(&self) -> Vec<ScannerFailure> {
        self.failures.snapshot()
    }

    /// Upserts the host at `ip`, applies `update`, and unconditionally announces
    /// the change. The convenience form of [`write_host`](Self::write_host) for
    /// the paths that always record a finding worth emitting - a port state, a
    /// merged host. Returns `true` if this call created the host.
    pub fn update_host(&self, ip: impl Into<ScopedIp>, update: impl FnOnce(&mut Host)) -> bool {
        self.write_host(ip, |host| {
            update(host);
            true
        })
    }
}

/// Builds a [`ScanSession`] and the [`ScanContext`] the strategies behind it
/// write into.
///
/// Everything a session can be given beyond its defaults, most of which a
/// caller leaves alone. A builder rather than constructors chaining into each
/// other, because such a chain puts the widest of them under the narrowest
/// name, and a caller who wants one setting without another has to know each
/// one's neutral value, such as `Checkpoint::default()` for no resume point.
/// Here each is named once and there is one neutral state.
///
/// ```no_run
/// use zond_engine::scanner::session::ScanSession;
///
/// let (session, ctx) = ScanSession::builder().build();
/// # let _ = (session, ctx);
/// ```
#[must_use]
#[derive(Debug, Default)]
pub struct SessionBuilder {
    exclusions: Exclusions,
    settled: crate::journal::cursor::Checkpoint,
    positions: Positions,
    planned: Option<u64>,
    plan_stage: Stage,
    staging: Vec<Stage>,
    detections: crate::detect::Detections,
    host_timeout: Option<Duration>,
    scan_timeout: Option<Duration>,
    host_probe_interval: Option<Duration>,
    order_seed: Option<u64>,
    send_source: Vec<IpAddr>,
    /// `None` for the default, [`RAW_PRINT_PORTS`](crate::config::RAW_PRINT_PORTS).
    listen_only: Option<BTreeSet<u16>>,
}

impl SessionBuilder {
    /// Addresses the scan may not record a finding against.
    ///
    /// A caller orchestrating their own scan and honouring an exclusion policy
    /// has to set this rather than subtract the addresses from their own target
    /// list: the subtraction covers the addresses they named, and a segment
    /// sweep does not confine itself to those. See [`Exclusions`] for what each
    /// of the two enforcements is for.
    pub fn excluding(mut self, exclusions: Exclusions) -> Self {
        self.exclusions = exclusions;
        self
    }

    /// The cursor this scan checkpoints from, for one continuing an earlier
    /// sitting.
    ///
    /// Without it a resumed scan writes a cursor covering only its own sitting,
    /// and the journal forgets everything the first one settled.
    pub fn resuming(mut self, settled: &crate::journal::cursor::Checkpoint) -> Self {
        self.settled = settled.clone();
        self
    }

    /// How this scan numbers an address, for one counted in addresses.
    ///
    /// A sweep sets this so a strategy that has earned a verdict for an address
    /// can settle it without knowing where in the plan it sits; see
    /// [`ScanContext::settle_address`].
    ///
    /// A port scan leaves it alone. It is counted in address-and-port pairs and
    /// numbers them on its target stream, so the discovery strategies running
    /// inside its liveness pass settle nothing -- which is what keeps a port
    /// plan's watermark from advancing over probes nobody sent.
    pub fn counting(mut self, positions: Positions) -> Self {
        self.positions = positions;
        self
    }

    /// The key the order this scan asks its targets in is a function of.
    ///
    /// Set it and the scan walks its plan in a rearrangement of the whole index
    /// space rather than in address order, which is what keeps a sweep of a
    /// range from being the one shape every correlating sensor is written
    /// against. See [`Permutation`](crate::scanner::order::Permutation).
    ///
    /// Leave it alone and the targets come out in plan order, shuffled within a
    /// batch, which is what a scan whose plan cannot be addressed by position
    /// falls back to anyway.
    ///
    /// A caller journalling their scan should pass what the journal recorded, so
    /// a resumed sitting continues in the order the first one was going to use.
    /// [`scan_with_journal`](crate::scanner::scan_with_journal) does.
    pub fn ordering(mut self, seed: Option<u64>) -> Self {
        self.order_seed = seed;
        self
    }

    /// How many targets the plan holds, and which [`Stage`] does that work.
    ///
    /// This is the denominator [`Progress::fraction`] divides into while that
    /// stage is running, so it has to be counted in the same unit the stage
    /// settles in: addresses for a sweep, address-and-port pairs for a port
    /// scan. [`Positions::total`](crate::model::ip::set::Positions::total) and
    /// [`TargetIndex::total`](crate::model::target::TargetIndex::total) are
    /// those two counts, and each has a companion that says whether it covered
    /// the whole plan.
    ///
    /// Naming the stage is what keeps the figure honest in a scan that has more
    /// than one. A port scan runs a liveness pass first, and measuring that pass
    /// against a plan of address-and-port pairs would report nought percent for
    /// the whole of it.
    ///
    /// Leave it alone and a consumer reads a running count of what has settled
    /// with nothing to measure it against, which is all a scan of an
    /// uncountable plan can honestly offer.
    pub fn planning(mut self, stage: Stage, total: Option<u64>) -> Self {
        self.plan_stage = stage;
        self.planned = total;
        self
    }

    /// The stages this scan expects to run, in the order it will run them.
    ///
    /// What [`Progress::overall`] measures a whole run against. A superset is
    /// the right thing to pass: a stage listed here and skipped moves the figure
    /// forward over it, where a stage that runs without being listed leaves the
    /// figure sitting still until the next one that was listed.
    ///
    /// [`discover`](crate::scanner::discover) and [`scan`](crate::scanner::scan)
    /// derive this from the settings they were handed. A caller orchestrating
    /// their own scan lists the stages they mean to run, or leaves it alone and
    /// reads progress one stage at a time.
    pub fn staging(mut self, stages: Vec<Stage>) -> Self {
        self.staging = stages;
        self
    }

    /// The corpus the detection phase runs, the shipped one unless set otherwise.
    ///
    /// [`scan`](crate::scanner::scan) sets the corpus it was given here; a caller
    /// orchestrating their own scan sets it directly so their detections run in it.
    pub fn detections(mut self, detections: crate::detect::Detections) -> Self {
        self.detections = detections;
        self
    }

    /// The wall-clock budget each host gets before the scan leaves it.
    ///
    /// A caller orchestrating their own scan sets this to have the same bound
    /// [`scan`](crate::scanner::scan) applies from
    /// [`ZondConfig::host_timeout`](crate::config::ZondConfig::host_timeout).
    /// Every strategy that probes a host reads it through
    /// [`ScanContext::host_expired`].
    pub fn host_timeout(mut self, budget: Option<Duration>) -> Self {
        self.host_timeout = budget;
        self
    }

    /// The wall-clock budget the whole scan gets before it winds down.
    ///
    /// Starts when [`build`](Self::build) is called, and reaches every strategy
    /// through the [`ScanHandle`] they already read. See
    /// [`ZondConfig::scan_timeout`](crate::config::ZondConfig::scan_timeout).
    pub fn scan_timeout(mut self, budget: Option<Duration>) -> Self {
        self.scan_timeout = budget;
        self
    }

    /// The shortest gap the scan keeps between two probes aimed at one host.
    ///
    /// A caller orchestrating their own scan sets this to have the same spacing
    /// [`scan`](crate::scanner::scan) applies from
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval).
    /// Every pass that sends reads it through
    /// [`ScanContext::host_ready_at`], which is also where what the two words
    /// mean for a probe that arrives early is written down.
    pub fn host_probe_interval(mut self, minimum: Option<Duration>) -> Self {
        self.host_probe_interval = minimum;
        self
    }

    /// The source addresses the connections this scan opens are forced to, one
    /// per family.
    ///
    /// A caller orchestrating their own scan sets this to have the same pinning
    /// [`scan`](crate::scanner::scan) applies from
    /// [`ZondConfig::send_source`](crate::config::ZondConfig::send_source):
    /// every connection to a routed target, the connect scan's and the service
    /// pass's alike, leaves from the forced source and by the interface holding
    /// it, as the raw probes before them do.
    pub fn send_source(mut self, sources: Vec<IpAddr>) -> Self {
        self.send_source = sources;
        self
    }

    /// The TCP ports this scan connects to and listens on, and sends nothing.
    ///
    /// Left unset, the printers' ports,
    /// [`RAW_PRINT_PORTS`](crate::config::RAW_PRINT_PORTS), as
    /// [`scan`](crate::scanner::scan) has them by default. A caller
    /// orchestrating their own scan sets this to what
    /// [`ZondConfig::listen_only_ports`](crate::config::ZondConfig::listen_only_ports)
    /// says, and an empty set probes every port alike.
    pub fn listening_only_to(mut self, ports: BTreeSet<u16>) -> Self {
        self.listen_only = Some(ports);
        self
    }

    /// Opens the session and the context.
    ///
    /// This is where a scan's own clock starts, so a caller holding a builder
    /// for a while and building later gets the budget they asked for rather
    /// than what is left of it.
    pub fn build(self) -> (ScanSession, ScanContext) {
        let store = Arc::new(DashMap::new());
        let handle = ScanHandle::bounded(self.scan_timeout);
        let (events_tx, rx) = broadcast::channel(ScanEvents::CAPACITY);
        let settlements = Arc::new(Settlements::resuming(&self.settled));
        let stages = Arc::new(Stages::new(self.staging));

        let session = ScanSession {
            store: HostStore::new(store.clone()),
            events: ScanEvents { rx },
            handle: handle.clone(),
            progress: Progress::new(
                settlements.clone(),
                self.planned,
                self.plan_stage,
                stages.clone(),
            ),
        };

        let ctx = ScanContext {
            handle,
            store,
            events_tx,
            failures: Arc::new(FailureLog::default()),
            refusals: Arc::new(RefusalLog::default()),
            probe_stats: Arc::new(ProbeStatsLog::default()),
            unroutable: Arc::new(UnroutableLog::default()),
            timed_out: Arc::new(TimedOutLog::default()),
            icmp_rate_limited: Arc::new(RateLimitedLog::default()),
            unswept: Arc::new(UnsweptLog::default()),
            reached_by_connect: Arc::new(ConnectLog::default()),
            silent: Arc::new(SilenceLog::default()),
            undecided: Arc::new(SilenceLog::default()),
            plan_stage: self.plan_stage,
            clocks: Arc::new(HostClocks {
                budget: self.host_timeout,
                started: DashMap::new(),
            }),
            spacing: Arc::new(HostSpacing {
                minimum: self.host_probe_interval,
                last_sent: DashMap::new(),
            }),
            zones: Arc::new(OnceLock::new()),
            swept_links: Arc::new(SweptLinks::default()),
            attachments: Arc::new(Attachments::default()),
            exclusions: Arc::new(self.exclusions),
            changed: Arc::new(ChangedHosts::default()),
            stages,
            settlements,
            positions: Arc::new(self.positions),
            order_seed: self.order_seed,
            responses: Arc::new(Responses::default()),
            tapes: Arc::new(Tapes::default()),
            detections: self.detections,
            forced: Arc::new(crate::transport::dial::ForcedSources::new(
                &self.send_source,
            )),
            listen_only: Arc::new(
                self.listen_only
                    .unwrap_or_else(|| crate::config::RAW_PRINT_PORTS.into_iter().collect()),
            ),
        };

        (session, ctx)
    }
}

impl ScanSession {
    /// A session and the context the strategies behind it write into, with
    /// nothing excluded, nothing resumed and no address numbering.
    ///
    /// A caller wrapping the engine normally receives the session already built,
    /// from [`discover`](crate::scanner::discover) or
    /// [`scan`](crate::scanner::scan), and never calls this. A caller
    /// orchestrating their own scan calls it first: every strategy in
    /// [`strategy`](crate::scanner::strategy) is constructed with a
    /// [`ScanContext`], and this is where one comes from.
    ///
    /// [`builder`](Self::builder) is the same thing with any of the three
    /// settings applied.
    pub fn new() -> (Self, ScanContext) {
        Self::builder().build()
    }

    /// A session with exclusions, a resume point or an address numbering.
    ///
    /// See [`SessionBuilder`].
    pub fn builder() -> SessionBuilder {
        SessionBuilder::default()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::host::{EvidenceSource, Hop, HostStatus, StatusProtocol, StatusReason};

    /// A whole run reads as one figure that only grows, rather than one per
    /// stage that starts over each time.
    #[test]
    fn a_whole_run_reads_as_one_figure_rather_than_one_per_stage() {
        let (session, ctx) = ScanSession::builder()
            .planning(Stage::Ports, Some(4))
            .staging(vec![Stage::Ports, Stage::Services, Stage::Detections])
            .build();

        ctx.enter_stage(Stage::Ports, None);
        ctx.record_outcome(Outcome::Answered { position: 0 });
        ctx.record_outcome(Outcome::Answered { position: 1 });

        // Half of the first stage of three, which is a sixth of the run.
        let (done, total) = session.progress().overall().expect("a staged run");
        assert_eq!(
            done * 6,
            total,
            "half of one stage in three: {done}/{total}"
        );

        ctx.enter_stage(Stage::Services, Some(2));
        ctx.stage_advanced();

        // One stage behind it and half way through the second, which is half the
        // run. The figure grew across the boundary rather than starting again.
        let (done, total) = session.progress().overall().expect("a staged run");
        assert_eq!(done * 2, total, "half the run: {done}/{total}");
    }

    /// A stage that turned out to have nothing to do is stepped over.
    ///
    /// Whether services, detections and TLS have any work depends on which ports
    /// are open, so the running order is a superset and some of it never
    /// announces itself. Waiting for a stage that will never arrive would park
    /// the figure for the rest of the run.
    #[test]
    fn a_stage_with_nothing_to_do_is_stepped_over_rather_than_waited_for() {
        let (session, ctx) = ScanSession::builder()
            .staging(vec![
                Stage::Ports,
                Stage::Services,
                Stage::Detections,
                Stage::Os,
            ])
            .build();

        ctx.enter_stage(Stage::Ports, Some(1));
        ctx.stage_advanced();

        // Neither services nor detections found anything to do, so neither
        // announced itself. The run is three stages further on all the same.
        ctx.enter_stage(Stage::Os, None);

        let (done, total) = session.progress().overall().expect("a staged run");
        assert_eq!(done * 4, total * 3, "three stages of four: {done}/{total}");
    }

    /// A session nobody told a running order reports no whole-run figure, rather
    /// than inventing one out of the stages it happens to see.
    #[test]
    fn a_session_with_no_running_order_reports_no_whole_run_figure() {
        let (session, ctx) = ScanSession::new();

        ctx.enter_stage(Stage::Services, Some(4));
        ctx.stage_advanced();

        let progress = session.progress();
        assert_eq!(progress.overall(), None, "nothing said how many stages");
        assert_eq!(
            progress.counted(),
            Some((1, 4)),
            "the stage still answers for itself"
        );
    }

    /// A stage that knows its own size answers for itself, and the plan is not
    /// consulted.
    ///
    /// This is the whole point of stages. The plan of a port scan is settled
    /// long before the scan is over, and measuring the detection stage against
    /// it would report a finished run for as long as the detections took.
    #[test]
    fn a_stage_that_counted_itself_answers_for_itself() {
        let (session, ctx) = ScanSession::builder()
            .planning(Stage::Ports, Some(4))
            .build();

        // The plan, settled in full. Nothing left by its own reckoning.
        ctx.enter_stage(Stage::Ports, None);
        ctx.record_outcome(Outcome::Answered { position: 0 });
        ctx.record_outcome(Outcome::Answered { position: 1 });
        ctx.record_outcome(Outcome::Answered { position: 2 });
        ctx.record_outcome(Outcome::Answered { position: 3 });
        assert_eq!(
            session.progress().fraction(),
            Some(1.0),
            "the ports are done"
        );

        ctx.enter_stage(Stage::Detections, Some(8));
        ctx.stage_advanced();
        ctx.stage_advanced();

        let progress = session.progress();
        assert_eq!(progress.stage(), Stage::Detections);
        assert_eq!(progress.stage_done(), 2);
        assert_eq!(progress.stage_total(), Some(8));
        assert_eq!(
            progress.fraction(),
            Some(0.25),
            "a quarter through the detections, not finished with the scan"
        );
        assert_eq!(progress.settled(), 4, "the plan is still settled in full");
    }

    /// A stage nobody could size reports that it is running, not that it is at
    /// nought.
    ///
    /// A port scan's liveness pass is the case worth naming: the plan counts
    /// address-and-port pairs, the pass settles none of them, and reporting the
    /// plan's figure would show nought percent for the whole of it.
    #[test]
    fn an_unsized_stage_that_is_not_the_plans_own_reports_nothing() {
        let (session, ctx) = ScanSession::builder()
            .planning(Stage::Ports, Some(1_000))
            .build();

        ctx.enter_stage(Stage::Discovery, None);
        let progress = session.progress();
        assert_eq!(progress.stage(), Stage::Discovery);
        assert_eq!(
            progress.fraction(),
            None,
            "a liveness pass is not nought percent of a port plan"
        );

        ctx.enter_stage(Stage::Ports, None);
        assert_eq!(
            session.progress().fraction(),
            Some(0.0),
            "the stage the plan was drawn for reads from the plan"
        );
    }

    /// Entering the stage that is already current adds to it.
    ///
    /// Service detection runs once per protocol, and two entries that each reset
    /// the count would send the bar back to the start half way through one
    /// stage.
    #[test]
    fn re_entering_a_stage_adds_to_it_rather_than_starting_it_over() {
        let (mut session, ctx) = ScanSession::new();

        ctx.enter_stage(Stage::Services, Some(3));
        ctx.stage_advanced();
        ctx.enter_stage(Stage::Services, Some(2));

        let progress = session.progress().clone();
        assert_eq!(progress.stage_total(), Some(5), "both runs' ports");
        assert_eq!(progress.stage_done(), 1, "and the one already finished");

        // One announcement, not two: the stage did not change the second time.
        let mut announced = 0;
        while let Some(event) = session.events().try_recv() {
            if matches!(event, ScanEvent::StageChanged { .. }) {
                announced += 1;
            }
        }
        assert_eq!(announced, 1, "one stage, announced once");
    }

    /// Every stage has a place in the list, and the list is in running order.
    ///
    /// The list is what a front end mapping stages onto a protocol of its own
    /// checks itself against, so a variant missing from it is a stage that
    /// front end never learns exists.
    #[test]
    fn the_list_of_stages_holds_every_one_of_them_in_running_order() {
        let codes: Vec<u8> = Stage::ALL.iter().map(|stage| stage.code()).collect();
        let mut sorted = codes.clone();
        sorted.sort_unstable();
        sorted.dedup();

        assert_eq!(codes, sorted, "the stages are listed in the order they run");
        assert_eq!(
            codes.len(),
            Stage::ALL.len(),
            "a stage is listed once and no stage twice"
        );

        for stage in Stage::ALL {
            assert_eq!(
                Stage::from_code(stage.code()),
                stage,
                "{stage} does not survive its own code"
            );
        }
    }

    /// Moving to a stage announces it, naming the stage moved to.
    #[test]
    fn a_stage_announces_itself_as_it_begins() {
        let (mut session, ctx) = ScanSession::new();

        ctx.enter_stage(Stage::Os, None);

        let Some(ScanEvent::StageChanged { stage }) = session.events().try_recv() else {
            panic!("entering a stage announces it");
        };
        assert_eq!(stage, Stage::Os);
    }

    /// A scan whose plan was never counted still counts what it settles.
    ///
    /// The two halves are independent, and this is the pairing a front end has
    /// to handle: a running total with nothing to divide it into. It is what a
    /// listener and a sweep of an IPv6 range too wide to number both look like.
    #[test]
    fn an_uncounted_plan_settles_targets_but_reports_no_fraction() {
        let (session, ctx) = ScanSession::new();

        ctx.record_outcome(Outcome::Answered { position: 0 });
        ctx.record_outcome(Outcome::Exhausted { position: 1 });

        let progress = session.progress();
        assert_eq!(progress.settled(), 2, "both targets settled");
        assert_eq!(
            progress.planned(),
            None,
            "nothing said how big the plan was"
        );
        assert_eq!(
            progress.fraction(),
            None,
            "so there is nothing to divide into"
        );
        assert_eq!(progress.remaining(), None);
    }

    /// The fraction is settled against the plan, and both move as the scan does.
    #[test]
    fn settling_targets_advances_the_fraction() {
        let (session, ctx) = ScanSession::builder()
            .planning(Stage::Discovery, Some(4))
            .build();

        assert_eq!(
            session.progress().fraction(),
            Some(0.0),
            "nothing settled yet"
        );

        ctx.record_outcome(Outcome::Answered { position: 0 });
        ctx.record_outcome(Outcome::Skipped { position: 1 });

        let progress = session.progress();
        assert_eq!(progress.settled(), 2);
        assert_eq!(progress.remaining(), Some(2));
        let fraction = progress.fraction().expect("a counted plan has a fraction");
        assert!(
            (fraction - 0.5).abs() < f64::EPSILON,
            "two of four settled is half the plan, got {fraction}"
        );
    }

    /// An outcome that settles nothing moves the scan no further through its
    /// plan.
    ///
    /// `Unasked` is what a scan that stopped early leaves behind, and counting
    /// it would draw a full bar over a run that did not finish. The short bar is
    /// the accurate one.
    #[test]
    fn an_unsettled_outcome_does_not_advance_the_plan() {
        let (session, ctx) = ScanSession::builder()
            .planning(Stage::Discovery, Some(2))
            .build();

        ctx.record_outcome(Outcome::Answered { position: 0 });
        ctx.record_many_outcomes(Outcome::Unasked, 1);

        let progress = session.progress();
        assert_eq!(progress.settled(), 1, "only the answered target settled");
        assert_eq!(
            progress.remaining(),
            Some(1),
            "the unasked one is still owed"
        );
    }

    /// A resumed sitting measures against the whole job rather than its own
    /// share of it.
    ///
    /// The numerator carries what earlier sittings settled, so the denominator
    /// has to be the whole plan or the bar would restart at zero every time a
    /// scan was continued.
    #[test]
    fn a_resumed_sitting_starts_part_way_through_the_plan() {
        let earlier = crate::journal::cursor::Checkpoint::new(6, []);
        let (session, ctx) = ScanSession::builder()
            .resuming(&earlier)
            .planning(Stage::Discovery, Some(8))
            .build();

        assert_eq!(
            session.progress().settled(),
            6,
            "what the earlier sitting settled is already covered"
        );

        ctx.record_outcome(Outcome::Answered { position: 6 });

        let fraction = session
            .progress()
            .fraction()
            .expect("a counted plan has a fraction");
        assert!(
            (fraction - 0.875).abs() < f64::EPSILON,
            "seven of eight, got {fraction}"
        );
    }

    /// An empty plan has nothing left to do, and a plan cannot be overshot.
    #[test]
    fn a_fraction_saturates_rather_than_passing_one() {
        let (empty, _ctx) = ScanSession::builder()
            .planning(Stage::Discovery, Some(0))
            .build();
        assert_eq!(
            empty.progress().fraction(),
            Some(1.0),
            "an empty plan is complete"
        );

        let (session, ctx) = ScanSession::builder()
            .planning(Stage::Discovery, Some(1))
            .build();
        ctx.record_outcome(Outcome::Answered { position: 0 });
        ctx.record_outcome(Outcome::Answered { position: 1 });
        assert_eq!(
            session.progress().fraction(),
            Some(1.0),
            "more settled than planned still reads as done"
        );
        assert_eq!(session.progress().remaining(), Some(0));
    }

    /// The gate, at the one place every finding in the engine passes through.
    ///
    /// Written against `write_host` directly rather than through a scan because
    /// the property is about this function and not about any scanner: a reply
    /// from an excluded address leaves no host, emits no event, and reports
    /// itself as having created nothing. What a scanner does with the `false` is
    /// the scanner's business; that it gets one is this test's.
    ///
    /// The `edit` closure panics on purpose. A drop that ran the caller's
    /// closure and then discarded the result would pass every assertion below
    /// while still letting a scanner's own bookkeeping, a deadline update, a
    /// counter, a hostname lookup keyed off the edit, run for a host nobody
    /// may look at.
    #[test]
    fn an_excluded_address_reaches_neither_the_store_nor_the_stream() {
        let excluded: IpAddr = "198.51.100.7".parse().expect("literal");
        let allowed: IpAddr = "203.0.113.7".parse().expect("literal");

        let mut ips = crate::model::ip::set::IpSet::new();
        ips.insert_range("198.51.100.0/24".parse().expect("a valid range"));
        let (mut session, ctx) = ScanSession::builder()
            .excluding(Exclusions::new(ips))
            .build();

        assert!(
            !ctx.write_host(excluded, |_| unreachable!(
                "an excluded address must not reach the caller's edit"
            )),
            "an excluded address is never reported as a new host"
        );
        assert!(ctx.write_host(allowed, |_| true));

        assert_eq!(ctx.store.len(), 1);
        assert!(!ctx.store.contains_key(&ScopedIp::unscoped(excluded)));

        // Exactly one announcement, for the address that was allowed to answer.
        let ScanEvent::HostUpdated(announced) =
            session.events().try_recv().expect("the allowed host")
        else {
            panic!("expected a host update");
        };
        assert_eq!(announced, ScopedIp::unscoped(allowed));
        assert!(session.events().try_recv().is_none());
    }

    /// The store's key, at the one address family where a bare address is not
    /// one. `fe80::1` names a different machine on every segment, so a host
    /// watching two of them finds two neighbours under one number.
    ///
    /// Keyed by the bare address, the second write would land on the first's
    /// entry, and one machine's hardware address, roles and round trips would be
    /// folded into another machine's record: under the wrong interface, since
    /// `Host::set_zone` keeps the first zone it is given.
    #[test]
    fn two_link_locals_on_different_segments_are_two_hosts() {
        let shared: IpAddr = "fe80::1".parse().expect("literal");
        let (_session, ctx) = ScanSession::new();

        ctx.write_host(ScopedIp::scoped(shared, Zone::new(1, "en0")), |host| {
            host.set_status(HostStatus::Up);
            true
        });
        ctx.write_host(ScopedIp::scoped(shared, Zone::new(2, "en1")), |host| {
            host.set_status(HostStatus::Up);
            true
        });

        assert_eq!(ctx.store.len(), 2, "two segments, two machines");

        // And each knows its own link, taken from the key it was created under
        // rather than from whichever scanner remembered to say.
        let mut zones: Vec<String> = ctx
            .store
            .iter()
            .filter_map(|entry| entry.value().zone().map(|zone| zone.name().to_owned()))
            .collect();
        zones.sort();
        assert_eq!(zones, ["en0", "en1"]);
    }

    /// A port scan addresses its targets one at a time and holds the address
    /// bare, so its verdicts arrive here with no interface on them. They belong
    /// to the host the sweep found on the interface the scan named, not to a
    /// second record beside it.
    ///
    /// Filed apart, a scoped link-local target would come back as two hosts,
    /// one carrying the hardware address and the NDP round trip, the other the
    /// ports.
    #[test]
    fn a_port_verdict_on_a_bare_link_local_lands_on_the_host_the_scan_named() {
        use crate::model::ip::range::Ipv6Range;

        let address: IpAddr = "fe80::1".parse().expect("literal");
        let (_session, ctx) = ScanSession::new();

        let mut zones = ZoneMap::new();
        let IpAddr::V6(v6) = address else {
            panic!("a v6 literal");
        };
        zones.insert(
            Ipv6Range::scoped(v6, v6, Some(1)).expect("a scoped range"),
            &[(1, "en0")],
        );
        ctx.learn_zones(zones);

        ctx.write_host(ScopedIp::scoped(address, Zone::new(1, "en0")), |host| {
            host.set_status(HostStatus::Up);
            true
        });
        ctx.write_host(address, |host| {
            host.set_status(HostStatus::Up);
            true
        });

        assert_eq!(ctx.store.len(), 1, "one machine, one record");
        assert!(
            ctx.read_host(address, |host| host.zone().is_some())
                .expect("the bare address reaches it too"),
            "and it is still the host on en0"
        );
    }

    /// A global address is the same machine through whichever interface answered
    /// it, so the zone is dropped from the key and two sightings are one host.
    ///
    /// The other half of the rule above: a key that carried the interface for
    /// *every* address would split every dual-homed host in two.
    #[test]
    fn one_global_address_seen_on_two_interfaces_is_one_host() {
        let global: IpAddr = "2001:db8::1".parse().expect("literal");
        let (_session, ctx) = ScanSession::new();

        ctx.write_host(ScopedIp::scoped(global, Zone::new(1, "en0")), |_| true);
        ctx.write_host(ScopedIp::scoped(global, Zone::new(2, "en1")), |_| true);

        assert_eq!(ctx.store.len(), 1, "one address, one machine");
    }

    /// The round trip every phase after discovery depends on: a strategy reads
    /// the addresses the store holds, decides something about one, and writes it
    /// back. Written back under anything but the key it was read by, the finding
    /// lands in a second entry and one host becomes two, each holding half of
    /// what was found.
    #[test]
    fn a_finding_written_back_under_a_key_from_the_store_lands_on_the_same_host() {
        let shared: IpAddr = "fe80::1".parse().expect("literal");
        let (_session, ctx) = ScanSession::new();

        ctx.write_host(ScopedIp::scoped(shared, Zone::new(1, "en0")), |host| {
            host.set_status(HostStatus::Up);
            true
        });

        for key in ctx.host_addresses() {
            ctx.write_host(key, |host| {
                host.add_reason(StatusReason::new(StatusProtocol::IcmpEcho, "echo answered"));
                true
            });
        }

        assert_eq!(ctx.store.len(), 1, "the same host, enriched");
        assert_eq!(
            ctx.store
                .iter()
                .next()
                .expect("the host")
                .value()
                .reasons()
                .len(),
            1,
            "and the finding reached it"
        );
    }

    #[test]
    fn a_failure_survives_a_consumer_that_never_listens() {
        let (session, ctx) = ScanSession::new();
        // The case this exists for: a caller that awaits the scan and reads the
        // store at the end, never touching the event stream.
        drop(session);

        ctx.record_failure(ScannerKind::Routed, "raw socket unavailable".into());

        let failures = ctx.take_failures();
        assert_eq!(failures.len(), 1);
        assert_eq!(failures[0].scanner(), ScannerKind::Routed);
        assert_eq!(failures[0].reason(), "raw socket unavailable");
    }

    #[test]
    fn a_failure_reaches_both_the_log_and_the_stream() {
        let (mut session, ctx) = ScanSession::new();

        ctx.record_failure(ScannerKind::Local, "eth0: no address".into());

        match session.events().try_recv() {
            Some(ScanEvent::ScannerFailed { scanner, reason }) => {
                assert_eq!(scanner, ScannerKind::Local);
                assert_eq!(reason, "eth0: no address");
            }
            other => panic!("expected a ScannerFailed event, got {other:?}"),
        }
        assert_eq!(ctx.take_failures().len(), 1);
    }

    /// A caller driving strategies themselves reads failures without closing a
    /// phase, so the snapshot has to leave the log alone. Draining here would
    /// take the failure out from under the report that is supposed to carry it.
    #[test]
    fn snapshotting_failures_leaves_them_for_the_report() {
        let (_session, ctx) = ScanSession::new();
        ctx.record_failure(ScannerKind::Local, "eth0: no address".into());

        assert_eq!(ctx.failures_snapshot().len(), 1);
        assert_eq!(ctx.failures_snapshot().len(), 1, "reading is not taking");
        assert_eq!(ctx.take_failures().len(), 1, "and the report still gets it");
    }

    #[test]
    fn taking_failures_empties_the_log() {
        let (_session, ctx) = ScanSession::new();
        ctx.record_failure(ScannerKind::Connect, "refused".into());

        assert_eq!(ctx.take_failures().len(), 1);
        // A context outliving its phase must not hand the same failure to a
        // second report.
        assert!(ctx.take_failures().is_empty());
    }

    #[test]
    fn failures_from_every_clone_land_in_one_log() {
        let (_session, ctx) = ScanSession::new();
        let clone = ctx.clone();

        ctx.record_failure(ScannerKind::Local, "eth0".into());
        clone.record_failure(ScannerKind::Routed, "gateway".into());

        // Each strategy gets its own clone of the context; the report is
        // assembled from one of them and must see all of it.
        assert_eq!(ctx.take_failures().len(), 2);
    }

    /// A session built to continue an earlier sitting starts from its progress.
    ///
    /// Without this the resumed scan's first checkpoint rolls the cursor back to
    /// what its own sitting settled, and everything the first one did is
    /// forgotten: silently, since both scans report success.
    #[test]
    fn a_resuming_session_starts_from_the_earlier_cursor() {
        use crate::journal::cursor::Checkpoint;

        let settled = Checkpoint {
            watermark: 12,
            settled_above: vec![14],
        };
        let (_session, ctx) = ScanSession::builder()
            .excluding(Exclusions::none())
            .resuming(&settled)
            .build();

        assert_eq!(ctx.settlements().settled_count(), 13);
        assert_eq!(ctx.settlements().checkpoint(), settled);

        // A fresh session has nothing inherited.
        let (_session, fresh) = ScanSession::new();
        assert_eq!(fresh.settlements().settled_count(), 0);
    }

    /// What a watcher is told and what a journal writes are two questions.
    ///
    /// An enrichment pass adding evidence to a host already announced answers
    /// `false`: there is nothing new to tell somebody watching a scan, and the
    /// echo probe says exactly that for a host the liveness pass already found.
    /// The record still moved, and a journal that took the same answer would
    /// give back a host missing whatever the pass learned.
    #[test]
    fn a_write_nobody_needs_announcing_is_still_a_write() {
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");
        let (mut session, ctx) = ScanSession::new();

        // Found, announced, and written down.
        ctx.update_host(ip, |host| host.set_status(HostStatus::Up));
        assert_eq!(ctx.take_changed_hosts().len(), 1);
        assert!(
            session.events().try_recv().is_some(),
            "a new host is announced"
        );

        // And then enriched, which is worth writing and not worth announcing.
        ctx.write_host(ip, |host| {
            host.record_evidence(
                HostStatus::Up,
                StatusReason::new(StatusProtocol::IcmpEcho, "echo reply to an OS probe"),
            );
            false
        });

        let changed = ctx.take_changed_hosts();
        assert_eq!(
            changed.len(),
            1,
            "the record moved, so a journal has something to write"
        );
        assert!(
            changed[0]
                .reasons()
                .iter()
                .any(|reason| reason.protocol == StatusProtocol::IcmpEcho),
            "and what it writes is what the pass learned"
        );
        assert!(
            session.events().try_recv().is_none(),
            "a host already announced is not announced again"
        );
    }

    /// The bound, at the size the stream is built with.
    ///
    /// A scan emits an event per meaningful change, so a host with a thousand
    /// open ports announces itself a thousand times. Nothing here reads the
    /// stream until the writing is over, which is the case the bound exists
    /// for: the scan runs to the end, the store holds everything it found, and
    /// what the buffer could not keep is declared rather than dropped in
    /// silence.
    #[test]
    fn a_stream_nobody_reads_drops_the_oldest_and_says_how_many() {
        let flooded: IpAddr = "192.0.2.1".parse().expect("literal");
        let last: IpAddr = "192.0.2.2".parse().expect("literal");
        let (mut session, ctx) = ScanSession::new();

        let overflow = 64;
        let sent = ScanEvents::CAPACITY + overflow;
        for _ in 0..sent - 1 {
            ctx.update_host(flooded, |host| host.set_status(HostStatus::Up));
        }
        ctx.update_host(last, |host| host.set_status(HostStatus::Up));

        assert_eq!(
            ctx.store.len(),
            2,
            "a full event buffer does not stop the scan writing findings"
        );

        let mut dropped = 0u64;
        let mut delivered = Vec::new();
        while let Some(event) = session.events().try_recv() {
            match event {
                ScanEvent::EventsDropped { count } => dropped += count,
                ScanEvent::HostUpdated(ip) => delivered.push(ip),
                other => panic!("unexpected event {other:?}"),
            }
        }

        assert_eq!(
            delivered.len(),
            ScanEvents::CAPACITY,
            "the stream holds its stated capacity and no more"
        );
        assert_eq!(
            dropped as usize + delivered.len(),
            sent,
            "every event is either delivered or declared missing"
        );
        assert_eq!(
            delivered.last(),
            Some(&ScopedIp::unscoped(last)),
            "the newest event survives, which is what drop-oldest means"
        );
    }

    /// A scan with no budget answers `false` for every host, however many times
    /// it is asked, and files nothing.
    #[test]
    fn a_scan_with_no_host_budget_leaves_no_host() {
        let (_session, ctx) = ScanSession::new();
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");

        assert!(!ctx.host_expired(ip));
        assert!(!ctx.host_expired(ip));
        assert!(ctx.take_timed_out().is_empty());
    }

    /// A spent budget is answered for every pass that asks, and the address is
    /// filed once however many of them do.
    #[test]
    fn a_spent_host_budget_is_filed_once() {
        let (_session, ctx) = ScanSession::builder()
            .host_timeout(Some(Duration::ZERO))
            .build();
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");

        assert!(ctx.host_expired(ip));
        assert!(ctx.host_expired(ip));
        assert_eq!(ctx.take_timed_out(), vec![ip]);
    }

    /// A scan with no gap set answers every question with "now" and never
    /// touches the map, which is what makes it cheap enough to ask per probe.
    #[test]
    fn a_scan_with_no_gap_never_holds_a_probe() {
        let (_session, ctx) = ScanSession::new();
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");
        let now = Instant::now();

        assert!(ctx.host_ready_at(ip, now).is_none());
        ctx.host_probed(ip, now);
        assert!(
            ctx.host_ready_at(ip, now).is_none(),
            "a recorded send moves nothing while there is no gap to move it against"
        );
    }

    /// The longest gap a caller can write holds a host's next probe past the
    /// end of any scan, not a panic: `Duration::MAX` after the last probe is
    /// past what a clock can count to.
    #[test]
    fn the_longest_gap_holds_a_host_rather_than_panicking() {
        let (_session, ctx) = ScanSession::builder()
            .host_probe_interval(Some(Duration::MAX))
            .build();
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");
        let now = Instant::now();

        ctx.host_probed(ip, now);
        let ready = ctx.host_ready_at(ip, now).expect("asked too recently");
        assert!(ready > now + Duration::from_secs(365 * 24 * 60 * 60));
    }

    /// A host is ready until it is probed, and then not until the gap has run.
    ///
    /// The first half is what lets a sweep send a first attempt without
    /// consulting anything: an address this scan has never asked about has no
    /// earlier probe to be too close to.
    #[test]
    fn a_gap_starts_at_the_first_probe_and_runs_from_the_last() {
        let gap = Duration::from_secs(3600);
        let (_session, ctx) = ScanSession::builder()
            .host_probe_interval(Some(gap))
            .build();
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");
        let now = Instant::now();

        assert!(
            ctx.host_ready_at(ip, now).is_none(),
            "an address nothing has probed is ready"
        );

        ctx.host_probed(ip, now);
        let ready = ctx.host_ready_at(ip, now).expect("asked too recently");
        assert_eq!(ready, now + gap);

        assert!(
            ctx.host_ready_at(ip, now + gap).is_none(),
            "the gap having run, the host is ready again"
        );
    }

    /// One host's gap says nothing about another's.
    ///
    /// The bound is per source and destination, which is the whole reason it is
    /// not `max_probe_rate`: a scan spaced at one address must not be spaced
    /// across the range.
    #[test]
    fn a_gap_at_one_host_leaves_every_other_host_ready() {
        let (_session, ctx) = ScanSession::builder()
            .host_probe_interval(Some(Duration::from_secs(3600)))
            .build();
        let probed: IpAddr = "192.0.2.1".parse().expect("an address");
        let other: IpAddr = "192.0.2.2".parse().expect("an address");
        let now = Instant::now();

        ctx.host_probed(probed, now);

        assert!(ctx.host_ready_at(probed, now).is_some());
        assert!(ctx.host_ready_at(other, now).is_none());
    }

    /// The clock starts on the first probe aimed at a host rather than when the
    /// phase did, so a host the scan has not reached yet still has its whole
    /// budget when it gets there.
    #[test]
    fn a_budget_still_running_leaves_the_host_alone() {
        let (_session, ctx) = ScanSession::builder()
            .host_timeout(Some(Duration::from_secs(3600)))
            .build();
        let ip: IpAddr = "192.0.2.1".parse().expect("an address");

        assert!(!ctx.host_expired(ip));
        assert!(ctx.take_timed_out().is_empty());
    }

    /// **A resume does not restore what this sitting is forbidden to report.**
    ///
    /// `Exclusions` promises that no excluded address appears in the report, and
    /// names the two places it is enforced. `restore_hosts` is a third way into
    /// the store, and one going through neither would let a scan interrupted
    /// before an exclusion was added bring the forbidden addresses back with it
    /// — under the operator's *current* configuration, in the engine's own
    /// continuation of its own scan.
    #[test]
    fn a_resume_leaves_out_an_address_this_sitting_may_not_report() {
        let excluded: IpAddr = "198.51.100.7".parse().expect("literal");
        let allowed: IpAddr = "203.0.113.7".parse().expect("literal");

        let mut ips = crate::model::ip::set::IpSet::new();
        ips.insert_range("198.51.100.0/24".parse().expect("a valid range"));
        let (mut session, ctx) = ScanSession::builder()
            .excluding(Exclusions::new(ips))
            .build();

        let restored = |ip: IpAddr| {
            let mut host = Host::new(ip);
            host.set_status(HostStatus::Up);
            host
        };
        ctx.restore_hosts(&[restored(excluded), restored(allowed)]);

        assert!(
            !ctx.store.contains_key(&ScopedIp::unscoped(excluded)),
            "the journal's own record of an excluded address must not come back"
        );
        assert!(
            ctx.store.contains_key(&ScopedIp::unscoped(allowed)),
            "and everything else still does"
        );
        assert_eq!(ctx.store.len(), 1);

        // One announcement, for the one host that was restored.
        let Some(ScanEvent::HostUpdated(announced)) = session.events().try_recv() else {
            panic!("a restored host is announced");
        };
        assert_eq!(announced.addr(), allowed);
        assert!(
            session.events().try_recv().is_none(),
            "an excluded address is not announced either"
        );
    }

    /// A session forbidding exactly `address`.
    fn forbidding(address: IpAddr) -> (ScanSession, ScanContext) {
        let mut ips = crate::model::ip::set::IpSet::new();
        ips.insert(address);
        ScanSession::builder()
            .excluding(Exclusions::new(ips))
            .build()
    }

    /// **What an edit attaches under a permitted key is held to the policy
    /// too.**
    ///
    /// The gate tests the key, and four callers add addresses inside the edit:
    /// the local sweep as a host's other replies arrive, listen mode merging a
    /// later sighting, hostname resolution folding in an mDNS record's other
    /// addresses, and the resume path. Every one of them passes the key, so a
    /// test of the key alone let an excluded address into the report beside it.
    #[test]
    fn an_address_an_edit_attaches_is_held_to_the_exclusions() {
        let key: IpAddr = "192.0.2.60".parse().expect("literal");
        let excluded: IpAddr = "192.0.2.61".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        ctx.write_host(key, |host| host.add_ip(excluded));

        let ips = ctx
            .read_host(key, |host| host.ips().clone())
            .expect("the permitted key is recorded");
        assert!(!ips.contains(&excluded), "{ips:?}");
        assert!(ips.contains(&key));
    }

    /// An excluded address never leads a host, which is the half that matters
    /// most: the address a host leads with is the one the service, SNMP, TLS
    /// and detection passes connect to. A global IPv6 address outranks a
    /// link-local, so one attached to a neighbour found at its link-local would
    /// take the lead from it.
    #[test]
    fn an_excluded_address_does_not_become_the_one_a_host_is_reached_at() {
        let key: IpAddr = "fe80::10".parse().expect("literal");
        let excluded: IpAddr = "2001:db8::5".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        ctx.write_host(key, |host| host.consider_primary_ip(excluded));

        let (primary, ips) = ctx
            .read_host(key, |host| (host.primary_ip(), host.ips().clone()))
            .expect("the permitted key is recorded");
        assert_eq!(primary, key, "led by the address the policy allows");
        assert!(!ips.contains(&excluded), "{ips:?}");
    }

    /// A path three routers long, whose second router is `router`.
    fn traced_through(target: IpAddr, router: IpAddr) -> [Hop; 3] {
        [
            Hop::answered(
                1,
                "203.0.113.1".parse().expect("literal"),
                Some(Duration::from_millis(1)),
            ),
            Hop::answered(2, router, Some(Duration::from_millis(4))),
            Hop::answered(3, target, None),
        ]
    }

    /// **A router the policy forbids keeps its distance on a traced host's
    /// path and loses its address.**
    ///
    /// A trace addresses nothing to the routers on the way: each hop is a
    /// router discarding a probe addressed to the host being traced. So the
    /// sending half of the policy holds for them without help, and the
    /// recording half is the one a path can break. The router answered, so
    /// the distance is not silent, and it is not dropped either, since a path
    /// with no entry where a router stood reads as though nothing were known
    /// there. What goes is everything that is about the router itself.
    #[test]
    fn a_router_the_exclusions_forbid_is_withheld_from_a_traced_hosts_path() {
        let target: IpAddr = "203.0.113.9".parse().expect("literal");
        let excluded: IpAddr = "198.51.100.1".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        ctx.write_host(target, |host| {
            for hop in traced_through(target, excluded) {
                host.record_hop(hop);
            }
            true
        });

        let path = ctx
            .read_host(target, |host| host.path().clone())
            .expect("the traced host is recorded");
        assert!(
            path.hops()
                .iter()
                .all(|hop| hop.address() != Some(excluded)),
            "{path:?}"
        );
        let at_two = path.hops()[1];
        assert_eq!(at_two.distance(), 2, "the router keeps its place");
        assert!(at_two.is_withheld(), "a router answered there: {at_two:?}");
        assert_eq!(at_two.rtt(), None, "its timing is a fact about the router");
        assert_eq!(path.length(), Some(3));
        assert_eq!(path.at(1), Some("203.0.113.1".parse().expect("literal")));
    }

    /// And a journal written before the router was excluded does not bring it
    /// back, since the resume path reaches the store without `write_host`.
    #[test]
    fn a_resume_withholds_a_router_this_sitting_may_not_report() {
        let target: IpAddr = "203.0.113.9".parse().expect("literal");
        let excluded: IpAddr = "198.51.100.1".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        let mut journalled = Host::new(target);
        for hop in traced_through(target, excluded) {
            journalled.record_hop(hop);
        }
        ctx.restore_hosts(&[journalled]);

        let path = ctx
            .read_host(target, |host| host.path().clone())
            .expect("the host is restored");
        assert!(
            path.hops()
                .iter()
                .all(|hop| hop.address() != Some(excluded)),
            "{path:?}"
        );
        assert!(path.hops()[1].is_withheld(), "{path:?}");
    }

    /// A host-down reason sent by `sender` rather than by the host it is about.
    fn unreachable_from(sender: IpAddr) -> StatusReason {
        StatusReason::new(StatusProtocol::IcmpUnreachable, "destination unreachable")
            .from_source(sender)
    }

    /// **A middlebox the policy forbids is withheld from the evidence it sent
    /// about a permitted host, and the evidence is kept.**
    ///
    /// An ICMP unreachable about a probed host arrives from whatever router or
    /// firewall stood in the way, which nothing addressed. Its sender is the
    /// same kind of claim as a router on a traced path, and the policy holds for
    /// it the same way: the finding is about the host and stays, and the address
    /// that sent it goes. Cleared rather than withheld, the reason would say the
    /// host answered for itself, which is the one reading a middlebox's message
    /// must never be given.
    #[test]
    fn an_excluded_middlebox_is_withheld_from_a_permitted_hosts_evidence() {
        let target: IpAddr = "203.0.113.9".parse().expect("literal");
        let excluded: IpAddr = "198.51.100.1".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        ctx.write_host(target, |host| {
            host.record_evidence(HostStatus::Down, unreachable_from(excluded));
            true
        });

        let (status, reasons) = ctx
            .read_host(target, |host| (host.status(), host.reasons().clone()))
            .expect("the host the evidence is about is recorded");
        assert_eq!(status, HostStatus::Down, "the evidence still counts");
        let sources: Vec<EvidenceSource> = reasons.iter().map(|reason| reason.source).collect();
        assert_eq!(sources, [EvidenceSource::Withheld], "{reasons:?}");
    }

    /// And a journal written before the middlebox was excluded does not bring
    /// its address back, since the resume path reaches the store without
    /// `write_host`.
    #[test]
    fn a_resume_withholds_a_middlebox_this_sitting_may_not_report() {
        let target: IpAddr = "203.0.113.9".parse().expect("literal");
        let excluded: IpAddr = "198.51.100.1".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        let mut journalled = Host::new(target);
        journalled.record_evidence(HostStatus::Down, unreachable_from(excluded));
        ctx.restore_hosts(&[journalled]);

        let sources: Vec<EvidenceSource> = ctx
            .read_host(target, |host| {
                host.reasons().iter().map(|reason| reason.source).collect()
            })
            .expect("the host is restored");
        assert_eq!(sources, [EvidenceSource::Withheld]);
    }

    /// The resume path, which writes into the store without going through
    /// `write_host`, holds a restored host's other addresses to the policy as
    /// well as the one it is keyed by.
    #[test]
    fn a_resume_brings_back_none_of_a_hosts_excluded_addresses() {
        let key: IpAddr = "192.0.2.60".parse().expect("literal");
        let excluded: IpAddr = "192.0.2.61".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        let mut host = Host::new(key);
        host.add_ip(excluded);
        ctx.restore_hosts(&[host]);

        let ips = ctx
            .read_host(key, |host| host.ips().clone())
            .expect("the host is restored");
        assert!(!ips.contains(&excluded), "{ips:?}");
    }

    /// And a host an earlier sitting recorded under an address excluded since
    /// is restored under its best remaining one, rather than dropped along with
    /// every address it was found at that the policy still allows.
    #[test]
    fn a_resumed_host_led_by_an_excluded_address_is_kept_at_its_others() {
        let other: IpAddr = "fe80::10".parse().expect("literal");
        let excluded: IpAddr = "2001:db8::5".parse().expect("literal");
        let (_session, ctx) = forbidding(excluded);

        let mut host = Host::new(other);
        host.consider_primary_ip(excluded);
        host.set_status(HostStatus::Up);
        assert_eq!(host.primary_ip(), excluded, "test premise");
        ctx.restore_hosts(&[host]);

        let (primary, ips) = ctx
            .read_host(other, |host| (host.primary_ip(), host.ips().clone()))
            .expect("the host is kept at the address the policy allows");
        assert_eq!(primary, other);
        assert!(!ips.contains(&excluded), "{ips:?}");
    }

    /// **A port scan's settlements count port targets, not the addresses its
    /// liveness pass left.** Its plan is numbered in address-and-port pairs, so
    /// three hundred addresses a stopped pass never asked are not three
    /// hundred port targets never asked. A sweep's plan is its addresses, and
    /// there they count.
    #[test]
    fn a_liveness_pass_leaves_a_port_scans_counters_alone() {
        let (_session, ports) = ScanSession::builder()
            .planning(Stage::Ports, Some(1_024))
            .build();
        ports.record_address_outcomes(Outcome::Unasked, 300);
        assert_eq!(ports.settlements().count(Outcome::Unasked), 0);

        let (_session, sweep) = ScanSession::builder()
            .planning(Stage::Discovery, Some(1_024))
            .build();
        sweep.record_address_outcomes(Outcome::Unasked, 300);
        assert_eq!(sweep.settlements().count(Outcome::Unasked), 300);
    }
}