zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
// 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

//! # Source Address Selection
//!
//! Answers a single question the raw-socket scanners keep asking: given a
//! destination, which of this host's addresses should a packet to it be sent
//! *from*? For a raw Layer-4 socket the kernel fills in the IP header's
//! source, but it does **not** compute the TCP checksum - so the source we
//! feed into the pseudo-header has to match the one the kernel will route the
//! packet out with, or the target silently drops it.
//!
//! Two access patterns share the machinery here:
//!
//! - **Bulk, up-front** ([`crate::system::interface::map_ips_to_interfaces`]):
//!   thousands of distinct targets classified once, in parallel. Callers match
//!   on-link targets against an [`OnLinkTable`] and ask the kernel about the
//!   rest.
//! - **Streaming, one-at-a-time** (the SYN port scanner): targets trickle in,
//!   with the *same* host revisited across many ports. [`SourceResolver`]
//!   wraps the same primitives behind a per-destination cache so that repeat
//!   is a single lookup rather than a fresh kernel probe each time.

use std::collections::HashMap;
use std::net::{IpAddr, UdpSocket};

use crate::model::ip::scoped::{ScopedIp, ZoneMap};
use crate::system::descriptors;
use crate::system::interface::{Link, LinkAddress};

/// The links usable as a probe source: up, not loopback, and holding at least
/// one assigned address. Centralizes a filter that source selection, interface
/// prioritization, and target routing would otherwise each repeat.
pub(crate) fn viable_interfaces() -> Vec<Link> {
    crate::system::interface::interfaces_or_none()
        .into_iter()
        .filter(|link| link.is_up() && !link.is_loopback() && !link.addresses().is_empty())
        .collect()
}

/// The host's own addresses, ordered most-specific-first so that the longest
/// matching prefix wins.
///
/// A destination on the same segment is reached directly, so its source is
/// simply this host's address on that segment: no kernel round-trip required.
///
/// One list rather than one per family, because a [`LinkAddress`] already knows
/// which family it is and declines a target of the other. Sorting the two
/// together is harmless for the same reason: the order only has to hold *within*
/// a family, and a v6 `/64` sitting between two v4 prefixes is never a candidate
/// for a v4 target to begin with.
pub struct OnLinkTable {
    held: Vec<LinkAddress>,
}

impl OnLinkTable {
    /// Builds the table from every address assigned to `links`.
    pub fn from_links(links: &[Link]) -> Self {
        let mut held: Vec<LinkAddress> = links
            .iter()
            .flat_map(|link| link.addresses().iter().copied())
            .collect();

        held.sort_by_key(|address| std::cmp::Reverse(address.prefix()));

        Self { held }
    }

    /// Returns the source address for `target` if it sits on one of the host's
    /// own subnets, or `None` if it has to be routed off-link.
    ///
    /// A link-local target answers `None`. Every interface holds an
    /// `fe80::/64`, so such a target matches all of them and identifies none,
    /// and the first match would be decided by whatever order the host listed
    /// its interfaces in. [`RoutedTargets::ambiguous`](super::RoutedTargets) is
    /// the same refusal made earlier and with a reason the caller can read.
    ///
    /// A target that named its interface is answered before this table is
    /// consulted, from the interface it named. See
    /// [`SourceResolver::with_zones`](super::SourceResolver::with_zones).
    pub fn source_for(&self, target: IpAddr) -> Option<IpAddr> {
        if ScopedIp::needs_zone(&target) {
            return None;
        }

        self.held
            .iter()
            .find(|held| held.contains(&target))
            .map(LinkAddress::address)
    }

    /// Whether the host has any assigned address to source from at all.
    pub fn is_empty(&self) -> bool {
        self.held.is_empty()
    }

    /// Whether `target` is the network or the broadcast address of an IPv4
    /// segment this host holds, which names the segment rather than a
    /// neighbour on it.
    ///
    /// A kernel refuses a socket to the broadcast address the way it refuses
    /// one to an address a policy keeps out, and some still treat the network
    /// address as a broadcast, so a refusal for either says nothing about a
    /// route. A `/31` and a `/32` have no such addresses.
    pub(crate) fn is_segment_edge(&self, target: IpAddr) -> bool {
        self.held.iter().any(|held| {
            held.contains(&target)
                && held.prefix() < 31
                && match held.network() {
                    crate::model::ip::range::IpRange::V4(range) => {
                        target == IpAddr::V4(range.start_addr())
                            || target == IpAddr::V4(range.end_addr())
                    }
                    crate::model::ip::range::IpRange::V6(_) => false,
                }
        })
    }

    /// The table of this host's segments: the prefixes of its links that
    /// carry frames, where a destination is a neighbour whose hardware address
    /// the kernel resolves before anything is sent to it. A tunnel's prefix
    /// is left out, since nothing on it is resolved.
    pub(crate) fn of_segments() -> Self {
        let framed: Vec<Link> = viable_interfaces()
            .into_iter()
            .filter(Link::carries_frames)
            .collect();
        Self::from_links(&framed)
    }
}

/// Picks an address on `interfaces` that could plausibly reach `target` when
/// the kernel's own route lookup has declined to answer.
///
/// A refusal is not always the truth about reachability. A VPN that claims the
/// IPv6 default route without carrying IPv6 makes every off-link IPv6 lookup
/// fail while the host still holds a global address on a segment with a working
/// router: measured on the machine this was written on, where `connect` to
/// every public resolver returned `No route to host` and the same addresses
/// answered in 22 ms once a source was named explicitly.
///
/// What follows from that is not that the kernel is wrong, but that giving up
/// here is worse than trying, where the kernel said it has no route. A route
/// that refuses by policy is another answer, and this is never asked after
/// one; see [`RouteAnswer::Forbidden`]. A probe sourced from an address the host really
/// holds either reaches the target or does not, and either way the scan reports
/// what it observed. Giving up produces a scan that reports nothing and blames
/// the network.
///
/// Scope-matched, since an address of the wrong scope cannot reach the target
/// whatever the routing table says: a global destination needs a global source.
///
/// A **link-local destination is declined** rather than matched. It would need
/// the link-local address of the interface it is on, and a bare [`IpAddr`]
/// cannot say which interface that is -- so the honest answer is that this
/// function does not know. See
/// [`OnLinkTable::source_for`](OnLinkTable::source_for).
///
/// An **IPv4 address written inside IPv6** is declined as IPv4 itself is. It
/// is an IPv4 host, reached only by a dual-stack socket from an IPv4 source,
/// and a global IPv6 address, the one thing the scope match below offers, is
/// the one source that certainly cannot reach it.
pub(crate) fn plausible_source(links: &[Link], target: IpAddr) -> Option<IpAddr> {
    let IpAddr::V6(target_v6) = target else {
        // IPv4 has no equivalent failure worth second-guessing: there is one
        // scope, and a kernel that cannot route a v4 address is describing a
        // host with no v4 connectivity.
        return None;
    };
    if target_v6.to_ipv4_mapped().is_some() {
        return None;
    }

    // A link-local destination cannot be answered here for the reason
    // `OnLinkTable::source_for` gives: every interface holds one, so any answer
    // is the interface list's order rather than a fact about the target. The
    // scope match below would otherwise pick the first and look deliberate.
    if target_v6.is_unicast_link_local() {
        return None;
    }

    links
        .iter()
        .flat_map(|link| link.ipv6())
        .map(|(addr, _)| addr)
        .find(|addr| !addr.is_unicast_link_local() && !addr.is_loopback())
        .map(IpAddr::V6)
}

/// Asks the kernel which local address it would route a packet to `target`
/// from, by `connect`-ing an unbound UDP socket to it and reading back the
/// address the routing layer selected. No datagram is ever sent - `connect`
/// on a UDP socket only performs the route lookup and binds the local end.
pub fn probe_route_source(target: IpAddr) -> Option<IpAddr> {
    match ask_route(target) {
        RouteAnswer::From(source) => Some(source),
        RouteAnswer::NoRoute
        | RouteAnswer::Forbidden
        | RouteAnswer::Unanswered(_)
        | RouteAnswer::Unasked(_) => None,
    }
}

/// What the kernel's routing table said about one destination.
///
/// Read off the error a UDP `connect` fails with, which is the route lookup's
/// own and never the neighbour's: neither kernel consults the neighbour table
/// on this path. Linux resolves the route in `ip_route_output_flow` and turns
/// a route's type into an error through `fib_props`, and reads no neighbour
/// state before a datagram is sent. XNU picks the source in `in_pcbladdr`,
/// which does not look at the `RTF_REJECT` a failed ARP resolution sets; that
/// flag turns sends away, from `arp_lookup_ip`, and is the sender's to report.
/// So a refusal here is the table's answer about the destination, in one of
/// the few words a table answers in, and anything else is a lookup that did
/// not finish.
#[derive(Debug)]
pub(crate) enum RouteAnswer {
    /// It routes there, from this address.
    From(IpAddr),
    /// It has no route there it can use: `ENETUNREACH` or `EHOSTUNREACH`, or
    /// `EADDRNOTAVAIL` for a route with no address of this host's to send
    /// from.
    ///
    /// What a missing route answers, and what a VPN holding the IPv6 default
    /// route without carrying IPv6 answers too, which is the case
    /// [`plausible_source`] steps around. An `unreachable` route an
    /// administrator added answers the same and cannot be told apart from
    /// here, and so does XNU's refusal of an interface this socket may not
    /// send on.
    NoRoute,
    /// A route there refuses by policy: a `prohibit` route answers `EACCES`
    /// and a `blackhole` route `EINVAL`, where Linux has them, and an IPsec
    /// policy that blocks the destination `EPERM`. No missing or unusable
    /// route answers any of these, so a refusal in these words is a decision
    /// this host's administrator made about the destination, and a scan that
    /// stepped around it by naming a source would be the one program on the
    /// machine that ignored it.
    Forbidden,
    /// The table was asked and gave no answer, in words no route refuses in:
    /// a lookup that ran out of memory or buffers, was interrupted or told to
    /// try again, as Linux tells a socket whose IPsec keys are still being
    /// negotiated, or found the interface down; and any error this does not
    /// know.
    ///
    /// Says nothing about the destination, and is asked again. An error not
    /// named here is read as this rather than as a refusal because the two
    /// mistakes cost differently: a lookup wrongly asked again costs a few
    /// questions and then settles as [`SourceResolver`] settles an
    /// unanswered one, and a refusal wrongly remembered files a live host
    /// unreachable for the rest of the scan.
    Unanswered(std::io::Error),
    /// Nothing was asked: no socket to ask with, which says nothing about the
    /// destination.
    Unasked(std::io::Error),
}

impl RouteAnswer {
    /// What a refused `connect` says of the route, by the error it refused
    /// with. See [`Forbidden`](Self::Forbidden), [`NoRoute`](Self::NoRoute)
    /// and [`Unanswered`](Self::Unanswered).
    fn refused_with(error: std::io::Error) -> Self {
        use std::io::ErrorKind;
        match error.kind() {
            ErrorKind::PermissionDenied | ErrorKind::InvalidInput => Self::Forbidden,
            ErrorKind::NetworkUnreachable
            | ErrorKind::HostUnreachable
            | ErrorKind::AddrNotAvailable => Self::NoRoute,
            _ => Self::Unanswered(error),
        }
    }

    /// What [`ask_route`] answers for a `connect` refused with `code`, for a
    /// test that needs the table to refuse as no host a test runs on does.
    #[cfg(all(test, unix))]
    pub(crate) fn connect_refused(code: i32) -> Self {
        Self::refused_with(std::io::Error::from_raw_os_error(code))
    }
}

/// Asks the kernel how it routes to `target`, keeping its refusal apart from a
/// question that could not be put. See [`probe_route_source`].
///
/// Each question is put on a socket of its own. A socket that has been
/// connected keeps the source its first connect chose on Linux, where
/// `__ip4_datagram_connect` fills the source in only while it is unset, so a
/// second connect is routed from the first answer's address: it answers a
/// target behind another link with an address that link does not hold, and
/// after a question about loopback refuses every routed target with the
/// `EINVAL` a loopback source off the loopback device gets, which reads as a
/// route refusing it by policy. XNU disconnects a datagram socket before
/// connecting it again and has no such memory, but a question that owes
/// nothing to the one before it is the same on both.
pub(crate) fn ask_route(target: IpAddr) -> RouteAnswer {
    let unbound = if target.is_ipv4() {
        "0.0.0.0:0"
    } else {
        "[::]:0"
    };
    let socket = match UdpSocket::bind(unbound) {
        Ok(socket) => socket,
        Err(error) => return RouteAnswer::Unasked(error),
    };
    if let Err(error) = socket.connect((target, 53)) {
        return RouteAnswer::refused_with(error);
    }
    match socket.local_addr() {
        Ok(local) => RouteAnswer::From(local.ip()),
        Err(error) => RouteAnswer::Unasked(error),
    }
}

/// Why [`SourceResolver::source`] has no address to send from.
#[derive(Debug)]
pub(crate) enum NoSource {
    /// No address on this host reaches the destination, or the routing table
    /// refuses it; [`refused_by_route`](SourceResolver::refused_by_route)
    /// says which. A fact about the destination, and the same answer the next
    /// time it is asked.
    Unreached,
    /// This process had no descriptor for the socket the routing table is
    /// asked through, so the table was never asked. A fact about this
    /// machine, which a socket closing elsewhere undoes: said as the shortage
    /// it is, and asked again next time rather than remembered as an address
    /// nothing reaches.
    Unasked(std::io::Error),
    /// The routing table was asked and gave no answer this time; see
    /// [`RouteAnswer::Unanswered`]. A fact about this machine at this
    /// moment, and asked again next time, up to
    /// [`UNANSWERED_LOOKUPS`] times for one destination.
    Unanswered(std::io::Error),
}

/// How many times [`SourceResolver`] asks the routing table about one
/// destination that it has not answered before it settles the destination
/// without the table's answer.
///
/// Each unanswered lookup costs the probe that needed it, which is not sent,
/// so the bound is what a lookup that never succeeds costs a host: two
/// probes, and the third sent on what the table has said, which is nothing.
/// A shortage of memory or buffers passes between one probe and the next,
/// and a table that failed three questions spread across a host's probes is
/// not answering. A refusal is never what runs this out: a route that refuses
/// says so in words [`RouteAnswer`] remembers the first time.
pub(crate) const UNANSWERED_LOOKUPS: u8 = 3;

/// Whether the routing table refuses `target`, a destination on one of this
/// host's own segments.
///
/// A segment this host holds is reached directly, so the table's answer for
/// it is the connected route unless a more specific one overrides it, and
/// every override that refuses is the host's policy: a `prohibit`,
/// `unreachable` or `blackhole` route, or the rules a VPN's kill switch keeps
/// the local network out with. A frame built for the neighbour never asks the
/// table, so asking it here is the only way such a policy is heard. A table
/// that could not be asked, for want of a socket to ask with, or that gave no
/// answer, is not read as a refusal: a policy refuses in its own words, which
/// [`RouteAnswer`] reads.
pub(crate) fn refuses_neighbour(target: IpAddr) -> bool {
    matches!(
        ask_route(target),
        RouteAnswer::NoRoute | RouteAnswer::Forbidden
    )
}

/// Resolves the source address for arbitrary destinations seen one at a time,
/// memoizing each answer. Built for the streaming SYN port scanner, where the
/// same host recurs across every port it probes: the first probe to a host
/// does the work, and every later port reuses the cached result.
///
/// Four sources, in descending order of confidence. A link-local destination the
/// scan scoped to an interface is answered from that interface's own link-local
/// address, which [`with_zones`](Self::with_zones) supplies. Other on-link
/// destinations are answered from an in-memory table of each interface's own
/// subnets. Everything else is put to the kernel, by connecting a UDP socket to
/// the target and reading back the address it chose, which asks the routing
/// table without sending a packet. When the kernel has no route, the last
/// resort is any address on an interface that could plausibly carry the
/// traffic. A source the scan [forced](Self::with_forced) answers between the
/// subnets and the kernel, and a route that refuses by policy is answered by
/// none of them.
pub struct SourceResolver {
    onlink: OnLinkTable,
    /// How the routing table is asked about a destination: [`ask_route`].
    route: fn(IpAddr) -> RouteAnswer,
    /// Whether the routing table is asked about a destination on one of the
    /// segments this resolver holds: for a resolver of this host's, and not
    /// for one built over links it was handed, which are not this host's
    /// table's to refuse.
    asks_on_link: bool,
    /// The destinations the routing table refused. See
    /// [`refused_by_route`](Self::refused_by_route).
    refused: std::collections::HashSet<IpAddr>,
    /// How many lookups of each destination still unsettled the routing
    /// table gave no answer to. See [`UNANSWERED_LOOKUPS`].
    unanswered: HashMap<IpAddr, u8>,
    cache: HashMap<IpAddr, Option<IpAddr>>,
    /// The interfaces themselves, kept for [`plausible_source`]. The
    /// [`OnLinkTable`] cannot answer for it: that table matches a destination
    /// against a prefix, and the case this exists for is a destination on no
    /// prefix this host holds.
    links: Vec<Link>,
    /// The interfaces this scan's link-local targets were named on, empty for a
    /// scan that named none. A prefix match cannot answer for these, since every
    /// interface holds an `fe80::/64`.
    zones: ZoneMap,
    /// Source addresses the caller forced, one per family at most. When set for
    /// a routed target's family, this is the answer, ahead of the routing
    /// table.
    forced: Vec<IpAddr>,
}

impl SourceResolver {
    /// Builds a resolver from the host's current viable interfaces.
    ///
    /// Such a resolver honours the routing table's refusals for destinations
    /// on this host's own segments; see [`resolve`](Self::resolve).
    pub fn from_system() -> Self {
        Self {
            asks_on_link: true,
            ..Self::from_links(&viable_interfaces())
        }
    }

    /// Builds a resolver from an explicit list of links (used in tests).
    pub fn from_links(links: &[Link]) -> Self {
        Self {
            onlink: OnLinkTable::from_links(links),
            route: ask_route,
            asks_on_link: false,
            refused: std::collections::HashSet::new(),
            unanswered: HashMap::new(),
            cache: HashMap::new(),
            links: links.to_vec(),
            zones: ZoneMap::new(),
            forced: Vec::new(),
        }
    }

    /// Teaches the resolver which interface each of a scan's link-local targets
    /// was named on.
    ///
    /// Without this a link-local destination has no source address, since the
    /// prefix it sits in is one every interface holds. With it, the source is the
    /// link-local address of the interface the target named, and
    /// [`zone_of`](Self::zone_of) is the scope id the send needs alongside it.
    pub fn with_zones(mut self, zones: ZoneMap) -> Self {
        self.zones = zones;
        self
    }

    /// Forces the source addresses, one per family, ahead of the routing table
    /// for every target no prefix of this host's holds; see
    /// [`resolve`](Self::resolve).
    pub fn with_forced(mut self, forced: Vec<IpAddr>) -> Self {
        self.forced = forced;
        self
    }

    /// The interface index a destination is valid on, for a scan that named one.
    ///
    /// A raw send carries this as the scope id of its destination. Everything
    /// that identifies its host on its own answers `None` and needs none.
    pub fn zone_of(&self, target: IpAddr) -> Option<u32> {
        self.zones.zone_of(&target)
    }

    /// The link-local address of the interface `target` was named on.
    ///
    /// A link-local source is the only one a link-local destination can be
    /// reached from, and which interface holds it is the whole question a zone
    /// answers.
    fn scoped_source(&self, target: IpAddr) -> Option<IpAddr> {
        let zone = self.zones.zone_of(&target)?;
        self.links
            .iter()
            .find(|link| link.index() == zone)?
            .addresses()
            .iter()
            .map(LinkAddress::address)
            .find(|address| matches!(address, IpAddr::V6(v6) if v6.is_unicast_link_local()))
    }

    /// Whether `target` sits on one of this host's own segments, so a packet
    /// to it is framed to the target itself rather than to a gateway.
    ///
    /// A link-local target the scan named an interface for is on that
    /// interface's segment, which is the only place such an address means
    /// anything.
    pub(crate) fn is_on_link(&self, target: IpAddr) -> bool {
        self.zones.zone_of(&target).is_some() || self.onlink.source_for(target).is_some()
    }

    /// Whether [`resolve`](Self::resolve) found no source for `target`
    /// because the routing table refuses it, rather than because nothing
    /// here reaches it.
    pub(crate) fn refused_by_route(&self, target: IpAddr) -> bool {
        self.refused.contains(&target)
    }

    /// Whether this host has any address to send probes from. When false,
    /// there is no point standing up a raw-socket scanner at all.
    pub fn has_sources(&self) -> bool {
        !self.onlink.is_empty()
    }

    /// The forced source matching `target`'s family, when one was set and
    /// applies to it. This is how [`with_forced`](Self::with_forced) overrides
    /// the routing table: a scan pinned to an interface sends a routed target
    /// from that interface's address rather than the one the kernel would have
    /// picked.
    ///
    /// Only a routed target, as the plan and the scan's connections apply it.
    /// [`resolve`](Self::resolve) asks this after this host's own prefixes,
    /// and loopback, an IPv4 address written inside IPv6, and a link-local
    /// address are no link's to be pinned to: the first two are the kernel's,
    /// and the third is on the link its zone names or on none.
    fn forced_source(&self, target: IpAddr) -> Option<IpAddr> {
        let no_link = target.is_loopback()
            || matches!(target, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some()
                || v6.is_unicast_link_local());
        if no_link {
            return None;
        }
        self.forced
            .iter()
            .copied()
            .find(|source| source.is_ipv4() == target.is_ipv4())
    }

    /// Returns the source address to send a probe to `target` from, or `None`
    /// if no address on this host could plausibly reach it.
    ///
    /// Five answers in order of authority: the interface a link-local target
    /// named, this host's own segments and tunnel prefixes, a forced source,
    /// the kernel's routing table, then `plausible_source` for the case where
    /// the kernel refuses but the host visibly holds an address of the right
    /// scope.
    ///
    /// The same order the scan's plan classifies in and its connections leave
    /// by. A target inside a prefix this host holds has one link that reaches
    /// it, which a forced source must not move it off; a forced source placed
    /// ahead would send its probes out by another link while the plan and
    /// every connection to it went by its own.
    ///
    /// A target on one of this host's segments that the routing table
    /// refuses has no source, whatever the segment says. A probe to it would
    /// be framed to the neighbour, or sent by a socket held to the link,
    /// neither of which asks the table, and would reach a host the machine's
    /// own policy keeps it from: the one scanner on the box that ignored a
    /// route its administrator added, found out by the probes arriving. A
    /// segment this host holds is reached directly, so the table's answer for
    /// it is the connected route unless a more specific one overrides it, and
    /// every override that refuses is the host's policy: a `prohibit`,
    /// `unreachable` or `blackhole` route, or the rules a VPN's kill switch
    /// keeps the local network out with. The table is asked by connecting a
    /// UDP socket, as for a routed target.
    ///
    /// A routed target whose route refuses by policy has no source either,
    /// forced or fallen back on. Both send by a socket held to an address,
    /// which the kernel sends from wherever the table refuses, and a routed
    /// target's refusal can be the kernel's own absence of a route as well as
    /// a policy, so only the policy's words decline it: the permission denied
    /// of a `prohibit` route and the invalid argument of a `blackhole` one,
    /// where Linux has them.
    pub fn resolve(&mut self, target: IpAddr) -> Option<IpAddr> {
        self.source(target).ok()
    }

    /// [`resolve`](Self::resolve), saying why there is no source.
    ///
    /// A lookup this process had no descriptor for is not remembered, and
    /// the next asks the table afresh; see [`NoSource::Unasked`]. Nor is one
    /// the table gave no answer to, up to [`UNANSWERED_LOOKUPS`] of them;
    /// see [`NoSource::Unanswered`]. Everything else is remembered for the
    /// life of the resolver.
    pub(crate) fn source(&mut self, target: IpAddr) -> Result<IpAddr, NoSource> {
        if let Some(cached) = self.cache.get(&target) {
            return cached.ok_or(NoSource::Unreached);
        }

        let source = self.find(target);
        let settled = match &source {
            Ok(address) => Some(*address),
            Err(NoSource::Unreached) => None,
            Err(NoSource::Unasked(_) | NoSource::Unanswered(_)) => return source,
        };
        self.cache.insert(target, settled);
        self.unanswered.remove(&target);
        source
    }

    /// Counts a lookup of `target` the routing table gave no answer to, and
    /// says whether to ask again: [`NoSource::Unanswered`] while the
    /// destination has had fewer than [`UNANSWERED_LOOKUPS`], and `Ok` once
    /// it has had that many, for the caller to settle it on what the table
    /// has said, which is nothing.
    fn unanswered(&mut self, target: IpAddr, error: std::io::Error) -> Result<(), NoSource> {
        let count = self.unanswered.entry(target).or_default();
        *count += 1;
        if *count < UNANSWERED_LOOKUPS {
            return Err(NoSource::Unanswered(error));
        }
        crate::info!(verbosity = 2, "{target} route lookup unanswered ({error})");
        Ok(())
    }

    /// [`source`](Self::source), asked afresh.
    ///
    /// A table this process could not ask about a target on its own segment
    /// is not read as one that allows it: the question is what keeps the
    /// probes from a neighbour the host's policy refuses, and it is put again
    /// once a descriptor is free rather than skipped.
    ///
    /// Nor is a table that gave no answer, or a socket to ask it with that
    /// could not be made for a reason other than the file limit, until it
    /// has done so [`UNANSWERED_LOOKUPS`] times. The destination is then
    /// settled on what the table has said, which is nothing: a target on
    /// this host's segment is sent from the segment, since a policy that
    /// refuses it says so in its own words the first time it is asked, and a
    /// routed target is given what a target the table has no route to is
    /// given, a forced source or the fallback, or none.
    fn find(&mut self, target: IpAddr) -> Result<IpAddr, NoSource> {
        if let Some(scoped) = self.scoped_source(target) {
            return Ok(scoped);
        }
        if let Some(on_link) = self.onlink.source_for(target) {
            if !self.asks_on_link {
                return Ok(on_link);
            }
            return match (self.route)(target) {
                RouteAnswer::NoRoute | RouteAnswer::Forbidden => {
                    // Unreached all the same, but not named refused by a
                    // route: the kernel refuses a segment's broadcast address
                    // on grounds of its own.
                    if !self.onlink.is_segment_edge(target) {
                        self.refused.insert(target);
                    }
                    Err(NoSource::Unreached)
                }
                RouteAnswer::Unasked(error) if descriptors::exhausted(&error) => {
                    Err(NoSource::Unasked(error))
                }
                RouteAnswer::Unasked(error) | RouteAnswer::Unanswered(error) => {
                    self.unanswered(target, error).map(|()| on_link)
                }
                RouteAnswer::From(_) => Ok(on_link),
            };
        }

        let routed = match (self.route)(target) {
            RouteAnswer::From(source) => Some(source),
            RouteAnswer::NoRoute => None,
            RouteAnswer::Forbidden => {
                // The limited broadcast address is refused as a segment's
                // is, which says nothing about a route.
                if !matches!(target, IpAddr::V4(v4) if v4.is_broadcast()) {
                    self.refused.insert(target);
                }
                return Err(NoSource::Unreached);
            }
            RouteAnswer::Unasked(error) if descriptors::exhausted(&error) => {
                return Err(NoSource::Unasked(error));
            }
            RouteAnswer::Unasked(error) | RouteAnswer::Unanswered(error) => {
                self.unanswered(target, error)?;
                None
            }
        };
        if let Some(forced) = self.forced_source(target) {
            return Ok(forced);
        }
        routed
            .or_else(|| plausible_source(&self.links, target))
            .ok_or(NoSource::Unreached)
    }

    /// This resolver, asking the routing table through `route` about every
    /// destination a resolver of this host's asks about, for a test that
    /// needs the table to answer as no host a test runs on does.
    #[cfg(all(test, unix))]
    pub(crate) fn asking_with(mut self, route: fn(IpAddr) -> RouteAnswer) -> Self {
        self.route = route;
        self.asks_on_link = true;
        self
    }
}

// โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
// โ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ•‘
// โ•‘ โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• โ•‘
// โ•‘    โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—  โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ•‘
// โ•‘    โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•”โ•โ•โ•  โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ•šโ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ•‘
// โ•‘    โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ•‘   โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•‘ โ•‘
// โ•‘    โ•šโ•โ•   โ•šโ•โ•โ•โ•โ•โ•โ•โ•šโ•โ•โ•โ•โ•โ•โ•   โ•šโ•โ•   โ•šโ•โ•โ•โ•โ•โ•โ• โ•‘
// โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

#[cfg(test)]
mod tests {

    /// The same address, with the interface named. The source is that
    /// interface's own link-local address, which is the only one a link-local
    /// destination can be reached from.
    #[test]
    fn a_link_local_target_that_named_an_interface_is_sourced_from_it() {
        use crate::model::ip::range::Ipv6Range;
        use crate::model::ip::scoped::ZoneMap;

        let mine = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xa);
        let en1 = Link::new("en1", 15).with_addresses(vec![v6net(mine, 64)]);
        let elsewhere = Link::new("en0", 16).with_addresses(vec![v6net(
            Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xb),
            64,
        )]);

        let target = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x99);
        let mut zones = ZoneMap::new();
        zones.insert(
            Ipv6Range::scoped(target, target, Some(15)).expect("a scoped range"),
            &[(15, "en1")],
        );

        let mut resolver = SourceResolver::from_links(&[elsewhere, en1]).with_zones(zones);

        assert_eq!(
            resolver.resolve(IpAddr::V6(target)),
            Some(IpAddr::V6(mine)),
            "the interface named, not whichever was listed first"
        );
        assert_eq!(
            resolver.zone_of(IpAddr::V6(target)),
            Some(15),
            "and the scope id the send has to carry"
        );
    }

    /// The defect this guard exists for, and the shape of it: every interface
    /// holds an `fe80::/64`, so a bare link-local target matched whichever one
    /// the host happened to list first. Measured before the fix: the same
    /// target answered `fe80::a` or `fe80::b` depending only on the order the
    /// links arrived in.
    #[test]
    fn a_bare_link_local_target_has_no_source_rather_than_an_arbitrary_one() {
        let en0 = mock_interface(vec![v6net(
            Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xa),
            64,
        )]);
        let en1 = mock_interface(vec![v6net(
            Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xb),
            64,
        )]);
        let target = IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x99));

        assert_eq!(
            OnLinkTable::from_links(&[en0.clone(), en1.clone()]).source_for(target),
            None
        );
        assert_eq!(
            OnLinkTable::from_links(&[en1, en0]).source_for(target),
            None,
            "and the answer does not depend on the order, because there is none"
        );
    }

    /// The fallback made the same guess, so it declines the same case. A global
    /// destination is still answered, which is what the fallback is for.
    #[test]
    fn the_fallback_declines_a_link_local_and_still_answers_a_global() {
        let links = [mock_interface(vec![
            v6net(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xa), 64),
            v6net(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 5), 64),
        ])];

        assert_eq!(
            plausible_source(
                &links,
                IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x99))
            ),
            None
        );
        assert_eq!(
            plausible_source(
                &links,
                IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 9, 0, 0, 0, 0, 1))
            ),
            Some(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 5))),
            "a global target still gets the global address the host holds"
        );
    }

    /// An ordinary on-link target is untouched: the guard is about one family
    /// of address and must not cost the rest anything.
    #[test]
    fn an_on_link_target_still_resolves_to_its_own_segment() {
        let table = OnLinkTable::from_links(&[mock_interface(vec![v4net(192, 0, 2, 10, 24)])]);

        assert_eq!(
            table.source_for(IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 50))),
            Some(IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 10)))
        );
        assert_eq!(
            table.source_for(IpAddr::V4(std::net::Ipv4Addr::new(198, 51, 100, 1))),
            None
        );
    }

    /// A target on this host's own segment that the routing table refuses has
    /// no source, and says why, while its neighbours on the segment keep
    /// theirs.
    ///
    /// A `prohibit`, `unreachable` or `blackhole` host route over an address
    /// on a connected segment is the host's own policy. A probe framed to the
    /// neighbour, or sent by a socket held to the link, never asks the table,
    /// so without this the one program on the box that ignored the route
    /// would be the scanner, found out by its probes arriving.
    #[test]
    fn a_target_on_link_the_routing_table_refuses_has_no_source() {
        let refused = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 13));
        let neighbour = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 14));
        let mut resolver = SourceResolver {
            route: |target| match target == IpAddr::V4(Ipv4Addr::new(192, 0, 2, 13)) {
                true => RouteAnswer::NoRoute,
                false => RouteAnswer::From(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10))),
            },
            asks_on_link: true,
            ..SourceResolver::from_links(&[mock_interface(vec![v4net(192, 0, 2, 10, 24)])])
        };

        assert_eq!(resolver.resolve(refused), None);
        assert!(resolver.refused_by_route(refused), "and says why");
        assert_eq!(
            resolver.resolve(neighbour),
            Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10)))
        );
        assert!(!resolver.refused_by_route(neighbour));
    }

    /// The table is asked, and an address it routes is not refused. Loopback
    /// is routed on every host a test runs on, and the one refusal a test
    /// could build takes privileges; that half is Tier 3's.
    #[test]
    fn an_address_the_kernel_routes_is_not_refused() {
        assert!(matches!(
            ask_route(IpAddr::V4(Ipv4Addr::LOCALHOST)),
            RouteAnswer::From(_)
        ));
    }

    /// A question about a route is answered as it would be were it the first
    /// one asked. A socket connected once keeps the source it was given on
    /// Linux, so asked through one, a question after loopback's was routed
    /// from `127.0.0.1` and refused with `EINVAL`, which reads as a route
    /// refusing the target by policy, and a target behind a second link was
    /// answered with the first link's address. On a host a test runs on with
    /// no route to the documentation range, both answers are the same
    /// refusal, and the test says nothing.
    #[test]
    fn a_route_question_is_answered_whatever_was_asked_before_it() {
        let routed = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
        let alone = format!("{:?}", ask_route(routed));

        assert!(matches!(
            ask_route(IpAddr::V4(Ipv4Addr::LOCALHOST)),
            RouteAnswer::From(_)
        ));
        assert_eq!(format!("{:?}", ask_route(routed)), alone);
    }

    /// A routed target whose route refuses by policy has no source, and the
    /// fallback that steps around a missing route does not step around it:
    /// a `prohibit` route over an off-link IPv6 address was probed through a
    /// socket held to the global address, the one program on the box that
    /// ignored the route. A missing route still gets the fallback, which is
    /// the case the fallback is for.
    #[test]
    fn a_routed_target_a_route_forbids_is_given_no_fallback() {
        let global = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0xb1a0);
        let links = [mock_interface(vec![v6net(global, 64)])];
        let target = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 9, 0, 0, 0, 0, 1));

        let mut forbidden = SourceResolver {
            route: |_| RouteAnswer::Forbidden,
            ..SourceResolver::from_links(&links)
        };
        assert_eq!(forbidden.resolve(target), None);
        assert!(forbidden.refused_by_route(target), "and says why");

        let mut missing = SourceResolver {
            route: |_| RouteAnswer::NoRoute,
            ..SourceResolver::from_links(&links)
        };
        assert_eq!(missing.resolve(target), Some(IpAddr::V6(global)));
        assert!(!missing.refused_by_route(target));
    }

    /// Nor does a forced source step around it: a scan pinned to an interface
    /// chose which link its probes leave by, not which of this host's routes
    /// they may ignore.
    #[test]
    fn a_forced_source_does_not_answer_for_a_target_a_route_forbids() {
        let lan = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50));
        let mut resolver = SourceResolver {
            route: |_| RouteAnswer::Forbidden,
            ..SourceResolver::from_links(&[mock_interface(vec![v4net(192, 0, 2, 50, 24)])])
                .with_forced(vec![lan])
        };
        let target = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1));
        assert_eq!(resolver.resolve(target), None);
        assert!(resolver.refused_by_route(target));
    }

    /// A segment's broadcast and network addresses, and the limited broadcast
    /// address, are refused a source as a neighbour a route refuses is, since
    /// the kernel refuses them too, and are not named refused by a route: a
    /// kernel refuses a socket to a broadcast address on grounds of its own,
    /// and a scan of a `/24` would otherwise name its two edges as addresses
    /// a route on this machine keeps out.
    #[test]
    fn a_segment_s_edges_are_unreached_without_being_named_refused_by_a_route() {
        let mut resolver = SourceResolver {
            route: |_| RouteAnswer::Forbidden,
            asks_on_link: true,
            ..SourceResolver::from_links(&[mock_interface(vec![v4net(192, 0, 2, 10, 24)])])
        };
        for edge in [
            Ipv4Addr::new(192, 0, 2, 0),
            Ipv4Addr::new(192, 0, 2, 255),
            Ipv4Addr::BROADCAST,
        ] {
            assert_eq!(resolver.resolve(IpAddr::V4(edge)), None, "{edge}");
            assert!(!resolver.refused_by_route(IpAddr::V4(edge)), "{edge}");
        }
        let neighbour = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 13));
        assert_eq!(resolver.resolve(neighbour), None);
        assert!(resolver.refused_by_route(neighbour));
    }

    /// A routing table this process had no descriptor to ask is a shortage
    /// said as one, and asked again next time: remembered as a target with
    /// no source, a moment's full table would file a live host unreachable
    /// for the rest of the scan. A target on this host's own segment is not
    /// given its segment's source unasked either, since the question is what
    /// keeps its probes from a neighbour the host's policy refuses.
    #[cfg(unix)]
    #[test]
    fn a_route_asked_without_a_descriptor_is_a_shortage_asked_again() {
        let global = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0xb1a0);
        let short =
            |_: IpAddr| RouteAnswer::Unasked(std::io::Error::from_raw_os_error(libc::EMFILE));
        let routed = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 9, 0, 0, 0, 0, 1));
        let mut resolver = SourceResolver::from_links(&[mock_interface(vec![v6net(global, 64)])])
            .asking_with(short);

        assert!(matches!(
            resolver.source(routed),
            Err(NoSource::Unasked(e)) if descriptors::exhausted(&e)
        ));
        assert!(!resolver.refused_by_route(routed));

        resolver.route = |_| {
            RouteAnswer::From(IpAddr::V6(Ipv6Addr::new(
                0x2001, 0xdb8, 0, 0, 0, 0, 0, 0xb1a0,
            )))
        };
        assert_eq!(
            resolver.resolve(routed),
            Some(IpAddr::V6(global)),
            "the next lookup asks again"
        );

        let neighbour = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 14));
        let mut on_link = SourceResolver {
            asks_on_link: true,
            ..SourceResolver::from_links(&[mock_interface(vec![v4net(192, 0, 2, 10, 24)])])
                .asking_with(short)
        };
        assert!(matches!(
            on_link.source(neighbour),
            Err(NoSource::Unasked(_))
        ));
    }

    /// A policy route is told from a missing one by the words the kernel
    /// refuses in: `prohibit` answers `EACCES`, `blackhole` `EINVAL` and a
    /// blocking IPsec policy `EPERM`, and a missing or `unreachable` route
    /// `ENETUNREACH` or `EHOSTUNREACH`, or `EADDRNOTAVAIL` where it leaves no
    /// address to send from. Every other word is a lookup that did not
    /// finish, which says nothing of the destination: read as a missing
    /// route, one `ENOBUFS` filed a live neighbour unreachable for a whole
    /// scan.
    #[cfg(unix)]
    #[test]
    fn a_refused_lookup_is_read_as_a_policy_a_missing_route_or_no_answer() {
        for code in [libc::EACCES, libc::EPERM, libc::EINVAL] {
            assert!(
                matches!(RouteAnswer::connect_refused(code), RouteAnswer::Forbidden),
                "{code}"
            );
        }
        for code in [libc::ENETUNREACH, libc::EHOSTUNREACH, libc::EADDRNOTAVAIL] {
            assert!(
                matches!(RouteAnswer::connect_refused(code), RouteAnswer::NoRoute),
                "{code}"
            );
        }
        for code in [
            libc::ENOBUFS,
            libc::ENOMEM,
            libc::EAGAIN,
            libc::EINTR,
            libc::EHOSTDOWN,
            libc::ENETDOWN,
            libc::EPROTO,
        ] {
            assert!(
                matches!(
                    RouteAnswer::connect_refused(code),
                    RouteAnswer::Unanswered(_)
                ),
                "{code}"
            );
        }
    }

    /// A lookup the routing table gave no answer to is asked again, for a
    /// neighbour on this host's segment and for a routed target alike, and
    /// the host is not named refused by a route. Remembered as a refusal, a
    /// moment's shortage of buffers filed a live neighbour unreachable for
    /// the rest of the scan, every port of it unasked.
    #[cfg(unix)]
    #[test]
    fn a_lookup_the_routing_table_did_not_answer_is_asked_again() {
        let neighbour = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 14));
        let routed = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1));
        let mut resolver = SourceResolver {
            route: |_| RouteAnswer::connect_refused(libc::ENOBUFS),
            asks_on_link: true,
            ..SourceResolver::from_links(&[mock_interface(vec![v4net(192, 0, 2, 10, 24)])])
        };

        for target in [neighbour, routed] {
            assert_eq!(resolver.resolve(target), None, "{target}");
            assert!(!resolver.refused_by_route(target), "{target}");
        }

        resolver.route = |_| RouteAnswer::From(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10)));
        for target in [neighbour, routed] {
            assert_eq!(
                resolver.resolve(target),
                Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10))),
                "the next lookup of {target} asks again"
            );
        }
    }

    /// A table that never answers is asked a bounded number of times, and
    /// the destination is then settled on what it has said, which is
    /// nothing: a neighbour is sent from its segment, since a policy refuses
    /// in its own words the first time, and a routed target with no route
    /// has no source. Neither is named refused by a route, and neither is
    /// asked about again, so a lookup that never succeeds costs a host a
    /// few probes rather than one question per probe for the whole scan.
    #[cfg(unix)]
    #[test]
    fn a_lookup_the_table_never_answers_is_settled_after_a_few_asks() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static ASKED: AtomicUsize = AtomicUsize::new(0);

        let segment = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
        let mut resolver = SourceResolver {
            route: |_| {
                ASKED.fetch_add(1, Ordering::SeqCst);
                RouteAnswer::connect_refused(libc::ENOBUFS)
            },
            asks_on_link: true,
            ..SourceResolver::from_links(&[mock_interface(vec![v4net(192, 0, 2, 10, 24)])])
        };
        let asks = usize::from(UNANSWERED_LOOKUPS);

        for (target, settled) in [
            (IpAddr::V4(Ipv4Addr::new(192, 0, 2, 14)), Some(segment)),
            (IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1)), None),
        ] {
            ASKED.store(0, Ordering::SeqCst);
            for _ in 1..asks {
                assert!(matches!(
                    resolver.source(target),
                    Err(NoSource::Unanswered(_))
                ));
            }
            assert_eq!(resolver.resolve(target), settled, "{target}");
            assert_eq!(resolver.resolve(target), settled, "{target}");
            assert_eq!(ASKED.load(Ordering::SeqCst), asks, "{target}");
            assert!(!resolver.refused_by_route(target), "{target}");
        }
    }

    /// A link-local written with its interface is not this case at all: it
    /// carries the answer, and the sweep that reaches it is the local one.
    #[test]
    fn a_zoned_link_local_is_not_what_this_declines() {
        use crate::model::ip::scoped::ScopedIp;
        let bare: IpAddr = "fe80::1".parse().expect("literal");
        assert!(ScopedIp::needs_zone(&bare), "bare is the case declined");

        let global: IpAddr = "2001:db8::1".parse().expect("literal");
        assert!(!ScopedIp::needs_zone(&global));
    }

    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr};

    fn mock_interface(nets: Vec<LinkAddress>) -> Link {
        Link::new("test0", 0).with_addresses(nets)
    }

    fn v4net(a: u8, b: u8, c: u8, d: u8, prefix: u8) -> LinkAddress {
        LinkAddress::new(IpAddr::V4(Ipv4Addr::new(a, b, c, d)), prefix)
    }

    #[test]
    fn on_link_target_uses_that_subnet_source() {
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24)]);
        let table = OnLinkTable::from_links(&[intf]);

        assert_eq!(
            table.source_for(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 200))),
            Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50)))
        );
    }

    #[test]
    fn off_link_target_has_no_on_link_source() {
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24)]);
        let table = OnLinkTable::from_links(&[intf]);

        assert_eq!(
            table.source_for(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))),
            None
        );
    }

    #[test]
    fn longest_prefix_wins() {
        let intf = mock_interface(vec![
            v4net(198, 51, 100, 1, 24),
            v4net(198, 51, 100, 130, 25),
        ]);
        let table = OnLinkTable::from_links(&[intf]);

        assert_eq!(
            table.source_for(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 200))),
            Some(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 130)))
        );
    }

    #[test]
    fn v6_and_v4_are_kept_separate() {
        // A global prefix rather than a link-local one: this is about the two
        // families not matching each other, and a link-local target is declined
        // for a different reason that would mask what is being tested.
        let v6 = v6net(Ipv6Addr::new(0x2001, 0xdb8, 0, 1, 0, 0, 0, 1), 64);
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24), v6]);
        let table = OnLinkTable::from_links(&[intf]);

        assert_eq!(
            table.source_for(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 1, 0, 0, 0, 99))),
            Some(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 1, 0, 0, 0, 1)))
        );
        assert_eq!(
            table.source_for(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 9, 0, 0, 0, 1))),
            None,
            "a prefix the host does not hold is not on-link"
        );
    }

    #[test]
    fn resolver_caches_and_reports_sources() {
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24)]);
        let mut resolver = SourceResolver::from_links(&[intf]);

        assert!(resolver.has_sources());
        let target = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 200));
        assert_eq!(
            resolver.resolve(target),
            Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50)))
        );
        assert_eq!(
            resolver.resolve(target),
            Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50)))
        );
    }

    #[test]
    fn empty_host_has_no_sources() {
        let resolver = SourceResolver::from_links(&[]);
        assert!(!resolver.has_sources());
    }

    /// A forced source answers a routed target ahead of the routing table, the
    /// override a scan pinned to an interface needs. It picks by family, so the
    /// IPv4 force answers the IPv4 target even listed behind the IPv6 one, and
    /// the kernel is never consulted.
    #[test]
    fn a_forced_source_answers_a_routed_target_by_family() {
        let v4 = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50));
        let v6 = IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 1));
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24)]);
        let mut resolver = SourceResolver::from_links(&[intf]).with_forced(vec![v6, v4]);

        let public = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1));
        assert_eq!(resolver.resolve(public), Some(v4));
    }

    /// A forced source is for a target the routing table would send out by the
    /// wrong link, and a target inside a prefix this host holds has one link
    /// that reaches it: a neighbour on another segment by that segment, a peer
    /// inside a tunnel's own prefix through the tunnel. The plan and every
    /// connection to such a target leave by its own link; a raw probe sourced
    /// from the forced LAN address would leave by the LAN, reach nothing the
    /// plan expected, and report a host the rest of the scan reached as silent.
    #[test]
    fn a_forced_source_leaves_a_target_inside_a_held_prefix_to_its_own_link() {
        use crate::system::interface::Addressing;

        let lan = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50));
        let tunnel_address = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2));
        let other_segment = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7));
        let links = [
            Link::new("en0", 4).with_addresses(vec![v4net(192, 0, 2, 50, 24)]),
            Link::new("en1", 5).with_addresses(vec![v4net(203, 0, 113, 7, 24)]),
            Link::new("utun9", 20)
                .with_addressing(Addressing::PointToPoint)
                .with_addresses(vec![v4net(198, 51, 100, 2, 24)]),
        ];
        let mut resolver = SourceResolver::from_links(&links).with_forced(vec![lan]);

        assert_eq!(
            resolver.resolve(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))),
            Some(tunnel_address),
            "a peer inside the tunnel's prefix is reached through the tunnel"
        );
        assert_eq!(
            resolver.resolve(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 9))),
            Some(other_segment),
            "a neighbour on another segment is reached on that segment"
        );
        assert_eq!(
            resolver.resolve(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9))),
            Some(lan),
            "and a neighbour on the forced source's own segment from it"
        );
    }

    /// Loopback and an IPv4 address written inside IPv6 are no link's, so the
    /// plan leaves them to the kernel whatever is forced, and so does this.
    #[test]
    fn a_forced_source_does_not_answer_for_loopback_or_a_mapped_address() {
        let lan = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 50));
        let global = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x50));
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24)]);
        let mut resolver = SourceResolver::from_links(&[intf]).with_forced(vec![lan, global]);

        for target in [
            IpAddr::V4(Ipv4Addr::LOCALHOST),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
            IpAddr::V6(Ipv4Addr::new(203, 0, 113, 1).to_ipv6_mapped()),
        ] {
            let source = resolver.resolve(target);
            assert!(
                source != Some(lan) && source != Some(global),
                "{target} was sourced from the forced {source:?}"
            );
        }
    }

    fn v6net(addr: Ipv6Addr, prefix: u8) -> LinkAddress {
        LinkAddress::new(IpAddr::V6(addr), prefix)
    }

    /// The ยง1.6 case: the kernel refuses to route an off-link IPv6 target - a
    /// VPN holding the default route without carrying IPv6 - while the host
    /// plainly has a global address to send from.
    ///
    /// Answering `None` here is what made a scan of seven live addresses report
    /// zero hosts in two milliseconds, having sent nothing. The address chosen
    /// may not work, and the scan will say so; refusing to try cannot.
    #[test]
    fn a_global_target_the_kernel_will_not_route_still_gets_a_global_source() {
        let global = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0xb1a0);
        let intf = mock_interface(vec![
            v6net(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x50), 64),
            v6net(global, 64),
        ]);

        let source = plausible_source(
            std::slice::from_ref(&intf),
            IpAddr::V6(Ipv6Addr::new(0x2606, 0x4700, 0x4700, 0, 0, 0, 0, 0x1111)),
        );

        assert_eq!(source, Some(IpAddr::V6(global)));
    }

    /// Scope is not negotiable in the other direction either: a link-local
    /// destination is reachable only from a link-local address, so a global one
    /// must not be offered for it.
    ///
    /// Nor may a link-local one be. The property above is real, but it does not
    /// establish *which* link-local address, and on a fixture with one
    /// interface there is only one to pick. Every interface holds an
    /// `fe80::/64`, so on a real host the answer would be whichever the platform
    /// listed first: a guess with the shape of an answer, and the one
    /// [`RoutedTargets::ambiguous`](super::RoutedTargets) names as exactly the
    /// mistake.
    #[test]
    fn a_link_local_target_is_offered_no_source_at_all() {
        let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x50);
        let intf = mock_interface(vec![
            v6net(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 64),
            v6net(link_local, 64),
        ]);

        let source = plausible_source(
            std::slice::from_ref(&intf),
            IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xAA)),
        );

        assert_eq!(
            source, None,
            "a global was never offered, and now nor is a guess"
        );
    }

    /// An IPv4 address written inside IPv6 is an IPv4 host, and a global IPv6
    /// source can never reach it. Offered one, a probe to it would leave as an
    /// IPv6 packet toward the router, the one place the host certainly is not.
    #[test]
    fn a_mapped_target_is_offered_no_ipv6_source() {
        let intf = mock_interface(vec![
            v4net(192, 0, 2, 50, 24),
            v6net(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 64),
        ]);

        assert_eq!(
            plausible_source(
                std::slice::from_ref(&intf),
                IpAddr::V6(Ipv4Addr::new(203, 0, 113, 1).to_ipv6_mapped())
            ),
            None
        );
    }

    /// IPv4 keeps the kernel's answer. It has one scope and no equivalent of a
    /// tunnel swallowing the default route for a family it does not carry, so
    /// second-guessing it would invent a source where the host genuinely has
    /// none.
    #[test]
    fn an_unroutable_v4_target_is_not_second_guessed() {
        let intf = mock_interface(vec![v4net(192, 0, 2, 50, 24)]);

        assert_eq!(
            plausible_source(
                std::slice::from_ref(&intf),
                IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8))
            ),
            None
        );
    }
}