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
// 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

//! # Resolving a whole target list
//!
//! The two-pass bridge between synchronous parsing and asynchronous resolution.
//! [`collect_names`] finds the names in a list of target expressions by asking
//! the address grammar which halves it cannot make an address of; those are
//! resolved concurrently, and the answers feed the
//! [`HostLookup`](crate::model::parse::target::HostLookup) the second pass reads.
//!
//! Nothing here re-implements the grammar. A name is what [`insert_expression`]
//! rejects as [`IpParseError::Malformed`], the same signal
//! [`TargetMapBuilder`](crate::model::parse::target::TargetMapBuilder) uses to
//! decide a token is worth resolving, so the classification cannot drift
//! from the one the builder applies when it later consumes the same input.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::net::IpAddr;
use std::sync::Arc;

use tokio::task::JoinSet;

use crate::config::ZondConfig;
use crate::model::exclusion::Exclusions;
use crate::model::ip::set::IpSet;
use crate::model::parse::ip::{
    IpParseError, Keyword, ResolverFn, ZoneResolverFn, insert_expression, names_keyword,
};
use crate::model::parse::target::{self, TargetContext, TargetExpr, TargetParseError};
use crate::model::port::PortSet;
use crate::model::target::TargetMap;
use crate::system::interface;
use crate::warn;

use super::{Resolver, Snapshot};

/// How many names are resolved at once.
///
/// An mDNS lookup holds a socket open for the length of its reply window, so the
/// ceiling bounds how many sockets a list of `.local` names opens at a time
/// rather than letting a large file open one per name. Unicast lookups are far
/// cheaper, but sharing one ceiling keeps the pass simple, and the network, not
/// this number, is the limit that matters for them.
const MAX_CONCURRENT_LOOKUPS: usize = 16;

/// Resolves every name in `exprs` concurrently, returning a map from each name
/// to the addresses it stands for.
///
/// A name nothing answered for is absent from the map rather than present with
/// an empty list, so a caller can tell "resolved to nothing" from "resolved" by
/// membership alone. This is the pass to run when a caller wants to build the
/// [`TargetMap`] itself, or to move the work across threads: it borrows nothing
/// but its arguments and returns an owned map, where the [`TargetContext`] the
/// build reads borrows the caller's keyword and zone resolvers and so cannot
/// cross a thread boundary.
///
/// No keyword or zone is looked up here. What is a name is decided by how it is
/// written, not by what the host's lookups answer; see `collect_names`.
pub async fn resolve_names<S: AsRef<str>>(
    exprs: &[S],
    resolver: &Resolver,
) -> HashMap<String, Vec<IpAddr>> {
    let names = collect_names(exprs);
    resolve_all(names, resolver).await
}

/// Parses `exprs` into a [`TargetMap`], resolving any hostnames along the way.
///
/// The asynchronous counterpart to
/// [`target::to_target_map`]: it
/// resolves first, then builds with a lookup that reads the results, so a name
/// becomes the addresses it stands for instead of the error an unresolved one
/// would raise.
///
/// The returned future borrows `ctx`, and so is only as `Send` as the keyword and
/// zone resolvers `ctx` holds, which are `&dyn Fn` and need not be. A caller that
/// has to move the work across threads resolves with [`resolve_names`] and builds
/// synchronously from the owned map it returns.
pub async fn to_target_map<S: AsRef<str>>(
    exprs: &[S],
    default_ports: PortSet,
    ctx: &TargetContext<'_>,
    resolver: &Resolver,
) -> Result<TargetMap, TargetParseError> {
    let resolved = resolve_names(exprs, resolver).await;

    // Read by the builder's second pass; owns its addresses so it outlives no
    // borrow of the map.
    let lookup = |name: &str| resolved.get(name).cloned();
    let ctx = TargetContext {
        keywords: ctx.keywords,
        zones: ctx.zones,
        hosts: Some(&lookup),
    };

    target::to_target_map(exprs, default_ports, &ctx)
}

/// What a port scan was asked to cover: the plan, and the name each address
/// was reached by where an expression named a host.
///
/// The two travel together for the reason [`DiscoveryTargets`] carries its
/// flag: a [`TargetMap`] holds addresses, and by the time a scan has one the
/// names it came from are gone. A web port on an address a name led to is
/// asked for by that name, and a caller who resolved the map and dropped the
/// names gets every virtual host's default site instead of the one it named.
#[derive(Debug, Clone)]
pub struct PortScanTargets {
    map: TargetMap,
    names: BTreeMap<IpAddr, String>,
}

impl PortScanTargets {
    /// The plan, for [`scan`](crate::scanner::scan).
    pub fn map(&self) -> &TargetMap {
        &self.map
    }

    /// Takes the plan, for handing to [`scan`](crate::scanner::scan).
    pub fn into_map(self) -> TargetMap {
        self.map
    }

    /// The name each address was reached by, where an expression named a
    /// host; see [`ZondConfig::target_names`].
    pub fn names(&self) -> &BTreeMap<IpAddr, String> {
        &self.names
    }

    /// Writes what these targets imply into `cfg`: the names, into
    /// [`target_names`](ZondConfig::target_names).
    pub fn apply_to(&self, cfg: &mut ZondConfig) {
        cfg.target_names = self.names.clone();
    }

    /// The same plan with `ports` in place of the empty set on every group
    /// that has none, which in a plan [`for_request`] built are the targets
    /// written without a port half.
    #[cfg(feature = "import-request")]
    pub(crate) fn with_unported_on(&self, ports: &PortSet) -> Self {
        let mut map = TargetMap::new();
        for unit in &self.map.units {
            if unit.ports().is_empty() {
                map.add_unit(crate::model::target::TargetSet::new(
                    unit.ips().clone(),
                    ports.clone(),
                ));
            } else {
                map.add_unit(unit.clone());
            }
        }
        Self {
            map,
            names: self.names.clone(),
        }
    }
}

/// Resolves target expressions once into what a discovery sweep needs and a
/// port scan's plan, for a caller that settles the ports an unported target
/// takes only afterwards, as a scan request does.
///
/// The plan keeps the ports each expression wrote, and groups every
/// expression that wrote none under the empty set, which no written port half
/// can be, since one naming nothing is refused.
/// [`PortScanTargets::with_unported_on`] gives those the ports settled later.
/// One pass rather than [`for_discovery`] and [`for_port_scan`] in turn, so a
/// name is looked up once and both halves hold the same answer.
#[cfg(feature = "import-request")]
pub(crate) async fn for_request<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
) -> Result<(DiscoveryTargets, PortScanTargets), TargetParseError> {
    let ctx = TargetContext {
        keywords: Some(&interface::resolve_keyword),
        zones: Some(&interface::resolve_zone),
        hosts: None,
    };
    let plan = for_port_scan(exprs, PortSet::new(), &ctx, names).await?;
    let discovery = DiscoveryTargets {
        ips: ips_of(&plan.map),
        segment_sweep: names_keyword(exprs, Keyword::Lan),
    };
    Ok((discovery, plan))
}

/// Parses `exprs` into a port scan's plan, resolving any hostnames under the
/// caller's DNS policy and keeping the name each address was reached by.
///
/// [`to_target_map`] with the names kept. `names` is the DNS policy, as on
/// [`for_discovery`]: `None` refuses a name rather than looking it up, and
/// the targets then carry none.
pub async fn for_port_scan<S: AsRef<str>>(
    exprs: &[S],
    default_ports: PortSet,
    ctx: &TargetContext<'_>,
    names: Option<&Resolver>,
) -> Result<PortScanTargets, TargetParseError> {
    let Some(resolver) = names else {
        let map = target::to_target_map(exprs, default_ports, ctx)?;
        return Ok(PortScanTargets {
            map,
            names: BTreeMap::new(),
        });
    };

    let written = collect_names(exprs);
    let resolved = resolve_all(written.clone(), resolver).await;
    let lookup = |name: &str| resolved.get(name).cloned();
    let with_lookup = TargetContext {
        keywords: ctx.keywords,
        zones: ctx.zones,
        hosts: Some(&lookup),
    };
    let map = target::to_target_map(exprs, default_ports, &with_lookup)?;

    Ok(PortScanTargets {
        map,
        names: names_by_address(&written, &resolved),
    })
}

/// The name each resolved address was reached by, the first written where
/// several led to one address, so the one asked for does not depend on which
/// lookup answered first.
///
/// Written as the target wrote it, less the trailing dot of a fully qualified
/// name, which a `Host` header and a TLS server name both leave off.
///
/// A later name that shares an address is said so at the first verbosity,
/// once per name, since it goes unasked there: no `Host` header and no server
/// name carries it, and no certificate is held against it. See
/// [`ZondConfig::target_names`] for why one name is kept per address.
fn names_by_address(
    written: &[String],
    resolved: &HashMap<String, Vec<IpAddr>>,
) -> BTreeMap<IpAddr, String> {
    let mut names: BTreeMap<IpAddr, String> = BTreeMap::new();
    for name in written {
        let bare = name.strip_suffix('.').unwrap_or(name);
        let mut shared = None;
        for address in resolved.get(name).into_iter().flatten() {
            match names.get(address) {
                Some(first) if first != bare => shared = Some((*address, first.clone())),
                Some(_) => {}
                None => {
                    names.insert(*address, bare.to_string());
                }
            }
        }
        if let Some((address, first)) = shared {
            crate::info!(
                verbosity = 1,
                "{bare} not asked by name at {address} (asked as {first})"
            );
        }
    }
    names
}

/// Resolves `exprs` into a single [`IpSet`], for the discovery phase, which asks
/// only whether a host is there and has no use for ports.
///
/// The convenience over [`to_target_map`] for a caller feeding
/// [`discover`](crate::scanner::discover): a name resolves the same way, and the
/// ports every expression is grouped by are discarded rather than carried.
/// Reports a [`TargetParseError`], which is richer than the address grammar's own
/// error since it can name a host that would not resolve.
pub async fn to_set<S: AsRef<str>>(
    exprs: &[S],
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
    resolver: &Resolver,
) -> Result<IpSet, TargetParseError> {
    let ctx = TargetContext {
        keywords,
        zones,
        hosts: None,
    };

    // The port specification is immaterial here: it only groups addresses, and
    // they are unioned back together below regardless of which group they fell
    // into.
    let map = to_target_map(exprs, PortSet::default(), &ctx, resolver).await?;

    Ok(ips_of(&map))
}

/// The addresses `exprs` names, under the caller's DNS policy.
///
/// The one decision [`for_discovery_with`] and [`for_exclusion_with`] both make,
/// made here once rather than in two identical blocks. `Some` resolves
/// hostnames through the resolver given; `None` refuses them all. Either way a
/// name that cannot be turned into addresses is reported rather than dropped.
///
/// An empty list of expressions is an empty set of addresses through the
/// ordinary path. A caller answering that case first and by hand would read as
/// a difference between the two callers, and there is none.
async fn addresses_of<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
) -> Result<IpSet, TargetParseError> {
    match names {
        Some(resolver) => to_set(exprs, keywords, zones, resolver).await,
        None => {
            let ctx = TargetContext {
                keywords,
                zones,
                hosts: None,
            };
            Ok(ips_of(&target::to_target_map(
                exprs,
                PortSet::default(),
                &ctx,
            )?))
        }
    }
}

/// Every address a target map covers, with the port groupings discarded.
///
/// The groups only ever decided which ports went with which addresses, so a
/// caller that has no use for ports is left with their union.
fn ips_of(map: &TargetMap) -> IpSet {
    let mut set = IpSet::new();
    for unit in &map.units {
        for range in unit.ips().v4() {
            set.push_v4_range(*range);
        }
        for range in unit.ips().v6() {
            set.push_v6_range(*range);
        }
    }
    set.canonicalize();
    set
}

/// What a discovery sweep was asked to cover.
///
/// The addresses, and the one thing about the request that the addresses no
/// longer say: whether a *network* was named.
///
/// Those two travel together because separating them is a mistake nobody
/// notices. `lan` and the range it expands to produce the same [`IpSet`], and by
/// the time [`discover`](crate::scanner::discover) has one it cannot tell which
/// was written, so a caller that resolves the addresses and forgets the flag gets
/// a targeted run where a sweep was asked for, no all-nodes echo, no
/// neighbour-table leads, and an IPv6 half that reports a network as empty. It
/// looks exactly like a working scan.
#[derive(Debug, Clone)]
pub struct DiscoveryTargets {
    ips: IpSet,
    segment_sweep: bool,
}

impl DiscoveryTargets {
    /// The addresses to probe.
    pub fn ips(&self) -> &IpSet {
        &self.ips
    }

    /// Takes the addresses, for handing to [`discover`](crate::scanner::discover).
    pub fn into_ips(self) -> IpSet {
        self.ips
    }

    /// Whether a network was named, rather than a set of addresses.
    ///
    /// What [`ZondConfig::segment_sweep`] wants. Prefer
    /// [`apply_to`](Self::apply_to), which puts it there without the caller
    /// having to remember that it is what the field is for.
    pub fn segment_sweep(&self) -> bool {
        self.segment_sweep
    }

    /// Writes what these targets imply into `cfg`.
    ///
    /// Only [`segment_sweep`](ZondConfig::segment_sweep) today. It is a method
    /// rather than a field the caller copies across because the copying is the
    /// step that gets skipped, and the same shape already exists on
    /// `import::settings::Settings::apply_to`.
    pub fn apply_to(&self, cfg: &mut ZondConfig) {
        cfg.segment_sweep = self.segment_sweep;
    }
}

/// Resolves target expressions into everything a discovery sweep needs.
///
/// The one call a front end makes. It wires this host's own interface table for
/// `lan` and for the `%interface` suffix, resolves any hostnames, and works out
/// whether a segment sweep was asked for: three steps that, left separate,
/// every consumer would have to remember, and every consumer would remember
/// differently.
///
/// `names` is the DNS policy, and it is the caller's because only they know it.
/// `Some` resolves hostnames through the resolver given; `None` refuses them.
/// A scan running under [`ZondConfig::no_dns`] passes
/// [`Resolver::hosts_file_only`]: looking a target up in DNS emits a query to a
/// resolver somebody else operates, and reading the hosts file emits nothing,
/// so a name listed there is scanned and any other is reported as an unknown
/// host. A name that cannot be resolved is reported rather than quietly
/// dropped.
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use zond_engine::{Resolver, ZondConfig, discover, resolve};
///
/// let resolver = Resolver::from_system();
/// let targets = resolve::for_discovery(&["lan"], Some(&resolver)).await?;
///
/// let mut cfg = ZondConfig::default();
/// targets.apply_to(&mut cfg);
///
/// let (_session, task) = discover(targets.into_ips(), &cfg).await?;
/// let report = task.join().await?;
/// # Ok(())
/// # }
/// ```
pub async fn for_discovery<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
) -> Result<DiscoveryTargets, TargetParseError> {
    for_discovery_with(
        exprs,
        names,
        Some(&interface::resolve_keyword),
        Some(&interface::resolve_zone),
    )
    .await
}

/// [`for_discovery`], with the host lookups supplied rather than assumed.
///
/// The same call with its two reads of the local machine handed in. That is what
/// makes the behaviour around `lan` and `%en0` testable somewhere that has
/// neither, and what lets a caller who means something else by `lan`, such as a
/// management network or a lab segment, say so.
pub async fn for_discovery_with<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
) -> Result<DiscoveryTargets, TargetParseError> {
    let ips = addresses_of(exprs, names, keywords, zones).await?;

    // Asked of what was written, not of what it expanded to. This is the whole
    // reason the flag has to be worked out here: the addresses cannot answer it.
    let segment_sweep = names_keyword(exprs, Keyword::Lan);

    Ok(DiscoveryTargets { ips, segment_sweep })
}

/// Resolves exclusion expressions into a policy [`scan`](crate::scanner::scan)
/// and [`discover`](crate::scanner::discover) will honour.
///
/// The counterpart of [`for_discovery`], and the same grammar. An exclusion is
/// written the way a target is, so `198.51.100.0/24`, `192.0.2.10-20`,
/// `db.internal`, `lan` and `fe80::1%en0` all work, because a person reading a
/// scope document transcribes both halves of it and a scanner that accepted CIDR
/// for
/// what it must scan and something narrower for what it must not would be asking
/// them to translate the half that matters more.
///
/// `names` is the DNS policy, exactly as on [`for_discovery`]. A name given to a
/// `None` is reported rather than dropped, which for this input is the whole
/// point: an exclusion that quietly failed to parse is an exclusion that quietly
/// does not apply.
///
/// A name is resolved once, here. What comes back is the addresses it stood for
/// at that moment, and the policy holds those rather than the name, so a host
/// that moves during the scan is no longer excluded and one whose record lists
/// two addresses is excluded at both. Write the addresses where that
/// matters, which is most of the time it matters at all.
///
/// # Combining with a settings document
///
/// Layer with [`Exclusions::extend`], never by assigning over
/// [`ZondConfig::exclusions`](crate::config::ZondConfig::exclusions):
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use zond_engine::{Resolver, ZondConfig, resolve};
///
/// let mut cfg = ZondConfig::default();
/// // ... a settings document has already contributed its own ...
///
/// let resolver = Resolver::from_system();
/// let from_arguments = resolve::for_exclusion(&["192.0.2.0/24"], Some(&resolver)).await?;
/// cfg.exclusions.extend(&from_arguments);
/// # Ok(())
/// # }
/// ```
///
/// Assigning would drop whatever an administrator put in a system-wide file, and
/// the resulting scan would look exactly like a correct one. See
/// [`Exclusions::extend`] for why this is the one setting that unions.
pub async fn for_exclusion<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
) -> Result<Exclusions, TargetParseError> {
    for_exclusion_with(
        exprs,
        names,
        Some(&interface::resolve_keyword),
        Some(&interface::resolve_zone),
    )
    .await
}

/// [`for_exclusion`], with the host lookups supplied rather than assumed.
///
/// The same relationship [`for_discovery_with`] has to [`for_discovery`], and it
/// exists for the same reason: what `lan` and `%en0` mean is a fact about this
/// machine, and a test asserting that an exclusion covers a segment should not
/// need the machine to have one.
pub async fn for_exclusion_with<S: AsRef<str>>(
    exprs: &[S],
    names: Option<&Resolver>,
    keywords: Option<ResolverFn<'_>>,
    zones: Option<ZoneResolverFn<'_>>,
) -> Result<Exclusions, TargetParseError> {
    Ok(Exclusions::new(
        addresses_of(exprs, names, keywords, zones).await?,
    ))
}

/// Every distinct hostname named across `exprs`, in first-seen order.
///
/// A name is an address half the grammar rejects as
/// [`IpParseError::Malformed`] **and** that
/// [`host_name`](target::host_name) then agrees is a name. Every other rejection,
/// whether a wrong address or a keyword with no resolver or a zone on a global
/// address, is an error about something meant to be an address, and is left for
/// the build pass to report against the expression it belongs to. A token that
/// will not even split is skipped for the same reason: the builder will raise it
/// verbatim.
///
/// The second half matters because `Malformed` alone is not the builder's
/// rule: it applies two more tests before it consults the lookup, so without
/// them `192.0.2.300` would be sent to a resolver here and refused as a
/// mistyped address there. Asking the same function is what makes the two
/// passes agree, rather than a comment saying they do.
///
/// The grammar is asked without the host's keyword and zone lookups. Neither can
/// make a token `Malformed` or stop it being so: a keyword or a zoned address is
/// refused as something else when its lookup is missing, and parsed when it is
/// present, so the answer here is the same either way. Passing them would only
/// resolve `lan` into a set this throws away, a read of the interface table the
/// build pass then repeats, and one more chance for the two reads to disagree.
fn collect_names<S: AsRef<str>>(exprs: &[S]) -> Vec<String> {
    let mut names = Vec::new();
    let mut seen = HashSet::new();

    for token in exprs {
        let Ok(expr) = TargetExpr::parse(token.as_ref()) else {
            continue;
        };

        for address in expr.addresses() {
            let mut throwaway = IpSet::new();
            if let Err(IpParseError::Malformed(_)) =
                insert_expression(address, &mut throwaway, None, None)
                && target::host_name(address) == target::HostName::Yes
                && seen.insert(address.to_string())
            {
                names.push(address.to_string());
            }
        }
    }

    names
}

/// Resolves a list of names concurrently, at most [`MAX_CONCURRENT_LOOKUPS`] in
/// flight, keeping only those that resolved to something.
///
/// One lookup per name rather than per spelling. DNS is case-insensitive, so
/// `NAS` and `nas` are one host, not two round trips and two map entries. They
/// are resolved once and the answer is recorded under every spelling that
/// asked for it, which leaves the returned map keyed as the caller wrote things:
/// the build pass looks a name up by the token in the expression, and lowering
/// the keys here would simply move the mismatch.
async fn resolve_all(names: Vec<String>, resolver: &Resolver) -> HashMap<String, Vec<IpAddr>> {
    let mut resolved = HashMap::new();
    if names.is_empty() {
        return resolved;
    }

    // Every spelling that asked for one host, under the one name to look up.
    let mut spellings: HashMap<String, Vec<String>> = HashMap::new();
    let mut order = Vec::new();
    for name in names {
        let folded = name.to_ascii_lowercase();
        let written = spellings.entry(folded.clone()).or_default();
        if written.is_empty() {
            order.push(folded);
        }
        written.push(name);
    }

    // Read once, so every name in the list is answered from the same hosts
    // file and asked of the same servers.
    let snapshot = Arc::new(resolver.snapshot());
    let mut set: JoinSet<(String, Vec<IpAddr>)> = JoinSet::new();
    let mut pending = order.into_iter();

    for name in pending.by_ref().take(MAX_CONCURRENT_LOOKUPS) {
        spawn_lookup(&mut set, resolver, &snapshot, name);
    }

    while let Some(joined) = set.join_next().await {
        match joined {
            Ok((folded, addresses)) if !addresses.is_empty() => {
                for spelling in spellings.remove(&folded).unwrap_or_default() {
                    resolved.insert(spelling, addresses.clone());
                }
            }
            Ok(_) => {}
            // A lookup that did not finish is a name that resolves to nothing,
            // which is what an absent entry says. Logged rather than swallowed,
            // because every other failure on this path is.
            Err(e) => warn!("a name lookup did not finish: {e}"),
        }

        if let Some(name) = pending.next() {
            spawn_lookup(&mut set, resolver, &snapshot, name);
        }
    }

    resolved
}

/// Spawns one lookup, cloning the resolver and the pass's snapshot into the
/// task so the set owns them.
fn spawn_lookup(
    set: &mut JoinSet<(String, Vec<IpAddr>)>,
    resolver: &Resolver,
    snapshot: &Arc<Snapshot>,
    name: String,
) {
    let resolver = resolver.clone();
    let snapshot = Arc::clone(snapshot);
    set.spawn(async move {
        let addresses = resolver.resolve_in(&snapshot, &name).await;
        (name, addresses)
    });
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::parse::ip::Keyword;

    /// The two passes agree about what a name is, because they ask the same
    /// function.
    ///
    /// A collector taking [`IpParseError::Malformed`] as the whole answer, while
    /// the builder applies two more tests before consulting the lookup, would
    /// send a mistyped address to a resolver somebody else operates and then
    /// refuse it here without ever looking it up. A typo in a target file would
    /// become a DNS query, which is what `no_dns` exists to prevent.
    #[test]
    fn a_token_the_builder_will_refuse_is_never_put_on_the_network() {
        let refused = [
            "192.0.2.300",     // an octet out of range
            "999.999.999.999", // every octet out of range
            "192.0.2",         // too few octets
        ];
        assert_eq!(
            collect_names(&refused),
            Vec::<String>::new(),
            "a mistyped address was collected as a name to look up"
        );

        // The builder's own verdict on the same tokens, which is what makes the
        // two agree rather than merely both refuse.
        for token in refused {
            assert_eq!(target::host_name(token), target::HostName::Mistyped);
        }

        // A real name is still collected, or the check above proves nothing.
        assert_eq!(
            collect_names(&["nas.local", "example.com"]),
            vec!["nas.local".to_string(), "example.com".to_string()]
        );
    }

    /// One host is one lookup, however many ways it is spelled.
    ///
    /// DNS is case-insensitive, so `NAS` and `nas` name one host, not two
    /// entries and two round trips.
    #[test]
    fn a_name_written_two_ways_is_looked_up_once() {
        // Collection keeps every spelling, since the build pass looks a name up
        // by the token the expression carried.
        let collected = collect_names(&["NAS", "nas", "Nas"]);
        assert_eq!(collected.len(), 3);

        // What must not be three is the number of names resolution asks for.
        let folded: std::collections::HashSet<String> = collected
            .iter()
            .map(|name| name.to_ascii_lowercase())
            .collect();
        assert_eq!(folded.len(), 1, "three spellings of one host");
    }

    /// A keyword resolver that expands `lan` to one address, so a list mixing a
    /// keyword, literals and names can be classified the way the builder would.
    fn keywords(keyword: Keyword, set: &mut IpSet) -> Result<(), IpParseError> {
        match keyword {
            Keyword::Lan => {
                set.insert("192.0.2.1".parse().expect("a valid address"));
                Ok(())
            }
        }
    }

    /// A keyword is resolved once per call, by the pass that builds the set.
    ///
    /// Resolving `lan` reads the whole interface table, and every read is a
    /// chance for the answer to differ from the one the set was built from. The
    /// pass that picks out hostnames has no use for the answer: a keyword is
    /// never a name, whatever it expands to.
    #[tokio::test]
    async fn a_keyword_is_resolved_once_per_call() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let calls = AtomicUsize::new(0);
        let counting = |keyword: Keyword, set: &mut IpSet| {
            calls.fetch_add(1, Ordering::Relaxed);
            keywords(keyword, set)
        };
        let resolver = Resolver::from_system();

        let set = to_set(&["lan", "203.0.113.1"], Some(&counting), None, &resolver)
            .await
            .expect("the keyword resolver answers");

        assert_eq!(set.len(), 2);
        assert_eq!(calls.load(Ordering::Relaxed), 1);
    }

    /// The distinction the addresses cannot carry. Both of these resolve to the
    /// same single address and only one is a request to sweep a segment, so a
    /// caller reading only the `IpSet` has already lost it.
    #[tokio::test]
    async fn only_the_keyword_asks_for_a_segment_sweep() {
        let keyword = for_discovery_with(&["lan"], None, Some(&keywords), None)
            .await
            .expect("the keyword resolver answers");
        assert!(keyword.segment_sweep());
        assert_eq!(keyword.ips().len(), 1);

        let spelled_out = for_discovery_with(&["192.0.2.1"], None, Some(&keywords), None)
            .await
            .expect("a literal address");
        assert!(!spelled_out.segment_sweep());
        assert_eq!(spelled_out.ips().len(), 1);
    }

    /// Found wherever it appears, including inside a comma-separated list, since
    /// that is where a person writes it when mixing it with something else.
    #[tokio::test]
    async fn the_keyword_is_found_alongside_other_targets() {
        let mixed = for_discovery_with(&["lan,198.51.100.0/30"], None, Some(&keywords), None)
            .await
            .expect("the keyword resolver answers");
        assert!(mixed.segment_sweep());
    }

    /// The step this type exists to stop anyone skipping.
    #[tokio::test]
    async fn applying_targets_to_a_config_sets_the_sweep() {
        let targets = for_discovery_with(&["lan"], None, Some(&keywords), None)
            .await
            .expect("the keyword resolver answers");

        let mut cfg = ZondConfig::default();
        assert!(!cfg.segment_sweep, "off until something asks for it");
        targets.apply_to(&mut cfg);
        assert!(cfg.segment_sweep);
    }

    /// A scan told to emit no DNS may not look a target name up either: the
    /// query would go to a resolver somebody else operates and announce the
    /// scan. Refused against the expression that caused it, rather than dropped.
    #[tokio::test]
    async fn a_name_is_refused_when_no_resolver_is_offered() {
        let refused = for_discovery_with(&["one.one.one.one"], None, Some(&keywords), None).await;

        let Err(TargetParseError::NoHostLookup(expression)) = refused else {
            panic!("a name with nothing to resolve it is not a target");
        };
        assert_eq!(expression, "one.one.one.one");
    }

    /// Literal addresses need no resolver at all, so refusing names does not
    /// cost a caller the rest of their target list.
    #[tokio::test]
    async fn addresses_still_resolve_with_no_name_resolver() {
        let targets = for_discovery_with(&["198.51.100.0/30", "2001:db8::1"], None, None, None)
            .await
            .expect("literals need nothing looked up");
        assert_eq!(targets.ips().len(), 5);
    }

    /// The whole point of the classification: names are picked out and nothing
    /// else is. A literal, a range, a CIDR block and a resolvable keyword are all
    /// addresses the grammar handles, and only the two hostnames are left for
    /// resolution, carrying their ports stripped since a name is the address half
    /// alone.
    /// Two names leading to one address ask for the one written first,
    /// whichever lookup answered first, and a fully qualified name is asked
    /// for without the dot that marks it.
    #[test]
    fn an_address_is_asked_for_by_the_first_name_that_led_to_it() {
        let shared: IpAddr = "192.0.2.10".parse().expect("an address");
        let own: IpAddr = "192.0.2.11".parse().expect("an address");
        let written = vec!["box.example.".to_string(), "dev.box.example".to_string()];
        let resolved = HashMap::from([
            ("dev.box.example".to_string(), vec![shared, own]),
            ("box.example.".to_string(), vec![shared]),
        ]);

        let mut names = BTreeMap::new();
        let logged = crate::logging::logged(|| names = names_by_address(&written, &resolved));
        assert_eq!(names.get(&shared).map(String::as_str), Some("box.example"));
        assert_eq!(names.get(&own).map(String::as_str), Some("dev.box.example"));

        // The name that goes unasked at the shared address is said to, once,
        // since no handshake there names it and no certificate is held to it.
        let said: Vec<_> = logged
            .iter()
            .filter(|line| line.message.contains("not asked by name"))
            .collect();
        assert_eq!(said.len(), 1, "{logged:?}");
        assert_eq!(said[0].verbosity, 1);
        assert_eq!(
            said[0].message,
            "dev.box.example not asked by name at 192.0.2.10 (asked as box.example)"
        );
    }

    #[test]
    fn only_the_hostnames_in_a_mixed_list_are_collected() {
        let exprs = [
            "192.0.2.10",
            "example.com:443",
            "198.51.100.0/24",
            "raspberrypi.local",
            "198.51.100.1-10",
            "lan",
        ];

        assert_eq!(
            collect_names(&exprs),
            vec!["example.com".to_string(), "raspberrypi.local".to_string()]
        );
    }

    /// A name written twice, or on two ports, is one name to resolve. Order is
    /// first-seen so a run over the same input resolves in the same order.
    #[test]
    fn a_repeated_name_is_collected_once() {
        let exprs = ["host.example:80", "host.example:443", "host.example"];

        assert_eq!(collect_names(&exprs), vec!["host.example".to_string()]);
    }

    /// The comma-separated address half is split before classification, so a
    /// single token naming a literal and a name yields just the name.
    #[test]
    fn names_are_found_inside_a_comma_list() {
        assert_eq!(
            collect_names(&["198.51.100.1,db.internal:5432"]),
            vec!["db.internal".to_string()]
        );
    }

    /// A keyword with no resolver is rejected by the grammar, but not as
    /// `Malformed`, so it is never mistaken for a hostname and sent to a
    /// resolver that would report "no such host" for it.
    #[test]
    fn a_keyword_without_a_resolver_is_not_taken_for_a_name() {
        assert!(collect_names(&["lan"]).is_empty());
    }

    /// An empty list resolves to an empty map with no tasks spawned, so the
    /// common case of a list with no names at all costs nothing.
    #[tokio::test]
    async fn resolving_no_names_yields_an_empty_map() {
        let resolver = Resolver::from_system();
        assert!(resolve_all(Vec::new(), &resolver).await.is_empty());
    }

    /// A list of literals reaches `to_set` without a name to resolve, so it
    /// touches no network, which is what makes this seam testable offline. What
    /// it pins is the union: expressions land in separate port groups, and
    /// `to_set` has to fold every group's addresses back into one set across
    /// both families rather than returning only the last group's.
    #[tokio::test]
    async fn to_set_unions_every_group_across_both_families() {
        let resolver = Resolver::from_system();

        let set = to_set(
            &["198.51.100.1:80", "198.51.100.2:443", "2001:db8::1"],
            None,
            None,
            &resolver,
        )
        .await
        .expect("literals resolve without a lookup");

        assert_eq!(set.len(), 3);
        assert!(set.contains(&"198.51.100.1".parse().unwrap()));
        assert!(set.contains(&"198.51.100.2".parse().unwrap()));
        assert!(set.contains(&"2001:db8::1".parse().unwrap()));
    }
}