zond-engine 0.15.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
// 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

//! # What every raw port scan does the same way
//!
//! A raw port scan is the same machine whatever protocol it speaks: send probes
//! from one source port as fast as pacing allows, correlate what comes back,
//! resend what goes unanswered until its budget runs out, and stop when one of
//! four things becomes true. Only the packets and what they prove differ.
//!
//! Two pieces make up that machine, and the division between them is the point
//! of the module. [`RawProbeScan`] is the state a raw port scan carries and the
//! questions it can answer about itself. [`drive`] is the loop that asks them,
//! and [`RawPortScan`] is the short list of things it cannot work out alone.
//!
//! [`tcp`], [`udp`] and [`sctp`] each hold a [`RawProbeScan`] and implement
//! [`RawPortScan`]. What stays with them is what is genuinely protocol
//! knowledge: how a probe is built, how a reply is recognised, what an answer
//! proves about a port and its host, and what silence means once a probe has
//! spent its budget. [`idle`] is the fourth and is not built this way, because
//! it reads its verdicts off a third party's counter rather than off a reply to
//! anything it sent.
//!
//! ## Why this line and not a different one
//!
//! The split is drawn where the two scanners were *identical*, not merely
//! similar. Their stop conditions, their pacing arithmetic, their unreachable
//! handling, their audit tails and the loop that drives all of it were
//! duplicated with no difference but a label, while their probe construction
//! and their evidence mapping differed in almost every line, because a RST and
//! an ICMP port unreachable prove genuinely different things. Sharing the first
//! and not the second is what keeps this an abstraction rather than a
//! coincidence.
//!
//! Where the two copies of the loop did differ, they differed in four
//! expressions: which protocol to accept, what silence means, and two labels.
//! [`RawPortScan`] is those four, written down.
//!
//! ## Why the shared half is the half worth sharing
//!
//! The four stop conditions are the subtlest code in either scanner and the
//! least visible when wrong. Each one is a claim about what silence means, and
//! stopping on the wrong one does not fail: it returns a smaller answer that
//! looks exactly like a quiet network. This engine has already paid for that
//! once: a stop condition was fixed in one discovery scanner and left standing
//! in its twin, because nothing tied the two together. One
//! copy is what makes that class of divergence impossible rather than merely
//! unlikely.
//!
//! ## Writing a fourth one
//!
//! Everything here is public because the argument above applies to a scanner
//! this engine does not have yet. The SCTP INIT scan was written this way after
//! the fact and needed no changes here, which is the evidence the line is in the
//! right place; any protocol added later needs the same stop conditions, the
//! same congestion window and the same audit tail. Implementing [`RawPortScan`]
//! gets all of it, and the only code to write is the part that is actually
//! about the protocol.

// Public rather than private-with-re-exports. A caller writing a fifth scanner
// has to be able to read the four that exist, and a module they cannot name is
// a file they have to already know about. Which is what the shared machinery
// here used to be, under a name that described where the target sat.
pub mod idle;
pub mod sctp;
pub mod tcp;
pub mod udp;

// And re-exported flat, because four scanners for one phase is exactly the case
// where a caller wants them in one list.
pub use idle::IdlePortScanner;
pub use sctp::{SctpPortScanner, SctpToken};
pub use tcp::{TcpPortScanner, TcpToken};
pub use udp::UdpPortScanner;

use std::net::IpAddr;
use std::num::NonZeroU32;
use std::time::{Duration, Instant};

use tokio::sync::mpsc;

use crate::config::ProbeTuning;
use crate::evasion::SegmentShaping;
use crate::journal::settle::Outcome;
use crate::model::host::{HostStatus, StatusProtocol, StatusReason};
use crate::model::port::{PortState, Protocol};
use crate::model::target::PlannedTarget;
use crate::report::ScannerKind;
use crate::report::StopReason;
use crate::scanner::audit::ProbeAudit;
use crate::scanner::pacing::congestion::{CongestionWindow, WindowLimits};
use crate::scanner::pacing::deadline::{AdaptiveDeadline, AdaptiveDeadlineConfig};
use crate::scanner::pacing::retry::{Due, ProbeLedger, Resolution, RetryPolicy, SilentHostPolicy};
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::PortScanner;
use crate::system::interface::SourceResolver;
use crate::transport::capture::CapturedSegment;
use crate::transport::probe::{Emission, ProbeTransport};

// ---------------------------------------------------------------------------
// What a raw port scan is paced and timed by
// ---------------------------------------------------------------------------
//
// Declared here rather than beside the sweep they were written next to. These
// are what a *port scan* is held to, and the four scanners below are their only
// readers; the profiles a routed probe shares whatever it is asking about are
// in `raw`.

/// How a **port scan's** probes are retransmitted.
///
/// [`RETRY_POLICY`] with a steeper backoff and a wider spread, and the reason is
/// specific to what a port scan's retries are recovering from. A sweep's probes
/// are lost to whatever the path is doing, which is not correlated with the
/// sweep; a port scan's are lost to the burst the port scan itself is making at
/// one stack, and a retry sent while that burst is still going is a second
/// packet into the same congested moment.
///
/// Measured, against a Raspberry Pi: a quarter of a thousand probes went
/// unanswered, and with three independent attempts at that loss rate an open
/// port should be missed one time in seventy: eleven open ports should have
/// come back as nearly eleven. Three runs found seven each. The attempts were
/// not independent; all three of them fitted inside the congestion that lost the
/// first.
///
/// So the schedule is stretched at the back and left alone at the front. The
/// first timeout stays as early as measurement allows, because it is what tells
/// [`TCP_PORT_WINDOW`] the target is struggling; the last lands far enough out
/// to sample a network state the scan has had time to stop causing. The jitter
/// is widened for the same reason one step down: probes admitted together time
/// out together, and an unspread retry wave rebuilds the burst it is escaping.
const PORT_RETRY_POLICY: RetryPolicy = RetryPolicy::new(
    3,
    Duration::from_millis(200),
    Duration::from_millis(25),
    Duration::from_secs(2),
    3.0,
    0.3,
    Some(SilentHostPolicy::new(32, 2)),
);

/// The window a **TCP** port scan paces itself by.
///
/// This is the answer to a question no fixed rate answers well. A port scan
/// aims every probe at one stack, and it is that stack's willingness to answer
/// that bounds the result: a number that differs by two orders of magnitude
/// between the consumer router and the Linux server on the same switch, and
/// that neither this crate nor its caller can know in advance. So the scan
/// discovers it: see [`congestion`](crate::scanner::pacing::congestion) for how,
/// and for why the signal it grows and cuts on is a probe answered *on a retry*
/// rather than a probe not answered at all.
///
/// Each of the four numbers, and what would go wrong at another value:
///
/// - **Start at 32.** Every stack in service answers a few dozen simultaneous
///   SYNs without noticing. Starting at one would spend a round trip per
///   doubling, and on a local segment the ramp would be most of the scan.
/// - **Never below 16.** The floor is what a target that is genuinely being
///   outrun gets cut back to, and it has to leave the scan able to finish: at
///   sixteen questions per round-trip budget a thousand silent ports still
///   settle in a few seconds, where single digits would take a minute. Past
///   that a scan is not being polite, it is failing, and an unfinished scan's
///   verdicts are indeterminate rather than late.
/// - **Never above 1024.** A thousand questions outstanding at one stack is
///   already more than any of them will answer; growth past it buys nothing and
///   the rate ceiling would bind first anyway.
/// - **Stop doubling at 64.** This is the number the controller is blind for.
///   Nothing can be known about a target until a probe to it has been answered
///   or has timed out, and slow start doubles every round trip in the meantime,
///   so the threshold is the worst overshoot a target can be subjected to before
///   the scan has any evidence about it at all. It was 256, and against a
///   Raspberry Pi that meant several hundred probes already in the air by the
///   time the first timeout arrived. Sixty-four outstanding still empties a
///   thousand ports in a fraction of a second on any local segment, and linear
///   growth carries it further wherever the evidence supports it.
const TCP_PORT_WINDOW: WindowLimits = WindowLimits::new(32, 16, 1_024, 64);

/// The most probes a TCP port scan leaves unresolved at once.
///
/// Not the pacing, [`TCP_PORT_WINDOW`] is, but the bound on how far the
/// bookkeeping may run ahead of it. A probe leaves the window at its first
/// timeout and stays on the ledger until its last, so against a range that
/// answers nothing the scan admits at window speed while the backlog of
/// half-finished probes grows behind it. Several times the window's ceiling,
/// because that backlog is the retry schedule's whole length divided by the
/// first timeout and is expected to be a multiple of what is in flight; far
/// below where the memory matters, because each entry is two durations and a
/// handful of tokens.
const TCP_PORT_UNRESOLVED: usize = 8_192;

/// The fastest a TCP port scan will go regardless of what the window says.
///
/// A **backstop**, not the pacing: [`TCP_PORT_WINDOW`] is the pacing. It is
/// here so that a defect in the controller cannot turn a scan into a flood, and
/// it is set far above any rate a correct scan reaches: at this rate a
/// thousand-port scan emits in fifty milliseconds, which is already faster than
/// the round trips it is waiting on. A caller who wants a real rate limit sets
/// `--max-probe-rate`, which replaces this.
const TCP_PORT_RATE_CEILING: NonZeroU32 = NonZeroU32::new(20_000).expect("a non-zero rate");

/// The fastest a **UDP** port scan puts probes on the wire, in probes per
/// second.
///
/// Two orders of magnitude below [`TCP_PORT_RATE_CEILING`], and it is a real
/// limit rather than a backstop, because UDP has no window to pace it with. A
/// UDP probe's ordinary outcome is silence and its replies name no attempt, so
/// neither half of the congestion signal exists (see
/// [`congestion`](crate::scanner::pacing::congestion)) and the scan is held to a
/// fixed rate instead.
///
/// The rate is set against the thing that actually answers a UDP probe. Most
/// UDP verdicts come from an ICMP port unreachable, and a Linux host emits those
/// under a token bucket that refills at roughly one per second; a burst that
/// outruns it does not merely go unanswered, it manufactures
/// [`OpenFiltered`](crate::model::port::PortState::OpenFiltered) verdicts on
/// ports that are closed. Spread across the hosts of a shuffled scan this is
/// survivable; aimed at one host it is the whole result.
///
/// This number is inherited reasoning, not a measurement. The sweep's rate
/// was measured; this is set an order of magnitude below it because the
/// per-target load is an order of magnitude higher, and that is an argument
/// rather than an experiment.
const UDP_PORT_RATE_PER_SEC: NonZeroU32 = NonZeroU32::new(400).expect("a non-zero rate");

/// A probe's identity within a scan: which address, which port.
pub type ProbeTarget = (IpAddr, u16);

/// The state a raw port scan carries, and everything it does that does not
/// depend on which protocol it speaks.
///
/// Generic over the correlation token `T`, the one piece of per-probe state
/// whose type differs: a TCP probe carries a nonce that its answer must echo
/// back, and a UDP probe has nothing to echo, so it correlates on the target
/// alone and its token is `()`.
pub struct RawProbeScan<T> {
    /// Resolves the source address to send each target's probe from, consulting
    /// on-link subnets and the kernel routing table. Each answer is cached, so
    /// the many ports probed on one host cost a single lookup.
    pub resolver: SourceResolver,
    /// Shared state (host store, event channel, abort signal) for the scan this
    /// prober is part of.
    pub ctx: ScanContext,
    /// Sends probes and receives replies.
    pub transport: ProbeTransport,
    /// Governs how long this scan keeps running, adapting to observed
    /// round-trip times.
    pub deadline: AdaptiveDeadline,
    /// Probes sent but not yet resolved, together with when each is next due to
    /// be resent or written off.
    /// Outstanding probes. The payload is each target's position in the
    /// plan, handed back when the probe retires so a resume can skip it.
    pub ledger: ProbeLedger<ProbeTarget, T, u64>,
    /// Scratch space for the probes coming due on one iteration, reused so a
    /// quiet tick allocates nothing.
    pub due: Vec<Due<ProbeTarget, u64>>,
    /// The source port every probe in this scan is sent from, and so the port
    /// its replies come back to. It is the scan's identity on the wire: the
    /// capture filter narrows to it, and anything addressed elsewhere answered
    /// somebody else.
    pub src_port: u16,
    /// The IP-header state every probe in this scan carries: its hop limit and
    /// any evasion override of the IP header. See
    /// [`Emission`].
    pub emission: Emission,
    /// The segment-level shaping every probe in this scan carries: the payload
    /// padding and, on the TCP paths, the bad-checksum choice. See
    /// [`SegmentShaping`].
    pub shaping: SegmentShaping,
    /// The decoy source addresses every probe in this scan is copied from, or
    /// empty. Resolved once from the scan's
    /// [`EvasionProfile`](crate::evasion::EvasionProfile).
    pub decoys: Vec<IpAddr>,
    /// Why the first probe that could not be sent failed, if any did.
    ///
    /// The *first*, and the send path keeps it that way by only recording when
    /// this is empty. It used to hold the last, which on a link that had stopped
    /// accepting sends meant the report named whichever of seven thousand
    /// identical failures happened to finish the run.
    ///
    /// Without this a scan whose probes never reached the wire reports every
    /// port with whatever its protocol reads silence as - the same answer a
    /// firewall produces - and says nothing about the difference. That verdict
    /// is a claim about the network; a probe that was never sent is a claim
    /// about this host.
    pub send_failure: Option<String>,
    /// Ports settled unasked because no probe for them was ever seen leaving.
    /// The report is driven off this, not the send tally, so a run that lost
    /// sends but still resolved every port stays quiet.
    pub unasked_unsent: u64,
    /// Per-run counters, so a scan that classified fewer ports than it asked
    /// about can be attributed to loss, to its own deadline, or to correlation
    /// rather than guessed at. Reported once when the loop exits.
    pub audit: ProbeAudit,
    /// How many questions this scan may have awaiting an answer, grown and cut
    /// from what the targets are managing to answer.
    ///
    /// This is what paces a raw port scan, and it is the answer to a
    /// question a fixed rate cannot answer. Measured, against a consumer router:
    /// asked as fast as the socket would take it, of a thousand ports it
    /// answered roughly four hundred and the rest were reported *filtered*:
    /// including one running a service. The host was not filtering anything. It
    /// was answering as fast as it could and being asked ten times faster.
    ///
    /// A rate chosen in advance is wrong in both directions at once: too fast
    /// for that router and far too slow for the Linux server on the same
    /// switch. A window is not chosen in advance. Probes leave as earlier ones
    /// are settled, so the send rate settles at the rate the target is actually
    /// resolving them. See [`congestion`](crate::scanner::pacing::congestion)
    /// for what occupies it, how it grows, what makes it cut, and why UDP is
    /// given one that does not move.
    pub window: CongestionWindow,
    /// How long to wait between releases, and the most probes one release may
    /// contain.
    ///
    /// The **backstop**, not the pacing. It exists so that a defect in
    /// [`window`](Self::window) cannot turn a scan into a flood, and so that a
    /// caller who asks for a specific rate gets one. On a healthy scan the
    /// window binds far below it and this never engages; `pacing_for` in the
    /// parent module has how the pair is derived from a rate.
    pub send_tick: Duration,
    /// The most probes one tick releases. See [`send_tick`](Self::send_tick).
    pub batch: usize,
    /// The most probes this scan leaves unresolved at once.
    ///
    /// A bound on memory and correlation state, not on pace. see
    /// [`admitting`](Self::admitting) for why the two are separate. A probe
    /// leaves the [`window`](Self::window) at its first timeout and stays on the
    /// ledger until its last, so against a range that answers nothing the
    /// backlog between those two points is what grows, and this is what bounds
    /// it.
    pub max_unresolved: usize,
    /// Probes waiting for the gap the scan keeps between two probes at one
    /// host, earliest first. Empty unless
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval)
    /// was set.
    ///
    /// Bounded by [`max_unresolved`](Self::max_unresolved) rather than by a
    /// number of its own. The two bound different things and both are memory a
    /// scan of a wide range would otherwise grow without limit; inventing a
    /// second figure would mean two knobs to reason about where the honest
    /// answer to "how much may this scan hold" is one.
    ///
    /// A full queue stops the target stream being read, which is where the
    /// backpressure belongs: every target pulled while it is full could only be
    /// held, so leaving them in the channel lets the dispatcher feel it exactly
    /// as it feels the [`window`](Self::window). It deliberately does **not**
    /// stop the send path, which is the only thing that empties this.
    pub held: std::collections::BinaryHeap<HeldProbe>,
}

/// What a [`RawProbeScan`] is built from.
///
/// A plain struct rather than positional arguments. Both raw port scanners
/// build the same core and disagree about four values, and passing fourteen
/// arguments through two constructors apiece is how the two came to share a
/// hundred and fifty lines of identical setup.
pub(super) struct CoreParts<'a> {
    /// Resolves the source address each target's probe leaves from.
    pub resolver: SourceResolver,
    /// The scan this prober is part of.
    pub ctx: ScanContext,
    /// Where probes go and replies come from.
    pub transport: ProbeTransport,
    /// What the caller asked for, which is where the evasion settings and the
    /// source port come from.
    pub tuning: &'a ProbeTuning,
    /// The port every probe in this scan leaves from.
    pub src_port: u16,
    /// How many endpoints the scan will ask about.
    pub target_count: usize,
    /// The retry schedule, which the deadline is derived from.
    pub retry: RetryPolicy,
    /// The send rate. Non-zero because the pacing divides by it.
    pub rate: NonZeroU32,
    /// The budgets the scan runs against. The two scanners differ here: a UDP
    /// scan is inherently slower and needs a silence floor above the ICMP
    /// rate-limit interval before quiet means anything.
    pub deadline: AdaptiveDeadlineConfig,
    /// The slowest pace the scan may settle at, which its deadline must outlive.
    /// The two scanners derive this differently: a TCP scan paces on its
    /// congestion window, a UDP scan on the rate itself.
    pub pace: Duration,
    /// The in-flight window.
    pub window: WindowLimits,
    /// The most probes that may be outstanding at once.
    pub max_unresolved: usize,
}

impl<T: Copy + PartialEq> RawProbeScan<T> {
    /// The core both raw port scanners run on.
    ///
    /// Seeds its timing from what the liveness phase already learned about these
    /// hosts, so the first wave of probes is timed against a measurement rather
    /// than a guess.
    pub(super) fn new(parts: CoreParts<'_>) -> Self {
        let CoreParts {
            resolver,
            ctx,
            transport,
            tuning,
            src_port,
            target_count,
            retry,
            rate,
            deadline,
            pace,
            window,
            max_unresolved,
        } = parts;

        let (send_tick, batch) = super::raw::pacing_for(rate);
        let deadline = deadline
            .allowing_for(retry.worst_case_probe_lifetime())
            .allowing_pace_of(pace, target_count);

        let mut core = Self {
            resolver,
            ctx,
            transport,
            deadline: AdaptiveDeadline::new(deadline, target_count),
            ledger: ProbeLedger::new(retry, target_count.min(max_unresolved)),
            due: Vec::new(),
            src_port,
            emission: tuning.evasion.emission(),
            shaping: tuning.evasion.segment_shaping(),
            decoys: tuning.evasion.decoys.clone(),
            send_failure: None,
            unasked_unsent: 0,
            audit: ProbeAudit::new(),
            window: CongestionWindow::new(window),
            send_tick,
            batch,
            max_unresolved,
            held: std::collections::BinaryHeap::new(),
        };
        core.seed_timing();
        core
    }

    /// Whether the loop should keep going, and if not, why it stopped.
    ///
    /// The four conditions in the order that makes each one's answer mean
    /// something. `sending_finished` says the target stream has run dry, which
    /// two of them depend on: an empty ledger means "everything has been
    /// answered or written off" only once there is nothing left to ask.
    ///
    /// - **Stopped.** The caller asked the scan to stop, or the wall-clock
    ///   budget it was given ran out. Checked first, so a scan winds down
    ///   promptly rather than after whatever else it was in the middle of;
    ///   [`ScanHandle::stopped`](crate::scanner::handle::ScanHandle::stopped) says
    ///   which of the two it was.
    /// - **Hard deadline.** The ceiling on the whole run, which nothing extends.
    /// - **Attempts spent.** Every probe asked as many times as its budget
    ///   allows, none is still outstanding, and none is waiting for the gap the
    ///   scan keeps between two probes at one host. Waiting longer cannot change
    ///   what this found. A held probe is counted here because it has not been
    ///   sent: stopping on an empty ledger while one waited would report a port
    ///   this scan chose to delay as one it had asked about and heard nothing
    ///   from.
    ///
    /// Silence is not one of them. It reads as a fourth
    /// condition and it cannot be one: with targets still queued, an empty
    /// ledger does not mean the scan has heard nothing, it means the scan has
    /// not *asked* yet, and the way that happens is the send path failing. A
    /// loop that gave up there would abandon everything still queued at the
    /// moment its own machine started refusing sends, and report the remainder
    /// as ports nobody could reach. Measured: a wireless host whose ARP entry
    /// went unresolved mid-scan returned `No route to host` for seven thousand
    /// probes, and the scan concluded after thirty seconds with thirty-one
    /// thousand targets never asked about.
    ///
    /// What still bounds the run is the hard deadline, which nothing extends.
    pub fn stop_reason(&self, sending_finished: bool) -> Option<StopReason> {
        if let Some(cause) = self.ctx.handle.stopped() {
            return Some(cause.into());
        }
        if self.deadline.hard_deadline_passed() {
            return Some(StopReason::DeadlineExpired);
        }
        if sending_finished && self.ledger.is_empty() && self.held.is_empty() {
            return Some(StopReason::AttemptsSpent);
        }
        None
    }

    /// Whether another target may be admitted from the stream.
    ///
    /// Three conditions, and they answer different questions. There may be
    /// nothing left to send: the stream is done and no probe is waiting for its
    /// host's next slot. The [`window`](Self::window) may be full, which is the
    /// pacing: too many questions are already awaiting an answer, and asking
    /// another would cost verdicts against a target that is being outrun. Or the
    /// ledger may be at [`max_unresolved`](Self::max_unresolved), which is not
    /// pacing at all but a bound on memory: a probe stays on the ledger long
    /// after it has stopped occupying the window, waiting out a retry schedule,
    /// and against a wide scan of a silent range that backlog is what grows
    /// without limit.
    ///
    /// The [`held`](Self::held) queue counts as something to send, so a stream
    /// that ran dry does not close the send path while probes are still waiting
    /// for the gap the scan keeps. How many may wait is
    /// [`held_is_full`](Self::held_is_full), which bounds the *stream* and
    /// deliberately not this.
    pub fn admitting(&self, sending_finished: bool) -> bool {
        let anything_to_send = !sending_finished || !self.held.is_empty();
        anything_to_send && self.window.has_room() && self.ledger.len() < self.max_unresolved
    }

    /// Whether the queue of held probes is full.
    ///
    /// What stops the target stream being read once the gap in
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval)
    /// is what limits the scan. Every target pulled while this is true could
    /// only be held, so leaving them in the channel is what lets the dispatcher
    /// feel it.
    ///
    /// Not part of [`admitting`](Self::admitting), and that is not an oversight.
    /// The send path is the only thing that empties this queue, so a full queue
    /// closing the send path would be a scan that stopped and never restarted.
    pub fn held_is_full(&self) -> bool {
        self.held.len() >= self.max_unresolved
    }

    /// Holds `probe` back until its host may be asked again.
    ///
    /// The caller has already established that the host is not ready. Callers
    /// that cannot hold a probe must not ask, since a probe dropped on that
    /// answer is a port reported as silent that nobody sent anything to; see
    /// [`ScanContext::host_ready_at`](crate::scanner::session::ScanContext::host_ready_at).
    fn hold(&mut self, ip: IpAddr, port: u16, position: Option<u64>, ready: Instant) {
        self.held.push(HeldProbe {
            ip,
            port,
            position,
            ready,
        });
    }

    /// The next held probe whose host may be asked now.
    ///
    /// The recorded instant is a hint and is re-checked here rather than
    /// trusted: a retry aimed at the same host moves its slot after an entry is
    /// queued, so an entry can reach the front before its host is actually
    /// ready. One that is still early is pushed back under the fresh instant.
    ///
    /// That cannot loop. A re-checked entry is pushed back with an instant
    /// strictly later than `now`, because that is the only kind
    /// [`host_ready_at`](crate::scanner::session::ScanContext::host_ready_at)
    /// returns, so it cannot be drawn again on this call: every iteration either
    /// yields a probe or takes one entry out of the queue's due prefix.
    fn take_ready(&mut self, now: Instant) -> Option<HeldProbe> {
        while let Some(next) = self.held.peek() {
            if next.ready > now {
                return None;
            }
            let mut entry = self.held.pop().expect("peeked");
            match self.ctx.host_ready_at(entry.ip, now) {
                None => return Some(entry),
                Some(ready) => {
                    entry.ready = ready;
                    self.held.push(entry);
                }
            }
        }
        None
    }

    /// Records one probe leaving the wire, or failing to.
    ///
    /// All three parts of the bookkeeping in one call because they are one event
    /// and were drifting apart: the audit counts every attempt so a scan that
    /// could not send can say so, the window counts only the ones that reached
    /// the wire, since a probe nobody sent occupied nothing and must not be part
    /// of the evidence that the path is busy, and `host`'s slot under
    /// [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval)
    /// moves on the same terms as the window, for the same reason.
    ///
    /// `first_attempt` decides whether the send takes a window slot. A retry
    /// does not: the slot went back when the question it repeats ran out of
    /// round-trip budget, and handing it back a second time would let the window
    /// admit more than it believes it has. The host's slot draws no such
    /// distinction: a retry is a packet at the target like any other, and the
    /// gap is about what the target receives rather than about what this scan is
    /// still waiting for.
    pub fn record_send(&mut self, host: IpAddr, sent: bool, first_attempt: bool) {
        self.audit.record_send(sent);
        if sent {
            self.ctx.host_probed(host, Instant::now());
        }
        match (sent, first_attempt) {
            // A send the kernel refused is the one signal this controller gets
            // from *its own machine* rather than from the network, and it is the
            // least ambiguous one there is. Whatever the reason, a full
            // interface queue, an unresolved neighbour, a link that has stopped
            // keeping up, offering it more of the same faster cannot help. So
            // it is read as congestion, and the damping bounds how far a
            // permanent failure can cut.
            (false, _) => self.window.record_congestion(),
            (true, true) => self.window.record_send(),
            (true, false) => self.window.record_resend(),
        }
    }

    /// Reads one probe's first timeout: frees the window slot it was holding,
    /// and decides what the silence meant.
    ///
    /// The whole of the decision is whether `host` has ever answered anything.
    /// See [`service_retries`](RawPortScan::service_retries) for the argument
    /// and [`congestion`](crate::scanner::pacing::congestion) for what it cost
    /// to get wrong.
    pub fn judge_timeout(&mut self, host: IpAddr) {
        self.window.release();
        if self.ledger.host_has_answered(&host) {
            self.window.record_congestion();
        } else {
            self.window.record_progress();
        }
    }

    /// Folds one answered probe into everything this scan tracks about itself:
    /// the deadline, the window and the audit.
    ///
    /// One place rather than one per protocol, because the three used to be
    /// three statements repeated in each scanner and the window is a fourth that
    /// would have been added to one of them.
    ///
    /// The window reads the *attempt* that was answered, not merely that
    /// something was. A reply to the first attempt says the target is keeping
    /// up; a reply to a later one says the target was willing all along and the
    /// first question did not survive, which is the only evidence a port scanner
    /// has that distinguishes being too fast from meeting a firewall. See
    /// [`congestion`](crate::scanner::pacing::congestion).
    pub fn record_answer<P: Copy>(&mut self, resolution: &Resolution<P>) {
        self.deadline.mark_activity();
        if let Some(rtt) = resolution.rtt {
            self.deadline.record_rtt(rtt);
        }

        // Three cases, and the middle one is the reason this reads the attempt
        // rather than the fact of an answer.
        match (resolution.attempts, resolution.answered_attempt) {
            // Asked once and answered: the slot is still held, and the target is
            // keeping up.
            (1, _) => {
                self.window.release();
                self.window.record_progress();
            }
            // Answered only because it was asked again: the target was willing
            // all along and the first ask did not survive. The slot went back at
            // that timeout, so this cuts and frees nothing.
            (_, Some(attempt)) if attempt > 1 => self.window.record_congestion(),
            // Answered late: the first ask was answered after its budget had
            // already expired, which the per-attempt token is what lets us see.
            // The timeout already released the slot and already judged it, and
            // doing either again would double-count.
            _ => {}
        }

        self.audit.record_host_found(resolution.answered_attempt);
    }

    /// How long the loop may sleep: until the scan's own next checkpoint, or
    /// until the next probe needs resending or retiring, whichever comes first.
    pub fn tick_delay(&self, now: Instant) -> Duration {
        let until_deadline_tick = self.deadline.time_until_next_tick();
        match self.ledger.next_due() {
            Some(due) => until_deadline_tick.min(due.saturating_duration_since(now)),
            None => until_deadline_tick,
        }
    }

    /// Seeds each host's retry timing from what an earlier phase already
    /// measured about it.
    ///
    /// A port scan almost never meets its targets cold: [`scan`](crate::scan)
    /// establishes that an address is there before spending a probe on each of
    /// its ports, and that liveness pass timed every host that answered. Without
    /// this the port scanner starts from first principles anyway, and the cost
    /// falls entirely on the ports that turn out to be filtered: each one waits
    /// the unmeasured starting timeout three times before silence is allowed to
    /// mean anything.
    ///
    /// Called once at construction rather than per probe. The store is finished
    /// being written by the time a port scanner is built, and a lookup per
    /// target would repeat the same answer for every port of a host.
    ///
    /// The median rather than the minimum, because a retry schedule sized from
    /// the fastest sample a host ever produced repeats every probe that is
    /// merely typical.
    pub fn seed_timing(&mut self) {
        for host in self.ctx.store.iter() {
            if let Some(rtt) = host.value().median_rtt() {
                self.ledger.seed_host_rtt(host.key().addr(), rtt);
            }
        }
    }

    /// Records that `sender` said the target cannot be reached.
    ///
    /// A host verdict rather than a port one: an unreachable names the
    /// destination it refers to, and nothing about any particular port on it.
    pub fn record_host_down(&mut self, ip: IpAddr, sender: IpAddr) {
        self.ctx.update_host(ip, |host| {
            host.record_evidence(
                HostStatus::Down,
                StatusReason::new(StatusProtocol::IcmpUnreachable, "destination unreachable")
                    .from_source(sender),
            );
        });
    }

    /// Closes out a run: reports probes that never reached the wire, then files
    /// the audit.
    ///
    /// `silence_verdict` is what this scan's protocol reads an unanswered probe
    /// as, named in the failure message so the two cases are distinguishable to
    /// whoever reads it. A scan that could not send is not a scan that found
    /// everything unanswered, and those are identical in every number a caller
    /// otherwise sees.
    ///
    /// Capture counters are read here, while the transport is still alive: they
    /// live with the capture threads it keeps running.
    pub fn finish(
        &mut self,
        kind: ScannerKind,
        audit_tag: &str,
        silence_verdict: &str,
        probes: u128,
        reason: StopReason,
    ) {
        if self.audit.sends_failed > 0 {
            self.ctx.record_failure(
                kind,
                format!(
                    "{} probes could not be sent, so their ports are recorded \
                     unasked rather than {silence_verdict}: {}",
                    self.audit.sends_failed,
                    self.send_failure.as_deref().unwrap_or("cause unrecorded"),
                ),
            );
        }

        if self.unasked_unsent > 0 {
            self.ctx.record_failure(
                kind,
                format!(
                    "{} recorded unasked rather than {silence_verdict}: this machine accepted                      their probes and never put them on the wire",
                    crate::logging::counted(u128::from(self.unasked_unsent), "port", "ports"),
                ),
            );
        }

        let capture = self.transport.capture_counts();
        self.audit.report(
            audit_tag,
            probes,
            reason,
            capture,
            Some(self.window.summary()),
        );
        self.ctx.record_probe_stats(self.audit.stats(
            kind,
            probes,
            reason,
            capture,
            Some(self.window.summary()),
        ));
    }
}

/// A probe held back because its host was asked too recently.
///
/// What [`ZondConfig::host_probe_interval`](crate::config::ZondConfig::host_probe_interval)
/// costs the port scanners and costs nothing else: this is the one pass that
/// aims thousands of probes at a single address, so it is the one that needs
/// somewhere to put a probe it may not send yet. A sweep asks each host once per
/// attempt and can move on to the next.
///
/// The two kinds a scan sends are told apart the way
/// [`RawPortScan::send`] already tells them apart, by whether
/// there is a plan position: a first attempt carries one and a retry keeps the
/// one the ledger holds. That is also what decides who accounts for the probe if
/// the scan ends while it is still held. See
/// [`resolve_held`](RawPortScan::resolve_held).
///
/// Public because it names an argument of a public trait method, with private
/// fields because nothing outside needs to read one: every scanner reaches the
/// wire through [`RawPortScan::send`], and the defaulted methods above it are
/// what turn a held probe back into that call. A position a caller could write
/// is a resume told a target was covered by a probe that never went out.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeldProbe {
    /// The address to probe.
    ip: IpAddr,
    /// The port to probe.
    port: u16,
    /// The plan position for a first attempt, and [`None`] for a retry.
    position: Option<u64>,
    /// When the host was thought to become ready, as it stood when this was
    /// held.
    ///
    /// A hint rather than a promise. A retry aimed at the same host is sent
    /// through the gap's own accounting and moves the slot, so an entry can
    /// reach the front of the queue before its host is actually ready. That is
    /// what [`RawProbeScan::take_ready`] re-checks rather than trusts.
    ready: Instant,
}

/// Ordered so that [`BinaryHeap`](std::collections::BinaryHeap), which is a
/// max-heap, yields the *earliest* ready instant first. The same inversion
/// [`ProbeLedger`]'s own timer queue uses, and for the same reason.
impl Ord for HeldProbe {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other
            .ready
            .cmp(&self.ready)
            .then_with(|| self.port.cmp(&other.port))
    }
}

impl PartialOrd for HeldProbe {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// What a raw port scan has to supply that [`drive`] cannot work out for itself.
///
/// Everything below is protocol knowledge: which transport this scan speaks,
/// how it builds a probe, how it reads a reply, what a verdict proves about the
/// host behind the port, and what silence means once a probe has spent its
/// budget. [`drive`] supplies the rest, which is the loop those answers are fed
/// into.
///
/// The division is the same one [`RawProbeScan`] draws and for the same reason:
/// a RST and an ICMP port unreachable prove genuinely different things, while
/// the machinery that decides when to stop asking does not know the difference
/// and should not have to.
pub trait RawPortScan: PortScanner {
    /// The per-probe correlation token. A TCP probe carries a nonce its answer
    /// must echo; a UDP probe has nothing to echo and uses `()`.
    type Token: Copy + PartialEq;

    /// The shared machinery this scan is built around.
    fn core(&self) -> &RawProbeScan<Self::Token>;

    /// The same, mutably.
    fn core_mut(&mut self) -> &mut RawProbeScan<Self::Token>;

    /// The transport this scan probes. Targets of any other protocol are not
    /// this scanner's to answer and are passed over.
    fn protocol(&self) -> Protocol;

    /// The verdict a probe takes once every attempt has gone unanswered.
    ///
    /// For UDP always [`PortState::OpenFiltered`], since an open port that did
    /// not recognise the payload is silent exactly as a firewall is. For TCP it
    /// depends on the technique: silence means a filter where any live stack
    /// would have answered, and open-or-filtered where an open port is required
    /// to ignore the probe.
    fn silence_means(&self) -> PortState;

    /// What the audit files this run under, and how its failure message names a
    /// port nobody answered for.
    ///
    /// The second half exists so a scan whose probes never reached the wire
    /// reads as what it is. Reporting "3000 ports unanswered" and "3000 ports
    /// open-filtered" describe the same silence, and only one of them is the
    /// word that scan's protocol would have used.
    fn audit_labels(&self) -> AuditLabels;

    /// Sends one probe at `(ip, port)` and arms the ledger for it.
    ///
    /// Called for the first attempt and every retry alike. A probe that cannot
    /// be sent is simply not armed: the ledger has already charged the attempt
    /// by the time a retry reaches here, so an unroutable target still runs out
    /// of attempts on schedule rather than waiting outstanding forever.
    /// Sends one probe. `position` is the target's place in the plan, kept by
    /// the ledger so it comes back when the probe retires.
    fn probe(&mut self, ip: IpAddr, port: u16, position: u64, now: Instant) {
        self.send(ip, port, Some(position), now);

        // The ledger is what says whether the probe left: `send` arms it only
        // once the segment is on the wire, and declines to send at all where the
        // target has no route. Nothing comes due for a probe that was never
        // armed and nothing drains it, so without this the target is the one
        // that vanishes from the host entirely. A retry is not this case, since
        // that probe is still on the ledger with attempts left.
        if !self.core().ledger.contains(&(ip, port)) {
            self.record_unasked_endpoint(ip, port);
        }
    }

    /// Resends a probe already outstanding. The ledger keeps its position.
    fn reprobe(&mut self, ip: IpAddr, port: u16, now: Instant) {
        self.send(ip, port, None, now);
    }

    /// Puts one probe on the wire.
    ///
    /// `position` is the target's place in the plan for a first attempt, and
    /// [`None`] for a retry, which keeps the position the ledger already holds.
    fn send(&mut self, ip: IpAddr, port: u16, position: Option<u64>, now: Instant);

    /// Reads one captured reply and resolves whatever probe it answers.
    fn handle_reply(&mut self, reply: &CapturedSegment, now: Instant);

    /// Files a port verdict and whatever the reply that produced it proves
    /// about the host.
    ///
    /// `sender` is the address the reply came from, or `None` when the verdict
    /// came from a spent attempt budget rather than from a packet.
    fn record_port(&mut self, ip: IpAddr, port: u16, state: PortState, sender: Option<IpAddr>);

    /// Records what became of one target, which is a different question from
    /// the verdict [`record_port`](Self::record_port) gave it.
    ///
    /// Every target reaches `record_port`, whether it was answered, asked and
    /// left quiet, or never asked at all, since an absent port is the shortfall
    /// a reader cannot see. Only the earned outcomes carry a position, and only
    /// a position lets a resume skip a target. See [`Outcome`].
    fn settle(&mut self, outcome: Outcome) {
        self.core().ctx.record_outcome(outcome);
    }

    /// Probes `target`, if it is one this scan speaks the protocol for.
    ///
    /// A target of another protocol is passed over rather than refused. The
    /// [`CompositePortScanner`](crate::scanner::strategy::composite::CompositePortScanner)
    /// routes by protocol and so should never send one, which is exactly why
    /// this holds: a router that started making mistakes would otherwise have
    /// this scanner probe a UDP port with a TCP segment.
    fn send_probe(&mut self, planned: PlannedTarget) {
        if planned.protocol() == self.protocol() {
            self.probe(
                planned.ip(),
                planned.port(),
                planned.position,
                Instant::now(),
            );
        }
    }

    /// Holds `planned` back until its host may be asked again.
    ///
    /// A target of another protocol is passed over on the same terms
    /// [`send_probe`](Self::send_probe) passes it over: it belongs to the other
    /// scanner, and queuing it here would hold a UDP port against a TCP scan's
    /// gap and then file it under that scan's account of itself.
    fn hold_probe(&mut self, planned: PlannedTarget, ready: Instant) {
        if planned.protocol() == self.protocol() {
            self.core_mut()
                .hold(planned.ip(), planned.port(), Some(planned.position), ready);
        }
    }

    /// Sends a probe that was held for its host's next slot.
    ///
    /// The two kinds part company here, on the same distinction the ledger draws
    /// between them: a first attempt carries a plan position and goes through
    /// [`probe`](Self::probe), which accounts for a target the send path
    /// refuses, and a retry has none and goes through
    /// [`reprobe`](Self::reprobe), which leaves the position the ledger is
    /// already holding alone.
    fn send_held(&mut self, held: HeldProbe, now: Instant) {
        match held.position {
            Some(position) => self.probe(held.ip, held.port, position, now),
            None => self.reprobe(held.ip, held.port, now),
        }
    }

    /// Accounts for every probe still held when the loop ended.
    ///
    /// A held first attempt was never armed, so nothing else will account for
    /// it: without this it is the port that vanishes from the host entirely,
    /// which is the one shortfall a reader cannot see. A held retry is still
    /// outstanding on the ledger and takes the scan's silence verdict with
    /// everything else there, so it is dropped rather than recorded twice.
    ///
    /// Nothing is counted. These targets were counted into the audit's
    /// denominator when they came off the stream, and counting them again would
    /// make a scan claim to have been handed more work than the plan holds.
    fn resolve_held(&mut self) {
        let held = std::mem::take(&mut self.core_mut().held);
        for entry in held {
            if entry.position.is_some() {
                self.record_unasked_endpoint(entry.ip, entry.port);
            }
        }
    }

    /// Resends everything due and writes off everything that has run out of
    /// attempts.
    ///
    /// Exhaustion is what makes a silent verdict mean something: nothing
    /// arrived across every attempt, rather than nothing arrived once.
    /// Retiring probes here rather than at the end of the scan also streams
    /// results to the caller while it is still running, and frees room under
    /// the [`window`](RawProbeScan::window) for the targets queued behind
    /// them.
    ///
    /// Running out of attempts is not treated as activity, so it
    /// never extends the scan's own deadline. Nothing answered.
    ///
    /// A probe's **first** timeout is also what releases its slot in the
    /// congestion window and what tells the window how the target is coping:
    /// whichever event carries that timeout, the retry that follows it or the
    /// exhaustion that follows it when the budget was one attempt.
    ///
    /// Which of the two signals it carries depends on the host and not on the
    /// probe. A host that has never answered anything is behind a firewall or is
    /// not there, and its silence says nothing about capacity; a host that is
    /// answering most of what it is asked and dropping the rest is being outrun,
    /// and that is the only warning a scan gets before it starts reporting a
    /// firewall that is not there. See
    /// [`congestion`](crate::scanner::pacing::congestion).
    fn service_retries(&mut self, now: Instant) {
        let core = self.core_mut();
        core.ledger.drain_due(now, &mut core.due);

        // Taken so the sends below can borrow `self` mutably; the buffer itself
        // is reused, so this costs no allocation.
        let due = std::mem::take(&mut self.core_mut().due);
        let silence = self.silence_means();
        for event in &due {
            match *event {
                Due::Retry {
                    key: (ip, port),
                    attempt,
                } => {
                    if attempt == 2 {
                        self.core_mut().judge_timeout(ip);
                    }
                    // A retry is a probe at a host like any other and is spaced
                    // like one. Held rather than skipped, because the ledger has
                    // already charged this attempt and scheduled the next: a
                    // skipped retry spends an attempt on a packet nobody sent,
                    // and a host spaced slower than its own retry schedule would
                    // spend all three that way and settle the port as silent
                    // having asked once.
                    match self.core().ctx.host_ready_at(ip, now) {
                        Some(ready) => self.core_mut().hold(ip, port, None, ready),
                        None => self.reprobe(ip, port, now),
                    }
                }
                Due::Exhausted {
                    key: (ip, port),
                    payload: position,
                    attempts,
                    witnessed,
                } => {
                    if attempts == 1 {
                        self.core_mut().judge_timeout(ip);
                    }
                    // No send ever seen leaving: unasked, not silent. Guarded on
                    // the run witnessing its egress at all, or every probe looks
                    // unsent.
                    if witnessed == 0 && self.core().audit.witnesses_its_sends() {
                        self.core_mut().unasked_unsent += 1;
                        self.record_unasked_endpoint(ip, port);
                        continue;
                    }
                    self.record_port(ip, port, silence, None);
                    // Earned: asked as many times as the policy allows.
                    self.settle(Outcome::Exhausted { position });
                }
            }
        }
        let core = self.core_mut();
        core.due = due;
        core.due.clear();
    }

    /// Gives every probe still outstanding the verdict this scan reads silence
    /// as.
    ///
    /// [`service_retries`](Self::service_retries) retires most probes as their
    /// budgets run out; what reaches here are the ones still mid-schedule when
    /// the scan itself ended.
    fn resolve_remaining(&mut self) {
        self.core_mut().window.release_all();
        let silence = self.silence_means();
        for (ip, port) in self.core_mut().ledger.drain_unresolved() {
            self.record_port(ip, port, silence, None);
            // Assigned, not earned: the schedule was cut off rather than spent.
            self.settle(Outcome::Interrupted);
        }
    }

    /// Records every target still queued when the scan stopped.
    ///
    /// A scan that hits its deadline with targets still queued used to leave
    /// them with no record whatsoever: not a filtered port, not an unknown one,
    /// simply absent from the host as though nobody had ever named it. That is
    /// the worst of the three ways a scan can fall short, because it is the only
    /// one a reader cannot see: a truncated port list and a complete one look
    /// identical, and the count in the summary agrees with itself.
    ///
    /// So they are written down and counted. They used to be written down under
    /// whatever the scan read silence as, argued for here as too kind but better
    /// than absence. Both halves of that were true, and the choice really was
    /// between those two. [`PortState::Unasked`] is the third option that did not
    /// exist then: the port stays on the host, which is what the argument was
    /// protecting, and it says what happened to it rather than borrowing the
    /// verdict of a port that was probed and stayed quiet.
    ///
    /// What is already queued, and no more. Waiting for the dispatcher to
    /// finish emitting would let a scan of a very large range spend longer
    /// filing verdicts than it spent scanning, and the deadline that stopped it
    /// is a guarantee of termination that this must not quietly undo. For every
    /// scan smaller than the dispatcher's buffer, which is every scan whose
    /// port list a person wrote, the queue is the whole remainder.
    fn resolve_unasked(&mut self, targets: &mut mpsc::Receiver<PlannedTarget>) -> u128 {
        let mut unasked = 0;
        while let Ok(target) = targets.try_recv() {
            unasked += 1;
            self.record_unasked(target);
        }
        unasked
    }

    /// Records one planned target no probe was sent to.
    ///
    /// A target of another protocol belongs to the other scanner and is passed
    /// over rather than recorded here, which would file a UDP port under a TCP
    /// scan's account of itself.
    fn record_unasked(&mut self, target: PlannedTarget) {
        if target.protocol() != self.protocol() {
            return;
        }
        self.record_unasked_endpoint(target.ip(), target.port());
    }

    /// The single account of an endpoint nobody asked about, shared by the three
    /// ways one arises: still queued when the loop ended, reached after its host
    /// had spent the budget in
    /// [`ZondConfig::host_timeout`](crate::config::ZondConfig::host_timeout),
    /// and refused by this machine's own sender before it reached the wire.
    ///
    /// All three were named and none was probed, so all three are written down
    /// the same way, and none leaves a port off the host.
    fn record_unasked_endpoint(&mut self, ip: IpAddr, port: u16) {
        self.record_port(ip, port, PortState::Unasked, None);
        // Nothing was sent, so nothing was learned, and a resume owes this
        // target the probe this sitting did not spend on it.
        self.settle(Outcome::Unasked);
    }
}

/// How a run names itself in the audit and in its own failure messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditLabels {
    /// The tag the audit line is filed under, such as `"tcp-port"`.
    pub tag: &'static str,
    /// How a port that nothing answered for is described, such as
    /// `"open-filtered"`.
    pub silence: &'static str,
}

/// Drives one raw port scan from its first probe to its audit line.
///
/// This is the whole of what the TCP and UDP scanners used to hold a copy of
/// each. The two copies differed in four expressions: which protocol to accept,
/// what silence meant, and two labels. Everything around those was identical
/// down to the comments, including the ordering that makes the stop conditions
/// mean anything, and that is a dangerous thing to keep two of. A stop
/// condition fixed in one copy and missed in the other does not fail; it
/// returns a smaller answer that looks exactly like a quiet network.
///
/// The shape of one iteration, and why it is that shape:
///
/// 1. **Service retries first.** Probes come due on a timer, and queuing them
///    before the stop conditions are read means the ledger is current when
///    those conditions ask whether anything is still outstanding.
/// 2. **Then decide whether to stop**, on the four conditions
///    [`RawProbeScan::stop_reason`] holds.
/// 3. **Then wait on whichever of three things happens first**: another target
///    to probe, a reply to read, or the moment the next probe is due.
///
/// Anything still outstanding when the loop ends takes the scan's silence
/// verdict, and anything still queued is recorded [`PortState::Unasked`], so a
/// scan cut short by its own deadline reports the ports it never reached instead
/// of leaving them off the host entirely, which is the one shortfall a reader
/// cannot see. See [`RawPortScan::resolve_unasked`] for how far that reaches.
pub async fn drive<S: RawPortScan>(scanner: &mut S, mut targets: mpsc::Receiver<PlannedTarget>) {
    // The rate backstop. What paces the scan is `RawProbeScan::window`, which
    // the batch loop below re-checks after every send; this bounds how fast a
    // window's worth of probes may be released, so a defect in the controller
    // cannot become a flood and a caller asking for a specific rate gets one.
    let mut send_tick = tokio::time::interval(scanner.core().send_tick);
    // Delay rather than Burst: a tick missed while the loop was busy is time the
    // probes were not going out, and catching up by releasing several at once
    // would put back exactly the burst this exists to prevent.
    send_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

    let mut sending_finished = false;
    // Counts what the scan was handed rather than what it sent. A target of
    // another protocol is not this scanner's to probe, but it was still part of
    // the work routed here, and the audit reads this as the denominator.
    let mut probes = 0u128;

    // The loop yields why it stopped, so the audit cannot report a reason the
    // code never actually took.
    let reason = loop {
        // Read once per iteration and reused throughout it: a scan at rate
        // takes this path constantly, and the arithmetic below only needs the
        // instants to agree with each other.
        let now = Instant::now();
        scanner.service_retries(now);

        if let Some(reason) = scanner.core().stop_reason(sending_finished) {
            break reason;
        }

        // Both are read before the `select!`, which borrows the receive half
        // mutably for the duration of the statement.
        let admitting = scanner.core().admitting(sending_finished);
        let tick = scanner.core().tick_delay(now);

        tokio::select! {
            // One tick releases a batch, which is how a rate faster than the
            // timer's resolution is expressed. Taken from the stream only when
            // the ledger has room: the ceiling still bounds how many answers are
            // outstanding, and the rate now bounds how fast they are asked for.
            _ = send_tick.tick(), if admitting => {
                let now = Instant::now();
                for _ in 0..scanner.core().batch {
                    // A probe already held for its host's next slot goes first.
                    // It was taken off the stream before anything still in the
                    // channel was looked at, and leaving it behind fresh targets
                    // would have a scan with a gap set starve the hosts it had
                    // already reached in favour of ones it had not.
                    if let Some(held) = scanner.core_mut().take_ready(now) {
                        scanner.send_held(held, now);
                        if !scanner.core().admitting(sending_finished) {
                            break;
                        }
                        continue;
                    }

                    // Nowhere to put another one. Every target pulled now could
                    // only be held, so the stream is left alone and the
                    // dispatcher feels it exactly as it feels a full window.
                    if scanner.core().held_is_full() {
                        break;
                    }

                    match targets.try_recv() {
                        Ok(target) => {
                            probes += 1;
                            // A host that has spent its own budget is left
                            // where it stands. The target is written down as
                            // one nobody asked about rather than dropped, so
                            // the shortfall reads the same as any other.
                            if scanner.core().ctx.host_expired(target.ip()) {
                                scanner.record_unasked(target);
                            } else if let Some(ready) =
                                scanner.core().ctx.host_ready_at(target.ip(), now)
                            {
                                // Asked too recently. Held rather than dropped:
                                // this target has been counted and owes a
                                // verdict, and the one thing that must not
                                // happen is a probe the scan chose to delay
                                // reading afterwards as a silent port.
                                scanner.hold_probe(target, ready);
                            } else {
                                scanner.send_probe(target);
                            }
                        }
                        // Nothing waiting: the dispatcher has not caught up, and
                        // blocking here would hold the receive half across the
                        // whole batch.
                        Err(mpsc::error::TryRecvError::Empty) => break,
                        Err(mpsc::error::TryRecvError::Disconnected) => {
                            sending_finished = true;
                            break;
                        }
                    }
                    if !scanner.core().admitting(sending_finished) {
                        break;
                    }
                }
            }

            res = scanner.core_mut().transport.rx.recv() => {
                match res {
                    Some(reply) => {
                        scanner.core_mut().audit.record_segment();
                        // The moment the capture thread took the segment, not
                        // the moment this loop reached it. See
                        // `CapturedSegment::received_at`.
                        let received_at = reply.received_at;
                        scanner.handle_reply(&reply, received_at);
                    }
                    None => break StopReason::StreamClosed,
                }
            }

            // Wakes when the next probe is due, so a retry is sent on time even
            // though nothing is arriving to wake the loop otherwise.
            _ = tokio::time::sleep(tick) => {}
        }
    };

    scanner.resolve_remaining();
    // Probes still waiting for a host's next slot. Before the channel drain
    // below and after the ledger above, because a held retry is accounted for by
    // `resolve_remaining` and a held first attempt by nothing at all.
    scanner.resolve_held();
    // Targets still in the channel when the loop ended. Counted into `probes`
    // so the audit's denominator is what the scan was handed rather than what it
    // got round to.
    probes += scanner.resolve_unasked(&mut targets);

    let kind = scanner.kind();
    let labels = scanner.audit_labels();
    scanner
        .core_mut()
        .finish(kind, labels.tag, labels.silence, probes, reason);
}

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

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

    use crate::scanner::pacing::congestion::WindowLimits;
    use crate::scanner::session::ScanSession;
    use crate::transport::probe::{Emission, ProbeSender, ProbeTransport, SendError};

    /// A sender that swallows everything. These tests never look at the wire;
    /// they ask when the loop decides to stop, which is a question about the
    /// ledger and the deadline alone.
    #[derive(Default)]
    struct NullSender;

    impl ProbeSender for NullSender {
        fn send(
            &self,
            _segment: &[u8],
            _src: IpAddr,
            _dst: IpAddr,
            _zone: Option<u32>,
            _emission: Emission,
        ) -> Result<(), SendError> {
            Ok(())
        }
    }

    const TARGET: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));

    /// A core with a generous deadline and a one-attempt retry budget, so the
    /// only thing that moves a verdict is what the test puts in the ledger.
    fn core() -> (RawProbeScan<()>, ScanSession) {
        let (session, ctx) = ScanSession::new();
        let (_tx, rx) = tokio::sync::mpsc::channel(1024);
        let core = RawProbeScan {
            resolver: SourceResolver::from_links(&[]),
            ctx,
            transport: ProbeTransport::from_parts(Box::new(NullSender), rx),
            deadline: AdaptiveDeadline::new(super::super::raw::DEADLINE_CONFIG, 8),
            ledger: ProbeLedger::new(super::super::raw::RETRY_POLICY, 8),
            due: Vec::new(),
            src_port: 54_321,
            emission: Emission::routed(),
            shaping: SegmentShaping::default(),
            decoys: Vec::new(),
            send_failure: None,
            unasked_unsent: 0,
            audit: ProbeAudit::new(),
            window: CongestionWindow::new(WindowLimits::fixed(4)),
            send_tick: Duration::from_millis(1),
            batch: 1,
            max_unresolved: 64,
            held: std::collections::BinaryHeap::new(),
        };
        (core, session)
    }

    /// [`core`] with a gap between probes at one host, for the tests that are
    /// about the queue rather than the ledger.
    fn spaced_core(gap: Duration) -> (RawProbeScan<()>, ScanSession) {
        let (session, ctx) = ScanSession::builder()
            .host_probe_interval(Some(gap))
            .build();
        let (_tx, rx) = tokio::sync::mpsc::channel(1024);
        let core = RawProbeScan {
            resolver: SourceResolver::from_links(&[]),
            ctx,
            transport: ProbeTransport::from_parts(Box::new(NullSender), rx),
            deadline: AdaptiveDeadline::new(super::super::raw::DEADLINE_CONFIG, 8),
            ledger: ProbeLedger::new(super::super::raw::RETRY_POLICY, 8),
            due: Vec::new(),
            src_port: 54_321,
            emission: Emission::routed(),
            shaping: SegmentShaping::default(),
            decoys: Vec::new(),
            send_failure: None,
            unasked_unsent: 0,
            audit: ProbeAudit::new(),
            window: CongestionWindow::new(WindowLimits::fixed(4)),
            send_tick: Duration::from_millis(1),
            batch: 1,
            max_unresolved: 64,
            held: std::collections::BinaryHeap::new(),
        };
        (core, session)
    }

    /// The queue yields the probe whose host is ready soonest, whatever order
    /// the entries were held in.
    #[test]
    fn the_earliest_slot_comes_off_the_queue_first() {
        let (mut core, _session) = spaced_core(Duration::from_secs(3600));
        let now = Instant::now();

        // Held out of order on purpose: the heap's job is that this does not
        // matter.
        core.hold(TARGET, 80, Some(0), now + Duration::from_secs(30));
        core.hold(TARGET, 22, Some(1), now + Duration::from_secs(10));
        core.hold(TARGET, 443, Some(2), now + Duration::from_secs(20));

        assert!(
            core.take_ready(now).is_none(),
            "nothing is ready yet, and nothing is handed back early"
        );

        let first = core
            .take_ready(now + Duration::from_secs(15))
            .expect("the ten-second slot has come round");
        assert_eq!(first.port, 22);
    }

    /// A recorded instant is a hint, and the queue re-checks it rather than
    /// trusting it.
    ///
    /// A retry aimed at the same host moves its slot after an entry is queued,
    /// so an entry reaches the front before its host is really ready. Trusting
    /// the stored instant would send a probe inside the gap the caller asked
    /// for, which is the one thing this feature must not do.
    #[test]
    fn a_slot_that_moved_after_the_probe_was_held_is_re_checked() {
        let gap = Duration::from_secs(3600);
        let (mut core, _session) = spaced_core(gap);
        let now = Instant::now();

        // Held as though its host were ready immediately.
        core.hold(TARGET, 80, Some(0), now);
        // And then the host is probed, which moves the real slot an hour out.
        core.ctx.host_probed(TARGET, now);

        assert!(
            core.take_ready(now).is_none(),
            "the stored instant said now; the host says otherwise and the host wins"
        );
        assert_eq!(
            core.held.len(),
            1,
            "and the probe is still held, not dropped"
        );

        assert!(
            core.take_ready(now + gap).is_some(),
            "once the gap has really run, it is handed back"
        );
    }

    /// A held probe is something still to send, so a stream that ran dry does
    /// not conclude the scan while one is waiting.
    ///
    /// Getting this wrong reports a port the scan chose to delay as one it asked
    /// about and heard nothing from, which is a verdict from a probe that was
    /// never sent.
    #[test]
    fn a_held_probe_keeps_the_scan_open_after_the_stream_ends() {
        let (mut core, _session) = spaced_core(Duration::from_secs(3600));
        let now = Instant::now();

        core.hold(TARGET, 80, Some(0), now + Duration::from_secs(1));

        assert_eq!(
            core.stop_reason(true),
            None,
            "the stream is done and the ledger empty, but a probe is still owed"
        );
        assert!(
            core.admitting(true),
            "and the send path stays open, since it is the only thing that empties the queue"
        );

        let _ = core.take_ready(now + Duration::from_secs(1));
        core.held.clear();
        assert_eq!(
            core.stop_reason(true),
            Some(StopReason::AttemptsSpent),
            "with the queue empty too, waiting cannot change what this found"
        );
    }

    /// The queue bounds the stream and deliberately not the send path.
    ///
    /// A full queue closing the send path would be a scan that stopped and never
    /// restarted, since sending is what empties it.
    #[test]
    fn a_full_queue_stops_the_stream_and_not_the_sending() {
        let (mut core, _session) = spaced_core(Duration::from_secs(3600));
        let now = Instant::now();

        for port in 0..core.max_unresolved {
            core.hold(TARGET, port as u16, Some(port as u64), now);
        }

        assert!(core.held_is_full());
        assert!(
            core.admitting(false),
            "a full queue must not close the one path that drains it"
        );
    }

    /// The condition the whole loop exists to get right: an empty ledger means
    /// "everything has been answered or written off" only once there is nothing
    /// left to ask. Reached before the stream runs dry it would end a scan that
    /// had not yet sent most of its probes.
    ///
    /// The way that actually happens is the send path failing. A link that has
    /// stopped accepting sends leaves the ledger empty while the stream is still
    /// full, and a loop that read the quiet as an answer abandoned thirty-one
    /// thousand queued targets and reported them as ports nobody could reach.
    #[test]
    fn an_empty_ledger_does_not_end_a_scan_that_still_has_targets_coming() {
        let (core, _session) = core();

        assert_eq!(
            core.stop_reason(false),
            None,
            "the target stream is still open, so nothing has been concluded"
        );
        assert_eq!(
            core.stop_reason(true),
            Some(StopReason::AttemptsSpent),
            "with the stream done and nothing outstanding, waiting cannot help"
        );
    }

    /// Silence is only evidence once nothing is outstanding. With probes still
    /// waiting on their timers, quiet is what the retry schedule expects.
    #[test]
    fn an_outstanding_probe_holds_the_scan_open_past_a_dry_target_stream() {
        let (mut core, _session) = core();
        core.ledger.arm(TARGET, (TARGET, 80), (), 0, Instant::now());

        assert_eq!(
            core.stop_reason(true),
            None,
            "a probe is still within its retry schedule"
        );
    }

    /// An abort is checked before anything else, so a scan winds down promptly
    /// rather than after whatever else it was in the middle of.
    #[test]
    fn an_abort_outranks_every_other_reason() {
        let (mut core, _session) = core();
        core.ledger.arm(TARGET, (TARGET, 80), (), 0, Instant::now());
        core.ctx.handle.abort();

        assert_eq!(core.stop_reason(false), Some(StopReason::Aborted));
    }

    /// The window is what makes a scan self-pacing: probes leave as earlier ones
    /// are resolved, rather than as fast as the socket accepts writes.
    #[test]
    fn the_ledger_stops_admitting_at_the_window() {
        let (mut core, _session) = core();
        assert!(core.admitting(false), "an empty ledger admits");

        for _ in 0..core.window.capacity() {
            core.window.record_send();
        }

        assert!(
            !core.admitting(false),
            "admitting past the window grows correlation state for nothing"
        );
        assert!(
            !core.admitting(true),
            "a finished stream never admits, window or not"
        );
    }

    /// A reply to the first attempt says the target is keeping up. A reply to a
    /// later one says it was willing all along and the first question did not
    /// survive, which is the one thing a port scanner can observe that
    /// separates being too fast from meeting a firewall.
    #[test]
    fn the_attempt_that_answered_is_what_moves_the_window() {
        let (mut core, _session) = core();
        core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));

        core.record_answer(&Resolution {
            payload: 0u64,
            rtt: None,
            attempts: 1,
            answered_attempt: Some(1),
        });
        assert!(core.window.capacity() > 64, "a clean answer buys headroom");

        let grown = core.window.capacity();
        core.record_answer(&Resolution {
            payload: 0u64,
            rtt: None,
            attempts: 2,
            answered_attempt: Some(2),
        });
        assert!(
            core.window.capacity() < grown,
            "an answer that needed a retry is loss, and loss cuts the window"
        );
    }

    /// A send the kernel refused is backpressure from this machine, and the one
    /// signal in the controller that does not come from the network at all.
    ///
    /// Whatever refused it, a full interface queue, a neighbour that will not
    /// resolve, offering more of the same faster cannot help. Measured: seven
    /// thousand `No route to host` failures in one run, at an unchanged window,
    /// because nothing was reading them.
    #[test]
    fn a_send_the_kernel_refused_cuts_the_window() {
        let (mut core, _session) = core();
        core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));

        core.record_send("192.0.2.1".parse().expect("a literal address"), false, true);

        assert!(
            core.window.capacity() < 64,
            "the local stack refusing is the least ambiguous evidence there is"
        );
        assert_eq!(
            core.window.in_flight(),
            0,
            "and a probe that never left takes no slot"
        );
    }

    /// Silence from a host that has never said anything is not congestion. It is
    /// what a firewall and a dead address both produce, and a controller that
    /// read it as congestion would crawl against exactly the hosts that are
    /// hardest to finish, while learning nothing, because nothing it did would
    /// change the answer.
    #[test]
    fn silence_from_a_host_that_never_answered_opens_the_window() {
        let (mut core, _session) = core();
        core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));

        core.window.record_send();
        core.judge_timeout(TARGET);

        assert!(
            core.window.capacity() >= 64,
            "nothing this host did says the path is busy"
        );
        assert_eq!(core.window.in_flight(), 0, "and the slot went back");
    }

    /// Silence from a host that is answering most of what it is asked is the
    /// opposite: it is not running a block list, it is failing to keep up.
    ///
    /// This is the signal the first version of the controller did not have, and
    /// its absence is measurable. Against a Raspberry Pi answering three quarters
    /// of a thousand probes, the window never cut once and the remaining quarter
    /// was reported as a firewall that did not exist: a different set of ports
    /// on every run.
    #[test]
    fn silence_from_a_host_that_is_answering_cuts_the_window() {
        let (mut core, _session) = core();
        core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));

        // One port answered, which is what makes this host's silence mean
        // something.
        let now = Instant::now();
        core.ledger.arm(TARGET, (TARGET, 22), (), 0, now);
        core.ledger.resolve(&(TARGET, 22), None, now);

        core.window.record_send();
        core.judge_timeout(TARGET);

        assert!(
            core.window.capacity() < 64,
            "a host that talks and then goes quiet is being outrun"
        );
        assert_eq!(core.window.in_flight(), 0, "and the slot still went back");
    }
}