zond-engine 0.18.0

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

//! # Service Fingerprinting
//!
//! Identifies the service, product, and version behind an open port. This is
//! distinct from discovery (which ports are alive); fingerprinting answers
//! *what is running there*.
//!
//! ## Shape
//!
//! ```text
//! open port ─▶ probe I/O (async) ─▶ responses ─▶ analyzers (CPU, off-reactor)
//!                                                     │
//!                                              Vec<Evidence>
//!                                                     ▼
//!                                        Resolver ─▶ ServiceVerdict ─▶ Service
//! ```
//!
//! * [`model`] is the shared vocabulary: [`Evidence`], [`ServiceVerdict`],
//!   [`Confidence`](crate::model::confidence::Confidence).
//! * [`SignatureDb`] is the runtime view of the signature database: a cheap
//!   `port -> name` index plus lazily compiled, cached matchers.
//! * [`Analyzer`]s are the extension point; [`BannerRegexAnalyzer`] is the first.
//!
//! ## Concurrency contract
//!
//! Every analyzer runs in two phases and `analyze` enforces the split: the
//! transport's first-contact I/O and each analyzer's own `collect` probes run on
//! the async reactor; all `analyze` (CPU) work is handed to the blocking pool.
//! Nothing in this module compiles a regex on a reactor thread; see
//! `SignatureDb` for why that matters.

pub mod model;

pub mod os;

mod analyzer;
pub(crate) mod authority;
mod context;
mod db;
mod extract;
mod favicon;
mod framed;
mod http;
mod jarm;
mod ldap;
mod matcher;
// Crate-visible so the Tier-1 flow interpreter compiles its `expect`/`bind`
// patterns through the one engine every Tier-0 signature does.
pub(crate) mod pattern;
mod prefilter;
mod response;
mod signature;
mod sip;
mod smb;
mod snmp;
mod ssh;
mod tls;
mod tls_cert;
mod tls_enum;
mod tls_summary;

#[cfg(test)]
mod corpus;
// Kept apart from `pattern` because `build.rs` loads that file with `#[path]`
// and has no `proptest`; see the module docs.
#[cfg(test)]
mod pattern_properties;

pub use analyzer::{Analyzer, BannerRegexAnalyzer, PortContext};
pub use db::{InvalidDefinition, SignatureDb};
pub use favicon::FaviconAnalyzer;
// The icon digest a scan would compute, for the container tier's harvest pass.
#[cfg(any(test, feature = "test-support"))]
pub use favicon::digest_of as favicon_digest;
pub use http::HttpHeadersAnalyzer;
pub use jarm::JarmAnalyzer;
pub use model::{Evidence, ServiceVerdict, SourceId, Tunnel};
pub use response::{Collected, ResponseSet, TlsInfo};
// The schema an `assets/fingerprinting` signature file is written against.
// `build.rs` compiles the shipped signatures out of it and validates them; these
// are exported so a consumer authoring signatures of their own is held to the
// same bounds rather than discovering them when a pattern is silently dropped.
// The register of every field a signature may be written against, and whether
// anything in this engine produces it. Exported because a consumer authoring
// signatures needs to know which fields actually arrive, and because a rule
// reading one that does not is inert in a way nothing else reveals.
pub use context::{CONTEXTS, Context, Reach, context_note, reach_of};
pub use signature::{
    CORPUS_ROOT, DefinitionError, MAX_COMPILED_REGEX_BYTES, MAX_UDP_PROBE_BYTES, MatchRule, Probe,
    RULE_ID_SEPARATOR, RuleIdDefect, ServiceDefinition, ServiceSignature, claim_rule_id,
    corpus_slug, rule_id,
};
// The payload decoder Tier-0 probes use, reused by the Tier-1 interpreter to turn
// a flow's `\x`/`\r\n` escapes into the bytes it sends. Crate-visible, not public.
pub(crate) use signature::unescape;
pub use ssh::SshAnalyzer;
pub use tls_cert::TlsCertAnalyzer;
pub use tls_enum::{EXCHANGE_TIMEOUT, MAX_OFFERS_PER_VERSION, enumerate_tls, enumerate_tls_named};
// The same walk answering to a scan's budget; see its documentation.
pub(crate) use tls_enum::enumerate_tls_while;

use std::borrow::Cow;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;

use crate::config::ServiceDetection;
use crate::model::port::{Port, PortState, Protocol, Service};
use crate::system::descriptors;
use crate::transport::dial::PathAllowance;
use crate::transport::dial::{Egress, Shaping};
use authority::Authority;

/// How long to wait for a service to speak first (banner grab).
///
/// This and every wait below that waits on the peer is how long the service
/// may take on a path that costs nothing. A scan that measured the path gives
/// each its allowance on top; see [`on_path`].
const BANNER_READ_TIMEOUT: Duration = Duration::from_millis(500);
/// How long to wait for a reply to an active probe.
const PROBE_READ_TIMEOUT: Duration = Duration::from_millis(1_000);
/// How long to keep reading once a response has started arriving.
///
/// Not a second timeout on the response: the response has already begun, and
/// this is only how long its remainder is worth waiting for. What it has to
/// bridge is the gap between a server writing its headers and writing its body,
/// which is a segment boundary rather than a delay, so sub-millisecond on a
/// segment and one round trip at worst anywhere else.
///
/// It is paid in full by every response that is *already* complete, since a
/// finished server simply goes quiet and there is no way to tell that apart from
/// a slow one without waiting. So it is set as low as the job allows: fifty
/// milliseconds bridges any real gap, and the ports pay it in parallel, so it
/// costs a scan the grace once rather than once per port.
const CONTINUATION_GRACE: Duration = Duration::from_millis(50);
/// What this engine calls itself when it asks an HTTP server a question.
///
/// One place, so the authored probe in `assets/fingerprinting/web/http.toml` and
/// the redirect this code follows on its own introduce the same scanner. A
/// server's logs should show one visitor, not two.
const USER_AGENT: &str = "ZondScanner/1.0";

/// How long to wait for the second connection a speculative TLS handshake needs.
///
/// The first one already completed to this same port, so this either succeeds
/// immediately or the port has stopped accepting, so there is nothing here worth
/// a long wait.
const CONNECT_RETRY_TIMEOUT: Duration = Duration::from_millis(500);
/// Upper bound on how much of a single response we read/keep.
const MAX_RESPONSE_BYTES: usize = 4096;

/// The longest a single identity field lifted from a response may be.
///
/// A product name, a version and a supplementary technology are all short by
/// nature. What a bound stops is a hostile response putting a kilobyte into
/// each: measured without it, one reply yields a 1500-byte `product` and a
/// 1500-byte `extrainfo`, and both travel into the store, the journal, the
/// JSON, the CSV, the HTML and the nmap XML.
///
/// Refused rather than truncated, which is the argument
/// the SNMP reader already makes about `sysDescr`: half a value matched
/// against a corpus of whole ones is a match nobody can reproduce, and a
/// truncated version is a version that is simply wrong. A field this long is a
/// pattern that ran away or a peer being difficult, and neither is worth
/// reporting.
///
/// Every sibling reading here already bounded itself, at 255 bytes for a system
/// description, 40 for a document title and 32 for a last-resort banner label,
/// and each said why. These three had no argument for being unbounded, only no
/// author.
pub const MAX_IDENTITY_BYTES: usize = 256;

/// `value` as an identity field, or `None` where it is empty or past
/// [`MAX_IDENTITY_BYTES`].
///
/// The one place the bound is applied, so the three readings that lift text off
/// a response cannot disagree about it.
pub(crate) fn identity_field(value: &str) -> Option<&str> {
    let value = value.trim();
    (!value.is_empty() && value.len() <= MAX_IDENTITY_BYTES).then_some(value)
}

/// How long a response may go on arriving, measured from its first byte.
///
/// [`CONTINUATION_GRACE`] bounds the gap between two reads and nothing bounded
/// how many of them there could be, so a peer writing one byte every forty
/// milliseconds stayed permanently inside the grace and held a task for
/// ninety-seven seconds. Measured, against a loopback server doing exactly
/// that, and it costs an attacker one socket.
///
/// Set where a legitimate response cannot reach it. What this has to cover is a
/// server writing its headers and then its body, which is a segment boundary
/// and at worst a round trip; two seconds is three orders of magnitude past
/// that. What it cuts off is a peer being slow on purpose.
const MAX_CONTINUATION: Duration = Duration::from_secs(2);

/// The ceiling on everything one port's collection may spend on the network.
///
/// A backstop rather than a working budget. Every stage below already has its
/// own bound, and the longest honest walk down the ladder in [`gather`] comes
/// to thirty-five and a half seconds. It is a port several services share and
/// none names: the generic question refused with a `400`, each sharing service
/// asked on a connection of its own and a redirect followed, then a handshake,
/// each service asked again through a tunnel of its own, and the redirect
/// followed. The longest at the thorough level, a failed handshake, a failed
/// legacy handshake, a port in the clear and then the last-resort probes,
/// comes to thirty, three and a half more for each probe authored for
/// strangers. This sits above both, so it never fires on a port behaving
/// normally;
/// `the_collection_budget_covers_every_path_through_gather` is what holds the
/// two together.
///
/// It is here because the stages are added to over time and their sum is nobody's
/// property. `read_bytes` grew a bound it did not have; the next stage to be
/// added will be bounded by whoever writes it, and this is what makes the total
/// somebody's responsibility rather than an emergent number.
///
/// Set for a path that costs nothing. On a measured one each wait along the
/// walk allows for the path once, so the budget allows for it once per wait
/// the longest walk makes; see [`COLLECTION_WAITS`].
///
/// So it has no ceiling of its own in wall time, and grows to minutes behind
/// a slow path. The honest walk grows with it: behind a round trip of two
/// seconds the longest runs near two minutes, every wait on it bounded and
/// every one allowing for the path, and a ceiling beneath that would cut short
/// the identifications the allowance exists to finish. What the backstop is
/// for is a stage with no bound, which a slow path does not make likelier.
const COLLECTION_BUDGET: Duration = Duration::from_secs(40);

/// The most waits on the peer any walk down the ladder in [`gather`] makes in
/// a row, each a connection or a read that allows for the path, with room for
/// probes still to be authored. The longest walk makes nineteen, the one the
/// budget above describes, and eighteen at the thorough level, two more for
/// each probe authored for strangers;
/// `the_collection_budget_covers_every_path_through_gather` holds the two
/// together.
const COLLECTION_WAITS: u32 = 20;

/// Whether a reply from this port over this protocol is one the engine can read.
///
/// What decides whether a port is worth the exchange a service pass costs. A TCP
/// port always is: any of them may volunteer a banner, and reading one costs a
/// connection. A UDP port is worth a datagram only where something here can turn
/// the answer into text. Otherwise the reply proves the port open, which the
/// scan that found it already knew.
#[must_use]
pub fn reads_replies(port: u16, protocol: Protocol) -> bool {
    extract::reads(port, protocol)
}

/// The service name registered for a port number, if any.
///
/// A pure metadata lookup with **no regex compilation**, safe to call on the
/// scan hot path for every classified port. Returns the same names the fuller
/// fingerprinting path uses, so a quick label and a deep identification agree.
///
/// Registration is per port and not per transport, because a signature file
/// names the numbers a service claims and says nothing about how they are
/// reached. This took a `Protocol` for a while and ignored it, which is worse
/// than not taking one: [`reads_replies`] next door does branch on the
/// transport, so the two signatures read as though both meant it.
pub fn lookup_service_name(port: u16) -> Option<String> {
    SignatureDb::global()
        .service_name(port)
        .map(|s| s.to_string())
}

/// What a service said about the *machine* it runs on, as distinct from what it
/// said about itself.
///
/// Two findings filed in two places: the service belongs to the port, and the
/// operating system, the hardware and the names the machine goes by to the
/// host. They travel together because
/// one banner routinely states both, and separating them at the source would
/// mean two passes over the same evidence.
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct AboutTheHost {
    /// What the responses implied about the operating system.
    pub os: Vec<crate::model::host::OsEvidence>,
    /// The hardware they described, where they described any. Over five hundred
    /// shipped rules name a box and no system at all.
    pub hardware: Option<crate::model::host::HardwareInfo>,
    /// The names the machine gave for itself, in the order they were read.
    pub names: Vec<crate::model::host::HostName>,
}

impl AboutTheHost {
    /// Whether nothing was concluded about the machine.
    pub fn is_empty(&self) -> bool {
        self.os.is_empty() && self.hardware.is_none() && self.names.is_empty()
    }

    /// Records everything this says about `host`, and reports whether the
    /// operating-system reading changed.
    ///
    /// One call because the findings arrive together and land in separate
    /// places, and a caller doing it in steps is a caller that will one day do
    /// only the first. Hardware is merged rather than replaced: a record read from an
    /// address block and one a banner described are both about the same box, and
    /// [`HardwareInfo::merge`](crate::model::host::HardwareInfo::merge) knows
    /// which half of each to keep.
    pub fn apply(self, host: &mut crate::model::host::Host) -> bool {
        if let Some(described) = self.hardware {
            match host.hardware().cloned() {
                Some(mut known) => {
                    known.merge(described);
                    host.set_hardware(known);
                }
                None => host.set_hardware(described),
            }
        }
        for name in self.names {
            host.record_name(name);
        }
        os::identify(host, self.os)
    }

    /// What a verdict says about the machine: everything, where it named the
    /// service, and the names alone where it did not.
    ///
    /// A name is read from a reply's structure by an analyzer, not matched by
    /// a rule, so it is the machine's whether or not any rule named the
    /// service that gave it: a directory on a port nothing registers still
    /// names its controller. An operating system and hardware are what a rule
    /// concluded about the software it identified, and a verdict that
    /// identified nothing has no such conclusion to stand behind.
    fn of_verdict(verdict: Option<&ServiceVerdict>) -> Self {
        match verdict {
            Some(verdict) if !verdict.is_empty() => Self::from_evidence(&verdict.evidence),
            Some(verdict) => Self {
                names: names_in(&verdict.evidence),
                ..Self::default()
            },
            None => Self::default(),
        }
    }

    /// Reads both from a resolved verdict's whole evidence set.
    ///
    /// Taken from every observation rather than the winning one: a host running
    /// two identifiable services says the same thing about itself twice, and a
    /// signature that lost the ranking for *service* may be the one that named
    /// the machine.
    fn from_evidence(evidence: &[Evidence]) -> Self {
        Self {
            os: evidence.iter().filter_map(|e| e.os.clone()).collect(),
            hardware: evidence
                .iter()
                .filter_map(|e| e.hardware.as_ref())
                .cloned()
                .reduce(|mut best, other| {
                    best.merge(other);
                    best
                }),
            names: names_in(evidence),
        }
    }
}

/// Every name an observation in `evidence` gave for the machine, in order.
fn names_in(evidence: &[Evidence]) -> Vec<crate::model::host::HostName> {
    evidence
        .iter()
        .flat_map(|e| e.names.iter().cloned())
        .collect()
}

/// The text a UDP reply from `port` carries, where this engine can read one.
///
/// The other half of [`reads_replies`], which says whether a port qualifies and
/// leaves a caller who dialled one themselves with no way to read the answer.
/// `None` for a port with no decoder, which is most of them: a datagram nothing
/// can read is still proof the port is open, and that is what the scan already
/// took from it.
///
/// Returns owned text because decoding is not always a borrow: a value lifted
/// out of a binary encoding has no text in the datagram to point at, and more
/// than one where a reply answers more than one question: an SNMP agent is asked
/// for its description and its object identifier in a single datagram.
pub fn decode_udp_reply(port: u16, datagram: &[u8]) -> Vec<String> {
    extract::from_datagram(port, datagram)
}

/// What a completed handshake established, as the record a report carries.
///
/// A summary rather than the chain: who the certificate claims to be, who
/// vouched for it, when it stops being valid, and a fingerprint to compare two
/// sightings by. Nothing here is a trust decision: validity is recorded as
/// two instants and left for the reader to compare against whatever time they
/// care about, precisely so that expired, self-signed and wrong-host
/// certificates are reported rather than rejected.
///
/// Always produces a record. A chain this cannot read is a finding rather than a
/// reason to report nothing, and the version and cipher agreed are worth keeping
/// on their own.
///
/// For a caller who performed their own handshake: this crate's connector is not
/// public, and a [`TlsInfo`] built from what any TLS client hands back turns into
/// a report record here.
pub fn tls_security(tls: &TlsInfo) -> crate::model::port::Security {
    tls_summary::security(tls)
}

/// The confidence-0 label every scan path seeds before deeper fingerprinting:
/// the name the port number is registered under, and **nothing at all where it
/// is registered under none**.
///
/// Centralising it keeps the SYN, connect and service-detection paths agreeing
/// on the same starting point.
///
/// A port with no registered name yields `None` rather than a placeholder.
/// A placeholder is a service name as far as every consumer is concerned: it
/// reaches the exported JSON, the CSV a spreadsheet opens, the HTML somebody
/// reads and the nmap XML another tool ingests, and each of them then says the
/// port is running something called `???`. Absence is what the scan actually
/// established, and absence is representable.
///
/// The zero is what marks the rest as guesses; see
/// [`Service::is_inferred`](crate::model::port::Service::is_inferred).
pub fn baseline_service(port: u16) -> Option<Service> {
    lookup_service_name(port).map(|name| Service::new(name, 0))
}

/// Waits for the shipped signature corpus to be built, building it on the
/// blocking pool where nothing has started to, for a scan to call before its
/// first probe leaves.
///
/// The corpus is built the first time anything asks for it, and the first to
/// ask in a scan is a probe filing its verdict: every verdict carries the
/// port's registered name. The build is tens of milliseconds of work, and a
/// runtime worker busy with it holds up the readiness of every connection in
/// flight, not only its own. On loopback every connect that completes
/// meanwhile is read the moment the build ends, some 40 ms on in a debug
/// build, where a loopback handshake takes a tenth of a millisecond. A
/// connect's round trip runs from its start to its readiness being read, so
/// each would be filed as a 40 ms path, and a host with more ports than its
/// round-trip window holds would report nothing else. Built here, before
/// anything is timed and off the workers, it holds up no probe.
///
/// A scan starts the build as it opens, with [`start_loading_corpus`], so what
/// is waited for here is whatever of it the passes before the port scan have
/// not already covered.
pub(crate) async fn load_corpus() {
    // A panic building it is the embedded corpus failing to decode, which
    // the next caller meets and reports the same way; nothing is lost here.
    // A build already under way is waited for on the blocking thread too.
    let _ = tokio::task::spawn_blocking(|| {
        SignatureDb::global();
    })
    .await;
}

/// Starts building the shipped signature corpus on the blocking pool, where
/// nothing has yet, and returns at once, for a scan to call as it opens.
///
/// Its passes before the port scan, liveness above all, never ask for the
/// corpus, so the build runs beside them rather than ahead of the port scan's
/// first probe, which [`load_corpus`] would otherwise hold up for all of it.
pub(crate) fn start_loading_corpus() {
    drop(tokio::task::spawn_blocking(|| {
        SignatureDb::global();
    }));
}

/// A [`Port`] in the given `state` carrying only the [`baseline_service`] label.
///
/// This is the shape every discovery path records before (and if) a full
/// fingerprint refines it: the SYN and filtered/closed paths stop here, while
/// the connect and service-detection paths hand the result to
/// [`fingerprint_tcp_detailed`] to upgrade in place.
pub fn baseline_port(port: u16, protocol: Protocol, state: PortState) -> Port {
    let mut classified = Port::new(port, protocol, state);
    if let Some(service) = baseline_service(port) {
        classified.set_service(service);
    }
    classified
}

/// Actively fingerprints an open TCP `stream` and refines `port`'s service.
///
/// Network I/O, meaning the banner grab and any active probes, runs here on the
/// async reactor with bounded reads and per-stage timeouts. The CPU-bound
/// signature
/// matching is handed to `analyze`, which runs on the blocking pool so a large
/// match set can never stall the scheduler.
///
/// If nothing identifies, a trimmed printable banner is kept rather than lost:
/// as the detail beside the name the port's number gives it, or as a
/// last-resort label on a port whose number names nothing.
pub async fn fingerprint_tcp(stream: TcpStream, port: Port, detection: ServiceDetection) -> Port {
    fingerprint_tcp_detailed(stream, port, detection).await.port
}

/// [`fingerprint_tcp`], also returning what the service said about the *machine*.
///
/// Over half the shipped signature corpus carries operating-system metadata, and
/// a banner naming a distribution, such as `OpenSSH_9.6p1 Debian`, is the most
/// direct statement a host ever makes about itself. It is read here because this
/// is
/// where the text already is; no probe is added to collect it.
///
/// Separate from [`fingerprint_tcp`] rather than replacing it because the two
/// findings belong to different places: the service belongs to the port, and what
/// it implies about the operating system belongs to the host. A caller with no
/// host to file it against should not have to handle it.
///
/// The gathered responses come back too, for a caller that runs a later
/// detection over them rather than redrawing them; they are empty when nothing
/// was read. So does whether the identification was starved of a socket, which
/// is what separates a port that had nothing more to say from one that was
/// never asked; see [`Fingerprinted::starved`].
///
/// Every further connection it makes to the port, for a later question or an
/// active analyzer, goes where the routing table sends it. A scan forced to a
/// source reaches the same engine with its connections pinned there instead.
pub async fn fingerprint_tcp_detailed(
    stream: TcpStream,
    port: Port,
    detection: ServiceDetection,
) -> Fingerprinted {
    fingerprint_tcp_via(
        stream,
        port,
        detection,
        Egress::KERNEL,
        PathAllowance::NONE,
        None,
    )
    .await
}

/// What identifying one port came to: the port as it was named, what its
/// service said about the machine, the responses it drew, and whether the
/// process ran short of sockets while asking.
///
/// A struct with named fields rather than a tuple because the last of those is
/// a different kind of fact from the rest, one about this machine rather than
/// the port, and a caller has to be able to see it by name to act on it.
/// Non-exhaustive, so a further fact the identification learns reaches callers
/// as a field they may read rather than a change to a shape they destructure.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Fingerprinted {
    /// The port, its service refined where anything named it.
    pub port: Port,
    /// What the port's service said about the machine behind it.
    pub about_the_host: AboutTheHost,
    /// The responses gathered, for a later detection to read.
    pub responses: Vec<String>,
    /// Whether a connection or datagram the identification needed was given
    /// up because the process had no socket to give it, for as long as it
    /// waited for one.
    ///
    /// What was learned is kept, and is a floor: the question that socket
    /// would have carried went unasked for a reason that is this machine's
    /// rather than the port's, and raising the process's file limit is its
    /// remedy. Over TCP it is a later question, a redirect followed or an
    /// analyzer's own connection, since the first connection is the caller's.
    /// Over UDP it is a datagram, and as each is sent only after the one
    /// before drew nothing readable, a starved UDP identification learned
    /// nothing at all.
    pub starved: bool,
    /// Whether a wait for the port to say something ran its clock out with
    /// nothing heard: a greeting, a reply or a handshake that did not come.
    ///
    /// With nothing drawn, what separates a port that had nothing to say from
    /// one whose answer was still queued behind another's when the clock ran
    /// out. A port that closed on every question waited for nothing.
    pub(crate) ran_out_waiting: bool,
    /// Whether a reply came only after more than half the wait it was given,
    /// counting the service's time and not the path's.
    ///
    /// A service answering that late fits one answer in a wait and not two,
    /// so a question queued behind one of its answers is not answered in time.
    /// The path's round trip is the same for every answer and delays a
    /// queued one no further, so it is no part of the lateness.
    pub(crate) answered_late: bool,
    /// How long the waits that ran out were given, together.
    ///
    /// A host serving its questions one at a time still serves each question
    /// nobody waits for any longer, and this is how long those can hold it,
    /// as long as it answers any question within the wait it is given.
    pub(crate) waited_in_vain: Duration,
}

/// [`fingerprint_tcp_detailed`], with every further connection to the port
/// leaving by `egress`, which is how `stream` was reached, every wait on the
/// port allowing for `path`, the port asked for by `name` where a target
/// named its address (see [`Authority`]), and with whether one of the
/// connections was refused a socket.
pub(crate) async fn fingerprint_tcp_via(
    stream: TcpStream,
    port: Port,
    detection: ServiceDetection,
    egress: Egress,
    path: PathAllowance,
    name: Option<Arc<str>>,
) -> Fingerprinted {
    // Every connection after `stream` dials through this scope, and every
    // wait on the port is sized in it, which is also where a connection given
    // up for want of a socket, and how the port's replies came, are told; see
    // `DIALLING`.
    let tally = Arc::new(Tally::default());
    let dialling = Dialling {
        egress,
        path,
        tally: Arc::clone(&tally),
    };
    let (port, about_the_host, responses) = DIALLING
        .scope(
            dialling,
            identify_tcp(stream, port, detection, egress, path, name),
        )
        .await;
    Fingerprinted {
        port,
        about_the_host,
        responses,
        starved: tally.starved.load(Ordering::Relaxed),
        ran_out_waiting: tally.ran_out_waiting.load(Ordering::Relaxed),
        answered_late: tally.answered_late.load(Ordering::Relaxed),
        waited_in_vain: *tally
            .waited_in_vain
            .lock()
            .unwrap_or_else(|held| held.into_inner()),
    }
}

/// The identification [`fingerprint_tcp_via`] runs inside its dialling scope.
async fn identify_tcp(
    stream: TcpStream,
    mut port: Port,
    detection: ServiceDetection,
    egress: Egress,
    path: PathAllowance,
    name: Option<Arc<str>>,
) -> (Port, AboutTheHost, Vec<String>) {
    // Capture the peer address before `gather` consumes the stream, so active
    // analyzers can open their own connection to the same target. Only at a
    // level that sends: an active analyzer's connection carries a request,
    // an SSH key exchange or a favicon fetch, and one handed no address to
    // dial is left with the passive reading the level promises.
    let addr = stream.peer_addr().ok().filter(|_| detection.sends());
    // Every stage inside `gather` is bounded and their sum is nobody's property;
    // see [`COLLECTION_BUDGET`]. A port that runs out of it is left exactly as
    // the scan recorded it, which is what a port that said nothing gets.
    let Ok((responses, tunnel)) = timeout(
        path.over_each(COLLECTION_BUDGET, COLLECTION_WAITS),
        gather(stream, port.number(), detection, egress, name.clone()),
    )
    .await
    else {
        return (port, AboutTheHost::default(), Vec::new());
    };
    if responses.is_empty() {
        return (port, AboutTheHost::default(), Vec::new());
    }

    // Recorded before the response set is handed off, and independently of what
    // the analyzers conclude. A handshake is a fact about the port; whether any
    // analyzer manages to name the service behind it is a separate question, and
    // a port whose service stays unidentified still has a certificate worth
    // reporting.
    if let Some(tls) = responses.tls.as_ref() {
        port.set_security(tls_summary::security(tls));
    }

    // Analysis runs off the reactor. Keep a last-resort banner label, and the
    // gathered responses a later detection may read, before the response set is
    // handed to the blocking pool.
    let fallback = first_printable(&responses.banners);
    let banners = responses.banners.clone();
    let stated = responses.names.clone();
    // The analyzers dial through the port's egress. They are handed a context
    // whose shape is public and cannot carry it, so it reaches them as the
    // scope their collection runs in; see `DIALLING`.
    let verdict = analyze(
        port.number(),
        Protocol::Tcp,
        addr,
        responses,
        tunnel,
        detection,
        name,
    )
    .await;
    let mut about_the_host = AboutTheHost::of_verdict(verdict.as_ref());
    match verdict {
        Some(verdict) if !verdict.is_empty() => {
            if let Some(service) = verdict.to_service() {
                port.set_service(service);
            }
        }
        // What an unrecognised reply is filed as depends on whether the number
        // names anything. A port the number names keeps that name, still
        // marked as the guess it is, and carries what it said as the detail
        // beside it; only a port it names nothing on is labelled by its
        // banner. The number's guess and a banner nothing recognised are both
        // short of an identification, and of the two the name is the one
        // every scan of the port records. A scan that finds ports without a
        // connection records the name first and folds the identification into
        // it, where a label no more certain than the name cannot displace it;
        // one that finds them by connecting records what this returns. Were
        // the label to replace the name here, the same port would read one
        // way or the other by which kind of scan found it.
        _ => {
            if let Some(banner) = fallback {
                let fallen_back = match port.service() {
                    Some(named) if named.extrainfo().is_none() => {
                        Some(named.clone().with_extrainfo(banner))
                    }
                    Some(_) => None,
                    None => Some(Service::new(format!("banner: {banner}"), 0)),
                };
                if let Some(service) = fallen_back {
                    port.set_service(service);
                }
            }
        }
    }
    // The names the replies gave are the machine's whether or not any rule
    // named the service that gave them.
    about_the_host.names.extend(stated);

    (port, about_the_host, banners)
}

/// Fingerprints an open **UDP** port, returning the upgraded [`Port`] and
/// whatever the reply said about the machine behind it.
///
/// The sibling of [`fingerprint_tcp_detailed`], and the same shape:
/// draw a response, turn it into the text the corpus is written against, and
/// hand it to the same analyzers. Only the drawing differs, because UDP has no
/// connection to open and no banner to wait for.
///
/// # Why this is a second datagram rather than the scan's own
///
/// The UDP port scan already sends this exact payload and already sees this
/// exact reply, which is how the port was known to be open at all, and then
/// discards the body, since what it needed was the fact of an answer. Wiring
/// that reply through would save a datagram and cost the thing that makes the
/// scan fast: the scanner would have to hold every response body for every port
/// it probed, through a paced run, against the chance that a later phase wants
/// one. This is the same trade the TCP side already makes, where the service
/// pass reconnects to a port the scan has already knocked on.
///
/// # What it will not do
///
/// Speak to a port it cannot read. A datagram is only worth sending where
/// something here could turn the answer into text, for which see
/// [`reads_replies`], since unlike a TCP banner grab an unread UDP reply teaches
/// nothing the scan does not already know.
///
/// Claim a port answered when it did not. `None` means silence, and silence
/// over UDP is the ordinary case: no connection is refused and no banner is
/// withheld, so nothing distinguishes a filtered port from one with nothing
/// behind it. A caller that dialled a port on its own account uses this to tell
/// whether it found anything at all.
///
/// Call it silence when it was not. A datagram the process had no socket for
/// was never sent, and the port was never asked; that comes back as the port
/// as it was given, with [`starved`](Fingerprinted::starved) set, since it is
/// this machine's shortfall and a caller reading it as the port's would
/// record a question as answered that was never put.
///
/// The datagram leaves where the routing table sends it; a scan forced to a
/// source sends it from there instead.
pub async fn fingerprint_udp_detailed(
    addr: std::net::SocketAddr,
    port: Port,
) -> Option<Fingerprinted> {
    fingerprint_udp_via(addr, port, Egress::KERNEL).await
}

/// [`fingerprint_udp_detailed`], with the datagram leaving by `egress`.
pub(crate) async fn fingerprint_udp_via(
    addr: std::net::SocketAddr,
    port: Port,
    egress: Egress,
) -> Option<Fingerprinted> {
    fingerprint_udp_on(addr, port, egress, PathAllowance::NONE).await
}

/// [`fingerprint_udp_via`], with each wait for a reply allowing for `path`.
pub(crate) async fn fingerprint_udp_on(
    addr: std::net::SocketAddr,
    port: Port,
    egress: Egress,
    path: PathAllowance,
) -> Option<Fingerprinted> {
    fingerprint_udp_within(addr, port, egress, descriptors::PATIENCE, path).await
}

/// [`fingerprint_udp_on`], waiting out a full descriptor table for
/// `patience` before a datagram is given up as starved.
async fn fingerprint_udp_within(
    addr: std::net::SocketAddr,
    mut port: Port,
    egress: Egress,
    patience: Duration,
    path: PathAllowance,
) -> Option<Fingerprinted> {
    let responses = match probe_udp(addr, egress, patience, path).await {
        Datagram::Reply(responses) => responses,
        Datagram::Silent => return None,
        Datagram::Starved => {
            return Some(Fingerprinted {
                port,
                about_the_host: AboutTheHost::default(),
                responses: Vec::new(),
                starved: true,
                ran_out_waiting: false,
                answered_late: false,
                waited_in_vain: Duration::ZERO,
            });
        }
    };
    let banners = responses.banners.clone();
    let stated = responses.names.clone();

    // No tunnel: nothing here carries UDP over TLS, and no peer address is
    // handed to the analyzers either, since an active analyzer dials TCP and
    // this port's address is not one it could speak to. With no address, the
    // detection level cannot change what runs, so the default stands in for a
    // parameter this function would otherwise have to take and never use.
    let verdict = analyze(
        addr.port(),
        Protocol::Udp,
        None,
        responses,
        None,
        ServiceDetection::default(),
        None,
    )
    .await;

    // The names a reply gave are the machine's whether or not any rule named
    // the service that gave them.
    let mut about_the_host = AboutTheHost::of_verdict(verdict.as_ref());
    about_the_host.names.extend(stated);
    let service = verdict.and_then(|verdict| verdict.to_service());
    if service.is_none() && about_the_host.names.is_empty() {
        return None;
    }
    if let Some(service) = service {
        port.set_service(service);
    }

    Some(Fingerprinted {
        port,
        about_the_host,
        responses: banners,
        starved: false,
        ran_out_waiting: false,
        answered_late: false,
        waited_in_vain: Duration::ZERO,
    })
}

/// What asking a UDP port came to.
enum Datagram<T> {
    /// It answered, with this.
    Reply(T),
    /// It was asked and said nothing, or nothing readable.
    Silent,
    /// The process had no socket to ask it with, for as long as it waited
    /// for one, so it was never asked.
    Starved,
}

/// Sends this port's registered probes and reads back whatever text a reply
/// carries, or `None` if none carried any.
///
/// Bound to an ephemeral port of the same family as the target, and
/// connected, so the kernel drops anything from another address before it
/// reaches here: a scanner reading unsolicited datagrams off an unconnected
/// socket would attribute one host's answer to another's port.
///
/// # Why this asks more than once where the port scan asks once
///
/// [`payload::for_port`](crate::scanner::payload::for_port) takes the first
/// probe a port registers and stops, which is right for what it is doing: any
/// reply at all settles the port's state, so a second datagram would buy
/// nothing.
///
/// Identification is a different question, and one probe does not always ask
/// it. NTP is the case this exists for. A client request draws a packet of
/// timestamps, which proves the port open and says nothing else; the daemon's
/// own account of itself comes back only to a mode 6 control message, and the
/// corpus registers both. Taking the first here sent the client request,
/// discarded the timestamps, and left seventy-five rules unreached that had
/// just been given a decoder.
///
/// So each registered probe is tried in turn and the first that yields text,
/// or a name for the machine, wins. A port registering one probe, which is nearly all of them, costs
/// exactly what it did before.
///
/// A probe the process had no socket for ends the walk as starved rather than
/// passing on to the next: the table that refused one socket is the table the
/// next would ask, and the port has not been asked anything yet.
async fn probe_udp(
    addr: std::net::SocketAddr,
    egress: Egress,
    patience: Duration,
    path: PathAllowance,
) -> Datagram<ResponseSet> {
    for payload in SignatureDb::global().udp_probe_payloads(addr.port()) {
        match exchange_datagram(addr, payload, egress, patience, path).await {
            Datagram::Reply(reply) => {
                let read = ResponseSet {
                    banners: extract::from_datagram(addr.port(), &reply),
                    names: extract::names_from_datagram(addr.port(), &reply),
                    ..ResponseSet::default()
                };
                if !read.banners.is_empty() || !read.names.is_empty() {
                    return Datagram::Reply(read);
                }
            }
            Datagram::Silent => {}
            Datagram::Starved => return Datagram::Starved,
        }
    }
    Datagram::Silent
}

/// Sends `payload` to `addr` and reads back whatever text the reply carries.
///
/// The same exchange `probe_udp` performs, with the question supplied rather
/// than taken from the corpus. A corpus probe is one payload per port, which is
/// all a port number can decide; a question about a *particular host* cannot come
/// from there. An mDNS device-info record is the case this exists for: it is
/// published under the host's own name, so the query naming it is different for
/// every target.
///
/// The reply is decoded by the same port-keyed decoder either way, so a caller's
/// question and this engine's reading of the answer cannot drift apart.
///
/// Empty when nothing answered or nothing could be read from what did.
pub async fn probe_udp_with(addr: std::net::SocketAddr, payload: &[u8]) -> Vec<String> {
    probe_udp_with_via(addr, payload, Egress::KERNEL).await
}

/// [`probe_udp_with`], with the datagram leaving by `egress`.
pub(crate) async fn probe_udp_with_via(
    addr: std::net::SocketAddr,
    payload: &[u8],
    egress: Egress,
) -> Vec<String> {
    match probe_udp_raw_via(addr, payload, egress).await {
        Some(reply) => extract::from_datagram(addr.port(), &reply),
        None => Vec::new(),
    }
}

/// The same exchange, handing back the datagram rather than what this engine
/// reads out of it.
///
/// For a caller whose question is answered in a form the port's decoder is not
/// for. An mDNS responder is asked two different things on one port: what it
/// calls itself, which is a name in a PTR record, and what hardware it is, which
/// is the text this engine decodes there. Only the second is a banner.
///
/// [`None`] when nothing answered.
pub async fn probe_udp_raw(addr: std::net::SocketAddr, payload: &[u8]) -> Option<Vec<u8>> {
    probe_udp_raw_via(addr, payload, Egress::KERNEL).await
}

/// [`probe_udp_raw`], with the datagram leaving by `egress`.
pub(crate) async fn probe_udp_raw_via(
    addr: std::net::SocketAddr,
    payload: &[u8],
    egress: Egress,
) -> Option<Vec<u8>> {
    match exchange_datagram(
        addr,
        payload,
        egress,
        descriptors::PATIENCE,
        PathAllowance::NONE,
    )
    .await
    {
        Datagram::Reply(reply) => Some(reply),
        Datagram::Silent | Datagram::Starved => None,
    }
}

/// Sends `payload` to `addr` from a socket of its own and reads the one
/// datagram that comes back, telling a port that said nothing from a process
/// that had no socket to ask it with, after waiting `patience` for one. The
/// wait for the reply allows for `path`.
async fn exchange_datagram(
    addr: std::net::SocketAddr,
    payload: &[u8],
    egress: Egress,
    patience: Duration,
    path: PathAllowance,
) -> Datagram<Vec<u8>> {
    let socket = match egress.udp(addr.ip(), patience).await {
        Ok(socket) => socket,
        Err(e) if descriptors::exhausted(&e) => return Datagram::Starved,
        Err(_) => return Datagram::Silent,
    };
    if socket.connect(addr).await.is_err() || socket.send(payload).await.is_err() {
        return Datagram::Silent;
    }

    let mut buffer = vec![0u8; MAX_RESPONSE_BYTES];
    match timeout(path.over(PROBE_READ_TIMEOUT), socket.recv(&mut buffer)).await {
        Ok(Ok(read)) => {
            buffer.truncate(read);
            Datagram::Reply(buffer)
        }
        _ => Datagram::Silent,
    }
}

/// Collects everything the transport can learn from the port over the network,
/// and how it was carried.
///
/// A ladder of questions rather than a choice between them. The port number sets
/// the *order* the rungs are tried in and never the set: a port numbered for TLS
/// is offered a handshake first and anything else is spoken to in the clear
/// first, and a rung that draws nothing falls through to the next.
///
/// Order is what a port number is good for and membership is what it is not. A
/// number is a convention, and a service can be moved off or onto any of them,
/// so a rung that ended the collection would make the convention the answer.
///
/// Whenever a handshake succeeds the collection re-runs *inside* the tunnel, so
/// the protocol carried by TLS is fingerprinted too, and the returned [`Tunnel`]
/// records that it was.
///
/// Every connection after the first leaves by `egress`, as the first did.
async fn gather(
    mut stream: TcpStream,
    port: u16,
    detection: ServiceDetection,
    egress: Egress,
    name: Option<Arc<str>>,
) -> (ResponseSet, Option<Tunnel>) {
    // Identify nothing. Reached only from the unprivileged path, where the
    // connection is how the port's state was established and so exists whether
    // or not anything is to be learned from it; the privileged path stops a
    // level earlier, in `service::detect`, and never opens one at all.
    if !detection.connects() {
        return (ResponseSet::default(), None);
    }

    // Listen only. Everything below this line puts bytes on the wire, the
    // ClientHello of a handshake as much as the probes, so the level that
    // promises to send nothing has to stop here rather than further in.
    if !detection.sends() {
        let banner = read_response(&mut stream, BANNER_READ_TIMEOUT).await;
        return (
            ResponseSet::from_banners(banner.into_iter().collect()),
            None,
        );
    }

    // Without the peer's address there is nowhere to reconnect to and no server
    // name for a handshake, so the socket in hand is asked in the clear and that
    // is the whole of it.
    let Ok(socket) = stream.peer_addr() else {
        return (plaintext(stream, port, None, egress).await, None);
    };
    let peer = Authority::new(socket).named(name);

    // The first rung inherits the connection the caller opened. Every rung after
    // it dials its own, because a handshake consumes the stream it was given and
    // a probe leaves its request on the one it wrote to.
    let mut opened = Some(stream);
    // Both handshakes refused in TLS, on a port numbered for it, held while the
    // port is asked in the clear; see `refused_every_handshake`.
    let mut refused: Option<ResponseSet> = None;
    for rung in Rung::ladder(port) {
        let stream = match opened.take() {
            Some(stream) => stream,
            None => match redial(socket, egress).await {
                Some(fresh) => fresh,
                None => return (refused.unwrap_or_default(), None),
            },
        };

        let (responses, tunnel) = rung.ask(stream, port, &peer, detection, egress).await;
        if let Some(held) = refused.take() {
            return match held.tls {
                Some(tls) if refused_in_the_clear(&responses) => {
                    (responses.with_tls(tls), Some(Tunnel::Tls))
                }
                tls => (ResponseSet { tls, ..held }, None),
            };
        }
        if responses.is_empty() {
            continue;
        }
        if matches!(rung, Rung::LegacyTls) && refused_every_handshake(&responses) {
            refused = Some(responses);
            continue;
        }
        if matches!(rung, Rung::Plaintext)
            && !tls::is_tls_port(port)
            && refused_in_the_clear(&responses)
        {
            return asked_through_tls(responses, port, &peer, egress).await;
        }
        return (responses, tunnel);
    }

    (refused.unwrap_or_default(), None)
}

/// Whether what the legacy handshake drew is a refusal in TLS and nothing
/// else, on a port whose modern handshake had already failed.
///
/// Such a port speaks TLS and would complete a handshake with this scanner on
/// neither version's terms, which is what a server keeping its certificates by
/// name answers a client naming no site it holds: every handshake where the
/// target named an address. The refusals say it speaks TLS and not what it
/// serves, so the port is asked in the clear as well, once. A web server
/// refuses that request with a plaintext `400`, and the port is then filed as
/// the web server through TLS its refusal said it was, as on a port its number
/// does not name (see `asked_through_tls`). Anything else it says leaves it
/// filed on its refusals, as a port that speaks TLS.
fn refused_every_handshake(responses: &ResponseSet) -> bool {
    responses.banners.is_empty()
        && responses
            .tls
            .as_ref()
            .is_some_and(|tls| tls.version == Some(tls::REFUSED))
}

/// Whether what a port answered in the clear is an HTTP server refusing the
/// request, which is how a web server listening for TLS answers one that
/// arrived without it.
///
/// nginx, Apache, Go and Caddy all answer a plaintext request on a TLS port
/// with a plaintext `400` rather than a TLS alert, and each says why in its
/// own words. The status is what is read, not the words: a well-formed `GET`
/// is refused as a bad request by little else, and asking such a port for a
/// handshake as well costs one connection.
fn refused_in_the_clear(responses: &ResponseSet) -> bool {
    responses.banners.first().is_some_and(|reply| {
        reply.starts_with("HTTP/") && reply.split_whitespace().nth(1) == Some("400")
    })
}

/// What a port that refused a request in the clear says through TLS, with
/// `clear`, what it said in the clear, where it says nothing.
///
/// Reached on a port whose number does not say TLS, since one that does has
/// been asked for a handshake before it was asked anything in the clear. A
/// handshake that completes is the answer, the protocol inside it
/// identified as on any TLS port. One refused on the terms a modern client
/// offers is put the legacy question, and a port answering that in TLS is
/// one that speaks HTTP through TLS and would not complete a handshake with
/// this scanner: a server keeping its certificates by name refuses a client
/// naming no site it holds. Its refusal in the clear is then the port's own
/// account of what it serves, filed as served through TLS, since that is what
/// the refusal said and the handshake bore out. A port answering neither in
/// TLS keeps its answer in the clear.
async fn asked_through_tls(
    clear: ResponseSet,
    port: u16,
    peer: &Authority,
    egress: Egress,
) -> (ResponseSet, Option<Tunnel>) {
    let Some(stream) = redial(peer.socket(), egress).await else {
        return (clear, None);
    };
    let handshake = tls::speculative_handshake(stream, peer.server_name()).await;
    let (through, tunnel) = tunneled(handshake, port, peer, egress).await;
    if !through.is_empty() {
        return (through, tunnel);
    }

    let Some(stream) = redial(peer.socket(), egress).await else {
        return (clear, None);
    };
    match legacy_tls(stream).await.tls {
        Some(tls) => (clear.with_tls(tls), Some(Tunnel::Tls)),
        None => (clear, None),
    }
}

/// A second connection to a port already reached once.
///
/// The first one succeeded, so this either succeeds immediately or the port has
/// stopped accepting; see [`CONNECT_RETRY_TIMEOUT`], which allows for the path.
/// It leaves by `egress`, the way the first one did.
///
/// No share of the process's descriptor budget of its own: the pass that
/// fingerprints the port holds one for the whole identification, whose
/// connections follow one another. A table full for other reasons is waited
/// out before that timeout starts, not within it; see [`dial_again`].
async fn redial(socket: SocketAddr, egress: Egress) -> Option<TcpStream> {
    dial_again(socket, egress, Some(on_path(CONNECT_RETRY_TIMEOUT)))
        .await
        .ok()
}

/// A further connection to the port being identified, leaving by `egress`
/// and given `limit` to connect where one is set.
///
/// Every connection an identification makes after its first comes through
/// here, so that one given up for want of a socket is never read as a port
/// that said nothing. A socket the process refuses is asked for again for up
/// to [`patience`](descriptors::patience), each attempt on a clock of its own.
/// Should the table stay full past that, or the caller's own clock run out
/// while this still waits on it, the identification is marked starved on the
/// way out, which is what its caller files: whatever the connection was to
/// ask went unasked, and raising the limit is the remedy.
async fn dial_again(
    addr: SocketAddr,
    egress: Egress,
    limit: Option<Duration>,
) -> std::io::Result<TcpStream> {
    let refused = Refused::default();
    let refused = &refused;
    descriptors::patiently(descriptors::patience(), || async move {
        let attempt = match limit {
            Some(limit) => timeout(limit, egress.connect_shaped(addr, Shaping::default()))
                .await
                .unwrap_or_else(|_elapsed| Err(std::io::ErrorKind::TimedOut.into())),
            None => egress.connect_shaped(addr, Shaping::default()).await,
        };
        refused.saw(&attempt);
        attempt
    })
    .await
}

/// Whether the connection [`dial_again`] is making was last refused a socket,
/// which it reports to the identification's scope if it ends that way, by
/// giving up or by being dropped while it waits.
#[derive(Default)]
struct Refused(AtomicBool);

impl Refused {
    /// Notes how one attempt went.
    fn saw(&self, attempt: &std::io::Result<TcpStream>) {
        let refused = attempt.as_ref().is_err_and(descriptors::exhausted);
        self.0.store(refused, Ordering::Relaxed);
    }
}

impl Drop for Refused {
    fn drop(&mut self) {
        if self.0.load(Ordering::Relaxed) {
            tell(|tally| tally.starved.store(true, Ordering::Relaxed));
        }
    }
}

/// One question a port can be asked, and the unit [`gather`] falls through.
///
/// Each rung is asked on a connection of its own and reports what it drew.
/// Nothing at all is the signal to try the next, so a rung that cannot answer
/// costs the collection a fall-through rather than the identification.
#[derive(Clone, Copy)]
enum Rung {
    /// Handshake and collect through the tunnel, patiently, on a port where TLS
    /// is what the number says to expect.
    Tls,
    /// The same on a port where it is a guess, under the tighter budget a guess
    /// is worth. See [`tls::SPECULATIVE_TLS_TIMEOUT`].
    SpeculativeTls,
    /// A ClientHello offering the versions rustls will not, for a server too old
    /// for the one above.
    LegacyTls,
    /// Listen and probe in the clear: the port's own probes where something
    /// claims it, and the generic question where nothing does.
    Plaintext,
    /// The questions other services registered, put to a port that has answered
    /// none of its own.
    ///
    /// For a service that speaks only when spoken to and is not on the port its
    /// probe is registered against, this is the only rung that can reach it.
    LastResort,
}

impl Rung {
    /// The rungs for `port`, in the order they are worth asking in.
    ///
    /// The whole of the port number's influence on collection. A number
    /// registered for implicit TLS earns the handshake first, which spares an
    /// ordinary HTTPS port a banner timeout it could only lose. It does not earn
    /// the handshake alone.
    ///
    /// `LegacyTls` sits above `Plaintext` because a 1.0-only server answers a
    /// plaintext probe with an alert record: bytes, which the clear-text rung
    /// would report as a banner, ending the ladder one rung above the question
    /// that names the version.
    fn ladder(port: u16) -> &'static [Rung] {
        if tls::is_tls_port(port) {
            &[
                Rung::Tls,
                Rung::LegacyTls,
                Rung::Plaintext,
                Rung::LastResort,
            ]
        } else {
            &[Rung::Plaintext, Rung::SpeculativeTls, Rung::LastResort]
        }
    }

    /// Asks this rung's question over `stream`, which it consumes.
    ///
    /// [`LastResort`](Self::LastResort) is the one rung that may dial again on
    /// its own account, because it asks several unrelated protocols and each
    /// leaves the socket unusable for the next.
    async fn ask(
        self,
        stream: TcpStream,
        port: u16,
        peer: &Authority,
        detection: ServiceDetection,
        egress: Egress,
    ) -> (ResponseSet, Option<Tunnel>) {
        match self {
            Rung::Tls => {
                let handshake = tls::handshake(stream, peer.server_name()).await;
                tunneled(handshake, port, peer, egress).await
            }
            Rung::SpeculativeTls => {
                let handshake = tls::speculative_handshake(stream, peer.server_name()).await;
                tunneled(handshake, port, peer, egress).await
            }
            Rung::LegacyTls => (legacy_tls(stream).await, None),
            Rung::Plaintext => (plaintext(stream, port, Some(peer), egress).await, None),
            Rung::LastResort => (
                last_resort(stream, peer, port, detection, egress).await,
                None,
            ),
        }
    }
}

/// Puts other services' questions to a port that has answered none of its own.
///
/// One connection per probe and one probe per connection, because the protocols
/// are unrelated and most of them end the conversation on a question they do not
/// recognise: PostgreSQL reads `PING` as a four-byte length and gives up, and
/// Redis closes on the second line of an HTTP request rather than answering it.
/// Reusing a socket across two of them would ask the second question of a peer
/// that had already hung up.
///
/// Every probe is asked and the replies accumulate, unlike the rungs above,
/// where one exchange goes to every analyzer and anything that came back is
/// worth handing on. Here each probe is a *different protocol's* question, and a
/// refusal of one says only that the port does not speak that protocol. A
/// service that answers an unknown command with an error rather than a closed
/// socket would otherwise end the rung on the probe before its own.
///
/// Which probes are asked is [`ServiceDetection::probe_intensity`], and how
/// many of them the path decides; see [`guesses_worth_the_path`].
async fn last_resort(
    first: TcpStream,
    peer: &Authority,
    port: u16,
    detection: ServiceDetection,
    egress: Egress,
) -> ResponseSet {
    let mut probes =
        SignatureDb::global().universal_tcp_probe_payloads(port, detection.probe_intensity());
    probes.truncate(guesses_worth_the_path(probes.len(), detection));

    let mut replies = Vec::new();
    let mut opened = Some(first);
    for payload in probes {
        let Some(mut stream) = (match opened.take() {
            Some(stream) => Some(stream),
            None => redial(peer.socket(), egress).await,
        }) else {
            break;
        };

        if stream.write_all(&peer.addressed(payload)).await.is_err() {
            continue;
        }
        if let Some(reply) = read_document(&mut stream, PROBE_READ_TIMEOUT).await {
            replies.push(reply);
        }
    }

    ResponseSet::from_banners(replies)
}

/// How many of `guesses` other services' questions a port that has answered
/// none of its own is asked, likeliest first, at `detection`.
///
/// All of them where the path costs less than a question's own wait, which is
/// every path under a third of a second. Across a slower one, the default
/// level asks the likeliest alone. Each guess is a connection and a read, and
/// each allows for the path in full, since an answer to it has the path to
/// cross; across a path of two seconds that is near nine seconds a guess, on a
/// port that has already stayed silent through every wait its own questions
/// allowed for the path. The likeliest guess is the one worth that price, a
/// database moved off its number, and the rest would multiply the silent
/// port's cost by their number for services rarer than it. The thorough level
/// asks every guess whatever the path, which is what a caller choosing it has
/// said the time is for.
fn guesses_worth_the_path(guesses: usize, detection: ServiceDetection) -> usize {
    let slow = on_path(PROBE_READ_TIMEOUT) > PROBE_READ_TIMEOUT * 2;
    match detection {
        ServiceDetection::Thorough => guesses,
        _ if slow => guesses.min(1),
        _ => guesses,
    }
}

/// Everything a port will say in the clear.
///
/// Two shapes, chosen by whether anything in the signature database claims the
/// number. A claimed port is listened to and then asked what that service asks,
/// in that order, since a service that greets on connect should be heard before
/// it is interrupted. An unclaimed port is asked generically; see
/// [`ask_generically`].
///
/// A port several services claim is asked each one's questions on a connection
/// of its own, the likeliest service first and on the connection already open,
/// since one protocol's question is often the end of another's conversation;
/// see [`SignatureDb::tcp_probe_conversations`]. The connection before is
/// closed before the next is dialled, so the identification holds one socket
/// at a time. Without the peer's address there is nothing to dial, and every
/// question goes down the one connection there is while it lasts.
///
/// A port services only share, and none names as its own, is asked the
/// generic question first, and theirs after. Nothing says what such a port
/// holds any more than it says what an unclaimed port holds, and what 3000 or
/// 5000 most often holds is a development web server, which the generic
/// question names and a sharing service's question does not.
///
/// A reply that is a TLS record is reported as nothing rather than as a banner,
/// on either shape. The port spoke, but not in this rung's language, and the
/// ladder has a rung that can read it.
async fn plaintext(
    mut stream: TcpStream,
    port: u16,
    peer: Option<&Authority>,
    egress: Egress,
) -> ResponseSet {
    let db = SignatureDb::global();
    let mut conversations = db.tcp_probe_conversations(port).peekable();
    let named = db.service_name(port).is_some();

    // The port's own service on the connection already open, or, where no
    // service names the port, the generic question, which follows its own
    // redirect.
    let (mut responses, mut held) = match conversations.next_if(|_| named) {
        Some(first) => {
            let listen = !db.asked_first(port);
            let responses = collect_responses(&mut stream, port, first, peer, listen).await;
            // Read back off the decoded text, which is sound only because
            // every byte `looks_like_tls` constrains is under 0x80, comes
            // first, and so survives `extract::reply_text` unchanged and in
            // place.
            if responses
                .banners
                .first()
                .is_some_and(|first| looks_like_tls(first.as_bytes()))
            {
                return ResponseSet::default();
            }
            (responses, Some(stream))
        }
        None => match ask_generically(stream, peer, egress).await {
            GenericReply::Spoke(banners) => (ResponseSet::from_banners(banners), None),
            GenericReply::Silent => (ResponseSet::default(), None),
            GenericReply::Tls => return ResponseSet::default(),
        },
    };

    // Every other service's questions, each on a connection of its own.
    let mut theirs = ResponseSet::default();
    for probes in conversations {
        if let Some(peer) = peer {
            drop(held.take());
            held = redial(peer.socket(), egress).await;
        }
        let Some(stream) = held.as_mut() else {
            break;
        };
        theirs.extend(ask_in_turn(stream, port, probes, peer).await);
    }
    drop(held);

    // A redirect among the services' own replies is followed once the last
    // connection is closed. The generic question's was followed as it was
    // asked, so on a port nothing names only the rest are looked through.
    if named {
        responses.extend(theirs);
        let banners = std::mem::take(&mut responses.banners);
        responses.banners = with_redirect_followed(banners, peer, egress).await;
    } else {
        theirs.banners = with_redirect_followed(theirs.banners, peer, egress).await;
        responses.extend(theirs);
    }
    responses
}

/// What a generic probe drew out of a port nothing in the database claims.
enum GenericReply {
    /// It answered in something we can read. Whatever it said is here.
    Spoke(Vec<String>),
    /// It answered in TLS, most likely an alert, since what went out was not a
    /// ClientHello. The port speaks, just not to that question.
    Tls,
    /// Nothing came back at all.
    Silent,
}

/// Asks an unclaimed port the one question worth asking of any open port, and
/// reads whatever comes back.
///
/// The request goes out before anything is read, which inverts the order the
/// claimed-port path uses, and the inversion is safe for a reason worth writing
/// down: a service that greets on connect has already sent its greeting by the
/// time anything is written, and TCP delivers it whether or not it was asked for
/// first. So writing first cannot lose a banner, and it saves the timeout that
/// waiting for a banner nobody is going to send would cost.
///
/// That saving is the whole point. Waiting half a second for a greeting, sending
/// nothing, concluding the port is silent, and then spending up to another
/// second and a half guessing that the silence is TLS costs two seconds per
/// unidentified port. Measured against one ordinary home server, that was seven
/// of its eleven open ports, to learn nothing about any of them. An HTTP request
/// answers in a round trip and names most of them.
///
/// The stream is closed once its reply is read, before a redirect is followed
/// over a connection of its own, so the identification holds one socket at a
/// time, which is the one share of the descriptor budget its pass took.
async fn ask_generically(
    mut stream: TcpStream,
    peer: Option<&Authority>,
    egress: Egress,
) -> GenericReply {
    for payload in SignatureDb::global().generic_tcp_probe_payloads() {
        let payload = match peer {
            Some(peer) => peer.addressed(payload),
            None => Cow::Borrowed(&payload[..]),
        };
        if stream.write_all(&payload).await.is_err() {
            break;
        }
    }

    let read = read_bytes(&mut stream, PROBE_READ_TIMEOUT, CONTINUATION_GRACE).await;
    drop(stream);
    let Some(bytes) = read else {
        return GenericReply::Silent;
    };
    if looks_like_tls(&bytes) {
        return GenericReply::Tls;
    }

    let first = extract::reply_text(&bytes);

    // A redirect is not an answer but a forwarding address, and for a great
    // many self-hosted applications it is the only thing the root serves. See
    // `redirect_path`.
    let followed = match (peer, redirect_path(&first, peer)) {
        (Some(peer), Some(path)) => follow_redirect(peer, &path, egress).await,
        _ => None,
    };

    GenericReply::Spoke(std::iter::once(first).chain(followed).collect())
}

/// Where a response says to look instead, when that is somewhere on the same
/// host and reachable by the same means.
///
/// The root of a self-hosted application is very often a redirect and nothing
/// else. Jellyfin's is a 302 to `/web/index.html` and Sonarr's is one to its
/// login page, so the page that names either is one hop away and a scanner that
/// stops at the first response sees only the framework underneath, which for
/// both of those and a dozen others is `Kestrel`.
///
/// Refused unless the destination is the port already being identified. A
/// redirect naming somewhere else is an instruction to go and talk to a third
/// party, which is not something a scan of *this* address should do on its own
/// account: it would put traffic on somebody uninvolved and attribute what came
/// back to a host that never served it. Which URLs lead back is
/// [`Authority::path_of`]'s to say, so the check and the `Host` the redirect is
/// then asked with name the port the same way.
fn redirect_path(response: &str, peer: Option<&Authority>) -> Option<String> {
    let (status, headers) = response.split_once("\r\n").or(response.split_once('\n'))?;
    // `HTTP/1.1 302 Found`: the code is the second field.
    let code: u16 = status.split_whitespace().nth(1)?.parse().ok()?;
    if !(300..400).contains(&code) {
        return None;
    }

    let location = headers
        .lines()
        .take_while(|line| !line.trim_end_matches('\r').is_empty())
        .find_map(|line| {
            let (name, value) = line.split_once(':')?;
            name.trim()
                .eq_ignore_ascii_case("location")
                .then(|| value.trim())
        })?;

    // A control character is refused rather than carried. `lines()` has already
    // made a CRLF impossible, but a lone carriage return survives in the middle
    // of a value and some servers still treat one as a line terminator, so this
    // would be a remote value spliced into a request line. The blast radius is
    // the peer's own socket, which is why this is hygiene rather than a hole,
    // though the class is worth removing.
    if location.is_empty() || location.chars().any(char::is_control) {
        return None;
    }

    match location {
        // An absolute URL, which is what a great many servers send: Grafana,
        // Portainer and Prometheus all answer `GET /` with a `Location` naming
        // themselves in full. Declining every one of them left three of five
        // self-hosted applications unidentified on a test segment, because the
        // page that names them is the one behind the redirect.
        //
        // So the host is compared rather than the shape. `peer` is the port
        // being identified, and only a URL naming it is followed; anything else
        // is somebody else's, and a scan of one address has no business putting
        // traffic on an uninvolved host.
        url if url.contains("://") || url.starts_with("//") => peer?.path_of(url),
        // Same host by construction: a path is relative to where it was served.
        path if path.starts_with('/') => Some(path.to_string()),
        // A relative reference, which RFC 7231 §7.1.2 permits and RFC 2616 did
        // not. Jellyfin answers `GET /` with `Location: web/`, and reading that
        // as "somewhere else" left the page it points at unread. Every caller
        // here issues its request at the root, so a reference resolves against
        // `/`; a caller requesting a deeper path would have to resolve it
        // against that instead.
        relative => Some(format!("/{relative}")),
    }
}

/// Fetches `path` from `peer` over a fresh connection and returns whatever
/// came back.
///
/// A new connection rather than the one in hand: the response carrying the
/// redirect may well have closed it, and a follow-up written into a socket the
/// peer has already gone away from is a write that succeeds and a read that
/// never returns. One round trip, and only on a response that asked for it,
/// leaving by `egress` as the connection that drew the redirect did.
///
/// Through a handshake of its own where the port is spoken to through TLS,
/// naming the site the port is asked for as the first did.
async fn follow_redirect(peer: &Authority, path: &str, egress: Egress) -> Option<String> {
    let stream = dial_again(peer.socket(), egress, Some(on_path(CONNECT_RETRY_TIMEOUT)))
        .await
        .ok()?;
    match peer.is_tls() {
        true => {
            let (mut tunnel, _) = tls::handshake(stream, peer.server_name()).await?;
            ask_for(&mut tunnel, peer, path).await
        }
        false => {
            let mut stream = stream;
            ask_for(&mut stream, peer, path).await
        }
    }
}

/// Asks `stream` for `path` on `peer` and reads the document that comes back.
async fn ask_for<S>(stream: &mut S, peer: &Authority, path: &str) -> Option<String>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    // `Host` names the port actually being identified, which is what a virtual
    // host would route on and is in any case more truthful than a placeholder.
    let request = format!(
        "GET {path} HTTP/1.1\r\nHost: {}\r\nUser-Agent: {USER_AGENT}\r\n\
         Accept: */*\r\nConnection: close\r\n\r\n",
        peer.header()
    );
    stream.write_all(request.as_bytes()).await.ok()?;

    read_document(stream, PROBE_READ_TIMEOUT).await
}

/// `banners` with the page the first HTTP reply among them redirects to
/// added, where the redirect leads back to `peer`; see [`redirect_path`].
///
/// Asked wherever a port answers its probes, a claimed one and one through TLS
/// as much as one nothing claims, since the root of a self-hosted application
/// is often a redirect and nothing else, and the ports it is served on most
/// are the ones a service claims. The connection that drew the redirect is to
/// be closed before this runs, so the identification holds one socket at a
/// time.
async fn with_redirect_followed(
    mut banners: Vec<String>,
    peer: Option<&Authority>,
    egress: Egress,
) -> Vec<String> {
    let Some(peer) = peer else {
        return banners;
    };
    let path = banners
        .iter()
        .find(|reply| reply.starts_with("HTTP/"))
        .and_then(|reply| redirect_path(reply, Some(peer)));
    if let Some(path) = path
        && let Some(page) = follow_redirect(peer, &path, egress).await
    {
        banners.push(page);
    }
    banners
}

/// Whether `bytes` open a TLS record.
///
/// A content type in the range TLS defines, then a major version of 3 and a
/// minor version no higher than TLS 1.3 uses on the wire. What this catches in
/// practice is the alert a TLS server sends when it is handed a plaintext
/// request: our `G` of `GET` is not a record type it knows, so it says so and
/// closes. Read as text that alert is a handful of unprintable bytes, and taking
/// it for a banner would leave a TLS service reported as an unidentifiable one.
fn looks_like_tls(bytes: &[u8]) -> bool {
    matches!(bytes, [0x14..=0x17, 0x03, 0x00..=0x04, ..])
}

/// What a port numbered for TLS turns out to speak, where a modern handshake
/// would not complete.
///
/// rustls implements TLS 1.2 and 1.3 and implements neither 1.0 nor 1.1, so a
/// legacy-only server fails the rung above this one and would otherwise go down
/// as a port that answered nothing.
///
/// The result carries no certificate and no tunnel. A legacy handshake sends its
/// certificate in the clear and reading it would be possible, and it is
/// not done here: the finding is the version, and a second binary
/// parser over remote bytes wants an argument of its own before it exists.
async fn legacy_tls(stream: TcpStream) -> ResponseSet {
    match tls::legacy_version(stream).await {
        Some(version) => {
            ResponseSet::default().with_tls(TlsInfo::new(Vec::new()).with_version(version))
        }
        None => ResponseSet::default(),
    }
}

/// Given the outcome of a handshake, re-probes through the tunnel (if it
/// completed) and packages the decrypted responses with the captured
/// certificate. A failed handshake yields nothing.
async fn tunneled(
    handshake: Option<(tls::TlsTunnel, TlsInfo)>,
    port: u16,
    peer: &Authority,
    egress: Egress,
) -> (ResponseSet, Option<Tunnel>) {
    let Some((mut tunnel, info)) = handshake else {
        return (ResponseSet::default(), None);
    };
    // Inside the tunnel the port's own probes apply if it has any, and the
    // generic question if it does not, since the protocol under TLS is as
    // unidentified as it would have been in the clear. A caller who asked to
    // send nothing never reaches here: `gather` returns before the handshake.
    //
    // The generic question goes out without listening first, as it does in
    // the clear; see `ask_generically` for why that loses no greeting.
    let db = SignatureDb::global();
    let peer = peer.through_tls();
    let mut conversations = db.tcp_probe_conversations(port);
    let mut drawn = match conversations.next() {
        Some(own) => {
            let listen = !db.asked_first(port);
            collect_responses(&mut tunnel, port, own, Some(&peer), listen).await
        }
        None => {
            let generic = db.generic_tcp_probe_payloads();
            collect_responses(&mut tunnel, port, generic, Some(&peer), false).await
        }
    };

    // Every other service's questions, each through a handshake of its own,
    // for the reason they are each asked on a connection of their own in the
    // clear: a question in one protocol is very often the end of a
    // conversation in another, and a web server closes its connection after
    // one answer as readily through TLS as without it. A tunnel is torn down
    // with its connection, so one shared by the services sharing the port
    // would carry the first service's questions and nobody else's. See
    // `Conversations`. What that costs is a handshake per service after the
    // first, on the few ports several services share.
    let mut held = Some(tunnel);
    for probes in conversations {
        drop(held.take());
        held = retunneled(&peer, egress).await;
        let Some(tunnel) = held.as_mut() else {
            break;
        };
        drawn.extend(ask_in_turn(tunnel, port, probes, Some(&peer)).await);
    }
    drop(held);
    drawn.banners = with_redirect_followed(drawn.banners, Some(&peer), egress).await;
    (drawn.with_tls(info), Some(Tunnel::Tls))
}

/// A fresh tunnel to a port whose handshake has already completed once, or
/// `None` where it can no longer be dialled or no longer completes one.
async fn retunneled(peer: &Authority, egress: Egress) -> Option<tls::TlsTunnel> {
    let stream = redial(peer.socket(), egress).await?;
    let (tunnel, _) = tls::handshake(stream, peer.server_name()).await?;
    Some(tunnel)
}

/// Grabs a first-speak banner where `listen` says one may come, then sends
/// `probes` over `stream`, returning every non-empty response. Generic over the
/// transport, so it runs identically on a raw socket or inside a TLS tunnel.
///
/// Not listening costs no greeting a port sends: one sent on connect is
/// already on its way when the first probe is written, and is read as the
/// first reply. What listening buys is not interrupting a service before it
/// has spoken, and on a port that never speaks first it is a wait that always
/// runs out; see [`SignatureDb::asked_first`].
///
/// The probes are passed in rather than looked up, because the caller is what
/// knows which set applies: a port's own where it has them, and the generic set
/// where it does not. Each is addressed to `peer` where there is one; see
/// [`Authority::addressed`].
async fn collect_responses<S>(
    stream: &mut S,
    port: u16,
    probes: &[Vec<u8>],
    peer: Option<&Authority>,
    listen: bool,
) -> ResponseSet
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    let mut drawn = ResponseSet::default();

    // Many services announce themselves on connect.
    if listen && let Some(banner) = read_response(stream, BANNER_READ_TIMEOUT).await {
        drawn.banners.push(banner);
    }

    drawn.extend(ask_in_turn(stream, port, probes, peer).await);
    drawn
}

/// Sends `probes` over `stream` one after another, each addressed to `peer`
/// where there is one, and returns what each drew: the fields of a reply this
/// engine reads as structure, then its text, and apart from both the names it
/// gave for the machine.
///
/// Nothing is listened for first. A service that greets has already sent its
/// greeting by the time the first probe goes, and it arrives ahead of the
/// reply; see [`ask_generically`], which relies on the same order.
async fn ask_in_turn<S>(
    stream: &mut S,
    port: u16,
    probes: &[Vec<u8>],
    peer: Option<&Authority>,
) -> ResponseSet
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    let mut drawn = ResponseSet::default();
    for payload in probes {
        let payload = match peer {
            Some(peer) => peer.addressed(payload),
            None => Cow::Borrowed(&payload[..]),
        };
        if stream.write_all(&payload).await.is_err() {
            break;
        }
        let Some(bytes) = read_bytes(stream, PROBE_READ_TIMEOUT, CONTINUATION_GRACE).await else {
            continue;
        };
        // A reply this engine can read as structure is offered as the fields it
        // holds, before the text of the whole. See `extract::from_stream`.
        drawn.banners.extend(extract::from_stream(port, &bytes));
        drawn.banners.push(extract::reply_text(&bytes));
        drawn.names.extend(extract::names_from_stream(port, &bytes));
    }

    drawn
}

/// How the port being fingerprinted is dialled after its first connection,
/// and how long it is waited on.
struct Dialling {
    /// The egress the port was reached by, which every further connection
    /// leaves by.
    egress: Egress,
    /// What the path to the port adds to every wait on it; see [`on_path`].
    path: PathAllowance,
    /// What the identification's connections and reads came to, beyond what
    /// they drew.
    tally: Arc<Tally>,
}

/// What an identification's connections and reads came to beyond what they
/// drew, told from wherever in its scope they happened; see [`Fingerprinted`].
#[derive(Debug, Default)]
struct Tally {
    /// A connection was given up for want of a socket; see [`dial_again`].
    starved: AtomicBool,
    /// A wait for the port to say something ran its clock out with nothing
    /// heard.
    ran_out_waiting: AtomicBool,
    /// A reply came only after more than half the wait it was given, net of
    /// the path; see [`Fingerprinted::answered_late`].
    answered_late: AtomicBool,
    /// How long the waits that ran out were given, together.
    waited_in_vain: std::sync::Mutex<Duration>,
}

impl Tally {
    /// Notes a wait for the port to say something that ran out after `wait`.
    fn ran_out(&self, wait: Duration) {
        self.ran_out_waiting.store(true, Ordering::Relaxed);
        *self
            .waited_in_vain
            .lock()
            .unwrap_or_else(|held| held.into_inner()) += wait;
    }
}

/// Tells the identification whose scope this runs in something its
/// connections or reads came to. Nothing is told outside one, which is an
/// analyzer or a read driven directly rather than through a scan.
fn tell(what: impl FnOnce(&Tally)) {
    let _ = DIALLING.try_with(|dialling| what(&dialling.tally));
}

/// `wait`, which a path that costs nothing needs, on the path to the port
/// being identified.
///
/// Every wait on the port, for a connection, a greeting, a reply or a
/// handshake, is set for how long the service may take to answer. A path that
/// costs a round trip adds it to each of them, and a wait that does not allow
/// for it gives up on an answer still on its way: behind a path of two
/// seconds, every greeting and every reply. The allowance is what the scan
/// measured of the path, sized as the port scans size their own probes'; see
/// [`PathAllowance`]. Outside an identification's scope the wait is as set.
fn on_path(wait: Duration) -> Duration {
    DIALLING
        .try_with(|dialling| dialling.path.over(wait))
        .unwrap_or(wait)
}

/// How much of `elapsed`, the time a reply from the port being identified
/// took, was the service's rather than the path's; see
/// [`PathAllowance::service_time`]. All of it outside an identification's
/// scope.
fn service_time(elapsed: Duration) -> Duration {
    DIALLING
        .try_with(|dialling| dialling.path.service_time(elapsed))
        .unwrap_or(elapsed)
}

/// [`on_path`] for a budget spanning `waits` waits on the port one after
/// another, each allowing for the path once.
fn on_path_each(budget: Duration, waits: u32) -> Duration {
    DIALLING
        .try_with(|dialling| dialling.path.over_each(budget, waits))
        .unwrap_or(budget)
}

tokio::task_local! {
    /// How the port being fingerprinted is dialled, by its later questions
    /// and by its analyzers.
    ///
    /// A scope rather than an argument because an analyzer is handed a
    /// [`PortContext`], which is public, non-exhaustive, and built by struct
    /// literal throughout the crate; what an analyzer dials through, and how
    /// it reports a connection the process could not make, is the engine's
    /// business and not a field a caller outside it could fill. Set around
    /// the whole identification, whose collection runs inline on the task
    /// that set it: the one task it spawns is the CPU phase, which dials
    /// nothing, so no connection is made from where the scope cannot reach.
    static DIALLING: Dialling;
}

/// Connects to `addr` for an analyzer, the way the port it is examining was
/// reached.
///
/// Outside a fingerprint's collection, which is an analyzer driven directly
/// through [`analyze_with`], the routing table decides, as it does for any
/// public entry point here, and a connection refused a socket has no scan to
/// report to.
pub(crate) async fn analyzer_connect(addr: SocketAddr) -> std::io::Result<TcpStream> {
    let egress = DIALLING
        .try_with(|dialling| dialling.egress)
        .unwrap_or(Egress::KERNEL);
    dial_again(addr, egress, None).await
}

/// The analyzer registry. New evidence sources (HTTP, JARM, SNMP, nerva binary
/// handlers, ...) are added here, the only place the set is enumerated. The
/// instances are stateless zero-sized values, so a `'static` slice of shared
/// references is free and lets both phases (and the blocking task) reference the
/// same set.
static ANALYZERS: &[&dyn Analyzer] = &[
    &BannerRegexAnalyzer,
    &FaviconAnalyzer,
    &HttpHeadersAnalyzer,
    &JarmAnalyzer,
    &ldap::LdapAnalyzer,
    &smb::SmbAnalyzer,
    &SshAnalyzer,
    &TlsCertAnalyzer,
];

/// The analyzers this engine runs, in the order they are consulted.
///
/// Exposed so a caller can run the built-in set beside one of their own:
///
/// ```no_run
/// # use zond_engine::fingerprint::{Analyzer, analyzers};
/// # fn example(mine: &'static dyn Analyzer) {
/// let mut set: Vec<&'static dyn Analyzer> = analyzers().to_vec();
/// set.push(mine);
/// # }
/// ```
///
/// The order is not a ranking. Evidence is ranked by
/// [`ServiceVerdict::resolve`], which sorts by confidence and breaks ties
/// stably, so this decides only what a full tie falls back on.
#[must_use]
pub fn analyzers() -> &'static [&'static dyn Analyzer] {
    ANALYZERS
}

/// Runs the registered analyzers over `responses` and resolves their evidence
/// into a verdict, honouring the two-phase contract: each interested analyzer's
/// [`collect`](Analyzer::collect) runs here on the reactor (I/O), then all the
/// [`analyze`](Analyzer::analyze) work is handed to the blocking pool (CPU).
/// `tunnel` marks how the shared responses were carried, so evidence drawn from
/// decrypted data is labelled accordingly. Returns `None` if analysis produced
/// nothing (or the blocking task failed to join).
async fn analyze(
    port: u16,
    protocol: Protocol,
    addr: Option<std::net::SocketAddr>,
    responses: ResponseSet,
    tunnel: Option<Tunnel>,
    detection: ServiceDetection,
    name: Option<Arc<str>>,
) -> Option<ServiceVerdict> {
    // Read before the context is built, so an active analyzer's `collect` can
    // gate on it: `collect` is handed no responses and runs before any evidence
    // is resolved.
    let speaks_http = responses
        .banners
        .iter()
        .any(|banner| banner.starts_with("HTTP/"));

    let ctx = PortContext::new(port, protocol)
        .with_addr(addr)
        .with_tunnel(tunnel)
        .with_speaks_http(speaks_http)
        .with_detection(detection)
        .with_host_name(name.map(|name| name.to_string()));
    analyze_with(ctx, responses, analyzers()).await
}

/// Runs `analyzers` over `responses` and resolves their evidence into a verdict,
/// honouring the two-phase contract.
///
/// Each interested analyzer's [`collect`](Analyzer::collect) runs here on the
/// reactor (I/O), then all the [`analyze`](Analyzer::analyze) work is handed to
/// the blocking pool (CPU). Returns `None` if analysis produced nothing, or if
/// the blocking task failed to join.
///
/// This is where a caller's own analyzer goes. Gather responses by whatever
/// means, with [`fingerprint_tcp_detailed`] handing back the ones it read, then
/// pass [`analyzers()`] alongside it:
///
/// ```no_run
/// # use zond_engine::fingerprint::{Analyzer, PortContext, ResponseSet, analyze_with, analyzers};
/// # use zond_engine::model::port::Protocol;
/// # async fn example(mine: &'static dyn Analyzer) {
/// let mut set: Vec<&'static dyn Analyzer> = analyzers().to_vec();
/// set.push(mine);
/// // Leaked once at start-up, which is what a `'static` set means in practice.
/// let set: &'static [&'static dyn Analyzer] = Box::leak(set.into_boxed_slice());
///
/// let ctx = PortContext::new(8080, Protocol::Tcp);
/// let responses = ResponseSet::from_banners(vec!["HTTP/1.1 200 OK".to_string()]);
/// let verdict = analyze_with(ctx, responses, set).await;
/// # }
/// ```
///
/// The slice is `'static` because the CPU phase runs on the blocking pool and
/// has to own what it reads. That costs nothing in practice: an analyzer is a
/// stateless value, so a `static` of them is the natural way to hold a set, and
/// it is how the built-in registry is held.
pub async fn analyze_with(
    ctx: PortContext,
    responses: ResponseSet,
    analyzers: &'static [&'static dyn Analyzer],
) -> Option<ServiceVerdict> {
    // Phase 1, I/O on the reactor: let each interested analyzer run its own
    // probes. Passive analyzers return an empty `Collected`, their inputs being
    // in the shared `responses`.
    //
    // `interested` is asked once and the answer kept, rather than asked again in
    // the CPU phase: it is documented as a cheap gate, and a gate answering
    // differently between the two phases would silently pair one analyzer's
    // frames with another's reading.
    let mut collected = Vec::with_capacity(analyzers.len());
    for analyzer in analyzers {
        let interested = analyzer.interested(&ctx);
        collected.push((
            interested,
            match interested {
                true => analyzer.collect(&ctx, &responses).await,
                false => Collected::default(),
            },
        ));
    }

    // Phase 2, CPU off the reactor: parse the shared responses plus each
    // analyzer's own frames into evidence, then resolve. A large match set can
    // never stall the scheduler from here.
    off_the_reactor(move || {
        let mut evidence = Vec::new();
        for (analyzer, (interested, collected)) in analyzers.iter().zip(&collected) {
            if *interested {
                evidence.extend(analyzer.analyze(&ctx, &responses, collected));
            }
        }

        (!evidence.is_empty()).then(|| ServiceVerdict::resolve(evidence))
    })
    .await
    .flatten()
}

/// How many threads the CPU phase of [`analyze_with`] runs on.
///
/// Few, and the same ones for the life of the process, for memory rather
/// than speed. A compiled regex keeps a search cache for the first thread to
/// use it and one more for each of up to eight groups of other threads,
/// sorted by thread number, and keeps them all until it is dropped, which for
/// the built-in signatures is never. A cache is sized by the regex, so a
/// signature's caches cost several times the signature. Measured on 5,000
/// identifications of ten banners, their signatures already compiled: on
/// tokio's blocking pool, whose threads come and go, the process went from
/// 57 MB to 200 MB, and on one thread from 53 MB to 60.
///
/// One costs little throughput. Matching a banner against the signatures that
/// could match it is some tens of microseconds, and compiling a signature,
/// which is the expensive part, happens once and on every core; see
/// [`SignatureDb::warm`]. The same 5,000 took 185 ms on one thread against
/// 140 on the blocking pool, and a scan spends its time waiting on the
/// network.
const ANALYSIS_THREADS: usize = 1;

/// The identification threads, see [`ANALYSIS_THREADS`], started on first
/// use, or `None` where they could not be.
fn analysis_pool() -> Option<&'static rayon::ThreadPool> {
    static POOL: std::sync::OnceLock<Option<rayon::ThreadPool>> = std::sync::OnceLock::new();

    POOL.get_or_init(|| {
        rayon::ThreadPoolBuilder::new()
            .num_threads(ANALYSIS_THREADS)
            .thread_name(|index| format!("zond-identify-{index}"))
            .build()
            .ok()
    })
    .as_ref()
}

/// Runs `work` on the identification threads, see [`ANALYSIS_THREADS`], and
/// hands back what it returns, or `None` if it panicked.
///
/// Falls back to tokio's blocking pool if the threads cannot be started, so
/// identification never fails for want of them; it only costs more memory.
async fn off_the_reactor<T: Send + 'static>(
    work: impl FnOnce() -> T + Send + 'static,
) -> Option<T> {
    let Some(pool) = analysis_pool() else {
        return tokio::task::spawn_blocking(work).await.ok();
    };

    let (sender, receiver) = tokio::sync::oneshot::channel();
    pool.spawn(move || {
        // Caught, since a panic on a rayon thread aborts the process, and a
        // panicking analyzer is a finding lost rather than a scan lost, as it
        // is on the blocking pool.
        let done = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work));
        let _ = sender.send(done.ok());
    });
    receiver.await.ok().flatten()
}

/// Runs `match_work`, a match against the signature corpus, on the
/// identification threads, blocking the caller until it is done, and hands
/// back what it returns.
///
/// For a caller asking the corpus directly rather than through
/// [`analyze_with`]. A compiled regex keeps a search cache for each thread
/// that uses it, for as long as it is compiled, which for the corpus is the
/// life of the process, so matches made wherever callers happen to be would
/// leave every signature a cache per thread that ever touched it; see
/// [`ANALYSIS_THREADS`]. Kept on one thread, each signature has one.
///
/// Called on the identification threads it runs in place. Where they could
/// not be started it runs on the caller's thread, which costs memory and
/// nothing else. A panic in `match_work` reaches the caller as it would have
/// in place.
pub(crate) fn on_the_matching_thread<T: Send>(match_work: impl FnOnce() -> T + Send) -> T {
    match analysis_pool() {
        Some(pool) => pool.install(match_work),
        None => match_work(),
    }
}

/// Reads one bounded chunk from `stream`, giving up after `wait`. Returns `None`
/// on timeout, error, or a clean empty read.
async fn read_response<S>(stream: &mut S, wait: Duration) -> Option<String>
where
    S: AsyncRead + Unpin,
{
    read_bytes(stream, wait, Duration::ZERO)
        .await
        .map(|bytes| extract::reply_text(&bytes))
}

/// [`read_response`], but reading on until the port goes quiet.
///
/// For a reply that may be a *document* rather than a line. One `read` returns
/// one segment, and an HTTP server that writes its headers and its body
/// separately hands over the headers alone, so the `Server` header arrives and
/// the `<title>` that names the application does not, on the ports where the
/// title is the only thing that would have named it.
///
/// Deliberately not what a banner grab uses. A greeting is one short write and
/// waiting on for a second one costs [`CONTINUATION_GRACE`] on every port that
/// greets, which is the fastest path there is and the last one worth taxing.
async fn read_document<S>(stream: &mut S, wait: Duration) -> Option<String>
where
    S: AsyncRead + Unpin,
{
    read_bytes(stream, wait, CONTINUATION_GRACE)
        .await
        .map(|bytes| extract::reply_text(&bytes))
}

/// Reads up to [`MAX_RESPONSE_BYTES`] of whatever the port sends, waiting `wait`
/// for the first byte, allowing for the path (see [`on_path`]), and `grace` for
/// each read after it.
///
/// It tells the identification it reads for when the first byte came late in
/// its wait or not at all; see [`Fingerprinted::answered_late`] and
/// [`Fingerprinted::ran_out_waiting`].
///
/// A `grace` of zero reads exactly once, which is what a banner grab wants; a
/// non-zero one reads on until the port goes quiet, which is what a document
/// wants. See [`read_response`] and [`read_document`].
///
/// Bytes rather than text, because the caller sometimes has to tell a banner
/// from a TLS alert, and a reading as text moves every byte behind the first
/// one from 0x80 up.
///
/// # Three bounds, each owning one thing
///
/// `wait` is how long the port has to say anything at all. `grace` is how long a
/// gap between two reads may be. [`MAX_CONTINUATION`] is how long the whole
/// remainder may take once the first byte has arrived, and it is the one that
/// makes the others safe: a peer that stays inside `grace` indefinitely is
/// inside every per-read bound and past any sensible total, which is how one
/// port held this function for ninety-seven seconds.
async fn read_bytes<S>(stream: &mut S, wait: Duration, grace: Duration) -> Option<Vec<u8>>
where
    S: AsyncRead + Unpin,
{
    // Late is judged against the service's own wait, net of the path: a
    // reply across a slow path takes its round trip whatever the service
    // does, and only the rest says whether a second answer would have fit.
    let late = wait / 2;
    let wait = on_path(wait);
    let asked = tokio::time::Instant::now();
    let mut collected: Vec<u8> = Vec::new();
    let mut buffer = [0u8; MAX_RESPONSE_BYTES];
    let mut budget = wait;
    // Set on the first byte rather than on entry, so a port that took its time
    // greeting is not then charged for it twice.
    let mut deadline = None;

    while collected.len() < MAX_RESPONSE_BYTES {
        let first = collected.is_empty();
        match timeout(budget, stream.read(&mut buffer)).await {
            Ok(Ok(n)) if n > 0 => {
                if first && service_time(asked.elapsed()) > late {
                    tell(|tally| tally.answered_late.store(true, Ordering::Relaxed));
                }
                let room = MAX_RESPONSE_BYTES - collected.len();
                collected.extend_from_slice(&buffer[..n.min(room)]);
                if grace.is_zero() {
                    break;
                }
                let deadline =
                    *deadline.get_or_insert_with(|| tokio::time::Instant::now() + MAX_CONTINUATION);
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                if remaining.is_zero() {
                    break;
                }
                budget = grace.min(remaining);
            }
            // Nothing at all within the wait, which the identification is
            // told, since a port that said nothing in time may yet have been
            // about to.
            Err(_elapsed) if first => {
                tell(|tally| tally.ran_out(wait));
                break;
            }
            // A clean close, an error, or the port going quiet: whatever has
            // arrived is all there is.
            _ => break,
        }
    }

    (!collected.is_empty()).then_some(collected)
}

/// The first 32 printable characters across `responses`, for a last-resort
/// banner label. `None` if there is nothing printable.
fn first_printable(responses: &[String]) -> Option<String> {
    let printable: String = responses
        .iter()
        .flat_map(|response| response.chars())
        .filter(|c| c.is_ascii_graphic() || *c == ' ')
        .take(32)
        .collect();

    (!printable.is_empty()).then_some(printable)
}

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

#[cfg(test)]
mod tests {
    use crate::testing::loopback::accept_from_this_process;

    /// One SNMP reply is one witness to what a host runs.
    ///
    /// A rule that names the box files its maker with the host's hardware, and
    /// identification then read the same maker back as the hardware vendor and
    /// counted it a second time. This MikroTik switch's description reached 86 on
    /// one datagram, past the 85 at which the active OS probe is skipped as having
    /// nothing left to settle. The host here is one reached through a gateway, so
    /// no hardware address stands behind the vendor at all.
    #[test]
    fn a_service_describing_its_hardware_is_one_witness_and_not_two() {
        let evidence = SignatureDb::global()
            .identify(161, Protocol::Udp, "CSS326-24G-2S+ SwOS v2.13")
            .expect("the corpus knows SwOS");
        assert!(
            evidence.os.is_some() && evidence.hardware.is_some(),
            "test premise: the rule names both the system and the box"
        );

        let mut host = crate::model::host::Host::new("192.0.2.1".parse().expect("literal"));
        AboutTheHost::from_evidence(&[evidence]).apply(&mut host);

        let os = host
            .os()
            .expect("an SNMP description is a verdict on its own");
        assert!(
            !os.is_highly_confident(),
            "one reply settled the host at {}",
            os.accuracy()
        );
    }

    /// A port number nothing is registered under yields no service at all.
    ///
    /// The alternative is a placeholder, and a placeholder is a service name as
    /// far as every consumer is concerned. The exported JSON, the CSV, the HTML
    /// page and the nmap XML another tool ingests would each say the port is
    /// running something called `???`.
    #[test]
    fn an_unregistered_port_is_seeded_with_nothing() {
        // 1 is `tcpmux` and registered; a high ephemeral port is not.
        assert!(baseline_service(22).is_some());

        let unregistered = (40_000..=65_535)
            .find(|port| lookup_service_name(*port).is_none())
            .expect("some port in the ephemeral range is unregistered");

        assert!(
            baseline_service(unregistered).is_none(),
            "port {unregistered} invented a service name"
        );
        assert!(
            baseline_port(unregistered, Protocol::Tcp, PortState::Closed)
                .service()
                .is_none()
        );
    }

    /// An SCTP port carries the name of whatever claims its number, which for
    /// the ports a scan of a mobile core asks about is the whole of what this
    /// engine can say about them.
    ///
    /// Nothing here fingerprints an SCTP service: naming one needs a completed
    /// association, and the scan opens none. A port reported with no label at
    /// all is the alternative, and `2905/sctp open` tells a reader less than
    /// their own notes would.
    #[test]
    fn an_sctp_port_is_named_by_the_service_that_claims_its_number() {
        let port = baseline_port(2905, Protocol::Sctp, PortState::Open);
        let service = port.service().expect("m3ua claims 2905");

        assert_eq!(service.name(), "m3ua");
        assert!(
            service.is_inferred(),
            "nothing asked the port what it was running"
        );
    }

    /// And what is seeded is marked as the guess it is.
    #[test]
    fn a_seeded_label_is_never_mistaken_for_an_identification() {
        let seeded = baseline_service(22).expect("ssh is registered");
        assert_eq!(seeded.name(), "ssh");
        assert!(
            seeded.is_inferred(),
            "nothing asked port 22 what it was running"
        );
    }
    /// The root of a self-hosted application is very often a redirect and
    /// nothing else, and the page one hop away is the only thing that names it.
    #[test]
    fn a_same_host_redirect_names_where_to_look_next() {
        let jellyfin = "HTTP/1.1 302 Found\r\n\
             Location: /web/index.html\r\n\
             Server: Kestrel\r\n\r\n";
        assert_eq!(
            redirect_path(jellyfin, Some(&peer())).as_deref(),
            Some("/web/index.html")
        );
    }

    /// The port a redirect test pretends to be identifying.
    fn peer() -> Authority {
        Authority::new("127.0.0.1:8096".parse().expect("a literal address"))
    }

    /// RFC 7231 §7.1.2 permits a relative reference, which RFC 2616 did not, and
    /// real servers send one: Jellyfin answers `GET /` with `Location: web/`.
    /// Reading that as somewhere else left the page it points at unread, and the
    /// application unidentified on a host that was serving its own name one hop
    /// away.
    #[test]
    fn a_relative_location_resolves_against_the_root_it_was_served_from() {
        let jellyfin = "HTTP/1.1 302 Found\r\nLocation: web/\r\nServer: Kestrel\r\n\r\n";
        assert_eq!(
            redirect_path(jellyfin, Some(&peer())).as_deref(),
            Some("/web/")
        );
    }

    /// Grafana, Portainer and Prometheus all answer `GET /` with a `Location`
    /// naming themselves in full. Declining every absolute URL left the page
    /// that identifies them unread on all three.
    #[test]
    fn an_absolute_location_naming_the_scanned_host_is_followed() {
        let grafana = "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:8096/login\r\n\r\n";
        assert_eq!(
            redirect_path(grafana, Some(&peer())).as_deref(),
            Some("/login")
        );

        // No path is the root, not an empty request line.
        let bare = "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:8096\r\n\r\n";
        assert_eq!(redirect_path(bare, Some(&peer())).as_deref(), Some("/"));
    }

    /// A different port is a different service, over a connection this path has
    /// not made. Same address, and still declined.
    #[test]
    fn an_absolute_location_on_another_port_is_declined() {
        let elsewhere = "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:9999/x\r\n\r\n";
        assert_eq!(redirect_path(elsewhere, Some(&peer())), None);
    }

    /// A scheme this path cannot speak needs a handshake there is no socket for.
    #[test]
    fn an_upgrade_to_https_is_declined_rather_than_guessed() {
        let upgrade = "HTTP/1.1 301 Moved\r\nLocation: https://127.0.0.1:8096/\r\n\r\n";
        assert_eq!(redirect_path(upgrade, Some(&peer())), None);
    }

    /// With no address to compare against, an absolute URL cannot be shown to be
    /// the host in hand, so it is not followed.
    #[test]
    fn an_absolute_location_is_declined_when_there_is_no_peer_to_check() {
        let named = "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:8096/login\r\n\r\n";
        assert_eq!(redirect_path(named, None), None);
    }

    /// A scheme-relative reference names a host, so it is somewhere else however
    /// much it looks like a path.
    #[test]
    fn a_scheme_relative_location_is_declined_like_any_other_host() {
        let elsewhere = "HTTP/1.1 302 Found\r\nLocation: //cdn.example/web/\r\n\r\n";
        assert_eq!(redirect_path(elsewhere, Some(&peer())), None);

        // The same spelling, naming the host in hand, is followed.
        let here = "HTTP/1.1 302 Found\r\nLocation: //127.0.0.1:8096/web/\r\n\r\n";
        assert_eq!(redirect_path(here, Some(&peer())).as_deref(), Some("/web/"));
    }

    /// A redirect somewhere else is an instruction to go and talk to a third
    /// party. A scan of one address has no business putting traffic on an
    /// uninvolved host, and attributing what came back to the host being scanned
    /// would be wrong even if it did.
    #[test]
    fn a_redirect_off_the_host_is_declined() {
        for location in [
            "https://example.com/login",
            "http://somewhere.else/",
            // A scheme change needs a handshake this path has no socket for.
            "https://127.0.0.1/web/",
            // A lone carriage return is not a CRLF and survives `lines()`, and
            // some servers read one as a line terminator. Nothing remote is
            // spliced into a request this engine writes.
            "/web/\rX-Injected: 1",
            "/web/\u{0}index.html",
        ] {
            let response = format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\n\r\n");
            assert_eq!(
                redirect_path(&response, Some(&peer())),
                None,
                "`{location}` is not somewhere this scan may follow"
            );
        }
    }

    /// Only a redirect is followed. A page that answered is the answer.
    #[test]
    fn a_response_that_is_not_a_redirect_names_nowhere_to_go() {
        assert_eq!(
            redirect_path(
                "HTTP/1.1 200 OK\r\nLocation: /ignored\r\n\r\n",
                Some(&peer())
            ),
            None,
            "a 200 is an answer, whatever else it carries"
        );
        assert_eq!(
            redirect_path("HTTP/1.1 302 Found\r\nServer: nginx\r\n\r\n", Some(&peer())),
            None,
            "and a redirect naming nowhere leads nowhere"
        );
        assert_eq!(
            redirect_path("SSH-2.0-OpenSSH_9.2p1\r\n", Some(&peer())),
            None
        );
        assert_eq!(redirect_path("", Some(&peer())), None);
    }

    /// An IPv6 address is written in brackets wherever a port may follow it,
    /// so a server naming itself by its IPv6 address names it bracketed, and a
    /// scan of that address follows the redirect as it would an IPv4 one.
    #[test]
    fn an_ipv6_redirect_naming_the_scanned_host_is_followed() {
        let peer: SocketAddr = "[2001:db8::1]:8096".parse().expect("a literal address");
        let grafana = "HTTP/1.1 302 Found\r\nLocation: http://[2001:db8::1]:8096/login\r\n\r\n";
        assert_eq!(
            redirect_path(grafana, Some(&Authority::new(peer))).as_deref(),
            Some("/login")
        );

        let elsewhere = "HTTP/1.1 302 Found\r\nLocation: http://[2001:db8::2]:8096/login\r\n\r\n";
        assert_eq!(redirect_path(elsewhere, Some(&Authority::new(peer))), None);
    }

    /// The `Host` a redirect is followed with names an IPv6 address in
    /// brackets. Unbracketed, its last group reads as a port, and a server
    /// either refuses the request or routes it to a site that is not there.
    #[tokio::test]
    async fn a_redirect_on_ipv6_is_asked_for_by_a_bracketed_host() {
        let Ok(listener) = tokio::net::TcpListener::bind("[::1]:0").await else {
            eprintln!("SKIP: no IPv6 loopback on this machine");
            return;
        };
        let addr = listener.local_addr().expect("a local address");
        let server = tokio::spawn(async move {
            let mut first = accept_from_this_process(&listener)
                .await
                .expect("the first connection");
            let mut buffer = [0u8; 1024];
            let _ = first.read(&mut buffer).await;
            let _ = first
                .write_all(b"HTTP/1.1 302 Found\r\nLocation: /next\r\nContent-Length: 0\r\n\r\n")
                .await;
            drop(first);
            let mut second = accept_from_this_process(&listener)
                .await
                .expect("the redirect followed");
            let read = second.read(&mut buffer).await.unwrap_or(0);
            let _ = second
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
                .await;
            String::from_utf8_lossy(&buffer[..read]).into_owned()
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let _ = plaintext(stream, 51987, Some(&Authority::new(addr)), Egress::KERNEL).await;
        let request = server.await.expect("the listener finishes");

        let host = format!("\r\nHost: [::1]:{}\r\n", addr.port());
        assert!(
            request.contains(&host),
            "the redirect was asked for without `{}`: {request:?}",
            host.trim()
        );
    }

    /// A TLS record is not a banner, and reading one as text loses exactly the
    /// bytes that say so. What a TLS server sends a plaintext request is an
    /// alert, and taking it for a greeting leaves the port unidentifiable.
    #[test]
    fn a_tls_alert_is_recognised_as_tls_rather_than_as_a_banner() {
        // Alert, TLS 1.2, two bytes: fatal, unexpected_message.
        assert!(looks_like_tls(&[0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x0A]));
        // A ServerHello, for a peer that answered the handshake it expected.
        assert!(looks_like_tls(&[0x16, 0x03, 0x01, 0x00, 0x2A]));

        assert!(!looks_like_tls(b"HTTP/1.1 200 OK"));
        assert!(!looks_like_tls(b"SSH-2.0-OpenSSH_9.2p1"));
        assert!(!looks_like_tls(&[0x15]), "too short to be a record");
        assert!(!looks_like_tls(&[]));
    }

    use super::*;

    /// Records the thread its CPU phase ran on, and panics on port 0.
    struct ThreadWitness;

    static WITNESSED: std::sync::Mutex<Vec<std::thread::ThreadId>> =
        std::sync::Mutex::new(Vec::new());

    #[async_trait::async_trait]
    impl Analyzer for ThreadWitness {
        fn id(&self) -> SourceId {
            SourceId::BannerRegex
        }

        fn interested(&self, _ctx: &PortContext) -> bool {
            true
        }

        fn analyze(&self, ctx: &PortContext, _: &ResponseSet, _: &Collected) -> Vec<Evidence> {
            assert!(ctx.port != 0, "the witness was asked about port 0");
            // Long enough that analyses started together overlap, which on a
            // pool of threads puts them on several.
            std::thread::sleep(Duration::from_millis(20));
            WITNESSED
                .lock()
                .expect("the witness list")
                .push(std::thread::current().id());
            vec![
                Evidence::new(
                    SourceId::BannerRegex,
                    crate::model::confidence::Confidence::Weak,
                )
                .with_service("witnessed"),
            ]
        }
    }

    static WITNESS: [&dyn Analyzer; 1] = [&ThreadWitness];

    /// **Every identification's CPU phase runs on the one thread kept for it,
    /// however many run at once, and a panic there loses one verdict and not
    /// the process.**
    ///
    /// A compiled regex keeps a search cache for every thread that has used
    /// it, for as long as it is compiled, so identifications spread over
    /// threads that come and go leave each signature several caches, and the
    /// caches were most of a full-range scan's memory. See
    /// [`ANALYSIS_THREADS`].
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn identification_runs_on_one_kept_thread_and_survives_a_panic() {
        let runs: Vec<_> = (1..=12u16)
            .map(|port| {
                tokio::spawn(analyze_with(
                    PortContext::new(port, Protocol::Tcp),
                    ResponseSet::default(),
                    &WITNESS,
                ))
            })
            .collect();
        for run in runs {
            assert!(run.await.expect("joins").is_some(), "every run is named");
        }

        let threads: std::collections::BTreeSet<String> = WITNESSED
            .lock()
            .expect("the witness list")
            .iter()
            .map(|id| format!("{id:?}"))
            .collect();
        assert_eq!(threads.len(), 1, "identification ran on {threads:?}");

        let panicked = analyze_with(
            PortContext::new(0, Protocol::Tcp),
            ResponseSet::default(),
            &WITNESS,
        )
        .await;
        assert!(panicked.is_none(), "a panicking analyzer names nothing");
        let after = analyze_with(
            PortContext::new(1, Protocol::Tcp),
            ResponseSet::default(),
            &WITNESS,
        )
        .await;
        assert!(after.is_some(), "and identification carries on after it");
    }

    /// A caller matching against the corpus directly, from any thread, is
    /// matched on the thread identification keeps, so the signatures it
    /// reaches keep the one search cache identification left them.
    #[test]
    fn a_direct_match_against_the_corpus_runs_on_the_identification_thread() {
        let threads: std::collections::BTreeSet<Option<String>> = (0..4)
            .map(|_| {
                std::thread::spawn(|| {
                    on_the_matching_thread(|| std::thread::current().name().map(str::to_owned))
                })
            })
            .collect::<Vec<_>>()
            .into_iter()
            .map(|thread| thread.join().expect("joins"))
            .collect();
        assert_eq!(
            threads,
            [Some("zond-identify-0".to_string())].into(),
            "matched on {threads:?}"
        );
    }

    #[tokio::test]
    async fn analyze_runs_both_phases_and_resolves() {
        // Drives the real orchestration, the collect phase (a no-op for the two
        // passive analyzers) followed by the off-reactor analyze phase, over a
        // recorded SSH banner, and asserts it resolves through to a verdict.
        let responses = ResponseSet::from_banners(vec!["SSH-2.0-OpenSSH_9.6p1 Debian".to_string()]);
        let verdict = analyze(
            22,
            Protocol::Tcp,
            None,
            responses,
            None,
            ServiceDetection::default(),
            None,
        )
        .await
        .expect("names a service");

        assert_eq!(verdict.service.as_deref(), Some("ssh"));
        assert_eq!(verdict.product.as_deref(), Some("OpenSSH"));
        assert_eq!(verdict.version.as_deref(), Some("9.6p1"));
    }

    #[tokio::test]
    async fn analyze_identifies_a_long_tail_http_server_end_to_end() {
        // The structured HTTP analyzer must carry a `Server:` value through to
        // product and version via the full pipeline.
        //
        // Two observations read this header and both are `Strong`: splitting it
        // on the slash yields `gunicorn` and nothing else, and the corpus rule
        // for the same value yields `Gunicorn`, the vendor, and the CPE. The
        // curated reading takes the slot, which is the only reason a version
        // here can reach a vulnerability catalogue at all.
        let responses = ResponseSet::from_banners(vec![
            "HTTP/1.1 200 OK\r\nServer: gunicorn/21.2.0\r\nContent-Type: text/html\r\n\r\n"
                .to_string(),
        ]);
        let verdict = analyze(
            8000,
            Protocol::Tcp,
            None,
            responses,
            None,
            ServiceDetection::default(),
            None,
        )
        .await
        .expect("names a service");

        assert_eq!(verdict.service.as_deref(), Some("http"));
        assert_eq!(verdict.product.as_deref(), Some("Gunicorn"));
        assert_eq!(verdict.version.as_deref(), Some("21.2.0"));
        assert_eq!(
            verdict.cpe.as_deref(),
            Some("cpe:/a:gunicorn:gunicorn:21.2.0"),
            "the reading that won the slot is the one the correlator can use"
        );
    }

    #[tokio::test]
    async fn analyze_composes_curated_product_vendor_with_powered_by_extrainfo() {
        // End-to-end composition across analyzers: the curated Apache signature
        // (banner analyzer) supplies the rich product + vendor, the structured
        // HTTP analyzer supplies the X-Powered-By extrainfo, and the framework
        // never usurps the product slot. All three land on one Service.
        let responses = ResponseSet::from_banners(vec![
            "HTTP/1.1 200 OK\r\nServer: Apache/2.4.58\r\nX-Powered-By: PHP/8.2.1\r\n\r\n"
                .to_string(),
        ]);
        let service = analyze(
            80,
            Protocol::Tcp,
            None,
            responses,
            None,
            ServiceDetection::default(),
            None,
        )
        .await
        .expect("names a service")
        .to_service()
        .expect("projects onto a service");

        assert_eq!(service.name(), "http");
        assert_eq!(service.product(), Some("Apache HTTP Server"));
        assert_eq!(service.vendor(), Some("Apache Software Foundation"));
        assert_eq!(service.version(), Some("2.4.58"));
        assert_eq!(service.extrainfo(), Some("PHP/8.2.1"));
    }

    #[tokio::test]
    async fn analyze_resolves_a_versionless_server_to_its_name_not_generic_http() {
        // A versionless `Server` is Probable, the same as the HTTP analyzer's
        // baseline. If the baseline names a product, the stable sort keeps it
        // first and the real server ("cloudflare") is buried under a generic
        // "http". This must resolve to the server name.
        let responses = ResponseSet::from_banners(vec![
            "HTTP/1.1 403 Forbidden\r\nServer: cloudflare\r\n\r\n".to_string(),
        ]);
        let verdict = analyze(
            8000,
            Protocol::Tcp,
            None,
            responses,
            None,
            ServiceDetection::default(),
            None,
        )
        .await
        .expect("names a service");

        assert_eq!(verdict.service.as_deref(), Some("http"));
        assert_eq!(verdict.product.as_deref(), Some("cloudflare"));
    }

    /// A hostile response cannot put a kilobyte into a report.
    ///
    /// Measured before [`MAX_IDENTITY_BYTES`] existed: one reply produced a
    /// 1500-byte `product` and a 1500-byte `extrainfo`, and both travelled into
    /// the store and every export. Every sibling reading in this module already
    /// bounded itself and said why; these had no argument for being unbounded,
    /// only no author.
    #[tokio::test]
    async fn a_hostile_response_cannot_fill_a_report_field() {
        use tokio::net::{TcpListener, TcpStream};

        let listener = TcpListener::bind("127.0.0.1:0").await.expect("a socket");
        let addr = listener.local_addr().expect("its address");
        let server = tokio::spawn(async move {
            let Ok(mut sock) = accept_from_this_process(&listener).await else {
                return;
            };
            let long = "A".repeat(1_500);
            let response =
                format!("HTTP/1.1 200 OK\r\nServer: {long}\r\nX-Powered-By: {long}\r\n\r\n");
            let _ = sock.write_all(response.as_bytes()).await;
            let mut buffer = [0u8; MAX_RESPONSE_BYTES];
            let _ = sock.read(&mut buffer).await;
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(80, Protocol::Tcp, PortState::Open);
        let identified = fingerprint_tcp(stream, port, ServiceDetection::Probe).await;
        server.abort();

        let service = identified.service().expect("the port is still named");
        for (field, value) in [
            ("product", service.product()),
            ("version", service.version()),
            ("extrainfo", service.extrainfo()),
        ] {
            if let Some(value) = value {
                assert!(
                    value.len() <= MAX_IDENTITY_BYTES,
                    "{field} is {} bytes, past the bound",
                    value.len()
                );
            }
        }
        assert_eq!(
            service.product(),
            None,
            "a fifteen-hundred-byte token is refused rather than truncated"
        );
    }

    /// And an ordinary value is untouched by the bound.
    #[test]
    fn an_ordinary_identity_field_passes_through() {
        assert_eq!(identity_field("nginx/1.24.0"), Some("nginx/1.24.0"));
        assert_eq!(identity_field("  PHP/8.2.1  "), Some("PHP/8.2.1"));
        assert_eq!(identity_field(""), None);
        assert_eq!(identity_field("   "), None);
        assert_eq!(
            identity_field(&"A".repeat(MAX_IDENTITY_BYTES)).map(str::len),
            Some(MAX_IDENTITY_BYTES)
        );
        assert_eq!(identity_field(&"A".repeat(MAX_IDENTITY_BYTES + 1)), None);
    }

    /// A legacy-only TLS server is reported, not lost.
    ///
    /// rustls implements TLS 1.2 and 1.3 and implements neither 1.0
    /// nor 1.1, so a server offering only the older versions fails the modern
    /// handshake. Without the legacy probe it would be reported as a port that
    /// answered nothing at all, which loses the identification and the finding
    /// together.
    ///
    /// The mock answers a ClientHello with a TLS 1.0 ServerHello and nothing
    /// else, which is enough: the finding is the version.
    #[tokio::test]
    async fn a_server_that_speaks_only_tls_ten_is_still_recorded() {
        use tokio::net::{TcpListener, TcpStream};

        let listener = TcpListener::bind("127.0.0.1:0").await.expect("a socket");
        let addr = listener.local_addr().expect("its address");
        let server = tokio::spawn(async move {
            // Twice: the modern handshake dials first and is answered with an
            // alert, then the legacy probe dials on its own connection.
            for round in 0..2 {
                let Ok(mut sock) = accept_from_this_process(&listener).await else {
                    return;
                };
                let mut buffer = [0u8; 1024];
                let _ = sock.read(&mut buffer).await;
                let reply: &[u8] = match round {
                    // Fatal alert: protocol_version. What a 1.0-only server
                    // answers a hello offering 1.2 and 1.3.
                    0 => &[0x15, 0x03, 0x01, 0x00, 0x02, 0x02, 0x46],
                    // A ServerHello naming TLS 1.0.
                    _ => &[
                        0x16, 0x03, 0x01, 0x00, 0x2a, 0x02, 0x00, 0x00, 0x26, 0x03, 0x01,
                    ],
                };
                let _ = sock.write_all(reply).await;
            }
        });

        // The port number decides the path, and the socket decides the peer, so
        // an implicit-TLS number over a loopback socket exercises the real
        // branch without binding a privileged port.
        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(443, Protocol::Tcp, PortState::Open);
        let (responses, tunnel) =
            gather(stream, 443, ServiceDetection::Probe, Egress::KERNEL, None).await;
        server.abort();
        let _ = port;

        assert!(
            tunnel.is_none(),
            "nothing was tunnelled and nothing claims to be"
        );
        let tls = responses
            .tls
            .as_ref()
            .expect("the port speaks TLS, which is the finding");
        assert_eq!(tls.version, Some("TLSv1.0"));

        // And it reaches the record a report carries.
        assert_eq!(tls_security(tls).tls_version(), Some("TLSv1.0"));
    }

    /// A port that trickles cannot hold a scan.
    ///
    /// One byte every forty milliseconds sits permanently inside
    /// [`CONTINUATION_GRACE`], so without [`MAX_CONTINUATION`] this read would
    /// run until the four-kilobyte cap was reached: measured at ninety-seven
    /// seconds for one socket, with nothing above it to cut the exchange short.
    ///
    /// The assertion is on the clock rather than on the bytes because the clock
    /// is the property. A generous ceiling keeps this from failing on a loaded
    /// machine while still being an order of magnitude below those ninety-seven
    /// seconds.
    #[tokio::test]
    async fn a_trickling_port_cannot_hold_the_reader() {
        use tokio::net::{TcpListener, TcpStream};

        let listener = TcpListener::bind("127.0.0.1:0").await.expect("a socket");
        let addr = listener.local_addr().expect("its address");
        let server = tokio::spawn(async move {
            let Ok(mut sock) = accept_from_this_process(&listener).await else {
                return;
            };
            // Just inside the grace, for longer than any budget here allows.
            for _ in 0..2_000 {
                if sock.write_all(b"A").await.is_err() {
                    return;
                }
                tokio::time::sleep(Duration::from_millis(40)).await;
            }
        });

        let mut stream = TcpStream::connect(addr).await.expect("connects");
        let started = std::time::Instant::now();
        let read = read_document(&mut stream, PROBE_READ_TIMEOUT).await;
        let held = started.elapsed();
        server.abort();

        assert!(read.is_some(), "what did arrive is still returned");
        assert!(
            held < PROBE_READ_TIMEOUT + MAX_CONTINUATION + Duration::from_secs(2),
            "one trickling port held the reader for {held:?}"
        );
    }

    /// And the whole collection has a ceiling of its own, above every path
    /// through [`gather`], so a stage added later cannot reintroduce the class.
    ///
    /// The paths are written out rather than summed, because their sum is not a
    /// walk anything takes and a budget sized against it would be loose by half.
    /// Whoever adds a rung adds it here, and finds out immediately whether the
    /// budget still covers it.
    ///
    /// A rung has two costs and which one it pays decides whether the ladder
    /// goes on. `spoke` is a rung that drew bytes, so it pays a continuation on
    /// every read and it is the last rung walked. `silent` is a rung that drew
    /// nothing, so it pays only the wait and hands on to the next. Charging both
    /// to every rung would be arithmetic no port can produce.
    ///
    /// The exception is a plaintext rung answered with a TLS record: bytes, so a
    /// continuation, and still nothing this rung can report. That is what
    /// `alert_then_tls` is.
    ///
    /// Each path is counted twice over: what it takes on a path that costs
    /// nothing, and how many of its waits allow for a path that does. A
    /// continuation is not one of them, since it starts once the answer has
    /// already arrived. The budget covers every path on every path only when
    /// it covers the first and allows for at least as many of the second.
    #[test]
    fn the_collection_budget_covers_every_path_through_gather() {
        /// A walk: how long it takes on a path that costs nothing, and how
        /// many of its waits allow for the path.
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
        struct Walk(Duration, u32);
        impl std::ops::Add for Walk {
            type Output = Walk;
            fn add(self, other: Walk) -> Walk {
                Walk(self.0 + other.0, self.1 + other.1)
            }
        }
        impl std::ops::Mul<u32> for Walk {
            type Output = Walk;
            fn mul(self, times: u32) -> Walk {
                Walk(self.0 * times, self.1 * times)
            }
        }
        let wait = |duration: Duration| Walk(duration, 1);
        let continuation = Walk(MAX_CONTINUATION, 0);

        // The longest read a port's own probes can draw: at most two are
        // registered for any port in the shipped corpus, each its own wait plus
        // its continuation.
        let probes = SignatureDb::global()
            .indexed_ports()
            .map(|port| SignatureDb::global().tcp_probe_payloads(port).len())
            .max()
            .unwrap_or(0)
            .max(1) as u32;
        let spoke = |count: u32| {
            wait(BANNER_READ_TIMEOUT) + (wait(PROBE_READ_TIMEOUT) + continuation) * count
        };
        let silent = |count: u32| wait(BANNER_READ_TIMEOUT) + wait(PROBE_READ_TIMEOUT) * count;
        let read_once = wait(PROBE_READ_TIMEOUT) + continuation;
        let rung = wait(CONNECT_RETRY_TIMEOUT);

        // In the clear, a port several services claim asks each after the
        // first on a connection of its own, one dial more per service.
        let services = SignatureDb::global()
            .indexed_ports()
            .map(|port| SignatureDb::global().tcp_probe_conversations(port).count())
            .max()
            .unwrap_or(0)
            .max(1) as u32;
        let redials = rung * (services - 1);
        let handshake = wait(tls::TLS_HANDSHAKE_TIMEOUT);
        // Through TLS, each service after the first is asked through a
        // handshake of its own, one dial and one handshake more per service.
        let retunnels = (rung + handshake) * (services - 1);
        let legacy = wait(tls::LEGACY_PROBE_TIMEOUT);
        let speculative = wait(tls::SPECULATIVE_TLS_TIMEOUT);

        // A reply that redirects back to the port is followed on a
        // connection of its own, through a handshake of its own where the
        // port is spoken to through TLS.
        let followed = rung + read_once;
        let followed_tls = rung + handshake + read_once;

        // Numbered for TLS: [Tls, LegacyTls, Plaintext].
        let tls_then_redirect = handshake + spoke(probes) + retunnels + followed_tls;
        let tls_all_three = handshake + rung + legacy + rung + spoke(probes) + redials + followed;
        let tls_then_silence = handshake + rung + legacy + rung + silent(probes) + redials;

        // Numbered for anything else: [Plaintext, SpeculativeTls]. Inside the
        // tunnel a claimed port asks its own probes again and an unclaimed one
        // asks the single generic question.
        let claimed_then_tls = silent(probes)
            + redials
            + rung
            + speculative
            + spoke(probes)
            + retunnels
            + followed_tls;
        let alert_then_tls = read_once + rung + speculative + spoke(1) + followed_tls;
        let unclaimed_then_redirect = read_once + rung + read_once;
        // A web server refusing the request in the clear, then asked for a
        // handshake, and for the legacy one where that is refused.
        let refused_then_tls =
            spoke(probes) + redials + rung + speculative + spoke(probes) + retunnels + followed_tls;
        let refused_then_legacy = spoke(probes) + redials + rung + speculative + rung + legacy;

        // A port services only share is asked the generic question first and
        // then each service's on a connection of its own, where every read is
        // a probe's rather than a greeting's, and a redirect among theirs is
        // followed too. A generic question refused with a 400 goes on to the
        // handshakes.
        let asked = |count: u32| (wait(PROBE_READ_TIMEOUT) + continuation) * count;
        let unasked = |count: u32| wait(PROBE_READ_TIMEOUT) * count;
        let shared_spoke = unclaimed_then_redirect + rung * services + asked(probes) + followed;
        let shared_silent = unasked(1) + rung * services + unasked(probes);

        // And the last rung, which is a connection and a read per probe, for
        // every probe, since a reply to one of them does not end it.
        let universal = SignatureDb::global()
            .universal_tcp_probe_payloads(0, ServiceDetection::Thorough.probe_intensity())
            .len()
            .max(1) as u32;
        let last_resort = (rung + read_once) * universal;

        let paths = [
            tls_then_redirect,
            tls_all_three + last_resort,
            tls_then_silence + last_resort,
            claimed_then_tls,
            alert_then_tls,
            unclaimed_then_redirect,
            refused_then_tls,
            refused_then_legacy,
            silent(probes) + redials + rung + speculative + last_resort,
            shared_spoke,
            shared_spoke + rung + speculative + spoke(probes) + retunnels + followed_tls,
            shared_spoke + rung + speculative + rung + legacy,
            shared_silent + rung + speculative + spoke(probes) + retunnels + followed_tls,
            shared_silent + rung + speculative + last_resort,
        ];
        let longest = paths.iter().map(|walk| walk.0).max().expect("a path");
        let most_waits = paths.iter().map(|walk| walk.1).max().expect("a path");

        assert!(
            longest < COLLECTION_BUDGET,
            "the budget ({COLLECTION_BUDGET:?}) is below the longest honest path \
             ({longest:?}), so it would cut real scans short"
        );
        assert!(
            most_waits <= COLLECTION_WAITS,
            "the budget allows for the path {COLLECTION_WAITS} times and a walk \
             waits on it {most_waits} times, so it would cut scans on a slow \
             path short"
        );
    }

    /// A level that sends nothing sends nothing through an analyzer either.
    ///
    /// The SSH analyzer's key exchange is a second connection carrying this
    /// engine's identification and a KEXINIT, and it is started from a banner
    /// alone. Listening is what a caller asks for on equipment that must not be
    /// sent anything, and what a scan does on a printer's raw-print port, so the
    /// port that greeted is asked nothing further. The port number is SSH's
    /// while the socket is an ephemeral loopback one, as in the legacy TLS test
    /// above: the number decides which analyzer is interested, the socket who
    /// is dialled.
    #[tokio::test]
    async fn a_port_only_listened_to_is_not_dialled_again_by_an_analyzer() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        // What each connection sent, reported once it closes, so a count
        // taken after the pass returns misses nothing still on its way.
        let (closed, mut sent) = tokio::sync::mpsc::unbounded_channel::<usize>();
        let server = tokio::spawn(async move {
            while let Ok(mut sock) = accept_from_this_process(&listener).await {
                let closed = closed.clone();
                tokio::spawn(async move {
                    let _ = sock.write_all(b"SSH-2.0-OpenSSH_9.6p1 Debian-3\r\n").await;
                    let mut buffer = [0u8; 1024];
                    let mut received = 0;
                    while let Ok(n) = sock.read(&mut buffer).await {
                        if n == 0 {
                            break;
                        }
                        received += n;
                    }
                    let _ = closed.send(received);
                });
            }
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(22, Protocol::Tcp, PortState::Open);
        let port = fingerprint_tcp_via(
            stream,
            port,
            ServiceDetection::Banner,
            Egress::KERNEL,
            PathAllowance::NONE,
            None,
        )
        .await
        .port;
        // Stopped taking connections, the server lets its last sender go with
        // the last connection it took, and the channel ends once all are read.
        server.abort();
        let mut per_connection = Vec::new();
        let every_close = async {
            while let Some(received) = sent.recv().await {
                per_connection.push(received);
            }
        };
        timeout(Duration::from_secs(60), every_close)
            .await
            .expect("every connection to the port closes");

        assert_eq!(
            port.service().map(Service::name),
            Some("ssh"),
            "the greeting alone names the service"
        );
        assert_eq!(per_connection.len(), 1, "the port was dialled again");
        assert_eq!(
            per_connection.iter().sum::<usize>(),
            0,
            "the port was sent a payload"
        );
    }

    /// What the clear-text rung sends a silent port numbered `number`, read
    /// off a loopback listener that records every byte and answers nothing.
    /// The number decides what is asked, the socket who is asked, as in the
    /// tests above. Asked with no peer to address it to, so what arrives is
    /// the probes as authored, whatever port the listener was given.
    async fn asked_in_the_clear(number: u16) -> Vec<u8> {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let server = tokio::spawn(async move {
            let mut sock = accept_from_this_process(&listener)
                .await
                .expect("one connection");
            let mut received = Vec::new();
            let _ = sock.read_to_end(&mut received).await;
            received
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        plaintext(stream, number, None, Egress::KERNEL).await;
        server.await.expect("the listener finishes")
    }

    /// A raw-print port a scan was told to probe is asked what a port nothing
    /// claims is asked.
    ///
    /// What spares a printer is the scan's listen-only list, which keeps these
    /// ports from ever reaching a rung that sends. A port taken off that list
    /// is one the operator chose to probe, and the corpus claiming it for a
    /// probe that sends nothing would quietly undo that choice: the rung would
    /// wait on a port that never greets and never put the question that names
    /// what is there.
    #[tokio::test]
    async fn a_raw_print_port_probed_on_purpose_is_asked_what_an_unclaimed_port_is() {
        let unclaimed = 51987;
        assert!(
            SignatureDb::global()
                .tcp_probe_payloads(unclaimed)
                .is_empty(),
            "test assumes port {unclaimed} is unclaimed"
        );
        let expected: Vec<u8> = SignatureDb::global().generic_tcp_probe_payloads().concat();
        assert!(
            !expected.is_empty(),
            "the corpus asks unclaimed ports nothing"
        );

        let (print, other) = tokio::join!(
            asked_in_the_clear(crate::config::RAW_PRINT_PORTS[0]),
            asked_in_the_clear(unclaimed)
        );

        assert_eq!(other, expected);
        assert_eq!(
            String::from_utf8_lossy(&print),
            String::from_utf8_lossy(&expected),
            "the raw-print port was asked something else"
        );
    }

    /// How many of other services' questions a port that answered none of its
    /// own is put, across a path measured at `round_trip`, at `detection`:
    /// counted as the connections a port that closes each at once takes, one
    /// per question.
    async fn guesses_put(round_trip: Option<Duration>, detection: ServiceDetection) -> usize {
        use crate::testing::loopback::accept_from_this_process;
        use std::sync::atomic::AtomicUsize;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let taken = Arc::new(AtomicUsize::new(0));
        let counting = Arc::clone(&taken);
        let server = tokio::spawn(async move {
            while let Ok(sock) = accept_from_this_process(&listener).await {
                counting.fetch_add(1, Ordering::Relaxed);
                drop(sock);
            }
        });

        let first = TcpStream::connect(addr).await.expect("connects");
        let dialling = Dialling {
            egress: Egress::KERNEL,
            path: PathAllowance::of_round_trips(round_trip),
            tally: Arc::new(Tally::default()),
        };
        let peer = Authority::new(addr);
        DIALLING
            .scope(
                dialling,
                last_resort(first, &peer, 2222, detection, Egress::KERNEL),
            )
            .await;
        server.abort();
        taken.load(Ordering::Relaxed)
    }

    /// A port silent to its own questions, across a path slower than a
    /// question's own wait, is put only the likeliest of other services'
    /// questions at the default level, and every one of them where the path
    /// is ordinary or the caller asked for the thorough level.
    ///
    /// Each question allows for the path in full, so across a path of two
    /// seconds every guess adds nearly nine seconds to a port that has shown
    /// it answers nothing: asked them all, a silent port behind such a path
    /// took most of a minute to be named by its number.
    #[tokio::test]
    async fn a_silent_port_across_a_slow_path_is_put_only_the_likeliest_guess() {
        let slow = Some(Duration::from_millis(1_900));
        let all = guesses_put(None, ServiceDetection::Probe).await;
        assert!(all >= 2, "the premise needs guesses to leave out: {all}");

        assert_eq!(guesses_put(slow, ServiceDetection::Probe).await, 1);
        assert_eq!(
            guesses_put(Some(Duration::from_millis(40)), ServiceDetection::Probe).await,
            all
        );
        assert!(guesses_put(slow, ServiceDetection::Thorough).await >= all);
    }

    /// An answer nothing recognised leaves the port the name its number gives
    /// it, whether the identification is recorded as it stands or folded into
    /// a port already recorded under that name.
    ///
    /// The two are how the two kinds of scan file it: one that connects to
    /// find a port records what identifying it returned, and one that finds
    /// it without a connection records the name first and folds the
    /// identification in after. What the port said is kept either way, as the
    /// detail beside the name.
    #[tokio::test]
    async fn an_unrecognised_answer_reads_the_same_however_the_port_was_found() {
        use crate::testing::loopback::accept_from_this_process;

        let greeting = "WIDGET/4.2 ready";
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let server = tokio::spawn(async move {
            while let Ok(mut sock) = accept_from_this_process(&listener).await {
                tokio::spawn(async move {
                    let _ = sock.write_all(format!("{greeting}\r\n").as_bytes()).await;
                    let mut buffer = [0u8; 1024];
                    while sock.read(&mut buffer).await.is_ok_and(|read| read > 0) {}
                });
            }
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let seeded = baseline_port(6379, Protocol::Tcp, PortState::Open);
        let found = fingerprint_tcp(stream, seeded.clone(), ServiceDetection::Probe).await;
        server.abort();

        let mut folded = seeded;
        folded.merge(found.clone());
        let read = |port: &Port| {
            port.service().map(|service| {
                (
                    service.name().to_owned(),
                    service.extrainfo().map(str::to_owned),
                )
            })
        };
        assert_eq!(
            read(&found),
            Some(("redis".to_owned(), Some(greeting.to_owned()))),
            "recorded as identified"
        );
        assert_eq!(read(&folded), read(&found), "folded into the recorded port");
    }

    /// **The realm a KDC names reaches its host as a name, masked where a
    /// report masks, and never the port's description.** Over sockets end to
    /// end: the corpus probe over TCP, the KDC's `KRB-ERROR` naming a realm of
    /// its own behind the four-byte length, and the host record a report is
    /// written from.
    ///
    /// On a domain controller the realm is the Active Directory domain, which
    /// names the organisation. Carried in the service's description it would
    /// reach every redacted report in the clear.
    #[tokio::test]
    async fn a_kdc_s_realm_reaches_its_host_masked_and_not_its_description() {
        use crate::export::schema::HostDto;
        use crate::export::{ExportOptions, Redaction};
        use crate::model::host::Host;
        use crate::testing::loopback::accept_from_this_process;

        // KDC_ERR_WRONG_REALM naming the realm (RFC 4120 §5.9.1), behind the
        // length RFC 4120 §7.2.2 puts in front of a message over TCP.
        let realm = b"CORP.EXAMPLE";
        let mut fields = vec![0xA6, 0x03, 0x02, 0x01, 68];
        fields.extend_from_slice(&[0xA9, realm.len() as u8 + 2, 0x1B, realm.len() as u8]);
        fields.extend_from_slice(realm);
        let mut sequence = vec![0x30, fields.len() as u8];
        sequence.extend_from_slice(&fields);
        let mut error = vec![0x7E, sequence.len() as u8];
        error.extend_from_slice(&sequence);
        let mut reply = (error.len() as u32).to_be_bytes().to_vec();
        reply.extend_from_slice(&error);

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let server = tokio::spawn(async move {
            while let Ok(mut sock) = accept_from_this_process(&listener).await {
                let reply = reply.clone();
                tokio::spawn(async move {
                    let mut buffer = [0u8; 1024];
                    if sock.read(&mut buffer).await.is_ok_and(|read| read > 0) {
                        let _ = sock.write_all(&reply).await;
                    }
                    while sock.read(&mut buffer).await.is_ok_and(|read| read > 0) {}
                });
            }
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(88, Protocol::Tcp, PortState::Open);
        let found = fingerprint_tcp_detailed(stream, port, ServiceDetection::Probe).await;
        server.abort();

        let service = found.port.service().expect("the port is named");
        assert_eq!(service.product(), Some("Kerberos KDC"));
        assert!(
            !format!("{service:?}").contains("CORP"),
            "the realm reached the service: {service:?}"
        );

        let mut host = Host::new(addr.ip());
        found.about_the_host.apply(&mut host);
        let render = |options: ExportOptions| {
            serde_json::to_value(HostDto::new(&host, &options)).expect("a host renders")
        };
        assert_eq!(
            render(ExportOptions::new())["names"],
            serde_json::json!([{"source": "kerberos", "kind": "domain", "name": "CORP.EXAMPLE"}])
        );
        let masked = render(ExportOptions::new().with_redaction(Redaction::Standard)).to_string();
        assert!(
            !masked.contains("CORP") && masked.contains(r#""source":"kerberos""#),
            "the realm survived redaction: {masked}"
        );
    }

    /// A port two services share has each asked on a connection of its own,
    /// so one's question cannot close the conversation before the other's.
    ///
    /// 3000 is shared by Aerospike and Grafana and named by neither, and what
    /// most often answers there is a web server of some kind, which reads
    /// Aerospike's binary info request as a malformed HTTP request, answers
    /// `400` and closes, as Node and Go both do. Asked down one connection,
    /// Grafana's `GET /login` then meets a socket already shut, and the port is
    /// named by the `400` alone. The peer here answers exactly that way, and
    /// what it heard first on each connection it took is what the test reads.
    #[tokio::test]
    async fn a_shared_port_asks_each_service_on_a_connection_of_its_own() {
        use crate::testing::loopback::accept_from_this_process;
        use std::sync::{Arc, Mutex};

        let shared = 3000;
        let db = SignatureDb::global();
        assert!(
            db.service_name(shared).is_none() && db.tcp_probe_conversations(shared).count() >= 2,
            "test assumes {shared} is shared by several services and named by none"
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let heard: Arc<Mutex<Vec<Vec<u8>>>> = Arc::default();
        let log = Arc::clone(&heard);
        let server = tokio::spawn(async move {
            while let Ok(mut sock) = accept_from_this_process(&listener).await {
                let log = Arc::clone(&log);
                tokio::spawn(async move {
                    let mut buffer = [0u8; 1024];
                    let read = sock.read(&mut buffer).await.unwrap_or(0);
                    let request = buffer[..read].to_vec();
                    let reply: &[u8] = if request.starts_with(b"GET /login ") {
                        b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n<title>Grafana</title>"
                    } else if request.starts_with(b"GET ") {
                        b"HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n"
                    } else {
                        b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n"
                    };
                    log.lock().unwrap().push(request);
                    let _ = sock.write_all(reply).await;
                });
            }
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(shared, Protocol::Tcp, PortState::Open);
        let found = fingerprint_tcp_detailed(stream, port, ServiceDetection::Probe).await;
        server.abort();

        let firsts = heard.lock().unwrap().clone();
        // Compared by the first line, since a request is addressed to the
        // port it is sent to before it goes; see `Authority::addressed`.
        let first_line = |bytes: &[u8]| -> Vec<u8> {
            let end = bytes
                .windows(2)
                .position(|pair| pair == b"\r\n")
                .unwrap_or(bytes.len());
            bytes[..end].to_vec()
        };
        for probes in db.tcp_probe_conversations(shared) {
            assert!(
                firsts
                    .iter()
                    .any(|first| first_line(first) == first_line(&probes[0])),
                "a service's question was never the first thing on a connection: \
                 {:?} not in {firsts:?}",
                String::from_utf8_lossy(&probes[0])
            );
        }
        assert_eq!(
            found.port.service().map(Service::name),
            Some("grafana"),
            "the port was named by another service's refusal"
        );
    }

    /// A connection an identification gives up for want of a socket marks
    /// the identification starved, and one that fails for any other reason
    /// does not.
    ///
    /// An analyzer's connection is made inside a clock of the analyzer's own,
    /// the SSH key exchange's or a favicon fetch's, which a full table runs
    /// out while the connection still waits for a descriptor. Unmarked, the
    /// port reads as one with nothing more to say where the question that
    /// would have said it was never put. A port that refuses the connection
    /// has answered, and is no shortfall of this machine's.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_connection_given_up_for_want_of_a_socket_marks_the_identification_starved() {
        use crate::system::descriptors::testing::{
            in_a_process_of_its_own, refuse_every_descriptor,
        };

        if !in_a_process_of_its_own(
            module_path!(),
            "a_connection_given_up_for_want_of_a_socket_marks_the_identification_starved",
        ) {
            return;
        }
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let open = listener.local_addr().expect("a local address");
        let closed = crate::testing::loopback::refused_port(std::net::IpAddr::from([127, 0, 0, 1]));

        // Dialled the way an analyzer dials, inside the identification's
        // scope and inside a clock of its own.
        let dial = |addr: SocketAddr| async move {
            let tally = Arc::new(Tally::default());
            let dialling = Dialling {
                egress: Egress::KERNEL,
                path: PathAllowance::NONE,
                tally: Arc::clone(&tally),
            };
            let _ = DIALLING
                .scope(
                    dialling,
                    timeout(Duration::from_millis(300), analyzer_connect(addr)),
                )
                .await;
            tally.starved.load(Ordering::Relaxed)
        };

        let held = refuse_every_descriptor();
        let refused_a_socket = dial(open).await;
        drop(held);
        let refused_by_the_port = dial(closed).await;
        drop(listener);

        assert!(
            refused_a_socket,
            "a connection the process had no socket for was read as the port's silence"
        );
        assert!(
            !refused_by_the_port,
            "a port that refused the connection was blamed on the file limit"
        );
    }

    /// A UDP identification the process had no socket for says so, rather
    /// than coming back as the silence an unanswered datagram is.
    ///
    /// Over UDP silence is the ordinary answer, so a datagram never sent reads
    /// exactly like one the port ignored unless it is marked: the scan would
    /// file the port as heard out when it was never asked. A port asked and
    /// silent is still silence.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_udp_identification_refused_a_socket_is_starved_and_not_silent() {
        use crate::system::descriptors::testing::{
            in_a_process_of_its_own, refuse_every_descriptor,
        };

        if !in_a_process_of_its_own(
            module_path!(),
            "a_udp_identification_refused_a_socket_is_starved_and_not_silent",
        ) {
            return;
        }
        // A port the corpus asks something of over UDP, with nothing on
        // loopback listening there, so the one asked is refused or unanswered.
        let snmp: SocketAddr = "127.0.0.1:161".parse().expect("an address");
        assert!(
            !SignatureDb::global().udp_probe_payloads(161).is_empty(),
            "test assumes the corpus asks port 161 something over UDP"
        );
        let port = || baseline_port(161, Protocol::Udp, PortState::Open);
        let patience = Duration::from_millis(50);

        let held = refuse_every_descriptor();
        let unasked =
            fingerprint_udp_within(snmp, port(), Egress::KERNEL, patience, PathAllowance::NONE)
                .await;
        drop(held);
        let asked =
            fingerprint_udp_within(snmp, port(), Egress::KERNEL, patience, PathAllowance::NONE)
                .await;

        let unasked = unasked.expect("a datagram never sent was read as the port's silence");
        assert!(unasked.starved);
        assert!(unasked.responses.is_empty());
        assert!(
            asked.is_none(),
            "a port asked and silent was not read as silence: {asked:?}"
        );
    }

    /// A redirect is followed once the connection that drew it is closed, so
    /// an identification holds the one socket its pass took a share of the
    /// descriptor budget for, and never two.
    #[tokio::test]
    async fn a_redirect_is_followed_after_the_connection_that_drew_it_is_closed() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let server = tokio::spawn(async move {
            let mut first = accept_from_this_process(&listener)
                .await
                .expect("the first connection");
            let mut buffer = [0u8; 1024];
            let _ = first.read(&mut buffer).await;
            // Held open, as a server keeping the connection alive does.
            let _ = first
                .write_all(b"HTTP/1.1 302 Found\r\nLocation: /next\r\nContent-Length: 0\r\n\r\n")
                .await;
            let mut second = accept_from_this_process(&listener)
                .await
                .expect("the redirect followed");
            // By now the first has to have been let go.
            let first_open = !matches!(
                tokio::time::timeout(Duration::from_millis(500), first.read(&mut buffer)).await,
                Ok(Ok(0))
            );
            let _ = second.read(&mut buffer).await;
            let _ = second
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
                .await;
            first_open
        });

        let stream = TcpStream::connect(addr).await.expect("connects");
        let banners = plaintext(stream, 51987, Some(&Authority::new(addr)), Egress::KERNEL)
            .await
            .banners;
        let first_open = server.await.expect("the listener finishes");

        assert_eq!(
            banners.len(),
            2,
            "the redirect was not followed: {banners:?}"
        );
        assert!(
            !first_open,
            "the redirect was followed while the connection that drew it was held"
        );
    }

    /// A Zabbix agent moved off its registered port is put its framed question
    /// at the thorough level, and only there.
    ///
    /// An agent answers nothing but a request in the protocol's own frame and
    /// closes on anything else, an HTTP request included, so on a port its
    /// number does not name only the questions other services registered can
    /// reach it. Those go to a stranger by the rarity authored on each: the
    /// thorough level is the one that promises them all, and the default level
    /// asks only what a silent port most often turns out to be.
    #[tokio::test]
    async fn a_zabbix_agent_on_a_port_of_its_own_is_named_at_the_thorough_level_alone() {
        let moved = 18801;
        assert!(
            SignatureDb::global().tcp_probe_payloads(moved).is_empty(),
            "test assumes port {moved} is unclaimed"
        );

        let mut named = Vec::new();
        for level in [ServiceDetection::Thorough, ServiceDetection::Probe] {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
                .await
                .expect("binds loopback");
            let addr = listener.local_addr().expect("a local address");
            let framed = Arc::new(AtomicBool::new(false));
            let heard = Arc::clone(&framed);
            let agent = tokio::spawn(async move {
                while let Ok(mut sock) = accept_from_this_process(&listener).await {
                    let mut buffer = [0u8; 1024];
                    let read = sock.read(&mut buffer).await.unwrap_or(0);
                    if buffer[..read].starts_with(b"ZBXD\x01") {
                        heard.store(true, Ordering::SeqCst);
                        // `1` for the ping, behind the header, the protocol
                        // flag and an eight-byte little-endian length.
                        let _ = sock.write_all(b"ZBXD\x01\x01\0\0\0\0\0\0\0\x31").await;
                    }
                }
            });

            let stream = TcpStream::connect(addr).await.expect("connects");
            let port = baseline_port(moved, Protocol::Tcp, PortState::Open);
            let found = fingerprint_tcp_detailed(stream, port, level).await;
            agent.abort();
            named.push((
                found
                    .port
                    .service()
                    .map(|service| service.name().to_owned()),
                framed.load(Ordering::SeqCst),
            ));
        }

        assert_eq!(
            named[0],
            (Some("zabbix".to_owned()), true),
            "a thorough identification did not name the agent (service, asked)"
        );
        assert_eq!(
            named[1],
            (None, false),
            "the default level put a rare question to a stranger (service, asked)"
        );
    }

    #[tokio::test]
    async fn analyze_returns_none_when_no_evidence() {
        // No banners and no TLS: both phases run, no analyzer produces evidence,
        // so the orchestration resolves to nothing rather than an empty verdict.
        assert!(
            analyze(
                1,
                Protocol::Tcp,
                None,
                ResponseSet::default(),
                None,
                ServiceDetection::default(),
                None,
            )
            .await
            .is_none()
        );
    }

    /// What a loopback server was asked, request by request, in the order
    /// they arrived: decrypted where they came through TLS.
    type Heard = Arc<std::sync::Mutex<Vec<String>>>;

    /// A loopback HTTPS server keeping a certificate for `name` alone, as a
    /// server holding its sites by name keeps one per site, so a handshake
    /// naming nothing, or something else, is refused. A request in the clear is
    /// answered the way Go's server answers one, with a plaintext `400`. Its
    /// root redirects to `/web/`, as a self-hosted application's often does.
    async fn https_by_name(name: &str) -> (SocketAddr, Heard) {
        let acceptor = crate::testing::loopback::tls_by_name(name);

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let addr = listener.local_addr().expect("a local address");
        let heard: Heard = Arc::default();
        let record = Arc::clone(&heard);
        tokio::spawn(async move {
            while let Ok(stream) = accept_from_this_process(&listener).await {
                let (acceptor, record) = (acceptor.clone(), Arc::clone(&record));
                tokio::spawn(async move {
                    let mut first = [0u8; 1];
                    if stream.peek(&mut first).await.unwrap_or(0) == 0 {
                        return;
                    }
                    let mut buffer = [0u8; 2048];
                    if first[0] != 0x16 {
                        let mut stream = stream;
                        let read = stream.read(&mut buffer).await.unwrap_or(0);
                        record.lock().expect("not poisoned").push(format!(
                            "clear: {}",
                            String::from_utf8_lossy(&buffer[..read])
                        ));
                        let _ = stream
                            .write_all(
                                b"HTTP/1.0 400 Bad Request\r\n\r\n\
                                  Client sent an HTTP request to an HTTPS server.\n",
                            )
                            .await;
                        return;
                    }
                    let Ok(mut tls) = acceptor.accept(stream).await else {
                        return;
                    };
                    let read = tls.read(&mut buffer).await.unwrap_or(0);
                    let request = String::from_utf8_lossy(&buffer[..read]).into_owned();
                    let reply: &[u8] = match request.starts_with("GET / ") {
                        true => {
                            b"HTTP/1.1 302 Found\r\nServer: Caddy\r\nLocation: /web/\r\n\
                              Content-Length: 0\r\nConnection: close\r\n\r\n"
                        }
                        false => {
                            b"HTTP/1.1 200 OK\r\nServer: Caddy\r\n\
                              Content-Length: 0\r\nConnection: close\r\n\r\n"
                        }
                    };
                    record.lock().expect("not poisoned").push(request);
                    let _ = tls.write_all(reply).await;
                    let _ = tls.shutdown().await;
                });
            }
        });
        (addr, heard)
    }

    /// A server keeping its certificates by name completes a handshake only
    /// for a client naming a site it holds, so a port on an address a target
    /// reached by name is asked for by that name, in the handshake and in the
    /// request inside it. Asked for by nothing, the port reads as one that does
    /// not speak TLS at all.
    #[tokio::test]
    async fn a_tls_port_on_a_named_address_is_asked_for_by_its_name() {
        let (addr, heard) = https_by_name("box.example").await;

        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(443, Protocol::Tcp, PortState::Open);
        let found = fingerprint_tcp_via(
            stream,
            port,
            ServiceDetection::Probe,
            Egress::KERNEL,
            PathAllowance::NONE,
            Some(Arc::from("box.example")),
        )
        .await;

        assert!(
            found.port.security().is_some(),
            "the handshake did not complete: {:?}",
            heard.lock().expect("not poisoned")
        );
        let service = found.port.service().expect("a service was named");
        assert_eq!(service.name(), "ssl/http");
        let asked = heard.lock().expect("not poisoned").clone();
        let host = format!("\r\nHost: box.example:{}\r\n", addr.port());
        assert!(
            asked.iter().any(|request| request.contains(&host)),
            "nothing inside the tunnel asked for `{}`: {asked:?}",
            host.trim()
        );
    }

    /// Each service sharing a TLS port is asked through a handshake of its
    /// own. A web server closes its connection after one answer, and the
    /// tunnel goes with it, so a second service's question sent down the same
    /// tunnel meets a closed connection and goes unasked, as it would in the
    /// clear. 8443 is the web alternate and shared with the Kubernetes API.
    #[tokio::test]
    async fn each_service_sharing_a_tls_port_is_asked_through_a_handshake_of_its_own() {
        let (addr, heard) = https_by_name("box.example").await;

        let stream = TcpStream::connect(addr).await.expect("connects");
        let port = baseline_port(8443, Protocol::Tcp, PortState::Open);
        let found = fingerprint_tcp_via(
            stream,
            port,
            ServiceDetection::Probe,
            Egress::KERNEL,
            PathAllowance::NONE,
            Some(Arc::from("box.example")),
        )
        .await;

        assert!(found.port.security().is_some(), "the handshake completed");
        let asked = heard.lock().expect("not poisoned").clone();
        for question in ["GET / ", "GET /api "] {
            assert!(
                asked.iter().any(|request| request.starts_with(question)),
                "`{}` went unasked: {asked:?}",
                question.trim()
            );
        }
    }

    /// A stream that notes, in order, whether each operation on it was a read
    /// or a write, over the client half of an in-memory pipe.
    struct Noting {
        inner: tokio::io::DuplexStream,
        seen: Vec<&'static str>,
    }

    impl AsyncRead for Noting {
        fn poll_read(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
            buf: &mut tokio::io::ReadBuf<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            if self.seen.last() != Some(&"read") {
                self.seen.push("read");
            }
            std::pin::Pin::new(&mut self.inner).poll_read(cx, buf)
        }
    }

    impl AsyncWrite for Noting {
        fn poll_write(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
            buf: &[u8],
        ) -> std::task::Poll<std::io::Result<usize>> {
            if self.seen.last() != Some(&"write") {
                self.seen.push("write");
            }
            std::pin::Pin::new(&mut self.inner).poll_write(cx, buf)
        }

        fn poll_flush(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            std::pin::Pin::new(&mut self.inner).poll_flush(cx)
        }

        fn poll_shutdown(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            std::pin::Pin::new(&mut self.inner).poll_shutdown(cx)
        }
    }

    /// What the clear-text rung does first on a port numbered `number`
    /// claimed by something that registered probes.
    async fn first_move_on(number: u16) -> &'static str {
        let (client, mut server) = tokio::io::duplex(8192);
        let answering = tokio::spawn(async move {
            let mut buffer = [0u8; 2048];
            while server.read(&mut buffer).await.unwrap_or(0) > 0 {
                let _ = server
                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
                    .await;
            }
        });
        let mut noting = Noting {
            inner: client,
            seen: Vec::new(),
        };
        let db = SignatureDb::global();
        let probes = db.tcp_probe_payloads(number);
        assert!(!probes.is_empty(), "port {number} registers probes");
        let _ = collect_responses(&mut noting, number, probes, None, !db.asked_first(number)).await;
        answering.abort();
        noting.seen.first().copied().unwrap_or("nothing")
    }

    /// An HTTP server never speaks first, so a web port is asked at once
    /// rather than listened to for a greeting that never comes, which cost
    /// every web port a scan identified the whole of a banner wait. A port
    /// where something that greets may be listening is listened to first.
    #[tokio::test]
    async fn a_web_port_is_asked_before_it_is_listened_to() {
        assert_eq!(
            first_move_on(8080).await,
            "write",
            "8080 waited for a greeting"
        );
        assert_eq!(
            first_move_on(9200).await,
            "write",
            "9200 waited for a greeting"
        );
        assert!(
            !SignatureDb::global().asked_first(21),
            "a port a greeting service claims is listened to first"
        );
    }

    /// Identifies an HTTPS server, the one `https_by_name` stands up, on a
    /// port whose number does not say TLS, asked for by `name`.
    async fn https_off_the_list(name: Option<&str>) -> Fingerprinted {
        let (addr, _heard) = https_by_name("box.example").await;
        let number = 9443;
        assert!(
            !tls::is_tls_port(number),
            "test assumes {number} is not numbered for TLS"
        );
        let stream = TcpStream::connect(addr).await.expect("connects");
        fingerprint_tcp_via(
            stream,
            baseline_port(number, Protocol::Tcp, PortState::Open),
            ServiceDetection::Probe,
            Egress::KERNEL,
            PathAllowance::NONE,
            name.map(Arc::from),
        )
        .await
    }

    /// A web server listening for TLS answers a request in the clear with a
    /// plaintext `400`, which is an answer and so ended the identification
    /// there: HTTPS on a port its number does not name was reported as plain
    /// `http`, with no certificate and none of the names it carries. The
    /// refusal is what sends the port a handshake.
    #[tokio::test]
    async fn https_on_a_port_numbered_for_nothing_is_reached_through_its_handshake() {
        let found = https_off_the_list(Some("box.example")).await;

        let service = found.port.service().expect("a service was named");
        assert_eq!(service.name(), "ssl/http");
        assert_eq!(service.product(), Some("Caddy"));
        let security = found.port.security().expect("the handshake is recorded");
        assert!(
            security.certificate().is_some(),
            "the certificate was not read: {security:?}"
        );
    }

    /// A server keeping its certificates by name refuses a handshake naming no
    /// site it holds, which is every handshake where the target named an
    /// address. It still answers in TLS, so the port is filed as the web
    /// server over TLS its refusal in the clear said it was, not as a plain
    /// `http` port the next pass would send requests to in the clear.
    #[tokio::test]
    async fn https_refusing_a_nameless_handshake_is_still_filed_as_https() {
        let found = https_off_the_list(None).await;

        let service = found.port.service().expect("a service was named");
        assert_eq!(service.name(), "ssl/http");
        assert!(
            found.port.security().is_some(),
            "the port's TLS went unrecorded"
        );
    }

    /// The same server on the port numbered for HTTPS, asked for by no name,
    /// is filed as a web server over TLS too.
    ///
    /// Asked for a handshake first, as its number says, it refuses the modern
    /// one for naming no site and the legacy one for its version, both in
    /// TLS. Those two refusals were the whole of what the port was filed on:
    /// a port that speaks TLS, with the name its number gives it and no word
    /// of what it serves. Its refusal of a request in the clear is what says
    /// that, as on a port its number does not name.
    #[tokio::test]
    async fn https_on_its_own_port_refusing_a_nameless_handshake_is_filed_as_https() {
        let (addr, _heard) = https_by_name("box.example").await;
        let stream = TcpStream::connect(addr).await.expect("connects");
        let found = fingerprint_tcp_via(
            stream,
            baseline_port(443, Protocol::Tcp, PortState::Open),
            ServiceDetection::Probe,
            Egress::KERNEL,
            PathAllowance::NONE,
            None,
        )
        .await;

        let service = found.port.service().expect("a service was named");
        assert_eq!(service.name(), "ssl/http");
        assert!(!service.is_inferred(), "the name is still the number's");
    }

    /// A redirect a web port answers with is followed wherever the port is
    /// asked, through TLS as in the clear and on a port its own service
    /// claims as on one nothing claims, provided it stays on the port. The
    /// root of a self-hosted application is often a redirect and nothing
    /// else, and the ports it is most often served on are the claimed ones.
    #[tokio::test]
    async fn a_redirect_is_followed_on_a_claimed_port_and_through_tls() {
        let (addr, heard) = https_by_name("box.example").await;
        let stream = TcpStream::connect(addr).await.expect("connects");
        let found = fingerprint_tcp_via(
            stream,
            baseline_port(443, Protocol::Tcp, PortState::Open),
            ServiceDetection::Probe,
            Egress::KERNEL,
            PathAllowance::NONE,
            Some(Arc::from("box.example")),
        )
        .await;
        let asked = heard.lock().expect("not poisoned").clone();
        assert!(
            asked
                .iter()
                .any(|request| request.starts_with("GET /web/ ")),
            "the redirect through TLS was not followed: {asked:?}"
        );
        assert_eq!(found.responses.len(), 2, "{:?}", found.responses);

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("binds loopback");
        let clear = listener.local_addr().expect("a local address");
        let server = tokio::spawn(async move {
            let mut asked = Vec::new();
            for reply in [
                &b"HTTP/1.1 302 Found\r\nLocation: /web/\r\nContent-Length: 0\r\n\r\n"[..],
                b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n",
            ] {
                let Ok(mut sock) = accept_from_this_process(&listener).await else {
                    break;
                };
                let mut buffer = [0u8; 1024];
                let read = sock.read(&mut buffer).await.unwrap_or(0);
                asked.push(String::from_utf8_lossy(&buffer[..read]).into_owned());
                let _ = sock.write_all(reply).await;
            }
            asked
        });
        let number = 8080;
        assert!(!SignatureDb::global().tcp_probe_payloads(number).is_empty());
        let stream = TcpStream::connect(clear).await.expect("connects");
        let banners = plaintext(stream, number, Some(&Authority::new(clear)), Egress::KERNEL)
            .await
            .banners;
        let asked = server.await.expect("the listener finishes");
        assert!(
            asked
                .iter()
                .any(|request| request.starts_with("GET /web/ ")),
            "the redirect in the clear was not followed: {asked:?}"
        );
        assert_eq!(banners.len(), 2, "{banners:?}");
    }

    /// A port that answered through TLS is asked for its icon through TLS.
    /// Asked in the clear, an HTTPS port receives requests it can only
    /// refuse, which is traffic a scan has no business sending it, and the
    /// icon that would have named the application is never read.
    #[tokio::test]
    async fn an_https_port_is_asked_for_its_icon_through_tls() {
        let (addr, heard) = https_by_name("box.example").await;
        let stream = TcpStream::connect(addr).await.expect("connects");
        let _ = fingerprint_tcp_via(
            stream,
            baseline_port(443, Protocol::Tcp, PortState::Open),
            ServiceDetection::Probe,
            Egress::KERNEL,
            PathAllowance::NONE,
            Some(Arc::from("box.example")),
        )
        .await;

        let asked = heard.lock().expect("not poisoned").clone();
        assert!(
            !asked.iter().any(|request| request.starts_with("clear:")),
            "an HTTPS port was asked in the clear: {asked:?}"
        );
        assert!(
            asked
                .iter()
                .any(|request| request.starts_with("GET /favicon.ico ")),
            "the icon was not asked for through TLS: {asked:?}"
        );
    }
}