zond-engine 0.16.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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

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

mod ipv6;
mod probes;

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

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

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

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

/// What a local sweep's capture admits, as a `libpcap` filter expression.
///
/// The union of what every [`DiscoveryProtocol`] declares it reads, plus the one
/// thing the sweep reads without one. Derived rather than written down, so that
/// adding a protocol widens the capture by the same edit that adds the reader.
/// see [`DiscoveryProtocol::capture_clause`] for why that is not a convenience.
///
/// Receiving the whole segment and rejecting the surplus in userspace would, on
/// a busy link, copy every frame on the wire to discard almost all of it.
///
/// 802.1Q-tagged frames are not admitted, and that loses nothing: the frame
/// reader below takes the EtherType from its fixed offset, so a tagged frame
/// would read as an unsupported EtherType and be rejected a layer up anyway.
fn sweep_filter() -> String {
    let mut clauses: Vec<&'static str> = frames::sweep_protocols()
        .iter()
        .map(|protocol| protocol.capture_clause())
        .collect();

    clauses.extend(ABSORBED_CLAUSES);

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

    clauses.join(" or ")
}

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

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

/// How an ARP request is retransmitted.
///
/// ARP is lost on a busy segment considerably more often than its reputation
/// suggests - requests are broadcast, and a switch under load drops broadcast
/// before anything else - and a sweep that never asks twice simply reports the
/// hosts it missed as absent.
///
/// The timings are a segment's, not an internet path's: a neighbour that is
/// going to answer does so in well under a millisecond, so the floor is what
/// governs almost immediately and a silent address is settled in about a second
/// rather than in the seconds a wide-area profile would spend.
///
/// No silent-host rule, because there would be nothing for it to do: each
/// address here is probed once, so no host ever accumulates the exhausted
/// probes that rule counts.
const RETRY_POLICY: RetryPolicy = RetryPolicy::new(
    3,
    Duration::from_millis(150),
    Duration::from_millis(25),
    Duration::from_secs(1),
    2.0,
    0.2,
    None,
);

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

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

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

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

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

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

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

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

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

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

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

/// What one turn of the send ticker put on the wire.
///
/// A first attempt is the only one the sweep counts, because it is the only
/// one that draws an address out of the packet iterator: everything else is
/// either a repeat of a question already asked or a question put to the whole
/// segment.
enum Dispatched {
    /// A repeat, a confirmation, or the all-nodes solicitation, none of which
    /// is a new address.
    Again,
    /// The next address the iterator held.
    FirstAttempt,
    /// The iterator is empty, so every address the sweep was handed has been
    /// asked at least once.
    Drained,
    /// Nothing was due, which is what an already-drained iterator looks like
    /// on a tick with no repeat behind it.
    Nothing,
}

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

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

    async fn discover_hosts(&mut self) -> Result<(), StrategyError> {
        let mut packet_iter = probes::eth_packet_iter(
            &self.identity.mac,
            &self.identity.ipv4,
            &self.identity.link_local_ipv6,
            &self.ip_set,
        );

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

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

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

        let mut sending_finished = false;
        // What the packet iterator has handed out, so what it still holds can be
        // counted as unasked without draining it: building those packets is the
        // work the sweep was stopped to avoid.
        let mut dispatched: u128 = 0;
        let mut send_interval: Interval = tokio::time::interval(SEND_INTERVAL);
        // Without this, an interval that went unpolled while the loop waited on
        // replies hands back every tick it missed at once, and the pacing this
        // ticker exists to impose evaporates exactly when the queue is longest.
        send_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

        // The loop yields why it stopped, so the audit cannot report a reason
        // the code never actually took.
        let reason = loop {
            let now = Instant::now();
            // Both schedules, and a sweep settles: it was asked whether an
            // address is there and has asked as many times as it may.
            self.sweep.service_retries(&self.ctx, now);
            self.sweep
                .service_second_ledger(&self.ctx, self.ipv6.ledger_mut(), now);

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

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

            tokio::select! {
                pkt = self.eth_handle.rx.recv() => {
                    match pkt {
                        Some(frame) => {
                            self.sweep.audit.record_segment();
                            _ = self.process_eth_packet(&frame, Instant::now());
                        }
                        None => break StopReason::StreamClosed,
                    }
                }

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

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

        self.report_outcome(reason, dispatched);
        Ok(())
    }
}

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

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

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

        // Saturating, not truncating. An address count is a `u128` and a `/64`
        // is exactly `usize::MAX + 1`, so the plain cast would turn the largest
        // possible sweep into a target count of zero and hand it the smallest
        // possible budget. `ScanBudget::unclamped` saturates its own cast for
        // the same reason one layer down.
        let target_count = usize::try_from(ip_set.len()).unwrap_or(usize::MAX);
        // The sweep has to outlive the schedule it commits each probe to, or
        // addresses are given up on having never been fully asked.
        // The longer of the two schedules, because the sweep has to outlive
        // whichever probe it commits to last. Sized from ARP alone, it ends
        // while solicitations are still legitimately outstanding - which is the
        // shape of the bug `ipv6::NDP_RETRY_POLICY` exists to fix, arriving one layer
        // up.
        let probe_lifetime = retry
            .worst_case_probe_lifetime()
            .max(ipv6::NDP_RETRY_POLICY.worst_case_probe_lifetime());
        let deadline_config = DEADLINE_CONFIG.allowing_for(probe_lifetime);
        let deadline = AdaptiveDeadline::new(deadline_config, target_count);

        Ok(Self {
            ctx,
            ip_set,
            identity,
            eth_handle,
            deadline,
            protocols: frames::sweep_protocols(),
            sweep: HostSweep::new(Ledger::new(retry, target_count)),
            dns_tx,
            mac_to_ip: HashMap::new(),
            declared: HashMap::new(),
            scope,
            ipv6: Ipv6Discovery::new(target_count),
            send_failure: None,
        })
    }

    /// Why the loop should stop, if it should.
    ///
    /// The order is the priority: a run somebody aborted, one whose wall-clock
    /// budget ran out, and one whose own deadline expired are reported as such
    /// even when the sweep had in fact finished, because the caller's next
    /// question is whether the result is complete.
    fn stop_reason(&self, now: Instant, 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.all_targets_responded() {
            return Some(StopReason::AllResponded);
        }
        // Silence is only evidence once nothing is outstanding: with probes
        // still waiting on their timers, quiet is what the retry schedule
        // expects rather than a sign the segment has gone quiet.
        if sending_finished && self.idle(now) && self.deadline.has_expired() {
            return Some(StopReason::DeadlineExpired);
        }

        None
    }

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

    /// What the sweep leaves behind once the loop has stopped: the addresses it
    /// never settled, the questions that went unanswered, the frames that never
    /// left, and the counters a later phase reads.
    ///
    /// `dispatched` is how many first attempts the packet iterator gave out.
    fn report_outcome(&mut self, reason: StopReason, dispatched: u128) {
        // What the sweep did not earn a verdict for, so a resumed one asks again
        // rather than skipping it. None of these carries a position: a probe
        // still mid-schedule was cut off rather than spent, and one the iterator
        // still holds was never built, let alone sent.
        let outstanding = self.sweep.ledger.drain_unresolved().len() as u64;
        self.ctx
            .record_many_outcomes(Outcome::Interrupted, outstanding);
        self.ctx.record_many_outcomes(
            Outcome::Unasked,
            u64::try_from(self.ip_set.len().saturating_sub(dispatched)).unwrap_or(u64::MAX),
        );

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

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

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

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

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

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

        if !self.ctx.may_probe(&address) {
            info!(
                verbosity = 2,
                "{address} was overheard and is excluded, so it is not asked about"
            );
            return;
        }

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

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

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

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

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

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

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

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

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

    /// Rebuilds and sends the probe for `target`, whichever kind its address
    /// calls for: an ARP request over IPv4, a neighbor solicitation over IPv6.
    ///
    /// Nothing about either is kept between attempts, because nothing needs to
    /// be: the frame is a function of this scanner's identity and the address
    /// being asked about, and rebuilding it is cheaper than holding a copy per
    /// outstanding probe.
    fn send_probe(&mut self, target: IpAddr, now: Instant) {
        let packet = match target {
            IpAddr::V4(target_v4) => {
                let Some(source_v4) = self.identity.ipv4 else {
                    return;
                };
                protocol::arp::build_request(self.identity.mac, source_v4, target_v4)
            }
            IpAddr::V6(target_v6) => {
                let Some(source_v6) = self.identity.link_local_ipv6 else {
                    return;
                };
                protocol::ndp::build_neighbor_solicitation(self.identity.mac, source_v6, target_v6)
            }
        };

        self.emit(&packet, "probe");
        if target.is_ipv6() {
            self.ipv6.record_asked(target, now);
        } else {
            self.sweep.ledger.arm(target, target, (), (), now);
        }
    }

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

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

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

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

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

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

        true
    }

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

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

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

        true
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Ok(())
    }

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

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

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

        Ok(rtt)
    }

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

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

        None
    }

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

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

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

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

        let first_sighting = !self.mac_to_ip.contains_key(&source_mac);
        let primary_ip = *self.mac_to_ip.entry(source_mac).or_insert(source_addr);

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

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

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

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

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

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

                changed
            });

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

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

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

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

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

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

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

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

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

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

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

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

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