zond-engine 0.17.0

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

//! # Unprivileged TCP Connect Scanning
//!
//! The fallback strategy for when raw sockets are not available, whether because
//! the process is not root, no usable interface exists, or the OS could not route
//! a target. Everything here is built on ordinary
//! [`TcpStream`] connects, so it needs no special
//! privileges and works anywhere the async runtime does.
//!
//! It answers both scan phases. [`discover`] establishes host presence by probing
//! a small set of common infrastructure ports and treating any TCP-layer response,
//! an accept or even a refusal, as proof the host is alive. [`scan`] takes known
//! targets and classifies each port from a full connect handshake.
//!
//! Both draw their work in shuffled batches and cap their in-flight connections
//! with a [`ProbePool`], and both record findings through the shared
//! [`ScanContext`] like every other strategy. What they draw differs with the
//! phase: a sweep asks about an address and a port scan about an address paired
//! with a port, which is the unit each of them settles.
//!
//! Every probe takes its socket from the process's descriptor budget first
//! (see `dial`), and a probe the process has no socket for waits for one.
//! A shell's file limit therefore slows a scan and never narrows it: a socket
//! the process could not open is a question nobody asked, not an answer.

use crate::config::ServiceDetection;
use crate::config::limits::{CONNECT_PROBE_TIMEOUT, DISCOVERY_CONCURRENCY};
use crate::counted;
use crate::evasion::EvasionProfile;
use crate::journal::settle::{Outcome, Settled};
use crate::logging::error;
use crate::model::host::{Host, HostStatus, NetworkRole, StatusProtocol, StatusReason};
use crate::model::ip::scoped::ZoneMap;
use crate::model::ip::set::IpSet;
use crate::model::port::discovery::{Discovery, ScanResponse};
use crate::model::port::{Port, PortState, Protocol};
use crate::model::target::PlannedTarget;
use crate::report::ScannerKind;
use crate::report::StopReason;
use crate::scanner::audit::ProbeAudit;
use crate::scanner::dispatcher::dispatch_addresses;
use crate::scanner::handle::ScanHandle;
use crate::scanner::payload;
use crate::scanner::pool::ProbePool;
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::routed::SynPorts;
use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
use crate::system::descriptors::{self, Descriptor};
use crate::transport::dial::{Connecting, Egress, Shaping};
use async_trait::async_trait;
use std::io::{self, ErrorKind};
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::time::timeout;

/// The evasion an unprivileged connect probe can honour: a source port to leave
/// from and a hop limit to carry.
///
/// Both are ordinary socket options that need no privilege, so they belong on
/// this path as much as on the raw one: a hop limit a filter keys on should be
/// the chosen value on *every* probe, the connect fallback included, or the
/// fallback would leak the real one. The framing techniques, a spoofed hardware
/// address, fragmentation, decoys, are absent here because they need a
/// self-built frame this path never touches; a profile that asks for one opens
/// the Ethernet path and never reaches this scanner. The segment shapers,
/// padding, a corrupt checksum, are absent for a different reason: the kernel
/// builds the segment a connect sends, so there is nothing here to shape.
impl From<&EvasionProfile> for Shaping {
    fn from(evasion: &EvasionProfile) -> Self {
        Self {
            source_port: evasion.source_port,
            hop_limit: evasion.ttl,
        }
    }
}

/// Adapts the unprivileged [`discover`] strategy to [`HostScanner`], so it can
/// be spawned alongside [`LocalScanner`](super::local::LocalScanner) and
/// [`RoutedScanner`](super::routed::RoutedScanner) from a single explorer list.
pub struct ConnectScanner {
    /// The addresses being probed for aliveness.
    ips: IpSet,
    /// Shared state (host store, event channel, abort signal) for the scan
    /// this explorer is part of.
    ctx: ScanContext,
    /// What each liveness probe changes about the packet it sends. Only the
    /// source port and hop limit reach the wire from here (see `dial::Shaping`).
    evasion: EvasionProfile,
    /// The ports every address is asked about.
    ports: SynPorts,
}

impl ConnectScanner {
    /// Checks each of `ips` for a pulse, connecting to a handful of common
    /// infrastructure ports and taking any TCP-layer answer, an accept or a
    /// refusal alike, as proof that something is there.
    ///
    /// Hosts are filed through `ctx`. Of `evasion`, only the source port and
    /// the hop limit reach the wire; the kernel builds the rest of what a
    /// connect sends.
    pub fn new(ips: IpSet, ctx: ScanContext, evasion: &EvasionProfile) -> Self {
        Self::asking(ips, ctx, evasion, SynPorts::common())
    }

    /// [`new`](Self::new), asking `ports` rather than the common five.
    ///
    /// The set a routed sweep of the same addresses would ask, so that which
    /// strategy reached an address decides nothing about which ports it was
    /// asked on. See [`discover_on`].
    pub fn asking(ips: IpSet, ctx: ScanContext, evasion: &EvasionProfile, ports: SynPorts) -> Self {
        Self {
            ips,
            ctx,
            evasion: evasion.clone(),
            ports,
        }
    }
}

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

    async fn discover_hosts(&mut self) -> Result<(), StrategyError> {
        // The targets are taken rather than cloned. A sweep asks each address
        // once, so a second call has nothing left to probe and correctly does
        // nothing, where a clone would silently re-probe the whole set.
        discover_on(
            std::mem::take(&mut self.ips),
            self.ctx.clone(),
            &self.evasion,
            self.ports,
        )
        .await
    }
}

/// What one finished prober task learned. A probe never fails, since every
/// network outcome maps to some combination of the fields below, so this is a
/// plain [`Option`] rather than a `Result`.
///
/// `None` means the target was not probed at all.
struct Probed {
    /// The address probed.
    ip: IpAddr,
    /// The port verdict, where the probe produced one.
    ///
    /// Separate from [`Probed::answered`] because the two say different things:
    /// a timeout yields a `Filtered` port and proves nothing about the host,
    /// while a refusal yields a `Closed` port *and* proves the host is up. Only
    /// a target that was never probed - UDP through a TCP prober - carries
    /// `None`.
    port: Option<Port>,
    /// What the port said while it was being fingerprinted, carried out of the
    /// probe for the detection phase to hand a passive detection.
    ///
    /// This scanner holds the only connection an unprivileged scan makes to the
    /// port, so bytes dropped here are bytes no later phase can read without
    /// dialling again. Empty for every probe that drew nothing.
    responses: Vec<String>,

    /// What those same bytes said about the *machine*, carried out for the same
    /// reason and filed in a different place: the service belongs to the port,
    /// the operating system to the host.
    ///
    /// Empty for every probe that drew nothing, and for every verdict that came
    /// from the kernel rather than from a conversation.
    about_the_host: crate::fingerprint::AboutTheHost,
    /// Whether the host answered. The kernel hands back a completed handshake or
    /// a `ConnectionRefused` only when something came back, and a refusal is
    /// almost always the target's own RST, so either is read as a live stack;
    /// a port unreachable standing in for one comes, as a rule, from a filter
    /// on the host itself. A timeout or any other unreachable proves
    /// nothing about the host, whose sender this path cannot see, and never
    /// sets this.
    answered: bool,
    /// What became of this target, for a resume.
    ///
    /// Distinct from [`answered`](Self::answered), which is about the *host*: a
    /// timeout proves nothing about the host and still settles the target,
    /// because the connect made its one and only attempt.
    outcome: Outcome,
    /// Whether a send was made, as the run's audit counts it.
    attempt: Attempt,
    /// How long the connect took to draw its answer, where it drew one.
    ///
    /// A completed handshake returns once the SYN/ACK is in and a refusal once
    /// the RST is, so either is one round trip to the host, timed from when
    /// the attempt began rather than from any wait for a socket. `None` for a
    /// timeout and for every probe that never left.
    rtt: Option<Duration>,
    /// What the reply proved the host *is*, where its protocol says so.
    ///
    /// A claim about the host rather than about the port, and carried alongside
    /// the verdict rather than folded into it for that reason: a name server
    /// and a socket bound to 53 produce the same `Open`, and only one of them
    /// is a name server. See [`payload::declared_role`].
    role: Option<NetworkRole>,
}

/// The outcome of one finished [`port_prober`] task.
type ProbedPort = Option<Probed>;

/// Whether a port probe put anything on the wire, which is what the run's
/// `sends_attempted` and `sends_failed` count.
///
/// Carried by the probe rather than counted when it is admitted, because only
/// the probe knows: a probe admitted can still find no socket, no route, or a
/// scan that stopped before it asked.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Attempt {
    /// The probe was sent.
    Sent,
    /// This machine refused the send before anything left it, for the reason
    /// carried, which the scan reports once it has drained.
    Refused(Refusal),
    /// The process had no socket to give the probe for as long as it would
    /// wait, which the scan reports once it has drained.
    Starved,
    /// Nothing was attempted: the scan stopped before the probe asked.
    Unmade,
}

/// Why this machine refused to send a probe, sorted the way the raw path sorts
/// a send it could not make: by whose fact it is.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Refusal {
    /// No route leads to the address. A fact about the address as seen from
    /// here rather than a fault, and reported against the address.
    NoRoute,
    /// Anything else: no source to send from, no local port, a probe that met
    /// itself on every try. This machine's failure, in the operating system's
    /// own words, which is the part a reader asking why can act on.
    Local(String),
}

impl Refusal {
    /// The refusal `error` is, raised before anything left this machine.
    fn of(error: &io::Error) -> Self {
        match error.kind() {
            ErrorKind::HostUnreachable | ErrorKind::NetworkUnreachable => Self::NoRoute,
            _ => Self::Local(error.to_string()),
        }
    }
}

/// What a scan's probes could not ask, and why, reported once it has drained.
///
/// Each is a port or address left unasked, which a resume asks again, and
/// each has a cause the report has to name: without it, a scan that could not
/// send reads as a network that did not answer.
#[derive(Debug, Default)]
struct Shortfall {
    /// Targets the process had no socket for.
    starved: u128,
    /// Addresses no route led to.
    unroutable: std::collections::BTreeSet<IpAddr>,
    /// Targets this machine refused for any other reason.
    refused: u128,
    /// The first of those refusals, in the operating system's words.
    first_refusal: Option<String>,
}

impl Shortfall {
    /// Counts one probe's `attempt` for `ip`, if it fell short.
    fn count(&mut self, ip: IpAddr, attempt: &Attempt) {
        match attempt {
            Attempt::Starved => self.starved += 1,
            Attempt::Refused(Refusal::NoRoute) => {
                self.unroutable.insert(ip);
            }
            Attempt::Refused(Refusal::Local(why)) => {
                self.refused += 1;
                self.first_refusal.get_or_insert_with(|| why.clone());
            }
            Attempt::Sent | Attempt::Unmade => {}
        }
    }

    /// Files what fell short, counting targets as `unit` and `units`.
    ///
    /// An address no route led to is filed against the address, the way the
    /// raw path files one, unless it answered something else, since an
    /// address that answered was reached and a report saying otherwise would
    /// contradict the ports it holds for it.
    fn report(self, ctx: &ScanContext, scanner: ScannerKind, unit: &str, units: &str) {
        if self.starved > 0 {
            let unasked = counted(self.starved, unit, units);
            report_starved(ctx, scanner, unasked, descriptors::PATIENCE);
        }
        for address in self.unroutable {
            let reached = ctx
                .read_host(address, |host| host.status() == HostStatus::Up)
                .unwrap_or(false);
            if !reached {
                ctx.record_unroutable(address);
            }
        }
        if self.refused > 0 {
            let cause = self.first_refusal.as_deref().unwrap_or("cause unrecorded");
            ctx.record_failure(
                scanner,
                format!(
                    "{} left unasked: this machine refused to send them: {cause}",
                    counted(self.refused, unit, units)
                ),
            );
        }
    }
}

/// Adapts the unprivileged [`scan`] engine to [`PortScanner`], so
/// [`crate::scanner::scan`] can drive it through the same path as the privileged
/// [`TcpPortScanner`](super::ports::TcpPortScanner).
///
/// It carries no [`detect_services`](PortScanner::detect_services) override,
/// because the connect engine fingerprints each port inline over the live stream
/// it already holds (see this module's port prober), so a second identification pass would
/// be wasted work. This is the reason service detection lives on the trait rather
/// than in the caller: the fact that connect needs no second pass is expressed
/// here by its absence, instead of as a branch at the call site.
pub struct ConnectPortScanner {
    /// Shared state (host store, event channel, abort signal) for the scan this
    /// strategy is part of.
    ctx: ScanContext,
    /// The ceiling on in-flight connect probes.
    concurrency: usize,
    /// How far each probe may go to name what answered.
    ///
    /// [`ServiceDetection::Off`] means something slightly different here than it
    /// does on the privileged path, and the difference is worth knowing: this
    /// scanner's connection *is* how the port's state is established, so turning
    /// identification off skips the conversation, never the connection. A caller
    /// who needs the target's application logs to stay clean needs raw sockets;
    /// without them, being seen is the price of the answer.
    detection: ServiceDetection,
    /// What each probe changes about the packet it sends. Only the source port
    /// and hop limit reach the wire from here (see `dial::Shaping`).
    evasion: EvasionProfile,
    /// The interface each link-local target was named on, empty for a scan that
    /// named none. A `SocketAddrV6` with a zero scope id will not connect to a
    /// neighbour however close it is, so the scope id is carried per target and
    /// applied where the endpoint is built.
    zones: ZoneMap,
}

impl ConnectPortScanner {
    /// Settles each `(address, port)` it is fed with a full handshake, holding
    /// at most `concurrency` connections open and recording verdicts through
    /// `ctx`.
    ///
    /// `detection` decides how far the conversation goes once a port answers,
    /// not whether the connection is made: the connection is what establishes
    /// the state. `evasion` contributes the source port and the hop limit.
    pub fn new(
        ctx: ScanContext,
        concurrency: usize,
        detection: ServiceDetection,
        evasion: &EvasionProfile,
    ) -> Self {
        Self {
            ctx,
            concurrency,
            detection,
            evasion: evasion.clone(),
            zones: ZoneMap::new(),
        }
    }

    /// Names the interface each of the scan's link-local targets was given on.
    ///
    /// Without it a link-local endpoint is built with a zero scope id, which the
    /// kernel refuses to connect however reachable the neighbour is.
    pub fn with_zones(mut self, zones: ZoneMap) -> Self {
        self.zones = zones;
        self
    }
}

#[async_trait]
impl PortScanner for ConnectPortScanner {
    fn kind(&self) -> ScannerKind {
        ScannerKind::Connect
    }

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

    async fn scan(&mut self, rx: mpsc::Receiver<PlannedTarget>) -> Result<(), StrategyError> {
        scan(
            rx,
            self.concurrency,
            self.ctx.clone(),
            self.detection,
            &self.evasion,
            &self.zones,
        )
        .await
    }
}

/// Unprivileged UDP port scanner.
pub struct ConnectUdpPortScanner {
    ctx: ScanContext,
    concurrency: usize,
    /// What each probe changes about the packet it sends. Only the source port
    /// and hop limit reach the wire from here (see `dial::Shaping`).
    evasion: EvasionProfile,
    /// How far the second pass may go to name what answered.
    ///
    /// Unlike [`ConnectPortScanner`] beside it, this one cannot identify a
    /// service inline: there is no connection to hold, and the datagram that
    /// establishes the port is open is not the one that identifies what is
    /// behind it. So it runs the second pass, and holds the level to run it at.
    service_detection: ServiceDetection,
    /// The interface each link-local target was named on, empty for a scan that
    /// named none. A `SocketAddrV6` with a zero scope id will not connect to a
    /// neighbour however close it is, so the scope id is carried per target and
    /// applied where the endpoint is built.
    zones: ZoneMap,
}

impl ConnectUdpPortScanner {
    /// Sends one datagram per `(address, port)` it is fed, `concurrency` of
    /// them in flight at a time, and files what came back through `ctx`. As on
    /// the TCP path, `evasion` reaches the wire as a source port and a hop
    /// limit and no further.
    ///
    /// A closed verdict here proves nothing about the host. It comes from an
    /// ICMP error the kernel matched to the socket, and the error's own source,
    /// a router as easily as the target, is not surfaced through this API. Only
    /// a datagram coming back proves the port and the host at once.
    pub fn new(ctx: ScanContext, concurrency: usize, evasion: &EvasionProfile) -> Self {
        Self::with_detection(ctx, concurrency, evasion, ServiceDetection::default())
    }

    /// The same scanner, told how far the second pass may go.
    ///
    /// [`new`](Self::new) is the ordinary way in and takes the default level;
    /// this is for a caller carrying a level of its own, which is every caller
    /// that read one from a configuration.
    pub fn with_detection(
        ctx: ScanContext,
        concurrency: usize,
        evasion: &EvasionProfile,
        service_detection: ServiceDetection,
    ) -> Self {
        Self {
            ctx,
            concurrency,
            evasion: evasion.clone(),
            service_detection,
            zones: ZoneMap::new(),
        }
    }

    /// Names the interface each of the scan's link-local targets was given on,
    /// as on the TCP scanner beside it.
    pub fn with_zones(mut self, zones: ZoneMap) -> Self {
        self.zones = zones;
        self
    }
}

#[async_trait]
impl PortScanner for ConnectUdpPortScanner {
    fn kind(&self) -> ScannerKind {
        ScannerKind::ConnectUdp
    }

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

    /// Identifies the UDP services this scanner found open.
    ///
    /// [`ConnectPortScanner`] needs no such pass because it fingerprints over
    /// the stream it already holds. There is no equivalent here: a UDP probe is
    /// one datagram, sent to establish that the port is open, and the question
    /// that identifies what answered is a second one. So the phase runs, scoped
    /// to [`Protocol::Udp`] so a composite's TCP member keeps its own half.
    async fn detect_services(&mut self, ctx: &ScanContext) {
        crate::scanner::service::detect(ctx, self.service_detection, Protocol::Udp).await;
    }

    async fn scan(&mut self, mut rx: mpsc::Receiver<PlannedTarget>) -> Result<(), StrategyError> {
        let ctx = self.ctx.clone();
        let shaping = Shaping::from(&self.evasion);
        let mut shortfall = Shortfall::default();
        let mut pool = ProbePool::new(
            self.concurrency,
            self.ctx.clone(),
            self.kind(),
            |probed, audit: &mut ProbeAudit| absorb_probe(&ctx, probed, audit, &mut shortfall),
        );

        let mut probes = 0u128;
        let mut reason = StopReason::AttemptsSpent;
        while let Some(target) = rx.recv().await {
            if let Some(cause) = self.ctx.handle.stopped() {
                reason = cause.into();
                record_unasked(&self.ctx, &target);
                break;
            }
            probes += 1;
            // A host past its own budget is left alone. Counted with the
            // probes, because it was work routed here, and recorded unasked so a
            // resume asks about it rather than trusting a verdict nobody earned.
            if self.ctx.host_expired(target.ip()) {
                record_unasked(&self.ctx, &target);
                continue;
            }
            let endpoint = self.zones.endpoint(target.ip(), target.port());
            let egress = self.ctx.egress_toward(target.ip());
            let handle = self.ctx.handle.clone();
            pool.admit(udp_port_prober(target, shaping, egress, endpoint, handle))
                .await;
        }

        // Anything still queued was never sent, and carries no position to
        // settle. The TCP scan above does the same; leaving it out here would
        // both lose the ports and leave the sitting's settlement counts short
        // of the targets it was handed.
        while let Ok(target) = rx.try_recv() {
            record_unasked(&self.ctx, &target);
        }

        pool.drain().await;
        let audit = pool.into_audit();
        shortfall.report(&self.ctx, self.kind(), "port", "ports");
        finish(&self.ctx, audit, self.kind(), probes, reason);
        Ok(())
    }
}

/// Performs a high-concurrency, unprivileged port scan.
///
/// This is the primary scanning strategy for callers without root privileges. It
/// consumes the randomized stream of targets a
/// [`Dispatcher`](crate::scanner::dispatcher::Dispatcher) produces, holding the
/// number of ports in flight at or below `concurrency_limit` and each
/// connection within the process's descriptor budget, and records every port it
/// probed into the shared
/// [`ScanContext`] store - open, closed and filtered alike, so the list does not
/// depend on whether the caller had root.
pub async fn scan(
    mut rx: mpsc::Receiver<PlannedTarget>,
    concurrency_limit: usize,
    ctx: ScanContext,
    detection: ServiceDetection,
    evasion: &EvasionProfile,
    zones: &ZoneMap,
) -> Result<(), StrategyError> {
    let shaping = Shaping::from(evasion);
    let folder = ctx.clone();
    let mut shortfall = Shortfall::default();
    let mut pool = ProbePool::new(
        concurrency_limit,
        ctx.clone(),
        ScannerKind::Connect,
        |probed, audit: &mut ProbeAudit| absorb_probe(&folder, probed, audit, &mut shortfall),
    );

    let mut probes = 0u128;
    let mut reason = StopReason::AttemptsSpent;
    while let Some(target) = rx.recv().await {
        if let Some(cause) = ctx.handle.stopped() {
            reason = cause.into();
            // This one was taken off the queue and never asked, so it is
            // recorded with the rest still waiting behind it.
            record_unasked(&ctx, &target);
            break;
        }
        probes += 1;
        // A host past its own budget is left alone, and its remaining ports are
        // recorded unasked rather than given a verdict nothing earned.
        if ctx.host_expired(target.ip()) {
            record_unasked(&ctx, &target);
            continue;
        }
        let endpoint = zones.endpoint(target.ip(), target.port());
        let egress = ctx.egress_toward(target.ip());
        // Identified over the connection that finds the port open, so the
        // port's own cap applies here rather than in a pass of its own.
        let identify = ctx.service_detection_on(detection, target.port(), target.protocol());
        pool.admit(port_prober(
            target,
            identify,
            shaping,
            egress,
            endpoint,
            ctx.handle.clone(),
        ))
        .await;
    }

    // Anything still queued was never sent, and carries no position to settle.
    while let Ok(target) = rx.try_recv() {
        record_unasked(&ctx, &target);
    }

    // Every target dispatched; wait out the probes still in flight.
    pool.drain().await;
    let audit = pool.into_audit();
    shortfall.report(&ctx, ScannerKind::Connect, "port", "ports");
    finish(&ctx, audit, ScannerKind::Connect, probes, reason);
    Ok(())
}

/// Folds one finished probe into the store: the port it classified, if it
/// classified one worth keeping, and what the exchange proved about the host.
///
/// A refused connection reaches here with no port and `answered` set, which is
/// the case worth noticing: this strategy declines to file closed ports, but the
/// RST behind the refusal still proves the host is there, and that evidence
/// would otherwise be dropped along with the port verdict.
///
/// The responses the inline fingerprint drew are kept here too. They belong to
/// no host record, so they go to the context the
/// [detection phase](crate::scanner::detection) reads them from, which is the same
/// place [`service::detect`](crate::scanner::service::detect) puts the ones a
/// raw scan draws in its second pass.
///
/// The send is counted here, from the probe's own [`Attempt`], and a probe
/// that could not ask is also counted into `shortfall`, which the scan reports
/// once it has drained.
fn absorb_probe(
    ctx: &ScanContext,
    probed: ProbedPort,
    audit: &mut ProbeAudit,
    shortfall: &mut Shortfall,
) {
    let Some(probed) = probed else {
        return;
    };
    match probed.attempt {
        Attempt::Sent => audit.record_send(true),
        Attempt::Refused(_) | Attempt::Starved => audit.record_send(false),
        Attempt::Unmade => {}
    }
    shortfall.count(probed.ip, &probed.attempt);
    ctx.record_outcome(probed.outcome);
    if probed.answered {
        // A connect probe carries no attempt token: the retransmission that may
        // have produced this answer was the host stack's, on its own schedule
        // (see `CONNECT_PROBE_TIMEOUT`), so which attempt was answered is
        // not knowable from here.
        audit.record_host_found(None);
    }
    if probed.port.is_none() && !probed.answered && probed.role.is_none() {
        return;
    }

    // Filed under the same key the port is, which is the key the detection
    // phase looks the responses up by: a host's zone comes from the key it was
    // stored under, so the two cannot disagree.
    if let Some((number, protocol)) = probed
        .port
        .as_ref()
        .map(|port| (port.number(), port.protocol()))
    {
        ctx.record_responses(probed.ip.into(), number, protocol, probed.responses);
    }

    ctx.update_host(probed.ip, |host| {
        if let Some(port) = probed.port.clone() {
            host.add_port(port);
        }
        if let Some(role) = probed.role {
            host.add_network_role(role);
        }
        if probed.answered {
            host.record_evidence(
                HostStatus::Up,
                StatusReason::new(StatusProtocol::TcpSyn, "tcp connect answered by the host"),
            );
        }
        // The handshake's round trip, which is the host's as much as the
        // liveness pass's own connect is: a scan that ran no such pass has no
        // other on this path.
        if let Some(rtt) = probed.rtt {
            host.add_rtt_from(rtt, StatusProtocol::TcpSyn);
        }
        if !probed.about_the_host.is_empty() {
            // The same call the service phase makes on the privileged path.
            // What a banner says about the machine is worth the same whichever
            // scanner happened to draw it, and this scanner is the only one
            // that draws it without a raw socket.
            probed.about_the_host.clone().apply(host);
        }
    });
}

/// A port in `state`, carrying the packet that settled it where one did.
///
/// This scanner never sees a segment, the kernel does the handshake and hands
/// back an outcome, but the outcome names what came back: a completed
/// connection is a SYN/ACK, a timeout is silence, an unreachable is an ICMP
/// error, and a refusal is one of two packets the kernel reports alike, a RST
/// or an ICMP port unreachable, and is named as a refusal for that reason.
/// Recorded so an unprivileged report can say what its verdicts rest on,
/// which is the one thing separating a port a firewall dropped from a port
/// nothing was listening on.
///
/// `None` where no packet is implied: a local failure, no route, no socket
/// left, is this host giving up, and crediting the target with a silence it was
/// never asked for would be evidence of the wrong thing.
fn settled(number: u16, state: PortState, reason: Option<ScanResponse>) -> Port {
    let port = crate::fingerprint::baseline_port(number, Protocol::Tcp, state);

    match reason {
        Some(reason) => port.with_discovery(Discovery::new(reason)),
        None => port,
    }
}

/// Records a planned target no probe was ever sent to.
///
/// Three ways one arises in this strategy: the scan stopped with targets still
/// queued, the target's host had already spent
/// [`ZondConfig::host_timeout`](crate::config::ZondConfig::host_timeout), and
/// this machine failed the connect locally before anything left it.
///
/// All three leave the port on the host rather than off it, for the reason
/// [`port_prober`]'s refusal branch gives about `Closed`: a port list whose shape
/// depends on how a run ended is a different answer rather than a smaller one,
/// and a comparison of two scans reads the difference as the network moving.
/// What the port says is [`PortState::Unasked`], which is the whole of what this
/// run established about it, and the outcome carries no position, so a resume
/// asks the question this sitting did not.
fn record_unasked(ctx: &ScanContext, target: &PlannedTarget) {
    let port =
        crate::fingerprint::baseline_port(target.port(), target.protocol(), PortState::Unasked);
    ctx.update_host(target.ip(), |host| {
        host.add_port(port);
    });
    ctx.record_outcome(Outcome::Unasked);
}

/// Probes a single [`PlannedTarget`] over a full TCP connect handshake and
/// classifies its port. Returns `None` only for a target this strategy doesn't
/// handle.
///
/// An accepted connection is `Open` and gets fingerprinted over the live stream,
/// a refusal is `Closed`, and an ICMP error or a timeout is `Filtered`. A
/// connect this machine refused before anything left it is `Unasked`; see
/// [`Handshake`] for how each is told from the others. Only TCP is supported,
/// so UDP targets are skipped.
///
/// A connect that met itself asked nothing, and is made again from a fresh
/// socket, up to [`SELF_MEETINGS`] times.
///
/// The connection, and every one the fingerprint makes after it, leaves by
/// `egress`. Its socket comes from the process's budget and is held until the
/// fingerprint is done with it; a port the process has no socket for, or that
/// the scan stopped before asking, is `Unasked` too.
async fn port_prober(
    planned: PlannedTarget,
    detection: ServiceDetection,
    shaping: Shaping,
    egress: Egress,
    socket_addr: SocketAddr,
    handle: ScanHandle,
) -> ProbedPort {
    let target = planned.target;
    if target.protocol == Protocol::Udp {
        // UDP can't be probed through a TCP stream; skip rather than misreport.
        // No outcome: unreported is re-probed, which is what a routing mistake
        // deserves.
        return None;
    }

    let position = planned.position;
    let verdict = |state, reason, answered, rtt, outcome| {
        Some(Probed {
            ip: target.ip,
            port: Some(settled(target.port, state, reason)),
            responses: Vec::new(),
            about_the_host: crate::fingerprint::AboutTheHost::default(),
            answered,
            rtt,
            outcome,
            attempt: Attempt::Sent,
            role: None,
        })
    };
    let unasked = |outcome, attempt| {
        Some(Probed {
            ip: target.ip,
            port: Some(settled(target.port, PortState::Unasked, None)),
            responses: Vec::new(),
            about_the_host: crate::fingerprint::AboutTheHost::default(),
            answered: false,
            rtt: None,
            outcome,
            attempt,
            role: None,
        })
    };

    let mut met_itself = None;
    for _ in 0..SELF_MEETINGS {
        let (handshake, rtt, descriptor) = match dial(&handle, descriptors::PATIENCE, || {
            std::future::ready(egress.start_connect(socket_addr, shaping))
        })
        .await
        {
            Dialled::Ran {
                result: Ok(connecting),
                began,
                descriptor,
            } => {
                let handshake = Handshake::sent(handshake(connecting).await);
                // Read before the fingerprint talks to the port, which is the
                // service's time rather than the path's.
                (handshake, began.elapsed(), Some(descriptor))
            }
            Dialled::Ran {
                result: Err(e),
                began,
                ..
            } => (Handshake::unsent(e), began.elapsed(), None),
            // Not a local failure: the scan ended first, as for a target still
            // queued (see `record_unasked`).
            Dialled::Stopped => return unasked(Outcome::Unasked, Attempt::Unmade),
            Dialled::Starved => return unasked(Outcome::Unroutable, Attempt::Starved),
        };

        return match handshake {
            Handshake::Accepted(stream) => {
                let port = settled(target.port, PortState::Open, Some(ScanResponse::TcpSynAck));
                // The detailed form, for the second and third values. This
                // handshake is the only conversation an unprivileged scan has
                // with the port, so what it draws here is everything any later
                // phase can read without dialling again: the responses a
                // passive detection needs, and what the same bytes said about
                // the machine. The descriptor is held until it is done.
                let (port, about_the_host, responses) =
                    crate::fingerprint::fingerprint_tcp_via(stream, port, detection, egress).await;
                drop(descriptor);
                Some(Probed {
                    ip: target.ip,
                    port: Some(port),
                    responses,
                    about_the_host,
                    answered: true,
                    rtt: Some(rtt),
                    outcome: Outcome::Answered { position },
                    attempt: Attempt::Sent,
                    // A TCP handshake proves a service, and the service is the
                    // port's to name. No role is read from one.
                    role: None,
                })
            }
            // A refusal is the clearest verdict this scanner ever gets, and it
            // is filed as one, under the name of what it is: a refusal, which
            // the operating system hands back alike for a reset and for an
            // ICMP port unreachable. Most are resets, a stack with nothing
            // listening, and the port is read closed. A filter rejecting with
            // a port unreachable reads closed here too, where the raw path,
            // which sees the packet, reads it filtered; no error code on any
            // platform separates the two, so the reason recorded says what
            // the verdict rests on rather than naming a reset nobody saw.
            //
            // Recorded rather than dropped because a port list that changes
            // with the caller's privilege level is not a smaller answer, it is
            // a different one: omitting it would leave an unprivileged report
            // with no `Closed` entry in its `ports_by_state` however many
            // refusals it collected, which somebody diffing two scans would
            // read as a change in the network.
            Handshake::Refused => verdict(
                PortState::Closed,
                Some(ScanResponse::ConnectionRefused),
                true,
                Some(rtt),
                Outcome::Answered { position },
            ),
            // Something on the way refused the connection with an ICMP error:
            // a firewall's reject, a router with no way on. The raw path reads
            // the same packet as filtered, and so does this one. Settled,
            // because it is an answer; the host is not credited, because the
            // error's sender is not surfaced and is as often a router as the
            // target, and neither is its round trip.
            Handshake::Unreachable => verdict(
                PortState::Filtered,
                Some(ScanResponse::IcmpUnreachable),
                false,
                None,
                Outcome::Answered { position },
            ),
            // Silence: the probe was dropped, the classic firewall signature.
            // Settled, because a connect gets one attempt and this was it.
            Handshake::Silent => verdict(
                PortState::Filtered,
                Some(ScanResponse::NoResponse),
                false,
                None,
                Outcome::Exhausted { position },
            ),
            Handshake::MetItself(e) => {
                met_itself = Some(e);
                continue;
            }
            // This machine refused the connect before anything left it, so
            // nothing was asked and the host has proved nothing. The next
            // sitting may well get further.
            //
            // No evidence recorded, since there is no packet to name, and no
            // verdict either: filing `Filtered` would credit the target with a
            // silence it was never asked for in the one field a reader takes
            // for a finding.
            Handshake::NotSent(e) => {
                unasked(Outcome::Unroutable, Attempt::Refused(Refusal::of(&e)))
            }
            // The SYN left and the connect failed in a way that names no
            // packet. It was asked, so the send counts, and it has no verdict,
            // so a resume asks again.
            Handshake::Failed(e) => {
                error!(
                    verbosity = 2,
                    "connect to {socket_addr} failed after sending: {e}"
                );
                unasked(Outcome::Unroutable, Attempt::Sent)
            }
        };
    }

    // Met itself every time, which only a pinned source port equal to the
    // target's, on this machine's own address, can do.
    let why = met_itself.map_or_else(String::new, |e| e.to_string());
    unasked(Outcome::Unroutable, Attempt::Refused(Refusal::Local(why)))
}

/// How many times a connect probe is made before a connect that keeps
/// meeting itself is given up.
///
/// A connect meets itself when the kernel draws the target's own port as its
/// source, which a fresh socket draws again with odds of about one in the
/// size of the ephemeral range. Three is room for that and for nothing else:
/// a probe that met itself three times is one pinned to the port it asks
/// about, which no retry changes.
const SELF_MEETINGS: usize = 3;

/// What one connect probe's handshake came to, read for what it says about
/// the port.
///
/// The operating system hands a connect back as an error code and nothing
/// else, and the codes are shared between causes that mean different things:
/// `EHOSTUNREACH` is a missing route on this machine and a firewall's reject
/// on the far side. What separates them is when the code arrived, so a
/// connect is made in two halves (see
/// [`Egress::start_connect`](crate::transport::dial::Egress::start_connect)),
/// and a code from the first half is always [`NotSent`](Self::NotSent).
#[derive(Debug)]
enum Handshake {
    /// The handshake completed: a SYN/ACK.
    Accepted(TcpStream),
    /// The connection was refused: a reset, or an ICMP port unreachable,
    /// which every platform reports alike.
    Refused,
    /// An ICMP error other than a port unreachable ended the connect after its
    /// SYN left: an administrative prohibition, a host or network the path
    /// could not reach, a protocol the far end does not speak.
    ///
    /// Linux ends a connect at the first such error; macOS and the BSDs hold
    /// it as a soft error and keep retrying, so there the same packet ends in
    /// [`Silent`](Self::Silent), which is filed as the same state.
    Unreachable,
    /// Nothing came back within the connect's budget, or the stack gave up
    /// first, which is the same outcome, a SYN out and nothing back; the
    /// second can come first on Windows, where a probe keeps a single
    /// retransmission.
    Silent,
    /// The connect reached its own socket; see
    /// [`met_itself`](crate::transport::dial::met_itself).
    MetItself(io::Error),
    /// This machine refused the connect before anything left it.
    NotSent(io::Error),
    /// The SYN left and the connect failed in a way that names no packet.
    Failed(io::Error),
}

impl Handshake {
    /// Reads a connect's first half refused, before anything left this
    /// machine.
    ///
    /// A refusal stays a refusal whichever half reported it, since no stack
    /// invents one: over loopback the answer can arrive before the connect
    /// call returns.
    fn unsent(error: io::Error) -> Self {
        if crate::transport::dial::met_itself(&error) {
            Self::MetItself(error)
        } else if error.kind() == ErrorKind::ConnectionRefused {
            Self::Refused
        } else {
            Self::NotSent(error)
        }
    }

    /// Reads the outcome of a connect's second half, after its SYN left.
    fn sent(result: io::Result<TcpStream>) -> Self {
        let error = match result {
            Ok(stream) => return Self::Accepted(stream),
            Err(error) => error,
        };
        if crate::transport::dial::met_itself(&error) {
            return Self::MetItself(error);
        }
        match error.kind() {
            ErrorKind::ConnectionRefused => Self::Refused,
            ErrorKind::TimedOut => Self::Silent,
            _ if is_unreachable(&error) => Self::Unreachable,
            _ => Self::Failed(error),
        }
    }
}

/// Whether `error`, raised after a probe left, is an ICMP error other than a
/// port unreachable: a host or network the path could not reach, an
/// administrative prohibition, which Linux reports as a host it cannot reach,
/// and on Linux a protocol unreachable (`ENOPROTOOPT`) or an unknown or
/// isolated host (`EHOSTDOWN`, `ENONET`), which the standard library has no
/// kind for.
fn is_unreachable(error: &io::Error) -> bool {
    if matches!(
        error.kind(),
        ErrorKind::HostUnreachable | ErrorKind::NetworkUnreachable
    ) {
        return true;
    }
    #[cfg(target_os = "linux")]
    {
        matches!(
            error.raw_os_error(),
            Some(libc::ENOPROTOOPT | libc::EHOSTDOWN | libc::ENONET)
        )
    }
    #[cfg(not(target_os = "linux"))]
    {
        false
    }
}

/// The second half of a connect, given [`CONNECT_PROBE_TIMEOUT`] to be
/// answered.
///
/// The budget running out and the stack giving up first are the same outcome,
/// a SYN out and nothing back, so both come back as [`ErrorKind::TimedOut`].
async fn handshake(connecting: Connecting) -> io::Result<TcpStream> {
    timeout(CONNECT_PROBE_TIMEOUT, connecting.finish())
        .await
        .unwrap_or_else(|_elapsed| Err(ErrorKind::TimedOut.into()))
}

/// Probes a single [`PlannedTarget`] for UDP using a standard OS `UdpSocket`,
/// the unprivileged counterpart of
/// [`UdpPortScanner`](super::ports::UdpPortScanner).
///
/// UDP has no handshake to read a verdict from, so this leans on what the local
/// kernel reports about the datagram it sent. The socket is *connected*, which
/// is what makes that possible: a connected UDP socket has a known peer, so the
/// kernel can attribute an inbound ICMP error to it and surface it as
/// `ConnectionRefused` on a subsequent operation. An unconnected socket
/// discards the same error with nowhere to deliver it.
///
/// A reply is `Open`, a refusal is `Closed`, any other ICMP error the kernel
/// surfaces is `Filtered`, and silence is `OpenFiltered` - the verdicts the
/// raw scanner reaches, by a different route.
/// Errors that say nothing about the target (no local socket, no route) are
/// logged and yield no record rather than a guess.
///
/// The datagram leaves by `egress`, from a socket out of the process's budget,
/// and a port the process has no socket for is recorded unasked.
async fn udp_port_prober(
    planned: PlannedTarget,
    shaping: Shaping,
    egress: Egress,
    socket_addr: SocketAddr,
    handle: ScanHandle,
) -> ProbedPort {
    let target = planned.target;
    if target.protocol != Protocol::Udp {
        return None;
    }

    let position = planned.position;
    // `answered` is set only where the kernel vouches for who sent the packet.
    // A datagram arriving on a connected socket came from the peer, so `Open`
    // proves the host. A refusal does not: it is an ICMP error the kernel
    // matched to this socket by the datagram it quotes, and the error's own
    // source address - a router's, or the target's - is not surfaced through
    // this API at all. The privileged scanner reads that address and can tell
    // the two apart; here the port verdict stands on its own and no claim is
    // made about the host.
    let record = |state, answered, outcome, attempt| {
        Some(Probed {
            ip: target.ip,
            port: Some(crate::fingerprint::baseline_port(
                target.port,
                Protocol::Udp,
                state,
            )),
            // Nothing on this path turns a datagram into the text a detection
            // reads: the reply is read for the role it declares and no more.
            responses: Vec::new(),
            about_the_host: crate::fingerprint::AboutTheHost::default(),
            answered,
            // A datagram's reply is the service's as much as the path's, so no
            // round trip is read from it.
            rtt: None,
            outcome,
            attempt,
            // Filled in by the one arm that has a reply to read it from.
            role: None,
        })
    };

    // Three ways this machine can fail before a datagram leaves it, below, and
    // each records the port unasked rather than dropping it. The target was
    // named by the plan, and a port that disappears from the host when the
    // scanner runs out of sockets is the shortfall a reader cannot see. The
    // outcome is `Unroutable` rather than `Unasked` for the reason the TCP
    // prober gives: this host gave up, which the next sitting may not.
    let refused = |e: &io::Error| Attempt::Refused(Refusal::of(e));
    let (socket, _descriptor) = match dial(&handle, descriptors::PATIENCE, || {
        egress.udp_shaped(target.ip, shaping)
    })
    .await
    {
        Dialled::Ran {
            result: Ok(socket),
            descriptor,
            ..
        } => (socket, descriptor),
        Dialled::Ran { result: Err(e), .. } => {
            error!(
                verbosity = 2,
                "no UDP socket for probing {socket_addr}: {e}"
            );
            return record(PortState::Unasked, false, Outcome::Unroutable, refused(&e));
        }
        Dialled::Stopped => {
            return record(PortState::Unasked, false, Outcome::Unasked, Attempt::Unmade);
        }
        Dialled::Starved => {
            return record(
                PortState::Unasked,
                false,
                Outcome::Unroutable,
                Attempt::Starved,
            );
        }
    };

    if let Err(e) = socket.connect(socket_addr).await {
        error!(
            verbosity = 2,
            "cannot address UDP probe to {socket_addr}: {e}"
        );
        return record(PortState::Unasked, false, Outcome::Unroutable, refused(&e));
    }

    if let Err(e) = socket.send(payload::for_port(target.port)).await {
        // A refusal can surface here rather than on the receive: the kernel
        // reports a queued ICMP error on whichever operation comes next.
        return match e.kind() {
            ErrorKind::ConnectionRefused => record(
                PortState::Closed,
                false,
                Outcome::Answered { position },
                Attempt::Sent,
            ),
            _ => {
                error!(
                    verbosity = 2,
                    "failed to send UDP probe to {socket_addr}: {e}"
                );
                record(PortState::Unasked, false, Outcome::Unroutable, refused(&e))
            }
        };
    }

    let mut buf = [0u8; 1024];
    match timeout(CONNECT_PROBE_TIMEOUT, socket.recv(&mut buf)).await {
        // Something answered, so something is listening, and what it said may
        // prove what the host is, which is a claim no port verdict can make.
        // Read here rather than left to the privileged path, so a scan without
        // root reaches the same conclusions about the network.
        Ok(Ok(read)) => record(
            PortState::Open,
            true,
            Outcome::Answered { position },
            Attempt::Sent,
        )
        .map(|probed| Probed {
            role: payload::declared_role(target.port, &buf[..read]),
            ..probed
        }),
        // An ICMP Port Unreachable, surfaced against the connected peer.
        Ok(Err(e)) if e.kind() == ErrorKind::ConnectionRefused => record(
            PortState::Closed,
            false,
            Outcome::Answered { position },
            Attempt::Sent,
        ),
        // Any other ICMP error the kernel surfaced: an administrative
        // prohibition, which Linux reports on a connected socket as a host it
        // cannot reach, or a protocol unreachable. The raw path reads the same
        // packet as filtered, and so does this one.
        Ok(Err(e)) if is_unreachable(&e) => record(
            PortState::Filtered,
            false,
            Outcome::Answered { position },
            Attempt::Sent,
        ),
        // Any other failure leaves the port as unknown as silence does.
        Ok(Err(e)) => {
            error!(
                verbosity = 2,
                "UDP probe to {socket_addr} failed after sending: {e}"
            );
            // A local read failure, not a fact about the target, and after
            // the datagram left, so the send itself was made.
            record(
                PortState::OpenFiltered,
                false,
                Outcome::Unroutable,
                Attempt::Sent,
            )
        }
        // No error and no reply: open but silent, or filtered. UDP cannot tell.
        // Settled either way: this probe had one attempt and spent it.
        Err(_) => record(
            PortState::OpenFiltered,
            false,
            Outcome::Exhausted { position },
            Attempt::Sent,
        ),
    }
}

/// What asking the process for a socket, and then using it, came to.
enum Dialled<T> {
    /// A socket was had and the attempt ran.
    Ran {
        /// What the attempt came to. Never the process running out of
        /// sockets, which is waited out rather than returned.
        result: io::Result<T>,
        /// When the attempt that ran began, after any wait for a socket, so a
        /// round trip timed from it is the target's and not the queue's.
        began: Instant,
        /// The socket's share of the process's budget, given back when it is
        /// dropped. Kept for as long as what `result` holds is, or the budget
        /// would count a socket as closed while it is still open.
        descriptor: Descriptor,
    },
    /// The scan stopped before a socket could be had.
    Stopped,
    /// The process had no socket to give for as long as the probe would wait.
    Starved,
}

/// Runs `attempt` on a socket from the process's descriptor budget.
///
/// The budget is taken first, so a sweep never asks for more sockets than
/// [`descriptors`] allows it. The attempt can still be refused a socket, when
/// something else in the process has filled the table, and that refusal is
/// never passed on: it is raised before anything is sent, so it says nothing
/// about the target, and read as an answer it becomes an address passed over
/// as silent or a port filed as asked. The attempt is made again once a
/// descriptor may have come free, for as long as `patience` allows from the
/// first refusal, and then given up as [`Dialled::Starved`].
///
/// Each attempt's own time budget starts only once it has its socket, so no
/// part of the wait is ever read as a target's silence.
///
/// The same wait as [`descriptors::patiently`], every other connection's, in a
/// loop of its own because a sweep keeps thousands of these in flight: each
/// gives its descriptor back while it waits, so a queued probe can use it, and
/// asks the scan's stop before it asks again.
async fn dial<T, F, Fut>(handle: &ScanHandle, patience: Duration, mut attempt: F) -> Dialled<T>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = io::Result<T>>,
{
    let mut refused_since: Option<Instant> = None;
    let mut pause = descriptors::FIRST_PAUSE;
    loop {
        let descriptor = descriptors::gate()
            .acquire()
            .await
            .expect("the descriptor gate is never closed");
        if handle.should_stop() {
            return Dialled::Stopped;
        }
        let began = Instant::now();
        match attempt().await {
            Err(e) if descriptors::exhausted(&e) => {
                drop(descriptor);
                if refused_since.get_or_insert(began).elapsed() >= patience {
                    return Dialled::Starved;
                }
                tokio::time::sleep(pause).await;
                pause = (pause * 2).min(descriptors::LONGEST_PAUSE);
            }
            result => {
                return Dialled::Ran {
                    result,
                    began,
                    descriptor,
                };
            }
        }
    }
}

/// One connect to `addr`, given [`CONNECT_PROBE_TIMEOUT`] to be answered.
///
/// The budget running out and the stack giving up first are the same outcome,
/// a SYN out and nothing back, so both come back as [`ErrorKind::TimedOut`].
async fn connect(egress: Egress, addr: SocketAddr, shaping: Shaping) -> io::Result<TcpStream> {
    timeout(CONNECT_PROBE_TIMEOUT, egress.connect_shaped(addr, shaping))
        .await
        .unwrap_or_else(|_elapsed| Err(ErrorKind::TimedOut.into()))
}

/// Files the targets a run left unasked because the process had no socket to
/// give them, once, as the failure it is. `patience` is how long each waited.
///
/// A failure rather than a log line because it narrows the result: those
/// targets have no verdict, and a report that did not say why would read as
/// a network that did not answer. The remedy is the caller's, not the
/// engine's, which reads the file limit and does not raise it.
/// `unasked` names what was left, counted.
fn report_starved(ctx: &ScanContext, scanner: ScannerKind, unasked: String, patience: Duration) {
    ctx.record_failure(
        scanner,
        format!("{unasked} left unasked: {}", descriptors::starved(patience)),
    );
}

/// Files what a finished sweep or scan measured.
///
/// Both halves of this strategy report the same way, so the audit line and the
/// recorded counters cannot drift between them.
fn finish(
    ctx: &ScanContext,
    audit: ProbeAudit,
    scanner: ScannerKind,
    probes: u128,
    reason: StopReason,
) {
    audit.report("connect", probes, reason, None, None);
    ctx.record_probe_stats(audit.stats(scanner, probes, reason, None, None));
}

/// Multi-port host discovery for unprivileged environments, asking the common
/// five ports: SSH (22), HTTP (80), HTTPS (443), SMB (445), and RDP (3389).
///
/// [`discover_on`] with [`SynPorts::common`], for a sweep that was asked about
/// no ports of its own.
pub async fn discover(
    ips: IpSet,
    ctx: ScanContext,
    evasion: &EvasionProfile,
) -> Result<(), StrategyError> {
    discover_on(ips, ctx, evasion, SynPorts::common()).await
}

/// Multi-port host discovery for unprivileged environments, asking each address
/// about every port of `ports` until one of them answers.
///
/// `ports` is the set a routed SYN sweep asks, and for the same reason: a host
/// behind a filter that drops a connection attempt to anything it does not
/// serve answers on the ports it serves and nowhere else, so a port scan's
/// liveness pass passes [`SynPorts::for_scan`] and the host is asked about the
/// ports the scan is about to probe. Taking the one type both sweeps take is
/// what keeps an unprivileged run from finding fewer hosts than a privileged
/// one over the same ports. See [`SynPorts`] for which ports those are.
///
/// One task per address, not per port. Its ports are tried in turn, in the
/// order the set holds them, and the first TCP-layer answer ends the address,
/// so a host that answers on SSH costs one connect whatever the set's size. A
/// silent address costs a connect per port, each waiting out the
/// [`CONNECT_PROBE_TIMEOUT`], so a silent range takes up to eight timeouts an
/// address where the common five alone take five. The socket budget is the
/// same either way: one descriptor per address in flight, held one connect at
/// a time, so a larger set lengthens a silent sweep and never widens it. A task
/// per port would spend the same descriptor-seconds on fewer addresses at a
/// time and answer no sooner.
///
/// That shape is also what lets a sweep be continued. An address is the unit a
/// journal counts, so its verdict has to be earned as a whole: answered, or
/// every port asked once and none of them answering. Interleaving the ports of
/// many addresses would give neither, because nothing would know when an
/// address was finished with.
///
/// Addresses are drawn from
/// [`dispatch_addresses`] to
/// spread load across the network instead of hammering one subnet at a time, and
/// each connect waits out the [`CONNECT_PROBE_TIMEOUT`] so that hosts on slow or
/// distant links still register.
pub async fn discover_on(
    ips: IpSet,
    ctx: ScanContext,
    evasion: &EvasionProfile,
    ports: SynPorts,
) -> Result<(), StrategyError> {
    sweep(ips, ctx, evasion, ports, descriptors::PATIENCE).await
}

/// [`discover_on`], waiting at most `patience` for a socket the process has
/// none of before leaving an address unasked.
async fn sweep(
    ips: IpSet,
    ctx: ScanContext,
    evasion: &EvasionProfile,
    ports: SynPorts,
    patience: Duration,
) -> Result<(), StrategyError> {
    let shaping = Shaping::from(evasion);
    let ports: Arc<[u16]> = ports.as_slice().into();

    let mut rx = dispatch_addresses(ips, 1024, ctx.order_seed, &ctx.handle);
    let folder = ctx.clone();
    let mut starved = 0u128;
    // No more probes than the process has sockets for: past the budget a
    // probe would only queue at the gate, holding a task and nothing else.
    let mut pool = ProbePool::new(
        DISCOVERY_CONCURRENCY.min(descriptors::budget()),
        ctx.clone(),
        ScannerKind::Connect,
        |probed, audit: &mut ProbeAudit| absorb_host(&folder, probed, audit, &mut starved),
    );

    let mut probes = 0u128;
    let mut reason = StopReason::AttemptsSpent;
    while let Some(ip) = rx.recv().await {
        if let Some(cause) = ctx.handle.stopped() {
            reason = cause.into();
            // Taken off the queue and never asked, so it counts with the rest
            // still waiting behind it.
            ctx.record_address_outcomes(Outcome::Unasked, 1);
            break;
        }
        probes += 1;
        let egress = ctx.egress_toward(ip);
        pool.admit(prober(
            ip,
            Arc::clone(&ports),
            ctx.handle.clone(),
            shaping,
            egress,
            patience,
        ))
        .await;
    }

    // Anything still queued was never asked, and carries no position to settle.
    while rx.try_recv().is_ok() {
        ctx.record_address_outcomes(Outcome::Unasked, 1);
    }

    // Every address dispatched; wait out the probes still in flight.
    pool.drain().await;
    let audit = pool.into_audit();
    if starved > 0 {
        let unasked = counted(starved, "address", "addresses");
        report_starved(&ctx, ScannerKind::Connect, unasked, patience);
    }
    finish(&ctx, audit, ScannerKind::Connect, probes, reason);
    Ok(())
}

/// What one address's liveness probe came to.
struct ProbedHost {
    /// The address asked about, which is the unit a sweep settles.
    ip: IpAddr,
    /// What became of it.
    fate: Fate,
}

/// The four things a sweep can honestly say about an address, before anything
/// knows where in the plan it sits.
///
/// Only the first two are verdicts the sweep earned. The others say the address
/// was not asked, or not finished with, and a resume must ask again. see
/// [`settle`](crate::journal::settle).
///
/// Each also says whether a send was made, which is what the sweep's
/// `sends_attempted` and `sends_failed` count: an address the process could not
/// open a socket for, or had no route to, was a send that failed, and one the
/// scan stopped before asking was no send at all.
enum Fate {
    /// It answered, and this is what the answer proved.
    ///
    /// Boxed because a [`Host`] is by far the largest thing a fate can carry and
    /// five of the six variants carry nothing: unboxed, every probe that found
    /// silence would still move a host-sized value through the sweep.
    Answered(Box<Host>),
    /// Every port was asked once and not one of them answered. **Settled**: a
    /// connect gets one attempt per port and those were all of them.
    Exhausted,
    /// Nothing this probe sent left the host, no route or no source to send
    /// from, so the address proved nothing and the next sitting may get
    /// further.
    Unroutable,
    /// The process had no socket to give the probe, for longer than it was
    /// willing to wait, so the address was never asked. Unsettled for the same
    /// reason as [`Unroutable`](Self::Unroutable), and told apart from it
    /// because the cause is this process's file limit, which the scan reports.
    Starved,
    /// The scan stopped while the address's ports were still being tried.
    Interrupted,
    /// The scan stopped before any of them were.
    Unasked,
}

/// Merges one finished discovery probe into the store, and settles the address
/// it asked about.
///
/// A freshly created entry starts from [`Host::new`] and absorbs the probe's
/// findings, so the recorded result is the same whether or not the host was seen
/// before.
///
/// The three cases are the three things a sweep can honestly say about an
/// address: it answered, it was asked as many times as it is going to be and
/// stayed silent, or it could not be asked from here at all. Only the first two
/// are settled. see [`settle`](crate::journal::settle).
///
/// An address starved of a socket is counted into `starved`, which the sweep
/// reports once it has drained.
fn absorb_host(ctx: &ScanContext, probed: ProbedHost, audit: &mut ProbeAudit, starved: &mut u128) {
    match probed.fate {
        Fate::Answered(host) => {
            let ip = host.primary_ip();
            audit.record_send(true);
            // See `absorb_probe`: this path has no attempt to attribute the
            // answer to, so every host it finds is counted as unattributed.
            audit.record_host_found(None);
            ctx.settle_address(probed.ip, Settled::Answered);
            ctx.update_host(ip, |existing| existing.merge(*host));
        }
        Fate::Exhausted => {
            audit.record_send(true);
            ctx.settle_address(probed.ip, Settled::Exhausted);
        }
        Fate::Unroutable => {
            audit.record_send(false);
            ctx.record_address_outcomes(Outcome::Unroutable, 1);
        }
        Fate::Starved => {
            audit.record_send(false);
            *starved += 1;
            ctx.record_address_outcomes(Outcome::Unroutable, 1);
        }
        Fate::Interrupted => {
            audit.record_send(true);
            ctx.record_address_outcomes(Outcome::Interrupted, 1);
        }
        Fate::Unasked => ctx.record_address_outcomes(Outcome::Unasked, 1),
    }
}

/// Probes one address for presence, over each of `ports` in turn.
///
/// Returns as soon as one of them answers at the TCP layer: a completed
/// handshake, or a reset the kernel surfaced as a connection error. Any other
/// failure says nothing about the address, only that this connect did not
/// finish, so the next port is tried.
///
/// The stop signal is checked between ports, not only between addresses.
/// One task covers up to eight connects, and a sweep that only looked once
/// per address would take eight timeouts to wind down rather than one. What has
/// been asked so far decides how the address is filed: cut off part way through
/// is not the same as asked and silent, and only the second is a verdict.
///
/// Every connect leaves by `egress`, on a socket from the process's budget,
/// and waits at most `patience` for one the process has none of.
async fn prober(
    ip: IpAddr,
    ports: Arc<[u16]>,
    handle: ScanHandle,
    shaping: Shaping,
    egress: Egress,
    patience: Duration,
) -> ProbedHost {
    let mut asked = false;
    let cut_short = |asked| ProbedHost {
        ip,
        fate: if asked {
            Fate::Interrupted
        } else {
            Fate::Unasked
        },
    };

    for &port in ports.iter() {
        if handle.should_stop() {
            return cut_short(asked);
        }

        let addr = SocketAddr::new(ip, port);
        // The descriptor is held until the attempt's socket is dropped, at the
        // end of this pass, so the budget counts every socket still open.
        let (attempt, start, _descriptor) =
            match dial(&handle, patience, || connect(egress, addr, shaping)).await {
                Dialled::Ran {
                    result,
                    began,
                    descriptor,
                } => (result, began, descriptor),
                Dialled::Stopped => return cut_short(asked),
                Dialled::Starved => {
                    return ProbedHost {
                        ip,
                        fate: Fate::Starved,
                    };
                }
            };

        match attempt {
            // A completed handshake means the host is alive.
            Ok(_) => return answered(ip, start),
            Err(e) => match e.kind() {
                // Only these TCP errors imply the host answered at the IP/TCP
                // layer.
                ErrorKind::ConnectionRefused
                | ErrorKind::ConnectionReset
                | ErrorKind::ConnectionAborted => return answered(ip, start),
                // A timeout, the budget's or the stack's, is the probe going
                // out and nothing coming back, which is the address being
                // asked and declining to answer.
                ErrorKind::TimedOut => asked = true,
                // Any other is a local failure, no route, permission denied,
                // and the probe never reached the wire.
                _ => {}
            },
        }
    }

    ProbedHost {
        ip,
        fate: if asked {
            Fate::Exhausted
        } else {
            Fate::Unroutable
        },
    }
}

/// The record an address earns by answering, timed from `start`, when the
/// connect that was answered began: after any wait for a socket and any port
/// asked before it, so the round trip is that connect's alone.
fn answered(ip: IpAddr, start: Instant) -> ProbedHost {
    let mut host = Host::new(ip);
    host.add_rtt_from(start.elapsed(), StatusProtocol::TcpSyn);
    // Every outcome that reaches here required a segment from the target: a
    // completed handshake, or a reset the kernel surfaced as a connection error.
    // `Host::merge` keeps the stronger status, so this survives being folded
    // into an entry another strategy created first.
    host.record_evidence(
        HostStatus::Up,
        StatusReason::new(StatusProtocol::TcpSyn, "tcp connect answered by the host"),
    );

    ProbedHost {
        ip,
        fate: Fate::Answered(Box::new(host)),
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::target::Target;
    use std::net::{Ipv4Addr, Ipv6Addr};
    use tokio::net::UdpSocket;

    fn udp_target(ip: IpAddr, port: u16) -> PlannedTarget {
        PlannedTarget::new(
            u64::from(port),
            Target {
                ip,
                port,
                protocol: Protocol::Udp,
            },
        )
    }

    /// Reserves a loopback UDP port and releases it, yielding a number nothing
    /// is listening on - so the kernel answers a probe with an ICMP error.
    async fn closed_loopback_udp_port(ip: IpAddr) -> u16 {
        let socket = UdpSocket::bind((ip, 0)).await.expect("bind to reserve");
        let port = socket.local_addr().expect("reserved addr").port();
        drop(socket);
        port
    }

    /// A socket bound IPv4-only would make a v6 target fail at `connect` and
    /// vanish without a record or a log. Loopback only, and no privileges
    /// required, so this runs everywhere the suite does.
    #[tokio::test]
    async fn closed_ipv6_port_is_classified_not_dropped() {
        let ip = IpAddr::V6(Ipv6Addr::LOCALHOST);
        let port = closed_loopback_udp_port(ip).await;

        let probed = udp_port_prober(
            udp_target(ip, port),
            Shaping::default(),
            Egress::KERNEL,
            SocketAddr::new(ip, port),
            ScanHandle::new(),
        )
        .await;

        let probed = probed.expect("an IPv6 target must produce a verdict");
        let probed_port = probed.port.expect("a closed port is still a verdict");
        assert_eq!(probed.ip, ip);
        assert_eq!(probed_port.number(), port);
        assert_eq!(probed_port.state(), PortState::Closed);
    }

    #[tokio::test]
    async fn closed_ipv4_port_is_closed() {
        let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
        let port = closed_loopback_udp_port(ip).await;

        let probed = udp_port_prober(
            udp_target(ip, port),
            Shaping::default(),
            Egress::KERNEL,
            SocketAddr::new(ip, port),
            ScanHandle::new(),
        )
        .await;

        assert_eq!(
            probed
                .and_then(|probed| probed.port)
                .expect("a verdict")
                .state(),
            PortState::Closed
        );
    }

    /// A TCP port that refuses a connect is a SYN out and a RST back, one round
    /// trip to the host, and the host is credited with it. Without it a scan
    /// that ran no liveness pass, the only other source of a round trip on this
    /// path, reports every host it found with none.
    #[tokio::test]
    async fn a_refused_connect_times_the_host() {
        let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
        let port = {
            let listener = std::net::TcpListener::bind((ip, 0)).expect("bind to reserve");
            listener.local_addr().expect("reserved addr").port()
        };
        let planned = PlannedTarget::new(
            0,
            Target {
                ip,
                port,
                protocol: Protocol::Tcp,
            },
        );

        let probed = port_prober(
            planned,
            ServiceDetection::Off,
            Shaping::default(),
            Egress::KERNEL,
            SocketAddr::new(ip, port),
            ScanHandle::new(),
        )
        .await;
        let (session, ctx) = crate::scanner::session::ScanSession::new();
        absorb_probe(
            &ctx,
            probed,
            &mut ProbeAudit::new(),
            &mut Shortfall::default(),
        );

        let host = session
            .hosts()
            .get(ip)
            .expect("the refusal proves the host");
        assert!(
            host.average_rtt().is_some(),
            "the connect's round trip was not recorded against the host"
        );
    }

    /// A listener that answers is `Open` over either family.
    #[tokio::test]
    async fn a_listener_that_answers_is_open() {
        for ip in [
            IpAddr::V4(Ipv4Addr::LOCALHOST),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
        ] {
            let service = UdpSocket::bind((ip, 0)).await.expect("bind service");
            let port = service.local_addr().unwrap().port();
            tokio::spawn(async move {
                let mut buf = [0u8; 64];
                if let Ok((_, from)) = service.recv_from(&mut buf).await {
                    let _ = service.send_to(b"pong", from).await;
                }
            });

            let probed = udp_port_prober(
                udp_target(ip, port),
                Shaping::default(),
                Egress::KERNEL,
                SocketAddr::new(ip, port),
                ScanHandle::new(),
            )
            .await;

            assert_eq!(
                probed
                    .and_then(|probed| probed.port)
                    .expect("a verdict")
                    .state(),
                PortState::Open,
                "a live {ip} listener must read as open"
            );
        }
    }

    fn tcp_target(ip: IpAddr, port: u16) -> PlannedTarget {
        PlannedTarget::new(
            u64::from(port),
            Target {
                ip,
                port,
                protocol: Protocol::Tcp,
            },
        )
    }

    /// A connect that reaches its own socket is never filed as an open port.
    ///
    /// On Linux, and on macOS over IPv6, a connect given its target's port as
    /// its source completes a handshake with itself, and a prober that took
    /// the completed connect for an answer filed a port nothing listened on
    /// as open and identified its service from its own questions. On macOS
    /// over IPv4 the kernel refuses it instead. Either way nothing was asked.
    ///
    /// Pinning the source port to the target's is what makes every attempt
    /// meet itself, so the prober's fresh tries meet itself too and the port
    /// ends unasked, with the reason reported, rather than with a verdict.
    #[tokio::test]
    async fn a_connect_that_reaches_itself_is_never_filed_as_an_open_port() {
        for ip in [
            IpAddr::V4(Ipv4Addr::LOCALHOST),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
        ] {
            let port = {
                let reserved = std::net::TcpListener::bind((ip, 0)).expect("a free port");
                reserved.local_addr().expect("its address").port()
            };
            let shaping = Shaping {
                source_port: Some(port),
                hop_limit: None,
            };

            let probed = port_prober(
                tcp_target(ip, port),
                ServiceDetection::default(),
                shaping,
                Egress::KERNEL,
                SocketAddr::new(ip, port),
                ScanHandle::new(),
            )
            .await
            .expect("a TCP target is probed");

            assert_eq!(
                probed.port.as_ref().map(Port::state),
                Some(PortState::Unasked),
                "{ip}: a connect that met itself was filed as {:?}",
                probed.port
            );
            assert!(
                matches!(&probed.attempt, Attempt::Refused(Refusal::Local(why))
                    if why.contains("reached itself")),
                "{ip}: the refusal says why, and has {:?}",
                probed.attempt
            );
            assert!(!probed.answered, "{ip}: nothing answered");
        }
    }

    /// Where an error surfaced decides what it means: the same code before
    /// the SYN left is this machine's failure, and after it is an answer.
    ///
    /// `EHOSTUNREACH` is both a missing route here and a firewall's
    /// administrative prohibition on the far side, which Linux reports alike.
    /// Read as a local failure, a firewalled port is filed unasked and asked
    /// again on every resume; read as an answer, a port this machine could
    /// not reach would be filed filtered, a finding about a target nothing
    /// was sent to.
    #[test]
    fn an_unreachable_is_an_answer_after_the_syn_left_and_a_local_failure_before() {
        for kind in [ErrorKind::HostUnreachable, ErrorKind::NetworkUnreachable] {
            assert!(
                matches!(
                    Handshake::sent(Err(io::Error::from(kind))),
                    Handshake::Unreachable
                ),
                "{kind:?} after the SYN left"
            );
            assert!(
                matches!(
                    Handshake::unsent(io::Error::from(kind)),
                    Handshake::NotSent(_)
                ),
                "{kind:?} before anything left"
            );
            assert_eq!(
                Refusal::of(&io::Error::from(kind)),
                Refusal::NoRoute,
                "{kind:?} before anything left is filed against the address"
            );
        }
        let refused = || io::Error::from(ErrorKind::ConnectionRefused);
        assert!(matches!(
            Handshake::sent(Err(refused())),
            Handshake::Refused
        ));
        assert!(matches!(Handshake::unsent(refused()), Handshake::Refused));
        assert!(matches!(
            Handshake::sent(Err(io::Error::from(ErrorKind::TimedOut))),
            Handshake::Silent
        ));
        assert!(matches!(
            Handshake::unsent(io::Error::from(ErrorKind::AddrNotAvailable)),
            Handshake::NotSent(_)
        ));
    }

    /// A port this machine refused to send to is left unasked, and the report
    /// says why, in the operating system's words.
    ///
    /// Without the line, a scan whose every connect failed locally reads as
    /// one that asked and heard nothing: the ports are unasked, but nothing
    /// says the cause was here. The refusal is made by pinning connections to
    /// a source no interface holds, so the bind fails before anything is sent
    /// and the documentation address is never dialled.
    #[tokio::test]
    async fn a_port_this_machine_refused_to_send_is_unasked_and_the_report_says_why() {
        let target = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 7));
        let (session, ctx) = crate::scanner::session::ScanSession::builder()
            .send_source(vec![IpAddr::V4(Ipv4Addr::new(192, 0, 2, 250))])
            .build();
        let (tx, rx) = mpsc::channel(2);
        tx.send(tcp_target(target, 443)).await.expect("queued");
        drop(tx);

        scan(
            rx,
            1,
            ctx.clone(),
            ServiceDetection::Off,
            &EvasionProfile::default(),
            &ZoneMap::new(),
        )
        .await
        .expect("the scan runs");

        let state = session.hosts().read(target, |host| {
            host.ports().map(Port::state).collect::<Vec<_>>()
        });
        assert_eq!(state, Some(vec![PortState::Unasked]));
        let failures = ctx.failures_snapshot();
        assert!(
            failures.iter().any(|failure| failure
                .reason()
                .starts_with("1 port left unasked: this machine refused")),
            "the report says the refusal was this machine's, and has {failures:?}"
        );
        let stats = &ctx.probe_stats_snapshot()[0];
        assert_eq!(
            (stats.sends_attempted(), stats.sends_failed()),
            (1, 1),
            "a send this machine refused is a send that failed"
        );
    }

    /// TCP targets belong to the connect scanner next door; this prober must
    /// leave them alone rather than misreport them over the wrong protocol.
    #[tokio::test]
    async fn tcp_targets_are_skipped() {
        let target = PlannedTarget::new(
            0,
            Target {
                ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
                port: 80,
                protocol: Protocol::Tcp,
            },
        );
        assert!(
            udp_port_prober(
                target,
                Shaping::default(),
                Egress::KERNEL,
                SocketAddr::new(target.ip(), target.port()),
                ScanHandle::new(),
            )
            .await
            .is_none()
        );
    }

    /// The two fields a connect can carry cross over from the profile, and a
    /// default profile stays inert so the scanner takes its plain path.
    ///
    /// The guard is the mapping itself: a version that dropped either field, or
    /// reported an inert profile as active, would send the wrong packet while
    /// every higher-level test still passed.
    #[test]
    fn the_profile_maps_onto_what_a_connect_can_carry() {
        let profile = EvasionProfile {
            source_port: Some(53),
            ttl: Some(12),
            ..Default::default()
        };
        let shaping = Shaping::from(&profile);

        assert_eq!(shaping.source_port, Some(53));
        assert_eq!(shaping.hop_limit, Some(12));
        assert!(shaping.is_active());
        assert!(!Shaping::from(&EvasionProfile::default()).is_active());
    }

    #[cfg(unix)]
    use crate::system::descriptors::testing::{
        exhaust as exhaust_descriptors, in_a_process_of_its_own,
    };

    /// A sweep that cannot have a socket waits for one, and finds the host
    /// the moment the table has room, rather than passing the address over
    /// as if it had been asked.
    ///
    /// The address is this machine's own, which answers every connect on
    /// every platform, and the only thing standing between the sweep and that
    /// answer is a full descriptor table that empties a moment after the
    /// sweep starts.
    #[cfg(unix)]
    #[test]
    fn a_sweep_short_of_descriptors_waits_for_one_rather_than_passing_the_address_over() {
        if !in_a_process_of_its_own(
            module_path!(),
            "a_sweep_short_of_descriptors_waits_for_one_rather_than_passing_the_address_over",
        ) {
            return;
        }
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime, built while descriptors remain");
        let held = exhaust_descriptors(64);
        let local = IpAddr::V4(Ipv4Addr::LOCALHOST);

        runtime.block_on(async {
            let (session, ctx) = crate::scanner::session::ScanSession::new();
            tokio::spawn(async move {
                tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                drop(held);
            });
            discover(IpSet::from(local), ctx.clone(), &EvasionProfile::default())
                .await
                .expect("the sweep runs");

            assert!(
                session.hosts().contains(local),
                "this machine answers every connect, so a sweep that missed it \
                 passed the address over for want of a socket"
            );
            let stats = &ctx.probe_stats_snapshot()[0];
            assert_eq!(
                (stats.sends_attempted(), stats.sends_failed()),
                (1, 0),
                "one address, asked once it had a socket"
            );
        });
    }

    /// A sweep that never gets a socket says so: the address is left
    /// unsettled for a resume to ask, the send is counted as failed rather
    /// than made, and the report names the file limit as the reason, so a
    /// sweep that found nothing cannot be read as a network that answered
    /// nothing.
    #[cfg(unix)]
    #[test]
    fn a_sweep_that_never_gets_a_socket_reports_it_rather_than_an_empty_network() {
        if !in_a_process_of_its_own(
            module_path!(),
            "a_sweep_that_never_gets_a_socket_reports_it_rather_than_an_empty_network",
        ) {
            return;
        }
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("a runtime, built while descriptors remain");
        let _held = exhaust_descriptors(64);
        let local = IpAddr::V4(Ipv4Addr::LOCALHOST);

        runtime.block_on(async {
            let (session, ctx) = crate::scanner::session::ScanSession::new();
            let patience = std::time::Duration::from_millis(200);
            sweep(
                IpSet::from(local),
                ctx.clone(),
                &EvasionProfile::default(),
                SynPorts::common(),
                patience,
            )
            .await
            .expect("the sweep runs");

            assert!(!session.hosts().contains(local), "no socket, no answer");
            assert_eq!(
                ctx.settlements().settled_count(),
                0,
                "an address never asked is not settled"
            );
            let stats = &ctx.probe_stats_snapshot()[0];
            assert_eq!(
                (stats.sends_attempted(), stats.sends_failed()),
                (1, 1),
                "the send was attempted and the process refused it"
            );
            let failures = ctx.failures_snapshot();
            assert!(
                failures
                    .iter()
                    .any(|failure| failure.reason().contains("file descriptor limit of 64")),
                "the report names the limit the sweep ran into, and has {failures:?}"
            );
        });
    }
}