Skip to main content

zond_engine/model/
target.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # What a scan was asked to cover
10//!
11//! A [`Target`] is one address, one port, one protocol: the smallest thing a scan can
12//! ask about. The two types above it describe many targets without holding them.
13//!
14//! [`TargetSet`] pairs an [`IpSet`] with a [`PortSet`] and yields their cross product
15//! lazily. A `/8` on a thousand ports is sixteen billion targets.
16//!
17//! [`TargetMap`] holds several sets, since one scan can ask different questions of
18//! different hosts: `192.0.2.1:22` and `192.0.2.0/24:80` are one job with two shapes.
19//! Counts here are gross: two units naming one address are two questions about it, and
20//! both get asked.
21
22use crate::model::ip::range::{IpRange, Ipv6Range};
23use crate::model::ip::scoped::ZoneMap;
24use crate::model::ip::set::{IpSet, Positions};
25use crate::model::port::{PortSet, Protocol};
26use std::{net::IpAddr, ops::Range, sync::Arc};
27use thiserror::Error;
28
29/// Errors that can occur during target composition and calculation.
30#[non_exhaustive]
31#[derive(Debug, Clone, PartialEq, Eq, Error)]
32pub enum TargetError {
33    /// The number of targets is too large to represent in a `u128`.
34    ///
35    /// Reachable: `::/0` is already `u128::MAX` addresses, so a second port
36    /// overflows. Reported, since a wrapped count would pass a budget check.
37    #[error("Target calculation resulted in an integer overflow")]
38    CapacityOverflow,
39}
40
41/// One address, one port, one protocol: the smallest thing a scan can ask
42/// about.
43#[non_exhaustive]
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub struct Target {
46    /// The address to probe.
47    ///
48    /// Bare, with no zone. A link-local address's zone is written on the range the
49    /// target came from, and a scan keeps the pairing in a [`ZoneMap`] for the phases
50    /// that open a socket or send a frame. See
51    /// [`ScopedIp`](crate::model::ip::scoped::ScopedIp) for an address that carries
52    /// its own.
53    pub ip: IpAddr,
54    /// The port to probe.
55    pub port: u16,
56    /// Which transport to probe it over.
57    pub protocol: Protocol,
58}
59
60impl Target {
61    /// A target of `port` over `protocol` at `ip`.
62    pub const fn new(ip: IpAddr, port: u16, protocol: Protocol) -> Self {
63        Self { ip, port, protocol }
64    }
65}
66
67/// A target together with its position in the plan it came from.
68///
69/// The position is the target's index in [`TargetMap::iter`], reproducible for a given
70/// plan, so a journal records how far a scan got in a few bytes.
71///
72/// A separate type because a target from a file or a hand-built set has no position.
73/// Only the dispatcher numbers targets.
74#[non_exhaustive]
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub struct PlannedTarget {
77    /// Where in the plan's enumeration this target sits.
78    pub position: u64,
79    /// What to probe.
80    pub target: Target,
81}
82
83impl PlannedTarget {
84    /// Pairs `target` with its position.
85    pub fn new(position: u64, target: Target) -> Self {
86        Self { position, target }
87    }
88
89    /// The address to probe.
90    pub fn ip(&self) -> IpAddr {
91        self.target.ip
92    }
93
94    /// The port to probe.
95    pub fn port(&self) -> u16 {
96        self.target.port
97    }
98
99    /// The transport to probe it over.
100    pub fn protocol(&self) -> Protocol {
101        self.target.protocol
102    }
103}
104
105/// A set of addresses paired with the ports to try on each of them.
106///
107/// [`new`](Self::new) merges the addresses and nothing mutates them afterwards, so a
108/// `TargetSet` never holds overlapping ranges or miscounts them.
109#[derive(Debug, Clone, Default, PartialEq, Eq)]
110pub struct TargetSet {
111    /// Internal IP set, canonical by construction.
112    ips: IpSet,
113    /// The ports to try on each of them.
114    ///
115    /// Private so nobody replaces it under a set that has been counted.
116    ports: PortSet,
117}
118
119impl TargetSet {
120    /// Creates a scan blueprint over `ips` and `ports`.
121    ///
122    /// Merges `ips` once, here, so every read takes `&self`.
123    pub fn new(mut ips: IpSet, ports: PortSet) -> Self {
124        ips.canonicalize();
125        Self { ips, ports }
126    }
127
128    /// Returns a read-only reference to the underlying IP set.
129    pub fn ips(&self) -> &IpSet {
130        &self.ips
131    }
132
133    /// Takes the IP set, discarding the ports.
134    ///
135    /// For a phase with no use for ports, such as
136    /// [`discover`](crate::scanner::discover), without cloning a set that may hold a
137    /// `/8`.
138    pub fn into_ips(self) -> IpSet {
139        self.ips
140    }
141
142    /// Takes the set apart into the two halves it was built from.
143    ///
144    /// For rebuilding one, for example to withhold an excluded range, through
145    /// [`new`](Self::new). A `&mut IpSet` would let a caller leave the addresses
146    /// unmerged, which every count and membership test assumes they are not.
147    pub fn into_parts(self) -> (IpSet, PortSet) {
148        (self.ips, self.ports)
149    }
150
151    /// Returns a read-only reference to the underlying Port set.
152    pub fn ports(&self) -> &PortSet {
153        &self.ports
154    }
155
156    /// Returns the number of unique IP addresses in this set.
157    pub fn ip_count(&self) -> u128 {
158        self.ips.len()
159    }
160
161    /// Returns the number of unique ports in this set.
162    pub fn port_count(&self) -> usize {
163        self.ports.len()
164    }
165
166    /// Returns the total number of targets.
167    ///
168    /// Returns a `TargetError::CapacityOverflow` if the calculation exceeds `u128::MAX`.
169    pub fn total_targets(&self) -> Result<u128, TargetError> {
170        let port_len = self.ports.len() as u128;
171        self.ips
172            .len()
173            .checked_mul(port_len)
174            .ok_or(TargetError::CapacityOverflow)
175    }
176
177    /// Every address paired with every port, lazily.
178    ///
179    /// Targets are produced one at a time, and the port list is shared behind an `Arc`
180    /// across addresses.
181    pub fn iter(&self) -> impl Iterator<Item = Target> + Send + '_ {
182        let ports_arc: Arc<[(u16, Protocol)]> = self.ports.to_vec().into();
183
184        self.ips.iter().flat_map(move |ip| {
185            let ports = Arc::clone(&ports_arc);
186            (0..ports.len()).map(move |i| {
187                let (port, protocol) = ports[i];
188                Target { ip, port, protocol }
189            })
190        })
191    }
192
193    /// Returns true if either the IP set or the Port set is completely empty.
194    pub fn is_empty(&self) -> bool {
195        self.ips.is_empty() || self.ports.is_empty()
196    }
197}
198
199/// A collection of multiple [`TargetSet`] units.
200#[non_exhaustive]
201#[derive(Debug, Clone, Default, PartialEq, Eq)]
202pub struct TargetMap {
203    /// The units, in the order they were added.
204    ///
205    /// Public because there is no invariant to protect: each [`TargetSet`] is
206    /// canonical and immutable, and this type caches nothing derived from them.
207    pub units: Vec<TargetSet>,
208}
209
210impl TargetMap {
211    /// Creates a new, empty `TargetMap`.
212    pub fn new() -> Self {
213        Self::default()
214    }
215
216    /// Adds a new unit definition to the map.
217    pub fn add_unit(&mut self, unit: TargetSet) {
218        self.units.push(unit);
219    }
220
221    /// Whether any unit names a port on `protocol`.
222    ///
223    /// Read when a scan is assembled, to decide whether a transport not probed by
224    /// default needs a socket.
225    pub fn names(&self, protocol: Protocol) -> bool {
226        self.units
227            .iter()
228            .any(|unit| !unit.ports().ranges(protocol).is_empty())
229    }
230
231    /// Returns the gross total of target connections across all units.
232    ///
233    /// Gross: two units naming the same address each count it, since they ask
234    /// different questions about it.
235    pub fn gross_targets(&self) -> Result<u128, TargetError> {
236        let mut total: u128 = 0;
237        for unit in &self.units {
238            let unit_total = unit.total_targets()?;
239            total = total
240                .checked_add(unit_total)
241                .ok_or(TargetError::CapacityOverflow)?;
242        }
243        Ok(total)
244    }
245
246    /// Returns the gross number of IP addresses across all units.
247    pub fn gross_ips(&self) -> Result<u128, TargetError> {
248        let mut total: u128 = 0;
249        for unit in &self.units {
250            total = total
251                .checked_add(unit.ip_count())
252                .ok_or(TargetError::CapacityOverflow)?;
253        }
254        Ok(total)
255    }
256
257    /// Returns true if no targets are defined across any unit.
258    pub fn is_empty(&self) -> bool {
259        self.units.is_empty() || self.units.iter().all(|u| u.is_empty())
260    }
261
262    /// Creates a flattened iterator over every target in every unit.
263    pub fn iter(&self) -> impl Iterator<Item = Target> + Send + '_ {
264        self.units.iter().flat_map(|unit| unit.iter())
265    }
266
267    /// Takes `excluded` out of every unit's ports, and drops a unit left with
268    /// none.
269    ///
270    /// A unit with every port excluded has nothing to ask, so a liveness pass spends no
271    /// probes on its addresses. A scan does this itself with
272    /// [`ZondConfig::excluded_ports`](crate::config::ZondConfig::excluded_ports); a
273    /// caller estimating a scan's cost beforehand does it to a copy.
274    pub fn withhold_ports(&mut self, excluded: &PortSet) {
275        if excluded.is_empty() {
276            return;
277        }
278        self.units = std::mem::take(&mut self.units)
279            .into_iter()
280            .filter_map(|unit| {
281                let (ips, ports) = unit.into_parts();
282                let kept = ports.difference(excluded);
283                (!kept.is_empty()).then(|| TargetSet::new(ips, kept))
284            })
285            .collect();
286    }
287
288    /// Takes out every target a port phase cannot probe, which it does before
289    /// anything numbers the plan: the link-local ranges that name no
290    /// interface or name an address another range names on another, then the
291    /// IPv6 ranges `walkable` refuses as too wide to walk. Hands back what it
292    /// took out and the interface each link-local range it kept was named on.
293    ///
294    /// The port phase, a journal's job total, and a caller announcing what a scan will
295    /// ask all use this, so they agree; a total that counted a withheld target would
296    /// never be reached. What is taken out depends on the targets alone, so every
297    /// sitting of a job takes out the same ones.
298    ///
299    /// `interfaces` is the host's interface table as index and name, naming the zones
300    /// handed back; `walkable` is the host's limit on what a walk may cover. The caller
301    /// supplies both.
302    pub(crate) fn take_unprobeable(
303        &mut self,
304        interfaces: &[(u32, &str)],
305        walkable: impl Fn(&Ipv6Range) -> bool,
306    ) -> Unprobeable {
307        let mut unscoped: Vec<Ipv6Range> = Vec::new();
308        let mut contested: Vec<Ipv6Range> = Vec::new();
309        let mut zones = ZoneMap::new();
310        for range in self.units.iter().flat_map(|unit| unit.ips().v6()) {
311            if range.is_ambiguous() {
312                unscoped.push(*range);
313            } else if zones.contests(range) {
314                contested.push(*range);
315            } else {
316                zones.insert(*range, interfaces);
317            }
318        }
319        self.keep_v6(|range| !unscoped.contains(range) && !contested.contains(range));
320        unscoped.sort_unstable_by_key(|range| range.start_addr());
321        unscoped.dedup();
322
323        let mut unwalkable: Vec<Ipv6Range> = self
324            .units
325            .iter()
326            .flat_map(|unit| unit.ips().v6().iter().copied())
327            .filter(|range| !walkable(range))
328            .collect();
329        if !unwalkable.is_empty() {
330            unwalkable.sort_unstable_by_key(|range| range.start_addr());
331            unwalkable.dedup();
332            self.keep_v6(&walkable);
333        }
334
335        Unprobeable {
336            zones,
337            unscoped,
338            contested,
339            unwalkable,
340        }
341    }
342
343    /// Keeps the IPv6 ranges `keep` accepts, dropping a unit left with no
344    /// address.
345    fn keep_v6(&mut self, keep: impl Fn(&Ipv6Range) -> bool) {
346        let mut kept = Vec::with_capacity(self.units.len());
347        for unit in std::mem::take(&mut self.units) {
348            let (ips, ports) = unit.into_parts();
349            let mut left = IpSet::new();
350            for range in ips.v4() {
351                left.push_v4_range(*range);
352            }
353            for range in ips.v6() {
354                if keep(range) {
355                    left.push_v6_range(*range);
356                }
357            }
358            left.canonicalize();
359            if !left.is_empty() {
360                kept.push(TargetSet::new(left, ports));
361            }
362        }
363        self.units = kept;
364    }
365}
366
367/// What [`TargetMap::take_unprobeable`] took out, and the zones the
368/// link-local ranges it kept were named on.
369pub(crate) struct Unprobeable {
370    /// The interface each kept link-local range was named on.
371    pub(crate) zones: ZoneMap,
372    /// Link-local ranges that name no interface, ascending.
373    pub(crate) unscoped: Vec<Ipv6Range>,
374    /// Link-local ranges naming an address another range names on another
375    /// interface.
376    pub(crate) contested: Vec<Ipv6Range>,
377    /// Ranges too wide to walk, ascending.
378    pub(crate) unwalkable: Vec<Ipv6Range>,
379}
380
381/// The same targets [`TargetMap::iter`] yields, addressed by position instead of
382/// walked in order.
383///
384/// [`iter`](TargetMap::iter) numbers a plan: its nth target is position n, and a journal
385/// records progress as one of those numbers. A scan asking in another order needs the
386/// reverse, the target a position names, which this provides.
387///
388/// The dispatcher decides what to probe by one and the cursor records what was probed
389/// by the other, so [`target_at`](Self::target_at) must agree with `iter().nth()` for
390/// every position; the tests below hold it to that.
391///
392/// Costs a few words per unit and nothing per target. Addresses are numbered by
393/// [`Positions`], a table of a unit's ranges; a position resolves with one binary
394/// search and two divisions.
395#[derive(Debug, Clone)]
396pub struct TargetIndex {
397    /// The numbered units, in the order [`TargetMap::iter`] walks them.
398    units: Vec<UnitIndex>,
399    /// How many targets are numbered.
400    total: u64,
401    /// How many hosts hold them; see [`hosts`](Self::hosts).
402    hosts: u64,
403    /// Whether that is every target the map holds.
404    complete: bool,
405    /// The addresses of the units the numbering stopped at and after, which is
406    /// every unit it left out. Empty exactly when `complete` is true.
407    unnumbered: Vec<IpRange>,
408}
409
410/// One unit of a [`TargetIndex`], and where its targets sit in the numbering.
411#[derive(Debug, Clone)]
412struct UnitIndex {
413    /// The unit's addresses, numbered.
414    addresses: Positions,
415    /// The unit's ports, in the order its iterator pairs them with an address.
416    ports: Arc<[(u16, Protocol)]>,
417    /// The position of the unit's first target.
418    start: u64,
419    /// How many targets it holds: its addresses times its ports.
420    len: u64,
421    /// The number of the unit's first host; see [`TargetIndex::hosts`].
422    first_host: u64,
423}
424
425impl TargetIndex {
426    /// Numbers `map`'s targets.
427    ///
428    /// Numbering stops at the first unit that cannot be counted whole, and every unit
429    /// after it is left out, since positions must stay contiguous (as in
430    /// [`Positions`]). [`is_complete`](Self::is_complete) then answers false; a caller
431    /// that needs the whole plan addressed checks that first.
432    ///
433    /// A unit is uncountable when its addresses are (an IPv6 range of a `/64` or
434    /// wider), or when addresses times ports overflows the numbering. Both describe a
435    /// plan no scan finishes.
436    pub fn of(map: &TargetMap) -> Self {
437        let mut units = Vec::with_capacity(map.units.len());
438        let mut total: u64 = 0;
439        let mut hosts: u64 = 0;
440        let mut complete = true;
441        let mut unnumbered = Vec::new();
442
443        for (at, unit) in map.units.iter().enumerate() {
444            let addresses = Positions::of(unit.ips());
445            let ports: Arc<[(u16, Protocol)]> = unit.ports().to_vec().into();
446
447            // A unit with no ports takes no positions; `iter` skips it too.
448            if ports.is_empty() {
449                continue;
450            }
451
452            let counted = u64::try_from(ports.len())
453                .ok()
454                .and_then(|ports| addresses.total().checked_mul(ports))
455                .filter(|_| addresses.unnumbered().is_empty());
456
457            let Some(len) = counted.filter(|len| total.checked_add(*len).is_some()) else {
458                complete = false;
459                // A unit without ports has nothing to ask, as above.
460                for left_out in map.units[at..]
461                    .iter()
462                    .filter(|unit| !unit.ports().is_empty())
463                {
464                    let ips = left_out.ips();
465                    unnumbered.extend(ips.v4().iter().copied().map(IpRange::V4));
466                    unnumbered.extend(ips.v6().iter().copied().map(IpRange::V6));
467                }
468                break;
469            };
470
471            let first_host = hosts;
472            // No more hosts than targets, which fit.
473            hosts += addresses.total();
474            units.push(UnitIndex {
475                addresses,
476                ports,
477                start: total,
478                len,
479                first_host,
480            });
481            total += len;
482        }
483
484        Self {
485            units,
486            total,
487            hosts,
488            complete,
489            unnumbered,
490        }
491    }
492
493    /// How many targets are numbered.
494    pub fn total(&self) -> u64 {
495        self.total
496    }
497
498    /// Whether every target the map holds is numbered.
499    ///
500    /// False for a plan whose addresses outrun the numbering, where
501    /// [`total`](Self::total) counts only a prefix of [`TargetMap::iter`]. A caller
502    /// walking positions must check this, or it covers part of the plan and reports
503    /// all of it.
504    pub fn is_complete(&self) -> bool {
505        self.complete
506    }
507
508    /// The target at `position`, or [`None`] past the end of the numbering.
509    pub fn target_at(&self, position: u64) -> Option<Target> {
510        let unit = self.unit_at(position)?;
511        let local = position - unit.start;
512
513        // The unit's iterator pairs each address with every port before moving
514        // to the next address, so the port index runs fastest.
515        let ports = unit.ports.len() as u64;
516        let (port, protocol) = unit.ports[(local % ports) as usize];
517        let ip = unit.addresses.address_at(local / ports)?;
518
519        Some(Target { ip, port, protocol })
520    }
521
522    /// The addresses holding at least one of the targets numbered `positions`,
523    /// as ranges.
524    ///
525    /// For a pass that asks about addresses. An address is included if any of its
526    /// targets is in the span, so a span starting on an address's third port still
527    /// holds that address.
528    ///
529    /// Positions past [`total`](Self::total) are ignored; see
530    /// [`unnumbered_addresses`](Self::unnumbered_addresses).
531    pub(crate) fn addresses_in(&self, positions: Range<u64>) -> Vec<IpRange> {
532        let end = positions.end.min(self.total);
533        let mut found = Vec::new();
534
535        // Units are contiguous and ascending: start at the first ending past the
536        // span's start.
537        let first = self
538            .units
539            .partition_point(|unit| unit.start + unit.len <= positions.start);
540
541        for unit in &self.units[first..] {
542            if unit.start >= end {
543                break;
544            }
545            let from = positions.start.max(unit.start) - unit.start;
546            let to = end.min(unit.start + unit.len) - unit.start;
547            if from >= to {
548                continue;
549            }
550
551            let ports = unit.ports.len() as u64;
552            let addresses = from / ports..(to - 1) / ports + 1;
553            found.extend(unit.addresses.ranges_in(addresses));
554        }
555
556        found
557    }
558
559    /// The positions of every target at `ip`, one run for each unit naming
560    /// it, and none where no unit numbers it.
561    ///
562    /// Contiguous for the reason [`host_run`](Self::host_run) gives: a unit
563    /// pairs an address with every port before moving to the next.
564    pub(crate) fn runs_at(&self, ip: IpAddr) -> impl Iterator<Item = Range<u64>> + '_ {
565        self.units.iter().filter_map(move |unit| {
566            let ports = unit.ports.len() as u64;
567            let start = unit.start + unit.addresses.find(ip)? * ports;
568            Some(start..start + ports)
569        })
570    }
571
572    /// How many hosts the numbering holds: an address of a unit and every port
573    /// the unit pairs it with.
574    ///
575    /// Numbered in plan order, each holding a contiguous run of positions; see
576    /// [`host_run`](Self::host_run). An address two units name is two hosts here.
577    pub(crate) fn hosts(&self) -> u64 {
578        self.hosts
579    }
580
581    /// The positions of the host numbered `host`, which is below
582    /// [`hosts`](Self::hosts); an empty run past the end.
583    pub(crate) fn host_run(&self, host: u64) -> Range<u64> {
584        let at = self
585            .units
586            .partition_point(|unit| unit.first_host + unit.addresses.total() <= host);
587        let Some(unit) = self.units.get(at) else {
588            return self.total..self.total;
589        };
590        let ports = unit.ports.len() as u64;
591        let start = unit.start + (host - unit.first_host) * ports;
592        start..start + ports
593    }
594
595    /// The host whose run holds `position`, which is below
596    /// [`total`](Self::total); [`hosts`](Self::hosts) past the end.
597    pub(crate) fn host_of(&self, position: u64) -> u64 {
598        match self.unit_at(position) {
599            Some(unit) => unit.first_host + (position - unit.start) / unit.ports.len() as u64,
600            None => self.hosts,
601        }
602    }
603
604    /// The addresses of every unit the numbering could not reach, which is
605    /// empty exactly when the index [is complete](Self::is_complete).
606    ///
607    /// No position names a target at these, so a caller asking which addresses have
608    /// work outstanding must count all of them.
609    pub(crate) fn unnumbered_addresses(&self) -> &[IpRange] {
610        &self.unnumbered
611    }
612
613    /// The unit holding `position`.
614    fn unit_at(&self, position: u64) -> Option<&UnitIndex> {
615        if position >= self.total {
616            return None;
617        }
618        let index = match self
619            .units
620            .binary_search_by_key(&position, |unit| unit.start)
621        {
622            Ok(index) => index,
623            // Units are contiguous and ascending by `start`, so the holder is the
624            // unit before the first one starting above `position`.
625            Err(0) => return None,
626            Err(index) => index - 1,
627        };
628        self.units
629            .get(index)
630            .filter(|unit| position < unit.start + unit.len)
631    }
632}
633
634// ╔════════════════════════════════════════════╗
635// ║ ████████╗███████╗███████╗████████╗███████╗ ║
636// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
637// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
638// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
639// ║    ██║   ███████╗███████║   ██║   ███████║ ║
640// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
641// ╚════════════════════════════════════════════╝
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    fn ips(written: &str) -> IpSet {
648        written.parse().expect("a valid address specification")
649    }
650
651    fn ports(written: &str) -> PortSet {
652        written.parse().expect("a valid port specification")
653    }
654
655    /// A plan that runs several units, of both families, with ports that do not
656    /// divide evenly into anything.
657    ///
658    /// Off-by-ones live at unit boundaries and at the wrap from one address's last port
659    /// to the next address's first, which an evenly sized fixture would miss.
660    fn awkward() -> TargetMap {
661        let mut map = TargetMap::new();
662        map.add_unit(TargetSet::new(ips("192.0.2.0/29"), ports("22, 80, u:53")));
663        map.add_unit(TargetSet::new(ips("198.51.100.7"), ports("443")));
664        map.add_unit(TargetSet::new(
665            ips("203.0.113.0/30, 192.0.2.200-192.0.2.203"),
666            ports("1-5, s:2905"),
667        ));
668        map.add_unit(TargetSet::new(ips("2001:db8::/126"), ports("80, u:161")));
669        map
670    }
671
672    /// A position names the target the plan's own walk gives it; otherwise a resume
673    /// would skip ground nobody probed.
674    #[test]
675    fn a_position_names_the_target_the_plans_own_walk_numbers_it() {
676        let map = awkward();
677        let index = TargetIndex::of(&map);
678
679        let walked: Vec<Target> = map.iter().collect();
680        assert!(index.is_complete());
681        assert_eq!(index.total(), walked.len() as u64);
682
683        for (position, expected) in walked.iter().enumerate() {
684            assert_eq!(
685                index.target_at(position as u64).as_ref(),
686                Some(expected),
687                "position {position}"
688            );
689        }
690        assert_eq!(index.target_at(index.total()), None, "past the end");
691    }
692
693    /// Every host's run is the positions of one address's targets in one unit, the
694    /// runs tile the numbering in order, and each position's host is the run holding
695    /// it. A resume reads which hosts have work left by these.
696    #[test]
697    fn the_hosts_tile_the_numbering_one_address_each() {
698        let index = TargetIndex::of(&awkward());
699
700        let mut next = 0;
701        for host in 0..index.hosts() {
702            let run = index.host_run(host);
703            assert_eq!(run.start, next, "host {host} starts where the last ended");
704            assert!(!run.is_empty());
705            let first = index.target_at(run.start).expect("inside the numbering");
706            for position in run.clone() {
707                assert_eq!(index.host_of(position), host, "position {position}");
708                let target = index.target_at(position).expect("inside the numbering");
709                assert_eq!(target.ip, first.ip, "position {position}");
710            }
711            next = run.end;
712        }
713        assert_eq!(next, index.total(), "and cover it");
714        assert_eq!(index.host_of(index.total()), index.hosts(), "past the end");
715    }
716
717    /// A unit naming no port takes no positions and leaves no gap.
718    #[test]
719    fn a_unit_with_no_ports_takes_no_positions() {
720        let mut map = TargetMap::new();
721        map.add_unit(TargetSet::new(ips("192.0.2.1"), ports("22")));
722        map.add_unit(TargetSet::new(ips("192.0.2.0/24"), PortSet::new()));
723        map.add_unit(TargetSet::new(ips("192.0.2.2"), ports("80")));
724
725        let index = TargetIndex::of(&map);
726        let walked: Vec<Target> = map.iter().collect();
727
728        assert_eq!(index.total(), 2);
729        assert_eq!(index.total(), walked.len() as u64);
730        assert_eq!(index.target_at(0).as_ref(), walked.first());
731        assert_eq!(index.target_at(1).as_ref(), walked.get(1));
732    }
733
734    /// An address range the numbering cannot reach marks the index incomplete.
735    #[test]
736    fn a_plan_wider_than_the_numbering_is_incomplete_and_says_so() {
737        let mut map = TargetMap::new();
738        map.add_unit(TargetSet::new(ips("192.0.2.1"), ports("22")));
739        map.add_unit(TargetSet::new(ips("2001:db8::/48"), ports("80")));
740        map.add_unit(TargetSet::new(ips("198.51.100.1"), ports("443")));
741
742        let index = TargetIndex::of(&map);
743
744        assert!(!index.is_complete());
745        assert_eq!(index.total(), 1, "only the units before the wide one");
746        assert_eq!(
747            index.target_at(1),
748            None,
749            "a position the numbering never reached names nothing"
750        );
751    }
752
753    /// A `/64` holds one address more than a position can count, so it is the first
754    /// prefix that cannot be numbered.
755    #[test]
756    fn a_sixty_four_is_the_first_prefix_the_numbering_cannot_reach() {
757        let indexed = |prefix: &str| {
758            let mut map = TargetMap::new();
759            map.add_unit(TargetSet::new(ips(prefix), ports("80")));
760            TargetIndex::of(&map).is_complete()
761        };
762
763        assert!(indexed("2001:db8::/65"), "a /65 fits");
764        assert!(!indexed("2001:db8::/64"), "a /64 is one address too many");
765        assert!(!indexed("2001:db8::/48"), "and anything wider is too");
766    }
767
768    /// An empty plan numbers nothing and is complete.
769    #[test]
770    fn an_empty_plan_numbers_nothing() {
771        let index = TargetIndex::of(&TargetMap::new());
772
773        assert!(index.is_complete());
774        assert_eq!(index.total(), 0);
775        assert_eq!(index.target_at(0), None);
776    }
777
778    /// Every span of the numbering names exactly the addresses its targets are
779    /// at, checked against the plan's own walk for every span there is.
780    ///
781    /// Exhaustive because the mistakes are at the edges: a span starting or ending
782    /// partway through an address's ports, crossing into the next unit, or ending on a
783    /// unit boundary.
784    #[test]
785    fn every_span_names_exactly_the_addresses_its_targets_are_at() {
786        let map = awkward();
787        let index = TargetIndex::of(&map);
788        let walked: Vec<Target> = map.iter().collect();
789        let total = walked.len();
790
791        for start in 0..=total {
792            for end in start..=total + 2 {
793                let mut expected = IpSet::new();
794                for target in &walked[start..end.min(total)] {
795                    expected.insert(target.ip);
796                }
797                expected.canonicalize();
798
799                let mut named = IpSet::new();
800                for range in index.addresses_in(start as u64..end as u64) {
801                    named.insert_range(range);
802                }
803                named.canonicalize();
804
805                assert_eq!(named, expected, "positions {start}..{end}");
806            }
807        }
808        assert!(index.unnumbered_addresses().is_empty(), "a complete index");
809    }
810
811    /// Units the numbering never reached come back as addresses; a unit naming no port
812    /// is left out.
813    #[test]
814    fn the_units_past_the_numbering_are_left_out_whole() {
815        let mut map = TargetMap::new();
816        map.add_unit(TargetSet::new(ips("192.0.2.1"), ports("22")));
817        map.add_unit(TargetSet::new(ips("2001:db8::/64"), ports("80")));
818        map.add_unit(TargetSet::new(ips("198.51.100.0/24"), PortSet::new()));
819        map.add_unit(TargetSet::new(ips("203.0.113.9"), ports("443")));
820
821        let index = TargetIndex::of(&map);
822        let mut unnumbered = IpSet::new();
823        for range in index.unnumbered_addresses() {
824            unnumbered.insert_range(*range);
825        }
826        unnumbered.canonicalize();
827
828        assert!(!index.is_complete());
829        assert_eq!(unnumbered, ips("2001:db8::/64, 203.0.113.9"));
830    }
831
832    /// Decides whether a scan opens a socket for SCTP.
833    #[test]
834    fn a_map_says_which_transports_its_units_name() {
835        let mut map = TargetMap::new();
836        map.add_unit(TargetSet::new(ips("192.0.2.1"), ports("80, u:53")));
837
838        assert!(map.names(Protocol::Tcp));
839        assert!(map.names(Protocol::Udp));
840        assert!(!map.names(Protocol::Sctp));
841
842        map.add_unit(TargetSet::new(ips("192.0.2.2"), ports("s:2905")));
843        assert!(map.names(Protocol::Sctp));
844    }
845
846    /// The cross product's size, which a caller checks a scan budget against.
847    #[test]
848    fn a_sets_target_count_is_its_addresses_times_its_ports() {
849        let ts = TargetSet::new(ips("192.0.2.0/24"), ports("80, 443"));
850        assert_eq!(ts.total_targets().unwrap(), 256 * 2);
851    }
852
853    /// A set is merged when it becomes a `TargetSet`, so overlapping ranges are not
854    /// counted twice.
855    #[test]
856    fn a_target_set_merges_its_addresses_on_construction() {
857        let mut overlapping = ips("192.0.2.0/24");
858        overlapping.insert_range("192.0.2.128/25".parse().expect("valid range"));
859
860        let ts = TargetSet::new(overlapping, ports("80"));
861
862        // 256, not the 384 the two arguments add up to.
863        assert_eq!(ts.ip_count(), 256);
864        assert_eq!(ts.total_targets().unwrap(), 256);
865    }
866
867    /// Pins the cross product's triples, since different pairings give the same count.
868    #[test]
869    fn a_set_yields_every_address_paired_with_every_port() {
870        let ts = TargetSet::new(ips("192.0.2.1-192.0.2.2"), ports("80, u:53"));
871
872        let mut targets: Vec<(String, u16, Protocol)> = ts
873            .iter()
874            .map(|target| (target.ip.to_string(), target.port, target.protocol))
875            .collect();
876        targets.sort();
877
878        assert_eq!(
879            targets,
880            vec![
881                ("192.0.2.1".to_string(), 53, Protocol::Udp),
882                ("192.0.2.1".to_string(), 80, Protocol::Tcp),
883                ("192.0.2.2".to_string(), 53, Protocol::Udp),
884                ("192.0.2.2".to_string(), 80, Protocol::Tcp),
885            ]
886        );
887    }
888
889    /// A map's iterator flattens its units in the order they were added.
890    #[test]
891    fn a_map_iterates_its_units_in_the_order_they_were_added() {
892        let mut map = TargetMap::new();
893        map.add_unit(TargetSet::new(ips("192.0.2.1"), ports("80")));
894        map.add_unit(TargetSet::new(ips("192.0.2.2"), ports("u:53")));
895
896        let targets: Vec<(String, u16, Protocol)> = map
897            .iter()
898            .map(|target| (target.ip.to_string(), target.port, target.protocol))
899            .collect();
900
901        assert_eq!(
902            targets,
903            vec![
904                ("192.0.2.1".to_string(), 80, Protocol::Tcp),
905                ("192.0.2.2".to_string(), 53, Protocol::Udp),
906            ]
907        );
908    }
909
910    /// `::/0` is 2^128 addresses, which [`IpSet::len`] saturates to `u128::MAX`. One
911    /// port fits; two must be refused, not wrapped.
912    #[test]
913    fn a_target_count_too_large_to_represent_is_refused_rather_than_wrapped() {
914        let two_ports = TargetSet::new(ips("::/0"), ports("80, 443"));
915        assert_eq!(
916            two_ports.total_targets(),
917            Err(TargetError::CapacityOverflow)
918        );
919
920        let one_port = TargetSet::new(ips("::/0"), ports("80"));
921        assert_eq!(one_port.total_targets().unwrap(), u128::MAX);
922    }
923
924    /// A map's total is the sum of its units'.
925    #[test]
926    fn a_maps_total_is_the_sum_of_its_units() {
927        let mut map = TargetMap::new();
928        map.add_unit(TargetSet::new(ips("192.0.2.1-192.0.2.5"), ports("80,443")));
929        assert_eq!(map.gross_targets().unwrap(), 10);
930    }
931}