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

//! # Deciding what a scan will do, before it does any of it
//!
//! A plan is the set of strategies a scan intends to run, worked out from the
//! targets and the host's own network configuration, with nothing opened and
//! nothing sent. [`discover`](crate::scanner::discover) and
//! [`scan`](crate::scanner::scan) build one and immediately execute it. A caller
//! orchestrating their own scan can build one, look at it, change it, and run
//! the parts they want.
//!
//! ## Why planning is separated from running at all
//!
//! Deciding is where every interesting judgement in a scan lives. Which
//! interface reaches a target, whether a `/64` can be walked, whether a
//! link-local address without a zone can be probed at all, whether a sweep may
//! take leads from the host's neighbour table, which protocols still need an
//! unprivileged fallback: all of that is settled before a single socket is
//! opened, and none of it needs a socket to settle.
//!
//! Fused into the code that spawns tasks, those judgements are unreachable: they
//! cannot be inspected without running a scan, cannot be tested without a host
//! that happens to have the right interfaces, and cannot be adjusted at all.
//! Split out, a plan is a value. `zond --dry-run` is a plan printed instead of
//! run. A caller who wants to sweep two of their five links drops three steps
//! and runs the rest. A test asserts on what *would* happen against a
//! hand-written interface table.
//!
//! ## What a plan costs to build
//!
//! No packets and no sockets. Building one does read the machine's own
//! configuration, the interface list, the routing table, and for a sweep the
//! IPv6 neighbour table, because which strategy reaches a target is a fact
//! about this host and cannot be guessed. Those are ordinary reads of local
//! state, they open nothing, and they are the same reads
//! [`crate::system::interface`] performs for any caller.
//!
//! ## What a plan does not promise
//!
//! That every step will run. A step becomes a strategy through
//! [`DiscoveryStep::into_scanner`], and that is where sockets are opened and
//! where the environment gets its say: a capture that cannot be opened, an
//! interface that disappeared between planning and running. Those surface as a
//! [`StrategyError`] per step, and the scan continues with the rest. A plan is
//! what the engine means to do, not a guarantee about a machine it does not
//! control.

use std::collections::HashMap;
use std::net::IpAddr;

use tokio::sync::mpsc::UnboundedSender;

use crate::config::limits;
use crate::config::{ProbeTuning, ZondConfig};
use crate::model::ip::range::{IpRange, Ipv6Range};
use crate::model::ip::scoped::ZoneMap;
use crate::model::ip::set::IpSet;
use crate::model::port::Protocol;
use crate::model::technique::TcpScanTechnique;
use crate::report::ScannerKind;
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::connect::{
    ConnectPortScanner, ConnectScanner, ConnectUdpPortScanner,
};
use crate::scanner::strategy::local::{LocalScanner, Scope};
use crate::scanner::strategy::ports::{
    IdlePortScanner, SctpPortScanner, TcpPortScanner, UdpPortScanner,
};
use crate::scanner::strategy::routed::RoutedScanner;
use crate::scanner::strategy::{HostScanner, PortScanner, StrategyError};
use crate::system::interface::Link;
use crate::system::interface::{self, RoutedTarget};
use crate::system::neighbor_cache;
use crate::system::privilege::Privilege;
use crate::{info, warn};

/// Something the scan will not do, decided at planning time.
///
/// A refusal is not a failure of the network and not an address that went
/// unanswered: it was never probed, and the reason is knowable before anything
/// is sent. It is carried out of the plan rather than dropped because the one
/// thing a scanner may never do is stay quiet about ground it did not cover: a
/// caller has to be able to tell "nothing is there" from "nobody looked", and
/// only one of those is visible in a host count.
#[derive(Debug, Clone)]
pub struct RefusedStep {
    /// The strategy that would have taken this work.
    pub scanner: ScannerKind,
    /// What cannot be done, and what the caller could write instead.
    pub reason: String,
}

impl RefusedStep {
    /// The TCP half left undone because `technique` cannot be expressed without
    /// raw sockets.
    ///
    /// A connect scan completes handshakes, so it answers roughly the question
    /// a SYN scan asks. It cannot send a FIN, a flagless segment or a bare ACK,
    /// so it cannot answer what any of those were asked, and substituting it
    /// silently would hand back verdicts from a technique nobody chose.
    ///
    /// Written once because it is reached from two places, and they are not
    /// redundant: [`PortScanPlan::build`] refuses ahead of time when there are
    /// no raw sockets to be had, while the scan's own coverage check refuses
    /// after the fact when a raw socket was expected and would not open. Same
    /// cause, same words, two moments at which it becomes knowable.
    pub fn technique_needs_raw_sockets(technique: TcpScanTechnique) -> Self {
        Self {
            scanner: ScannerKind::for_raw_tcp(technique),
            reason: format!(
                "the {technique} technique needs raw sockets, which this process does \
                 not have, and a connect scan answers a different question - so no TCP \
                 port was probed"
            ),
        }
    }

    /// SCTP ports were named by a scan with no raw sockets to probe them with.
    ///
    /// There is no unprivileged form of an INIT scan: the kernel offers no way
    /// to send a chunk and read the answer without an SCTP stack and an
    /// association, and an association is the one thing this scan avoids
    /// completing. So the ports are refused rather than answered by something
    /// that asked a different question.
    pub fn sctp_needs_raw_sockets() -> Self {
        Self {
            scanner: ScannerKind::SctpPort,
            reason: "the sctp ports named for this scan need raw sockets, which this process \
                     does not have, and there is no unprivileged init probe - so no sctp port \
                     was probed"
                .to_string(),
        }
    }

    /// SCTP ports were named for a scan running as an idle scan, which probes
    /// through a third party and has no way to carry an INIT.
    ///
    /// The refusal is the point rather than a limitation. An INIT sent directly
    /// would leave this host's own address on the target, which is the one thing
    /// an idle scan exists to avoid.
    pub fn sctp_not_in_an_idle_scan() -> Self {
        Self {
            scanner: ScannerKind::SctpPort,
            reason: "an idle scan reads a third party's counter, which carries no sctp probe, \
                     and sending one directly would put this host's address on the target - so \
                     no sctp port was probed"
                .to_string(),
        }
    }

    /// An idle scan was asked for without the privilege it needs.
    ///
    /// The forged source address of an idle scan's probe can only ride a
    /// self-built frame, which needs privilege. There is no
    /// fallback: scanning the target under this host's own address is the one
    /// thing an idle scan exists to avoid, so the whole of it is refused rather
    /// than run in the open.
    pub fn idle_needs_privilege() -> Self {
        Self {
            scanner: ScannerKind::Idle,
            reason: "an idle scan forges the source address of its probes, which needs \
                     a self-built frame this process cannot open without privilege - and \
                     scanning the target under this host's own address instead would \
                     betray the scan, so no TCP port was probed"
                .to_owned(),
        }
    }

    /// A routed IPv6 range with more addresses than any strategy can walk.
    ///
    /// See [`MAX_ENUMERABLE_ADDRESSES`](crate::system::interface::MAX_ENUMERABLE_ADDRESSES)
    /// for why there is a ceiling at all.
    pub fn routed_range_not_enumerable(range: &Ipv6Range) -> Self {
        Self {
            scanner: ScannerKind::Routed,
            reason: format!(
                "{}: too large to probe one address at a time, and routed IPv6 has \
                 no other strategy yet. Give specific addresses or a smaller prefix.",
                describe(range)
            ),
        }
    }

    /// The same range, refused by an unprivileged scan.
    ///
    /// Separate wording from [`routed_range_not_enumerable`](Self::routed_range_not_enumerable)
    /// because the remedy is different and it is the more useful half of the
    /// message: a range this size *is* reachable on the local segment with raw
    /// sockets, through the all-nodes echo, which sweeps a `/64` in one packet
    /// rather than walking it. A user told only "too large" would go and narrow
    /// a prefix that root would have covered whole.
    pub fn unprivileged_range_not_enumerable(range: &Ipv6Range) -> Self {
        Self {
            scanner: ScannerKind::Connect,
            reason: format!(
                "{}: too large to probe one address at a time, and an unprivileged \
                 scan has no other strategy. Run with root to sweep a segment this \
                 size, or give specific addresses or a smaller prefix.",
                describe(range)
            ),
        }
    }

    /// A port target that is link-local and names no interface.
    ///
    /// `fe80::1` names a different machine on every segment, and every interface
    /// holds an `fe80::/64`, so there is nothing to choose between them. Written
    /// `fe80::1%en0` it names one, and the scan sends from that interface.
    ///
    /// [`RoutedTargets::ambiguous`](crate::system::interface::RoutedTargets)
    /// refuses the same target on the discovery path.
    pub fn link_local_port_target_needs_an_interface(range: &Ipv6Range) -> Self {
        let target = name(range);
        Self {
            scanner: ScannerKind::SynPort,
            reason: format!(
                "{target} is link-local and names no interface, so it names a \
                 different machine on every segment this host is on. Say which: \
                 {}%en0, naming the interface the segment is reached through.",
                range.start_addr()
            ),
        }
    }

    /// One link-local address given on two interfaces in a single scan.
    ///
    /// Each is a different machine, and a port scan records its verdicts under
    /// the address it probed, so the two sets of answers would land on one host
    /// with nothing to say which segment either came from.
    pub fn link_local_port_target_names_two_segments(range: &Ipv6Range) -> Self {
        let target = name(range);
        Self {
            scanner: ScannerKind::SynPort,
            reason: format!(
                "{target} was named on two interfaces at once, and each is a \
                 different machine. Scan one segment at a time."
            ),
        }
    }

    /// An on-link IPv6 range too large to walk, in a scan that will not sweep
    /// the segment it is on.
    ///
    /// The one range this engine can reach and declines to. A local segment is
    /// covered by the all-nodes solicitation, which is a single packet whatever
    /// the prefix length, so the remedy is a sweep rather than a smaller
    /// prefix. A [`Scope::Sweep`] step already sends that packet and refuses
    /// nothing.
    ///
    /// Walking it instead is what used to happen, and the failure was silent:
    /// the address count overflowed the deadline's target count, the sweep was
    /// budgeted as though it had no targets at all, and it stopped a couple of
    /// thousand solicitations into a space of eighteen quintillion having
    /// reported the range covered.
    pub fn local_range_needs_a_sweep(range: &Ipv6Range) -> Self {
        Self {
            scanner: ScannerKind::Local,
            reason: format!(
                "{}: too large to probe one address at a time, and this scan is \
                 not sweeping the segment. The all-nodes solicitation reaches a \
                 prefix this size in one packet - scan the segment rather than \
                 the range, or give specific addresses.",
                describe(range)
            ),
        }
    }
}

/// Takes the IPv6 ranges out of `targets` that are too large to probe one
/// address at a time, leaving the rest.
///
/// The same test the routed path applies, applied where the local path needed
/// it: [`is_enumerable`](interface::is_enumerable) asks it of a range rather
/// than of a set, so a set holding a `/64` and three literal addresses keeps
/// the three.
///
/// IPv4 is untouched, on the same reasoning that leaves it untouched
/// everywhere else: every IPv4 range is finite in a way a person can reason
/// about.
fn withhold_unwalkable(targets: &mut IpSet) -> Vec<Ipv6Range> {
    let unwalkable: Vec<Ipv6Range> = targets
        .v6()
        .iter()
        .filter(|range| !interface::is_enumerable(range))
        .copied()
        .collect();

    if unwalkable.is_empty() {
        return unwalkable;
    }

    let mut kept = IpSet::new();
    for range in targets.v4() {
        kept.push_v4_range(*range);
    }
    for range in targets.v6() {
        if interface::is_enumerable(range) {
            kept.push_v6_range(*range);
        }
    }
    kept.canonicalize();
    *targets = kept;

    unwalkable
}

impl From<RefusedStep> for crate::report::Refusal {
    /// The recorded form of a refusal a plan carries.
    ///
    /// One direction only. A plan's refusal knows how it was decided, and a
    /// recorded one is what a reader is handed afterwards; going back would mean
    /// inventing the decision from the words.
    fn from(step: RefusedStep) -> Self {
        Self::new(step.scanner, step.reason)
    }
}

/// A range as a person wrote it: one address when it covers one, and the span
/// otherwise.
fn name(range: &Ipv6Range) -> String {
    match range.start_addr() == range.end_addr() {
        true => range.start_addr().to_string(),
        false => format!("{}-{}", range.start_addr(), range.end_addr()),
    }
}

/// The opening both refusals above share: which range, and how big it is.
///
/// The size is quoted because it is the argument. "Too large" invites the reader
/// to disagree; "18446744073709551616 addresses" does not.
fn describe(range: &Ipv6Range) -> String {
    format!(
        "{}-{} is {} addresses",
        range.start_addr(),
        range.end_addr(),
        range.len()
    )
}

/// One strategy a discovery sweep intends to run.
///
/// Each variant names a way of reaching a target and the targets it was given.
/// Turning one into a running strategy is [`into_scanner`](Self::into_scanner);
/// until then it is inert.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DiscoveryStep {
    /// ARP and ICMPv6 across one interface's own segment, for targets that share
    /// it. The cheapest and most informative of the three: it is the only one
    /// that yields a MAC address, and the only one that can find a neighbour
    /// nobody named.
    Local {
        /// The interface to sweep from.
        interface: Box<Link>,
        /// The addresses on its segment. May be empty for a
        /// [`Scope::Sweep`], whose most important probe is addressed to nobody.
        targets: IpSet,
        /// Whether this sweep may find hosts nobody asked about.
        scope: Scope,
    },
    /// Raw TCP SYN to targets reached through a gateway, each already paired
    /// with the source address the host would route it from.
    Routed {
        /// The destinations, with their source addresses.
        targets: Vec<RoutedTarget>,
    },
    /// Raw SCTP INIT to the same routed targets, for a scan whose ports name
    /// SCTP.
    ///
    /// Runs beside [`Routed`](Self::Routed) rather than instead of it. A host
    /// answers whichever transport reaches it, and one that answers only SCTP is
    /// reported down by a SYN sweep and never has its ports probed at all, since
    /// the port phase covers what discovery found.
    RoutedSctp {
        /// The destinations, with their source addresses.
        targets: Vec<RoutedTarget>,
        /// The port every INIT is aimed at.
        port: u16,
    },
    /// Ordinary TCP connect attempts, for targets with no route and no segment:
    /// loopback, or anything the OS declined to resolve. Needs no privileges.
    Connect {
        /// The addresses to try.
        targets: IpSet,
    },
}

impl DiscoveryStep {
    /// Which strategy this step becomes.
    pub fn kind(&self) -> ScannerKind {
        match self {
            Self::Local { .. } => ScannerKind::Local,
            Self::Routed { .. } => ScannerKind::Routed,
            Self::RoutedSctp { .. } => ScannerKind::RoutedSctp,
            Self::Connect { .. } => ScannerKind::Connect,
        }
    }

    /// How many addresses this step covers.
    ///
    /// Zero is meaningful rather than empty: a [`Scope::Sweep`] step with no
    /// addresses still sends the all-nodes solicitation its whole segment may
    /// answer.
    pub fn target_count(&self) -> u128 {
        match self {
            Self::Local { targets, .. } | Self::Connect { targets } => targets.len(),
            Self::Routed { targets } | Self::RoutedSctp { targets, .. } => targets.len() as u128,
        }
    }

    /// Opens whatever this step needs and hands back the strategy to run.
    ///
    /// This is where the plan stops being free. A local step opens a
    /// link-layer channel on its interface; a routed step opens a raw transport
    /// and a capture. Either can fail on an environment the plan could not see,
    /// and that is a [`StrategyError`] rather than a panic, so a caller can
    /// record it and carry on with the steps that did build.
    ///
    /// `dns_tx` is where a strategy posts addresses worth a reverse lookup;
    /// pass `None` to do no hostname resolution.
    pub fn into_scanner(
        self,
        ctx: ScanContext,
        dns_tx: Option<UnboundedSender<IpAddr>>,
        tuning: ProbeTuning,
    ) -> Result<Box<dyn HostScanner>, StrategyError> {
        match self {
            Self::Local {
                interface,
                targets,
                scope,
            } => Ok(Box::new(LocalScanner::new(
                *interface,
                targets,
                ctx,
                dns_tx,
                scope,
                tuning.retry,
            )?)),
            Self::Routed { targets } => {
                Ok(Box::new(RoutedScanner::new(targets, ctx, dns_tx, tuning)?))
            }
            Self::RoutedSctp { targets, port } => Ok(Box::new(RoutedScanner::over_sctp(
                targets, ctx, dns_tx, tuning, port,
            )?)),
            Self::Connect { targets } => {
                Ok(Box::new(ConnectScanner::new(targets, ctx, &tuning.evasion)))
            }
        }
    }
}

/// What a discovery sweep intends to do.
///
/// Build one with [`build`](Self::build), read it, change it, run it. See the
/// [module documentation](self) for why this is a value rather than a function
/// call.
#[derive(Debug, Clone)]
pub struct DiscoveryPlan {
    steps: Vec<DiscoveryStep>,
    refusals: Vec<RefusedStep>,
    ours: IpSet,
}

impl DiscoveryPlan {
    /// Works out which strategies would cover `targets`, opening nothing.
    ///
    /// `scope` decides whether the sweep may go beyond what it was given.
    /// [`Scope::Sweep`] earns a step for the link even when no address mapped to
    /// it, its all-nodes echo is one packet the whole segment may answer, and
    /// takes candidate addresses from the host's IPv6 neighbour table, which is
    /// the only source the engine has for an IPv6 address nobody named.
    /// [`Scope::Targeted`] does neither: probing addresses nobody asked about is
    /// defensible for `lan` and surprising for `zond <address>`.
    ///
    /// `forced` pins the source addresses off-link targets are probed from,
    /// empty for a scan that let the routing table choose.
    pub fn build(targets: IpSet, scope: Scope, forced: &[IpAddr]) -> Self {
        let mut steps = Vec::new();
        let mut refusals = Vec::new();

        let interface::RoutedTargets {
            mut local,
            routed,
            unmapped,
            ours,
            ambiguous,
            unenumerable,
        } = interface::map_ips_to_interfaces_forced(targets, forced);

        // A link-local target naming no interface. Refused rather than guessed
        // at: every interface has an `fe80::/64`, so probing the first one that
        // matches would scan an arbitrary segment and report the address absent
        // when it is present on another.
        for range in &ambiguous {
            refusals.push(RefusedStep {
                scanner: ScannerKind::Local,
                reason: format!(
                    "{} is link-local, so it names a different machine on every \
                     segment. Say which: {}%<interface>.",
                    range.start_addr(),
                    range.start_addr()
                ),
            });
        }

        // Ranges no strategy can take. A routed IPv6 prefix cannot be walked
        // (see `MAX_ENUMERABLE_ADDRESSES`), and until discovery gains a strategy
        // that searches a scope instead of a list, saying so is the whole of
        // what the engine can honestly do with one.
        for range in &unenumerable {
            refusals.push(RefusedStep::routed_range_not_enumerable(range));
        }

        // A sweep may probe addresses nobody named, so it may also take leads
        // from the host itself. A targeted run may not.
        if matches!(scope, Scope::Sweep) {
            include_swept_link(&mut local);
            seed_from_neighbor_table(&mut local);
        }

        for (interface, mut targets) in local {
            // An on-link range too large to walk is dropped here rather than
            // handed on. `map_ips_to_interfaces` keeps such a range whole,
            // because the strategy for a segment is the all-nodes solicitation
            // and that is one packet whatever the prefix length - but the
            // solicitation is a sweep's, and the walk below it is what a
            // targeted run has. See `local_range_needs_a_sweep`.
            for range in withhold_unwalkable(&mut targets) {
                match scope {
                    // Covered: the sweep sends the one packet the whole segment
                    // answers, so nothing is lost by not walking the prefix.
                    Scope::Sweep => info!(
                        verbosity = 1,
                        "{} is swept by solicitation rather than walked",
                        describe(&range)
                    ),
                    Scope::Targeted => {
                        refusals.push(RefusedStep::local_range_needs_a_sweep(&range))
                    }
                }
            }

            // A sweep's link earns a step whether or not any address mapped to
            // it. A targeted run has nothing to send without targets.
            if targets.is_empty() && matches!(scope, Scope::Targeted) {
                continue;
            }
            steps.push(DiscoveryStep::Local {
                interface: Box::new(interface),
                targets,
                scope,
            });
        }

        if !routed.is_empty() {
            steps.push(DiscoveryStep::Routed { targets: routed });
        }

        if !unmapped.is_empty() {
            steps.push(DiscoveryStep::Connect { targets: unmapped });
        }

        Self {
            steps,
            refusals,
            ours,
        }
    }

    /// Adds an SCTP sweep beside every routed step, asking `port`.
    ///
    /// Apart from [`build`](Self::build) for the reason
    /// [`PortScanPlan::cover_sctp`] is: what decides it is the
    /// port specification, which belongs to the targets and not to the addresses
    /// this plan was built from. A caller that never mentions SCTP sweeps with a
    /// SYN alone and opens no second socket.
    ///
    /// Only the routed steps gain one. A local segment is swept at the link
    /// layer, where ARP and neighbour discovery answer whatever the host speaks
    /// above them, and an unprivileged connect step has no raw socket to send an
    /// INIT through.
    pub fn also_over_sctp(&mut self, port: u16) {
        let sctp: Vec<DiscoveryStep> = self
            .steps
            .iter()
            .filter_map(|step| match step {
                DiscoveryStep::Routed { targets } => Some(DiscoveryStep::RoutedSctp {
                    targets: targets.clone(),
                    port,
                }),
                _ => None,
            })
            .collect();
        self.steps.extend(sctp);
    }

    /// The strategies this plan would run.
    pub fn steps(&self) -> &[DiscoveryStep] {
        &self.steps
    }

    /// The strategies this plan would run, to drop or reorder before running it.
    pub fn steps_mut(&mut self) -> &mut Vec<DiscoveryStep> {
        &mut self.steps
    }

    /// Ground this plan will not cover, and why.
    /// The targets that are this host's own addresses.
    ///
    /// Up by construction and covered by no step, because no strategy can
    /// establish one: the kernel routes traffic for an address this host holds
    /// through loopback, so a probe never reaches the link and nothing on the
    /// link answers for it. Before these were separated, scanning a machine by
    /// its own LAN address reported it down while `ping` to the same address
    /// succeeded.
    ///
    /// A caller running the plan itself records these up rather than probing
    /// them; [`orchestrator`](crate::scanner) does.
    pub fn ours(&self) -> &IpSet {
        &self.ours
    }

    /// Ground this plan will not cover, and why.
    pub fn refusals(&self) -> &[RefusedStep] {
        &self.refusals
    }

    /// Takes the steps out, leaving the plan empty.
    pub fn into_steps(self) -> Vec<DiscoveryStep> {
        self.steps
    }
}

/// One strategy a port scan intends to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PortScanStep {
    /// Raw TCP probes classified from a single exchange, without completing a
    /// handshake. Needs raw sockets.
    RawTcp {
        /// Which flags the probe carries, and so which question it asks.
        technique: TcpScanTechnique,
    },
    /// Raw UDP probes, classified from a direct reply or an ICMP unreachable.
    /// Needs raw sockets.
    RawUdp,
    /// Raw SCTP INIT probes, classified from the chunk that answers. Needs raw
    /// sockets, and has no unprivileged counterpart.
    RawSctp,
    /// A full TCP connect per target. Needs no privileges, and answers roughly
    /// the question a SYN scan asks.
    ConnectTcp,
    /// An unprivileged UDP probe.
    ConnectUdp,
    /// The idle (zombie) TCP scan: port states read off a third party's IP-ID
    /// counter, so the target is never addressed under this host's own address.
    /// Needs the self-built frame a forged source requires.
    Idle {
        /// The zombie whose counter is the side channel.
        zombie: IpAddr,
        /// The port on the zombie to read the counter from, or `None` for the
        /// scanner's default.
        zombie_port: Option<u16>,
    },
}

impl PortScanStep {
    /// Which strategy this step becomes.
    ///
    /// The raw TCP name depends on the technique, because
    /// [`ScannerKind::SynPort`] means a half-open connection attempt was made
    /// and the flag probes make none. [`ScannerKind::for_raw_tcp`] is where
    /// that rule lives, so a step and the scanner it builds cannot disagree.
    pub fn kind(&self) -> ScannerKind {
        match self {
            Self::RawTcp { technique } => ScannerKind::for_raw_tcp(*technique),
            Self::RawUdp => ScannerKind::UdpPort,
            Self::RawSctp => ScannerKind::SctpPort,
            Self::ConnectTcp => ScannerKind::Connect,
            Self::ConnectUdp => ScannerKind::ConnectUdp,
            Self::Idle { .. } => ScannerKind::Idle,
        }
    }

    /// The transport protocol this step probes.
    pub fn protocol(&self) -> Protocol {
        match self {
            Self::RawTcp { .. } | Self::ConnectTcp | Self::Idle { .. } => Protocol::Tcp,
            Self::RawUdp | Self::ConnectUdp => Protocol::Udp,
            Self::RawSctp => Protocol::Sctp,
        }
    }

    /// Whether this step needs raw sockets.
    ///
    /// Asked after a scan is assembled, to decide whether host enrichment is
    /// worth running: ARP, ICMPv6 and raw TCP are what yield a MAC and a round
    /// trip, and the connect fallbacks yield neither.
    ///
    /// A property of the step rather than of its [`kind`](Self::kind), because
    /// the two answer different questions. Read off the name instead, this went
    /// wrong the moment a technique stopped being called `syn_port`.
    pub fn is_raw(&self) -> bool {
        matches!(self, Self::RawTcp { .. } | Self::RawUdp | Self::RawSctp)
    }

    /// Opens whatever this step needs and hands back the strategy to run.
    ///
    /// `target_count` sizes the probe ledger; a raw scanner uses it to reserve
    /// correlation state up front rather than growing it under load.
    ///
    /// `zones` names the interface each of the scan's link-local targets was
    /// given on, which is where both families of scanner get the scope id they
    /// send under. It is empty for a scan that named none.
    pub fn into_scanner(
        self,
        ctx: ScanContext,
        target_count: usize,
        tuning: ProbeTuning,
        zones: ZoneMap,
    ) -> Result<Box<dyn PortScanner>, StrategyError> {
        match self {
            Self::RawTcp { technique } => Ok(Box::new(TcpPortScanner::new(
                interface::SourceResolver::from_system()
                    .with_zones(zones)
                    .with_forced(tuning.send_source.clone()),
                ctx,
                technique,
                target_count,
                tuning,
            )?)),
            Self::RawUdp => Ok(Box::new(UdpPortScanner::new(
                interface::SourceResolver::from_system()
                    .with_zones(zones)
                    .with_forced(tuning.send_source.clone()),
                ctx,
                target_count,
                tuning,
            )?)),
            Self::RawSctp => Ok(Box::new(SctpPortScanner::new(
                interface::SourceResolver::from_system()
                    .with_zones(zones)
                    .with_forced(tuning.send_source.clone()),
                ctx,
                target_count,
                tuning,
            )?)),
            Self::ConnectTcp => Ok(Box::new(
                ConnectPortScanner::new(
                    ctx,
                    limits::CONNECT_CONCURRENCY,
                    tuning.service_detection,
                    &tuning.evasion,
                )
                .with_zones(zones),
            )),
            Self::ConnectUdp => Ok(Box::new(
                ConnectUdpPortScanner::with_detection(
                    ctx,
                    limits::CONNECT_CONCURRENCY,
                    &tuning.evasion,
                    tuning.service_detection,
                )
                .with_zones(zones),
            )),
            Self::Idle {
                zombie,
                zombie_port,
            } => Ok(Box::new(IdlePortScanner::new(
                ctx,
                zombie,
                zombie_port,
                tuning,
            )?)),
        }
    }
}

/// What a port scan intends to do.
#[derive(Debug, Clone)]
pub struct PortScanPlan {
    steps: Vec<PortScanStep>,
    refusals: Vec<RefusedStep>,
    technique: TcpScanTechnique,
}

impl PortScanPlan {
    /// Works out which strategies would probe the requested ports, opening
    /// nothing.
    ///
    /// `privilege` is which sockets the scan would run with. It is a parameter
    /// rather than something read here so a caller can plan for a privilege
    /// level they do not currently hold: asking "what would a root scan do?"
    /// is a reasonable question and needs no root to answer.
    ///
    /// ## The fallback is decided per protocol, not per scan
    ///
    /// A host can be able to build one raw scanner and not the other: the TCP
    /// scanner needs a raw TCP socket, the UDP scanner a raw UDP one, and a
    /// sandbox can permit one and refuse the other. A protocol left with no
    /// strategy at all is not a degraded scan but a silent one: nothing would
    /// route those targets anywhere, so they would never be probed and never be
    /// reported.
    ///
    /// ## A connect fallback substitutes for a SYN scan and for nothing else
    ///
    /// It completes handshakes, so it answers roughly the question a SYN scan
    /// asks. It cannot send a FIN, a flagless segment or a bare ACK, so it
    /// cannot answer what any of those were asked. Where the caller chose one of
    /// those and raw sockets are unavailable, the TCP half is refused and left
    /// undone: worse for the caller, and honest, where a silent substitution
    /// would hand back verdicts from a technique they did not choose with no
    /// field in the report saying so.
    pub fn build(cfg: &ZondConfig, privilege: Privilege) -> Self {
        let mut steps = Vec::new();
        let mut refusals = Vec::new();

        // An idle scan replaces the ordinary port scan wholesale. It is TCP-only
        // by nature, a UDP port has no counter to be read through, and probing
        // one directly would announce the scanner the technique exists to hide,
        // so a UDP target is simply left unprobed, with no step to cover it.
        if let Some(idle) = &cfg.idle_scan {
            if privilege.is_raw() {
                steps.push(PortScanStep::Idle {
                    zombie: idle.zombie,
                    zombie_port: idle.zombie_port,
                });
            } else {
                refusals.push(RefusedStep::idle_needs_privilege());
            }
            return Self {
                steps,
                refusals,
                technique: cfg.tcp_technique,
            };
        }

        // Raw scanning needs both the privilege and an address to probe from.
        let raw = privilege.is_raw() && interface::SourceResolver::from_system().has_sources();
        if privilege.is_raw() && !raw {
            warn!("no usable network interface found; using TCP connect fallback");
        }

        if raw {
            steps.push(PortScanStep::RawTcp {
                technique: cfg.tcp_technique,
            });
            steps.push(PortScanStep::RawUdp);
        } else if cfg.tcp_technique.has_connect_fallback() {
            steps.push(PortScanStep::ConnectTcp);
            steps.push(PortScanStep::ConnectUdp);
        } else {
            refusals.push(RefusedStep::technique_needs_raw_sockets(cfg.tcp_technique));
            steps.push(PortScanStep::ConnectUdp);
        }

        Self {
            steps,
            refusals,
            technique: cfg.tcp_technique,
        }
    }

    /// The TCP technique this plan was built for.
    ///
    /// Kept because it outlives the steps: if a raw step fails to open, whether
    /// a connect scanner may stand in for it depends on which question the
    /// technique asks, and by then the step is gone.
    pub fn technique(&self) -> TcpScanTechnique {
        self.technique
    }

    /// The strategies this plan would run.
    pub fn steps(&self) -> &[PortScanStep] {
        &self.steps
    }

    /// The strategies this plan would run, to drop or reorder before running it.
    pub fn steps_mut(&mut self) -> &mut Vec<PortScanStep> {
        &mut self.steps
    }

    /// Ports this plan will not probe, and why.
    pub fn refusals(&self) -> &[RefusedStep] {
        &self.refusals
    }

    /// Takes the steps out, leaving the plan empty.
    pub fn into_steps(self) -> Vec<PortScanStep> {
        self.steps
    }

    /// Adds the step that probes SCTP, or the refusal that says why it could
    /// not be added.
    ///
    /// Apart from [`build`](Self::build) because what decides it is not in the
    /// configuration. SCTP ports are named in a target's port specification,
    /// which the plan is built before reading, and no default port list holds
    /// one: a scan that never mentions SCTP opens no socket for it, where a step
    /// added unconditionally would cost every privileged run a raw socket and a
    /// capture for a transport nobody asked about.
    ///
    /// Called with the same `privilege` the plan was built for.
    pub fn cover_sctp(&mut self, privilege: Privilege) {
        if self
            .steps
            .iter()
            .any(|step| matches!(step, PortScanStep::Idle { .. }))
        {
            self.refusals.push(RefusedStep::sctp_not_in_an_idle_scan());
            return;
        }

        // The same two conditions raw scanning is planned under in `build`:
        // the privilege, and an address to send from.
        if privilege.is_raw() && interface::SourceResolver::from_system().has_sources() {
            self.steps.push(PortScanStep::RawSctp);
        } else {
            self.refusals.push(RefusedStep::sctp_needs_raw_sockets());
        }
    }

    /// Whether any step covers `protocol`.
    ///
    /// Read after a caller has edited [`steps_mut`](Self::steps_mut): a plan
    /// with nothing for a protocol probes none of its ports and reports none of
    /// them, which is silence rather than a finding.
    pub fn covers(&self, protocol: Protocol) -> bool {
        self.steps.iter().any(|step| step.protocol() == protocol)
    }
}

/// Makes sure the link a sweep is about is among the links to be scanned, even
/// when no address mapped to it.
///
/// Mapping targets to interfaces can only ever produce interfaces some target
/// named, and the whole point of a sweep is the probe that names nobody. A link
/// addressed only in IPv6 resolves to no target list at all, a `/64` cannot be
/// enumerated and there is no IPv4 range to walk, so it maps to nothing, no
/// step is built for it, and the all-nodes echo that would have found its entire
/// segment is never sent. The scan reports an empty network and looks like it
/// worked.
///
/// Matching by name rather than by value: `map_ips_to_interfaces` and this both
/// read the platform's interface list, but a `NetworkInterface` compares on
/// every field, and being wrong here means scanning one link twice.
fn include_swept_link(local: &mut HashMap<Link, IpSet>) {
    let Some(link) = interface::lan_link() else {
        return;
    };

    if local.keys().any(|intf| intf.name() == link.link.name()) {
        return;
    }

    info!(
        verbosity = 1,
        "sweeping {} for IPv6 neighbours; it has no IPv4 range to walk",
        link.link.name()
    );
    local.insert(link.link, IpSet::new());
}

/// Adds the addresses in this host's IPv6 neighbour table to the targets of
/// whichever interface each belongs to.
///
/// This is the only source the engine has for an IPv6 address nobody named. A
/// neighbor solicitation is the mandatory probe, and it can only be aimed at an
/// address someone already holds; the all-nodes echo produces addresses but is
/// optional to answer and draws only link-local ones, since it goes out from a
/// link-local source. The operating system's own table has been accumulating
/// both for as long as the machine has been running, at no cost in packets: on
/// the segment this was written against it holds fifteen global and unique-local
/// addresses the engine could not otherwise learn at all.
///
/// Three exclusions, each for its own reason:
///
/// - **Other interfaces' entries.** A neighbour on `en1` is not reachable
///   through `en0`, and the entry says which it belongs to.
/// - **This host's own addresses.** The table lists them too, and a scan that
///   reported the machine running it as a discovered neighbour would be wrong in
///   a way nobody would think to check.
/// - **Loopback and the unspecified address**, which name nothing on a segment.
///
/// Nothing seeded here is treated as a discovered host. Every entry is an
/// address that answered *once*, from a table that goes stale, so each becomes a
/// probe like any other and earns its place in the report by answering now.
fn seed_from_neighbor_table(local: &mut HashMap<Link, IpSet>) {
    let table = neighbor_cache::ipv6_neighbors();
    if !table.is_empty() {
        seed_from_neighbor_table_with(local, &table);
    }
}

/// [`seed_from_neighbor_table`] against an explicit table, so the exclusions can
/// be tested without a host that happens to have the right neighbours.
fn seed_from_neighbor_table_with(
    local: &mut HashMap<Link, IpSet>,
    table: &[neighbor_cache::Neighbor],
) {
    for (intf, targets) in local.iter_mut() {
        let mut seeded = 0usize;
        for addr in candidates_for(intf, table) {
            let IpAddr::V6(addr) = addr else { continue };
            // The zone matters for exactly the addresses that cannot be probed
            // without one, and is dropped for the rest for the reason
            // `ScopedIp` drops it: the same global address through two
            // interfaces is one address, not two.
            let zone = addr.is_unicast_link_local().then_some(intf.index());
            if let Ok(range) = Ipv6Range::scoped(addr, addr, zone) {
                targets.insert_range(IpRange::V6(range));
                seeded += 1;
            }
        }

        if seeded > 0 {
            targets.canonicalize();
            info!(
                verbosity = 1,
                "took {seeded} IPv6 address(es) from the neighbour table as candidates on {}",
                intf.name()
            );
        }
    }
}

/// The neighbour-table addresses worth probing on `intf`, in table order.
fn candidates_for(link: &Link, table: &[neighbor_cache::Neighbor]) -> Vec<IpAddr> {
    let own: std::collections::HashSet<IpAddr> =
        link.addresses().iter().map(|held| held.address()).collect();

    table
        .iter()
        .filter(|entry| entry.interface_index == link.index())
        .filter(|entry| !own.contains(&entry.ip))
        .filter(|entry| match entry.ip {
            IpAddr::V6(addr) => !addr.is_loopback() && !addr.is_unspecified(),
            IpAddr::V4(_) => false,
        })
        .map(|entry| entry.ip)
        .collect()
}

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

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

    fn v6(addr: &str) -> IpAddr {
        addr.parse().unwrap()
    }

    fn interface_with(index: u32, name: &str, own: Vec<IpAddr>) -> Link {
        use crate::system::interface::LinkAddress;
        Link::new(name, index).with_addresses(
            own.into_iter()
                .map(|ip| LinkAddress::new(ip, if ip.is_ipv4() { 24 } else { 64 }))
                .collect(),
        )
    }

    fn entry(ip: &str, index: u32) -> neighbor_cache::Neighbor {
        neighbor_cache::Neighbor {
            ip: v6(ip),
            mac: None,
            interface_index: index,
        }
    }

    /// An SCTP sweep runs beside each routed step and nowhere else: a segment
    /// is swept at the link layer, where ARP and neighbour discovery answer
    /// whatever the host speaks above them, and a connect step has no raw
    /// socket to send an INIT through.
    #[test]
    fn an_sctp_sweep_is_added_to_the_routed_steps_alone() {
        let mut plan = DiscoveryPlan {
            ours: IpSet::new(),
            steps: vec![
                DiscoveryStep::Routed {
                    targets: vec![RoutedTarget {
                        target: v6("192.0.2.1"),
                        source: v6("192.0.2.9"),
                    }],
                },
                DiscoveryStep::Connect {
                    targets: IpSet::new(),
                },
            ],
            refusals: Vec::new(),
        };

        plan.also_over_sctp(3868);

        let kinds: Vec<ScannerKind> = plan.steps().iter().map(DiscoveryStep::kind).collect();
        assert_eq!(
            kinds,
            vec![
                ScannerKind::Routed,
                ScannerKind::Connect,
                ScannerKind::RoutedSctp
            ]
        );
        assert!(matches!(
            plan.steps().last(),
            Some(DiscoveryStep::RoutedSctp { port: 3868, .. })
        ));
    }

    /// SCTP has no unprivileged form at all, so a scan that named SCTP ports
    /// without raw sockets is told those ports went unprobed rather than being
    /// handed a strategy that asked a different question.
    #[test]
    fn sctp_without_raw_sockets_is_refused_rather_than_substituted() {
        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
        plan.cover_sctp(Privilege::Connect);

        assert!(!plan.covers(Protocol::Sctp));
        assert!(
            plan.refusals()
                .iter()
                .any(|refusal| refusal.scanner == ScannerKind::SctpPort),
            "the sctp ports went unprobed and nothing in the report said so"
        );
    }

    /// An idle scan reads a third party's counter and has no way to carry an
    /// INIT. Sending one directly would leave this host's address on the target,
    /// which is the one thing the technique exists to avoid, so the ports are
    /// refused with that as the reason.
    #[test]
    fn an_idle_scan_refuses_sctp_rather_than_probing_it_directly() {
        let cfg = ZondConfig {
            idle_scan: Some(crate::config::IdleScan::new(v6("192.0.2.9"))),
            ..ZondConfig::default()
        };
        let mut plan = PortScanPlan::build(&cfg, Privilege::Raw);
        plan.cover_sctp(Privilege::Raw);

        assert!(!plan.covers(Protocol::Sctp));
        let refusal = plan
            .refusals()
            .iter()
            .find(|refusal| refusal.scanner == ScannerKind::SctpPort)
            .expect("the sctp ports are accounted for");
        assert!(
            refusal.reason.contains("idle"),
            "the reason names something other than the idle scan: {}",
            refusal.reason
        );
    }

    fn v6_set(cidr: &str) -> IpSet {
        crate::model::parse::ip::to_set(&[cidr], None, None).expect("a range")
    }

    /// A `/64` on the local segment is eighteen quintillion addresses, and the
    /// walk is what a targeted run does with a local range. It is withheld
    /// before a scanner is built from it, because the alternative was measured
    /// and is worse than useless: the count overflows `usize`, the sweep is
    /// budgeted as though it had no targets, and it stops two thousand
    /// solicitations in having reported the prefix covered.
    #[test]
    fn a_local_prefix_too_large_to_walk_is_withheld_from_the_targets() {
        let mut targets = v6_set("2001:db8:1:1::/64");
        assert_eq!(targets.len(), 1u128 << 64, "a /64, kept whole to here");

        let withheld = withhold_unwalkable(&mut targets);

        assert_eq!(withheld.len(), 1, "the prefix is taken out");
        assert!(targets.is_empty(), "and nothing is left to walk");
    }

    /// Asked of a range and not of a set, so a prefix beside three literal
    /// addresses costs the prefix and not the three.
    #[test]
    fn withholding_a_prefix_keeps_the_addresses_named_beside_it() {
        let mut targets = crate::model::parse::ip::to_set(
            &["2001:db8:1:1::/64", "2001:db8:2::1", "192.0.2.7"],
            None,
            None,
        )
        .expect("a mixed set");

        let withheld = withhold_unwalkable(&mut targets);

        assert_eq!(withheld.len(), 1);
        assert_eq!(targets.len(), 2, "the literal and the IPv4 address survive");
    }

    /// A range small enough to walk is left exactly as it was, so the ordinary
    /// case pays nothing.
    #[test]
    fn a_walkable_prefix_is_untouched() {
        let mut targets = v6_set("2001:db8::/120");
        let before = targets.len();

        assert!(withhold_unwalkable(&mut targets).is_empty());
        assert_eq!(targets.len(), before);
    }

    /// The three entries that must never become targets, each wrong in its own
    /// way: another interface's neighbour is not reachable through this one,
    /// this host would be reported as a discovered neighbour of itself, and
    /// loopback names nothing on a segment.
    #[test]
    fn seeding_skips_other_interfaces_our_own_addresses_and_loopback() {
        let own = v6("2001:db8::50");
        let intf = interface_with(7, "en0", vec![own]);
        let table = vec![
            entry("2001:db8::aa", 7),
            entry("fe80::bb", 7),
            entry("2001:db8::cc", 9),
            entry("2001:db8::50", 7),
            entry("::1", 7),
        ];

        let seeded = candidates_for(&intf, &table);

        assert_eq!(seeded, vec![v6("2001:db8::aa"), v6("fe80::bb")]);
    }

    /// A link-local candidate carries the interface it came from, because it
    /// cannot be probed without one. A global address does not, for the reason
    /// `ScopedIp` drops it: the same address through two interfaces is one
    /// address.
    #[test]
    fn a_seeded_link_local_keeps_its_interface_and_a_global_does_not() {
        let intf = interface_with(7, "en0", Vec::new());
        let table = vec![entry("fe80::bb", 7), entry("2001:db8::aa", 7)];
        let mut local = std::collections::HashMap::from([(intf, IpSet::new())]);

        seed_from_neighbor_table_with(&mut local, &table);

        let targets = local.into_values().next().unwrap();
        let zones: Vec<Option<u32>> = targets.v6().iter().map(|range| range.zone()).collect();
        assert!(
            zones.contains(&Some(7)),
            "the link-local needs its interface"
        );
        assert!(
            zones.contains(&None),
            "the global address needs no interface"
        );
    }

    /// An unprivileged plan still covers both protocols. A protocol with no step
    /// is not a degraded scan but a silent one: nothing routes those targets, so
    /// they are never probed and never reported.
    #[test]
    fn an_unprivileged_plan_covers_both_protocols() {
        let plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);

        assert!(plan.covers(Protocol::Tcp));
        assert!(plan.covers(Protocol::Udp));
        assert!(plan.refusals().is_empty());
    }

    /// A connect scan substitutes for a SYN scan and for nothing else. Asked for
    /// a technique it cannot express, an unprivileged plan has to leave the TCP
    /// half out and say why - a silent substitution would promise verdicts from
    /// a technique nobody chose, with no field in the report saying so.
    #[test]
    fn a_technique_the_fallback_cannot_express_is_refused_at_planning_time() {
        let cfg = ZondConfig {
            tcp_technique: TcpScanTechnique::Fin,
            ..ZondConfig::default()
        };
        let plan = PortScanPlan::build(&cfg, Privilege::Connect);

        assert!(
            !plan.covers(Protocol::Tcp),
            "a connect scan cannot send a FIN and must not plan to"
        );
        assert!(plan.covers(Protocol::Udp), "the UDP half is unaffected");

        assert_eq!(plan.refusals().len(), 1, "the caller has to be told");
        assert_eq!(plan.refusals()[0].scanner, ScannerKind::TcpPort);
        assert!(
            plan.refusals()[0].reason.contains("fin"),
            "the refusal has to name the technique: {}",
            plan.refusals()[0].reason
        );
    }

    /// A step and the scanner it becomes have to answer to the same name, or a
    /// failure lands in the report under one strategy and the same scanner's
    /// later failures under another.
    ///
    /// [`ScannerKind::SynPort`] is the one that matters. It is documented to
    /// mean a half-open connection attempt was made, and a plan that called
    /// every raw TCP step by that name attributed a FIN scan's socket failure
    /// to `syn_port` when no SYN was ever sent.
    #[test]
    fn a_step_reports_under_the_same_name_as_the_scanner_it_builds() {
        use crate::scanner::session::ScanSession;
        use crate::scanner::strategy::ports::TcpPortScanner;
        use crate::transport::probe::{Emission, ProbeSender, ProbeTransport, SendError};

        struct Unsendable;
        impl ProbeSender for Unsendable {
            fn send(
                &self,
                _: &[u8],
                _: IpAddr,
                _: IpAddr,
                _: Option<u32>,
                _emission: Emission,
            ) -> Result<(), SendError> {
                Ok(())
            }
        }

        let (_session, ctx) = ScanSession::new();
        for technique in TcpScanTechnique::ALL {
            let (_tx, rx) = tokio::sync::mpsc::channel(1024);
            let scanner = TcpPortScanner::with_transport(
                interface::SourceResolver::from_links(&[]),
                ctx.clone(),
                technique,
                ProbeTransport::from_parts(Box::new(Unsendable), rx),
                1,
            );

            assert_eq!(
                PortScanStep::RawTcp { technique }.kind(),
                scanner.kind(),
                "a {technique} step and its scanner disagree about what to call themselves"
            );
        }
    }

    /// Host enrichment runs beside a raw scan because the raw paths are what
    /// yield a MAC and an RTT. Which technique the raw TCP scanner carries has
    /// no bearing on that, so every one of them has to count as raw.
    #[test]
    fn every_raw_step_is_recognisable_as_one() {
        for technique in TcpScanTechnique::ALL {
            assert!(PortScanStep::RawTcp { technique }.is_raw(), "{technique}");
        }
        assert!(PortScanStep::RawUdp.is_raw());
        assert!(!PortScanStep::ConnectTcp.is_raw());
        assert!(!PortScanStep::ConnectUdp.is_raw());
    }

    /// The technique outlives the steps, because whether a connect scanner may
    /// stand in for a raw one that failed to open is a question asked after the
    /// step is gone.
    #[test]
    fn a_plan_remembers_the_technique_it_was_built_for() {
        let cfg = ZondConfig {
            tcp_technique: TcpScanTechnique::Ack,
            ..ZondConfig::default()
        };
        assert_eq!(
            PortScanPlan::build(&cfg, Privilege::Connect).technique(),
            TcpScanTechnique::Ack
        );
    }

    /// A plan is a value a caller may edit, and editing it changes what would
    /// run. The guard against editing it into silence is `covers`.
    #[test]
    fn dropping_a_step_is_visible_in_what_the_plan_covers() {
        let mut plan = PortScanPlan::build(&ZondConfig::default(), Privilege::Connect);
        plan.steps_mut()
            .retain(|step| step.protocol() != Protocol::Udp);

        assert!(plan.covers(Protocol::Tcp));
        assert!(!plan.covers(Protocol::Udp));
    }
}