Skip to main content

zond_engine/model/parse/
ip.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//! # Addresses, as a person writes them
10//!
11//! The grammar that turns what someone typed into an [`IpSet`]. This is the
12//! address half of a target expression; the ports after it are
13//! [`super::target`]'s business.
14//!
15//! ## What it accepts
16//!
17//! | Written | Means |
18//! |---|---|
19//! | `127.0.0.1`, `2001:db8::1` | one address |
20//! | `192.0.2.0/24`, `2001:db8::/64` | a CIDR block |
21//! | `198.51.100.1-198.51.100.50` | a range, both ends written out |
22//! | `198.51.100.1-50`, `192.168.1.1-2.254` | a range whose end continues the start's octets |
23//! | `fe80::1%en0` | a link-local address on a named interface |
24//! | `lan` | a keyword, resolved by the caller |
25//!
26//! The shortened range is IPv4 only: the end is read as however many trailing
27//! octets it names, so `198.51.100.1-50` ends at `198.51.100.50` and
28//! `192.168.1.1-2.254` at `192.168.2.254`. IPv6 has no comparable form, and
29//! inventing one would make `::1-5` ambiguous with hex.
30//!
31//! ## An IPv4-mapped address is the IPv4 host it spells
32//!
33//! `::ffff:192.0.2.1` is how RFC 4291 §2.5.5.2 writes `192.0.2.1` inside an IPv6
34//! address; a dual-stack socket handed it connects over IPv4, and no packet carries it.
35//! So an address, block or range written wholly inside `::ffff:0:0/96` becomes the IPv4
36//! one it spells, as [`Exclusions`](crate::model::exclusion::Exclusions) reads it too.
37//! Kept as IPv6 it would be probed as off-link IPv6 and reported apart from the same
38//! machine written normally.
39//!
40//! A range reaching outside the block is kept as written: whoever writes `::/0` means
41//! IPv6.
42//!
43//! ## Lookups are supplied by the caller
44//!
45//! Resolving `lan` reads this host's interface table, and resolving `%en0` looks up a
46//! name in it. Both arrive as caller-supplied functions ([`ResolverFn`],
47//! [`ZoneResolverFn`]), so this module knows nothing about the machine. An expression
48//! needing a lookup the caller did not supply is **refused**, so a scan never silently
49//! covers less than its input said.
50//!
51//! Hostnames are resolved by [`super::target::TargetMapBuilder`], since whether a name
52//! may be looked up is a policy question. An expression matching none of the forms
53//! above comes back as [`IpParseError::Malformed`], the signal to try it as a name.
54
55use std::net::IpAddr;
56use thiserror::Error;
57
58use crate::model::ip::range::{IpError, IpRange};
59use crate::model::ip::set::IpSet;
60
61/// A name standing for a set of addresses only the running host can supply.
62///
63/// Written in place of an address and expanded by the caller's [`ResolverFn`].
64#[non_exhaustive]
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Keyword {
67    /// The local segment: the network on the interface carrying this host's
68    /// default route.
69    Lan,
70}
71
72impl Keyword {
73    /// Every keyword this build knows, in declaration order.
74    ///
75    /// [`from_token`](Self::from_token) and [`names_keyword`] read this list, so a
76    /// keyword missing from it would fall through to the address parser, come back
77    /// [`Malformed`](IpParseError::Malformed), be looked up in DNS, and never trigger a
78    /// segment sweep.
79    pub const ALL: &'static [Self] = &[Self::Lan];
80
81    /// The word as it is written in a target expression.
82    pub fn as_str(self) -> &'static str {
83        match self {
84            Keyword::Lan => "lan",
85        }
86    }
87
88    /// The keyword `token` is, if it is one.
89    ///
90    /// Case-insensitive, and the same test [`insert_expression`] applies.
91    pub fn from_token(token: &str) -> Option<Self> {
92        let token = token.trim();
93        Self::ALL
94            .iter()
95            .copied()
96            .find(|keyword| token.eq_ignore_ascii_case(keyword.as_str()))
97    }
98}
99
100/// Whether any of these target expressions names `keyword`.
101///
102/// A scan of the local segment sends an all-nodes echo and reads the neighbour table,
103/// which a scan of the same addresses does not, so a caller offering `lan` needs to
104/// know whether it was used.
105///
106/// Splits on commas the way [`to_set`] does, so `"lan,198.51.100.0/24"` counts.
107pub fn names_keyword<S: AsRef<str>>(targets: &[S], keyword: Keyword) -> bool {
108    targets.iter().any(|target| {
109        target
110            .as_ref()
111            .split(',')
112            .any(|part| Keyword::from_token(part) == Some(keyword))
113    })
114}
115
116/// Errors encountered during the parsing or resolution of IP-related strings.
117#[non_exhaustive]
118#[derive(Debug, Clone, PartialEq, Eq, Error)]
119pub enum IpParseError {
120    /// The CIDR prefix is longer than its address family allows.
121    ///
122    /// The message names both families' bounds, since the variant does not carry the
123    /// family.
124    ///
125    /// A `u32`, so `/999` is reported as a bad prefix. In a `u8` it would be
126    /// [`Malformed`](Self::Malformed), which a caller takes as "might be a hostname",
127    /// sending a typo to DNS.
128    #[error("Invalid CIDR prefix: {0} (0-32 for IPv4, 0-128 for IPv6)")]
129    InvalidPrefix(u32),
130
131    /// The start address of a range is numerically higher than the end address.
132    #[error("Invalid range: start address {0} is greater than end address {1}")]
133    InvalidRange(IpAddr, IpAddr),
134
135    /// The input string does not match any known IP, Range, or CIDR format.
136    #[error("Malformed IP or range string: '{0}'")]
137    Malformed(String),
138
139    /// A keyword's resolver could not answer.
140    ///
141    /// Carries the keyword, since [`Keyword`] may grow. The reason is prose from the
142    /// caller's resolver.
143    #[error("could not resolve `{keyword}`: {reason}")]
144    KeywordUnresolved {
145        /// The word that could not be expanded.
146        keyword: &'static str,
147        /// What the caller's resolver said about it.
148        reason: String,
149    },
150
151    /// The provided input resulted in zero valid IP addresses.
152    #[error("Target input resulted in an empty set")]
153    EmptySet,
154
155    /// An `%interface` suffix was written on a target that cannot use one.
156    #[error("'{0}': only a link-local address is scoped to an interface")]
157    ZoneOnUnscopedTarget(String),
158
159    /// An `%interface` suffix named an interface this host does not have, or
160    /// none could be looked up at all.
161    #[error("No interface named '{0}'")]
162    UnknownInterface(String),
163}
164
165/// Expands a [`Keyword`] into the addresses it stands for.
166///
167/// Supplied by the caller, since answering reads the host's interface table. Writes into
168/// the set it is given, so a keyword mixed with literal targets accumulates alongside
169/// them.
170///
171/// A borrowed `dyn Fn`, so a resolver may close over state such as an interface table
172/// read once; it stays `Copy`, so [`TargetContext`](super::target::TargetContext) does
173/// too.
174///
175/// `Sync`, so a `&` to one is `Send` and a caller can hold the context across an await
176/// in a spawned task.
177pub type ResolverFn<'a> = &'a (dyn Fn(Keyword, &mut IpSet) -> Result<(), IpParseError> + Sync);
178
179/// Looks up an interface by name and returns its scope id.
180///
181/// Supplied by the caller, like [`ResolverFn`], and `Sync` for the same reason. `None`
182/// for a name no interface answers to.
183pub type ZoneResolverFn<'a> = &'a (dyn Fn(&str) -> Option<u32> + Sync);
184
185/// Resolves a list of address expressions into one [`IpSet`].
186///
187/// Each element may itself be a comma-separated list, so a single argument and
188/// a whole file of targets go through the same call. Surrounding whitespace is
189/// trimmed and empty elements are skipped.
190///
191/// # Errors
192///
193/// The first expression that does not parse, or [`IpParseError::EmptySet`] if nothing
194/// was named.
195///
196/// Without `zones`, a zoned link-local target fails with
197/// [`IpParseError::UnknownInterface`].
198///
199/// # Examples
200///
201/// ```
202/// use zond_engine::model::parse::ip::to_set;
203///
204/// let set = to_set(&["192.0.2.0/24", "198.51.100.1", "198.51.100.5-10"], None, None).unwrap();
205///
206/// // 256 from the block, one literal, six from the range.
207/// assert_eq!(set.len(), 263);
208/// ```
209pub fn to_set<S>(
210    ips: &[S],
211    resolver: Option<ResolverFn<'_>>,
212    zones: Option<ZoneResolverFn<'_>>,
213) -> Result<IpSet, IpParseError>
214where
215    S: AsRef<str>,
216{
217    let mut set = IpSet::new();
218
219    for ip in ips {
220        let s = ip.as_ref().trim();
221        if s.is_empty() {
222            continue;
223        }
224
225        for part in s.split(',').map(|p| p.trim()).filter(|p| !p.is_empty()) {
226            insert_expression(part, &mut set, resolver, zones)?;
227        }
228    }
229
230    if set.is_empty() {
231        return Err(IpParseError::EmptySet);
232    }
233
234    Ok(set)
235}
236
237/// Identifies the format of a single address expression and inserts it into an
238/// existing set.
239///
240/// The grammar without [`to_set`]'s list handling, for a caller that has already
241/// tokenized its input, such as an importer reading a file of targets.
242///
243/// Nothing is inserted when the expression is refused.
244///
245/// [`IpParseError::Malformed`] means the expression matches no address, range or CIDR
246/// form, which is also what a hostname looks like; a caller accepting hostnames tries
247/// resolving one. Every other error describes a wrong address.
248pub fn insert_expression(
249    s: &str,
250    set: &mut IpSet,
251    resolver: Option<ResolverFn<'_>>,
252    zones: Option<ZoneResolverFn<'_>>,
253) -> Result<(), IpParseError> {
254    // Trimmed here too, for direct callers: `Keyword::from_token` trims but
255    // `IpAddr::from_str` does not, so ` 198.51.100.1 ` would otherwise come back
256    // malformed and be tried as a hostname.
257    let s = s.trim();
258
259    // The suffix applies to whatever the rest parses to, so `fe80::1%en0` and
260    // `fe80::1-fe80::5%en0` both work.
261    if let Some((address, zone)) = s.split_once('%') {
262        return parse_scoped(s, address, zone, set, zones);
263    }
264
265    if s.contains('/') {
266        let range = parse_cidr(s)?;
267        set.insert_range(as_hosts(range));
268        return Ok(());
269    }
270
271    if s.contains('-') {
272        let range = parse_range(s)?;
273        set.insert_range(as_hosts(range));
274        return Ok(());
275    }
276
277    if let Some(keyword) = Keyword::from_token(s) {
278        let Some(resolve) = resolver else {
279            return Err(IpParseError::KeywordUnresolved {
280                keyword: keyword.as_str(),
281                reason: "no resolver was supplied to expand it".to_string(),
282            });
283        };
284        return resolve(keyword, set);
285    }
286
287    let ip = s
288        .parse::<IpAddr>()
289        .map_err(|_| IpParseError::Malformed(s.to_string()))?;
290    set.insert(ip.to_canonical());
291
292    Ok(())
293}
294
295/// `range` as the hosts it names: a range written wholly inside the
296/// IPv4-mapped block is the IPv4 range it spells, and anything else is itself.
297/// See the module documentation.
298fn as_hosts(range: IpRange) -> IpRange {
299    match range {
300        IpRange::V6(v6) => v6.spelled_ipv4().map_or(range, IpRange::V4),
301        IpRange::V4(_) => range,
302    }
303}
304
305/// Parses a target carrying an explicit `%interface` suffix.
306///
307/// The suffix is only meaningful on a link-local address, and only resolvable with a
308/// caller-supplied lookup. Both failures are reported.
309fn parse_scoped(
310    original: &str,
311    address: &str,
312    zone: &str,
313    set: &mut IpSet,
314    zones: Option<ZoneResolverFn<'_>>,
315) -> Result<(), IpParseError> {
316    if zone.is_empty() {
317        return Err(IpParseError::Malformed(original.to_string()));
318    }
319
320    let range = address
321        .parse::<IpRange>()
322        .map_err(|_| IpParseError::Malformed(original.to_string()))?;
323    let IpRange::V6(v6) = range else {
324        return Err(IpParseError::ZoneOnUnscopedTarget(original.to_string()));
325    };
326    // The whole range must be link-local; checking only the start would accept
327    // `fe80::1-fec0::1` and refuse `fe00::1-fe80::5`.
328    if !v6.is_link_local() {
329        return Err(IpParseError::ZoneOnUnscopedTarget(original.to_string()));
330    }
331
332    // Zero is what a name lookup returns for no such name. Refused here, the one
333    // place that still holds the name to report.
334    let lookup = zones.ok_or_else(|| IpParseError::UnknownInterface(zone.to_string()))?;
335    let index = lookup(zone)
336        .filter(|index| *index != 0)
337        .ok_or_else(|| IpParseError::UnknownInterface(zone.to_string()))?;
338
339    let scoped =
340        crate::model::ip::range::Ipv6Range::scoped(v6.start_addr(), v6.end_addr(), Some(index))
341            .map_err(|e| map_range_error(original, e))?;
342    set.insert_range(IpRange::V6(scoped));
343    Ok(())
344}
345
346/// Parses a hyphenated range, deferring to the one range grammar.
347///
348/// A thin wrapper, so ranges parse the same here as through [`IpRange`]'s `from_str`.
349fn parse_range(s: &str) -> Result<IpRange, IpParseError> {
350    s.parse::<IpRange>().map_err(|error| match error {
351        // "Not an address", which tells a caller it may be a hostname.
352        IpError::InvalidFormat(_) | IpError::AddrParse(_) | IpError::PrefixParse(_) => {
353            IpParseError::Malformed(s.into())
354        }
355        other => map_range_error(s, other),
356    })
357}
358
359/// Parses CIDR notation strings into an [`IpRange`].
360fn parse_cidr(s: &str) -> Result<IpRange, IpParseError> {
361    let (ip_str, prefix_str) = s
362        .split_once('/')
363        .ok_or_else(|| IpParseError::Malformed(s.into()))?;
364
365    let ip = ip_str
366        .parse::<IpAddr>()
367        .map_err(|_| IpParseError::Malformed(s.into()))?;
368
369    // Read as a `u32`, so a huge number is a bad prefix, not an unrecognised
370    // token that would be tried as a hostname.
371    let prefix = prefix_str
372        .parse::<u32>()
373        .map_err(|_| IpParseError::Malformed(s.into()))?;
374    let prefix = u8::try_from(prefix).map_err(|_| IpParseError::InvalidPrefix(prefix))?;
375
376    crate::model::ip::range::cidr_range(ip, prefix).map_err(|e| map_range_error(s, e))
377}
378
379/// Restates a range error in this module's vocabulary, against the expression
380/// the caller wrote.
381///
382/// `original` is passed in so the error quotes what the caller wrote.
383fn map_range_error(original: &str, e: IpError) -> IpParseError {
384    match e {
385        IpError::InvalidRange(s, e) => IpParseError::InvalidRange(s, e),
386        IpError::InvalidPrefix(p) => IpParseError::InvalidPrefix(u32::from(p)),
387        _ => IpParseError::Malformed(original.to_string()),
388    }
389}
390
391// ╔════════════════════════════════════════════╗
392// ║ ████████╗███████╗███████╗████████╗███████╗ ║
393// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
394// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
395// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
396// ║    ██║   ███████╗███████║   ██║   ███████║ ║
397// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
398// ╚════════════════════════════════════════════╝
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403    use std::net::Ipv4Addr;
404    use std::str::FromStr;
405
406    /// This module and [`IpSet`]'s string constructors (via [`IpRange::from_str`]) are
407    /// one grammar and accept the same spellings.
408    ///
409    /// They differ in one reading: this module reads an IPv4-mapped address as the
410    /// host it names, where an [`IpSet`] keeps the value it was given. See
411    /// `a_mapped_address_is_read_as_the_ipv4_host_it_spells`.
412    #[test]
413    fn both_ways_into_the_parser_accept_the_same_spellings() {
414        for expression in [
415            "198.51.100.1-50",
416            "192.168.1.1-2.254",
417            "198.51.100.1-198.51.100.50",
418            "192.0.2.0/24",
419            "2001:db8::1-2001:db8::5",
420            "8.8.8.8",
421            // Spellings most easily read differently.
422            "198.51.100.0-0",
423            "  198.51.100.1  ",
424        ] {
425            let direct = to_set(&[expression], None, None)
426                .unwrap_or_else(|e| panic!("to_set rejected `{expression}`: {e}"));
427            let via_set = IpSet::from_str(expression)
428                .unwrap_or_else(|e| panic!("IpSet::from_str rejected `{expression}`: {e}"));
429
430            assert_eq!(
431                direct, via_set,
432                "`{expression}` means different things through the two entry points"
433            );
434        }
435    }
436
437    /// An address written the IPv4-mapped way is read as the IPv4 host it
438    /// spells, in every form the grammar has.
439    ///
440    /// Kept as IPv6, a frame for it would go to the router as off-link IPv6.
441    #[test]
442    fn a_mapped_address_is_read_as_the_ipv4_host_it_spells() {
443        for (mapped, plain) in [
444            ("::ffff:192.0.2.1", "192.0.2.1"),
445            ("::ffff:127.0.0.1", "127.0.0.1"),
446            ("::ffff:192.0.2.0/120", "192.0.2.0/24"),
447            ("::ffff:192.0.2.1-::ffff:192.0.2.9", "192.0.2.1-192.0.2.9"),
448            ("::ffff:0:0/96", "0.0.0.0/0"),
449        ] {
450            assert_eq!(
451                to_set(&[mapped], None, None).expect("parses"),
452                to_set(&[plain], None, None).expect("parses"),
453                "`{mapped}`"
454            );
455        }
456    }
457
458    /// A range reaching outside the mapped block, such as `::/0`, is kept as written.
459    #[test]
460    fn a_range_that_only_overlaps_the_mapped_block_is_kept_as_written() {
461        for written in ["::/0", "::fffe:ffff:ffff-::ffff:0:5"] {
462            let set = to_set(&[written], None, None).expect("parses");
463            assert!(set.v4().is_empty(), "`{written}` gained IPv4");
464            assert_eq!(set, IpSet::from_str(written).expect("parses"));
465        }
466    }
467
468    /// A single address.
469    #[test]
470    fn a_single_literal_address_becomes_a_set_of_one() {
471        let input = vec!["192.0.2.1"];
472        let set = to_set(&input, None, None).expect("Should parse single IP");
473        assert_eq!(set.len(), 1);
474        assert!(set.contains(&IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1))));
475    }
476
477    /// One argument may itself be a comma-separated list.
478    #[test]
479    fn one_argument_may_name_several_addresses() {
480        let input = vec!["198.51.100.1, 198.51.100.2, 198.51.100.5"];
481        let set = to_set(&input, None, None).expect("Should parse comma list");
482        assert_eq!(set.len(), 3);
483        assert!(set.contains(&IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))));
484    }
485
486    /// A block counts every address it covers.
487    #[test]
488    fn a_cidr_block_covers_every_address_in_it() {
489        let input = vec!["203.0.113.0/24"];
490        let set = to_set(&input, None, None).expect("Should parse CIDR");
491        assert_eq!(set.len(), 256);
492    }
493
494    /// The shorthand crosses an octet boundary: `.250-2.10` is seventeen addresses.
495    #[test]
496    fn a_shortened_range_end_continues_the_starts_octets() {
497        let input = vec!["192.168.1.250-2.10"];
498        let set = to_set(&input, None, None).unwrap();
499        assert_eq!(set.len(), 17);
500    }
501
502    /// A prefix too long for its family is refused, not clamped.
503    #[test]
504    fn a_prefix_longer_than_its_family_allows_is_refused() {
505        let input = vec!["192.0.2.1/33"];
506        let result = to_set(&input, None, None);
507        assert_eq!(result.unwrap_err(), IpParseError::InvalidPrefix(33));
508    }
509
510    /// `/999` is reported as an invalid prefix, like `/33`, not as
511    /// [`Malformed`](IpParseError::Malformed), which would send it to DNS.
512    #[test]
513    fn a_prefix_too_large_for_a_u8_is_still_a_prefix() {
514        let too_large = to_set(&["198.51.100.0/999"], None, None).unwrap_err();
515        assert_eq!(too_large, IpParseError::InvalidPrefix(999));
516        assert!(too_large.to_string().contains("0-32"), "{too_large}");
517
518        // Text that is not a number stays malformed, so a hostname reaches DNS.
519        assert!(matches!(
520            to_set(&["198.51.100.0/wide"], None, None),
521            Err(IpParseError::Malformed(_))
522        ));
523    }
524
525    /// The message names both families' bounds.
526    #[test]
527    fn a_prefix_error_names_the_bound_for_both_families() {
528        let v6 = to_set(&["2001:db8::/129"], None, None).unwrap_err();
529        assert_eq!(v6, IpParseError::InvalidPrefix(129));
530        assert!(v6.to_string().contains("0-128"), "{v6}");
531
532        let v4 = to_set(&["192.0.2.1/33"], None, None).unwrap_err();
533        assert!(v4.to_string().contains("0-32"), "{v4}");
534    }
535
536    /// A backwards range is reported, not read as an empty set.
537    #[test]
538    fn a_range_written_backwards_is_refused() {
539        let input = vec!["198.51.100.10-1"];
540        let result = to_set(&input, None, None);
541        assert!(matches!(result, Err(IpParseError::InvalidRange(_, _))));
542    }
543
544    /// The interface a link-local target names survives into the target set.
545    ///
546    /// Every interface holds an `fe80::/64`, so without it the scan could probe the
547    /// wrong segment.
548    #[test]
549    fn a_link_local_target_keeps_the_interface_it_names() {
550        fn zones(name: &str) -> Option<u32> {
551            (name == "en0").then_some(7)
552        }
553
554        let set = to_set(&["fe80::aa%en0"], None, Some(&zones)).expect("parses");
555
556        assert_eq!(set.v6().len(), 1);
557        assert_eq!(set.v6()[0].zone(), Some(7));
558        assert!(!set.v6()[0].is_ambiguous());
559    }
560
561    /// The same address without an interface is accepted but marked ambiguous, for the
562    /// classifier to report.
563    #[test]
564    fn a_link_local_target_without_an_interface_is_ambiguous() {
565        let set = to_set(&["fe80::aa"], None, None).expect("parses");
566
567        assert!(set.v6()[0].is_ambiguous());
568    }
569
570    /// A resolver answering zero has not answered: zero means no such interface. Taken
571    /// at face value it would build a range that reads as scoped, hiding the problem
572    /// from `is_ambiguous`, and probes would go out on whichever link the kernel
573    /// picked.
574    #[test]
575    fn a_resolver_that_answers_zero_has_not_found_an_interface() {
576        fn zones(_: &str) -> Option<u32> {
577            Some(0)
578        }
579
580        assert!(matches!(
581            to_set(&["fe80::aa%en0"], None, Some(&zones)),
582            Err(IpParseError::UnknownInterface(name)) if name == "en0"
583        ));
584    }
585
586    /// [`insert_expression`] trims the token itself, so keywords and addresses behave
587    /// alike whatever whitespace a direct caller leaves.
588    #[test]
589    fn an_untrimmed_token_reads_the_same_as_a_trimmed_one() {
590        let mut set = IpSet::new();
591        insert_expression(" 198.51.100.1 ", &mut set, None, None).expect("an address with space");
592        insert_expression("\t192.0.2.0/24\n", &mut set, None, None).expect("a block with space");
593        insert_expression(" 198.51.100.5-10 ", &mut set, None, None).expect("a range with space");
594
595        assert_eq!(set.len(), 1 + 256 + 6);
596
597        fn keywords(_: Keyword, set: &mut IpSet) -> Result<(), IpParseError> {
598            set.insert("203.0.113.1".parse().expect("an address"));
599            Ok(())
600        }
601        let mut keyword = IpSet::new();
602        insert_expression(" lan ", &mut keyword, Some(&keywords), None).expect("a keyword");
603        assert_eq!(
604            keyword.len(),
605            1,
606            "which already worked, and is the half it matched"
607        );
608    }
609
610    /// An unknown interface is refused, not silently stripped.
611    #[test]
612    fn an_unknown_interface_is_refused() {
613        fn zones(_: &str) -> Option<u32> {
614            None
615        }
616
617        assert!(matches!(
618            to_set(&["fe80::aa%wlan9"], None, Some(&zones)),
619            Err(IpParseError::UnknownInterface(_))
620        ));
621        assert!(
622            matches!(
623                to_set(&["fe80::aa%en0"], None, None),
624                Err(IpParseError::UnknownInterface(_))
625            ),
626            "a caller with no lookup cannot express a scoped target and must be told"
627        );
628    }
629
630    /// A scope on an address that cannot use one is a mistake, not a hint.
631    #[test]
632    fn a_zone_on_a_global_target_is_refused() {
633        fn zones(_: &str) -> Option<u32> {
634            Some(7)
635        }
636
637        assert!(matches!(
638            to_set(&["2001:db8::1%en0"], None, Some(&zones)),
639            Err(IpParseError::ZoneOnUnscopedTarget(_))
640        ));
641        assert!(matches!(
642            to_set(&["192.0.2.1%en0"], None, Some(&zones)),
643            Err(IpParseError::ZoneOnUnscopedTarget(_))
644        ));
645    }
646
647    /// Nothing to scan is an error: an empty set would look like a scan that found no
648    /// hosts.
649    #[test]
650    fn input_naming_no_addresses_is_an_error() {
651        let input: Vec<&str> = vec!["", " "];
652        let result = to_set(&input, None, None);
653        assert_eq!(result.unwrap_err(), IpParseError::EmptySet);
654    }
655}