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

//! # Scoped Addresses
//!
//! An IPv6 link-local address is not an address on its own. `fe80::1` names a
//! different machine on every segment it is spoken on, and the operating system
//! will not send to one without being told which interface is meant: a
//! `SocketAddrV6` with a zero `scope_id` fails to connect however reachable the
//! neighbour is.
//!
//! That makes it a genuine defect for a scanner to discover a neighbour at
//! `fe80::…` and hand that address onward as though it were usable. Every later
//! phase - service detection, fingerprinting, the connect fallback - receives an
//! address it cannot open a socket to, and a report renders one its reader
//! cannot act on.
//!
//! [`ScopedIp`] is an address together with the interface it is valid on, where
//! it needs one. Addresses that do not need a zone do not carry one, so
//! equality and hashing stay the ordinary thing for the ordinary case.

use super::range::Ipv6Range;
use std::fmt;
use std::net::{IpAddr, SocketAddr, SocketAddrV6};
use std::str::FromStr;
use std::sync::Arc;

/// The interface an address is scoped to.
///
/// Both halves are kept because they answer to different audiences. The index is
/// what a `SocketAddrV6` needs and the only thing the kernel understands; the
/// name is what a person reads, what `%en0` means in a target expression, and
/// what a report has to print for its reader to act on. Deriving either from the
/// other costs a lookup at exactly the moments this is used in bulk.
///
/// A zone written down is not yet a zone found. Parsing `%en0` yields a
/// name and nothing else; only a lookup against the running host turns it into
/// an index. [`unresolved`](Self::unresolved) is that first state, and
/// [`index`](Self::index) is `None` for as long as it lasts.
///
/// Identity follows from which state it is in. A resolved zone is its index
/// alone: two of them naming the same interface are the same zone whatever
/// string was recorded alongside, since an interface's index is unique on a host
/// for longer than any one scan. An unresolved zone has only the name it was
/// written under, so that is its identity, and a resolved zone is never equal to
/// an unresolved one, since nothing here can know whether they name the same
/// interface.
#[derive(Debug, Clone)]
pub struct Zone {
    index: Option<u32>,
    name: Arc<str>,
}

impl Zone {
    /// Names the interface with index `index`, as a lookup against the host
    /// reported it.
    ///
    /// An index of zero is a lookup that failed, and is read as one. Zero is
    /// not an interface on any platform this builds for: `if_nametoindex`
    /// returns it to report that there is no such name, and a `SocketAddrV6`
    /// carrying it is the unsendable address this whole module exists to keep
    /// out of a scan. So a zone built from one is
    /// [`unresolved`](Self::unresolved), which is what it is, and the address
    /// scoped to it answers [`is_unusable`](ScopedIp::is_unusable) rather than
    /// being handed to a connect that fails with an error about the network.
    ///
    /// Taken here rather than refused, because there is only one honest reading
    /// of a zero and a caller that has to unwrap a `Result` to say what it
    /// already meant is worse off. A caller with a name and no index should say
    /// so directly.
    pub fn new(index: u32, name: impl Into<Arc<str>>) -> Self {
        match index {
            0 => Self::unresolved(name),
            index => Self {
                index: Some(index),
                name: name.into(),
            },
        }
    }

    /// Names an interface that nothing has looked up yet.
    ///
    /// What parsing `%en0` out of a target expression produces. An address
    /// scoped to one of these is [`unusable`](ScopedIp::is_unusable) until
    /// something that knows the host's interfaces replaces it: naming an
    /// interface is not the same as having found it, and a socket needs the
    /// index.
    pub fn unresolved(name: impl Into<Arc<str>>) -> Self {
        Self {
            index: None,
            name: name.into(),
        }
    }

    /// The interface index, as a `SocketAddrV6` scope id, once one is known.
    pub fn index(&self) -> Option<u32> {
        self.index
    }

    /// The interface name, as a person writes it.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// What identity compares. An index when there is one, and the name it was
    /// written under when there is not; the two states never match each other.
    fn identity(&self) -> (Option<u32>, Option<&str>) {
        match self.index {
            Some(index) => (Some(index), None),
            None => (None, Some(&*self.name)),
        }
    }
}

impl PartialEq for Zone {
    fn eq(&self, other: &Self) -> bool {
        self.identity() == other.identity()
    }
}

impl Eq for Zone {}

impl std::hash::Hash for Zone {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.identity().hash(state);
    }
}

impl PartialOrd for Zone {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Zone {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.identity().cmp(&other.identity())
    }
}

impl fmt::Display for Zone {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.name)
    }
}

/// An IP address, carrying the interface it is valid on when it needs one.
///
/// No [`Default`]. There is no address that means "no address": the obvious
/// candidate, `::`, is a perfectly good key for a host record and names
/// nothing, so a default would offer nothing but a way to be wrong quietly.
///
/// Constructed through [`ScopedIp::scoped`], which drops a zone the address has
/// no use for. That is what keeps equality honest: a global address is the same
/// address whichever interface it was seen through, so `2001:db8::1` observed on
/// two interfaces must not become two hosts. Only an address whose meaning
/// genuinely depends on the interface keeps one.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ScopedIp {
    /// Ordered first so sorting is by address, with the zone breaking ties
    /// between identically-numbered link-locals.
    addr: IpAddr,
    zone: Option<Zone>,
}

impl ScopedIp {
    /// An address that needs no interface to be meaningful.
    pub fn unscoped(addr: IpAddr) -> Self {
        Self { addr, zone: None }
    }

    /// An address observed through `zone`, keeping the zone only if the address
    /// is one that needs it. See the type's own documentation for why.
    pub fn scoped(addr: IpAddr, zone: Zone) -> Self {
        Self {
            addr,
            zone: Self::needs_zone(&addr).then_some(zone),
        }
    }

    /// Whether an address is meaningless without an interface to interpret it
    /// against.
    ///
    /// IPv6 link-local unicast only. A global or unique-local address identifies
    /// its host on its own, an IPv4 address has no zone concept at all, and
    /// loopback is scoped to a single interface by definition.
    pub fn needs_zone(addr: &IpAddr) -> bool {
        matches!(addr, IpAddr::V6(v6) if v6.is_unicast_link_local())
    }

    /// The address itself, without its zone.
    pub fn addr(&self) -> IpAddr {
        self.addr
    }

    /// The interface this address is valid on, if it needs one.
    pub fn zone(&self) -> Option<&Zone> {
        self.zone.as_ref()
    }

    /// Whether this address is one that needs a zone and has no *resolved* one.
    ///
    /// Such an address cannot be connected to, and the honest thing to do with
    /// it is say so rather than attempt a connection that fails with an error
    /// about the network.
    ///
    /// A zone that names an interface nothing has looked up counts as missing.
    /// The kernel takes a scope id and there is none, so `fe80::1%en0` straight
    /// out of a target file is exactly as unreachable as bare `fe80::1` until
    /// something resolves the name.
    pub fn is_unusable(&self) -> bool {
        Self::needs_zone(&self.addr) && self.zone.as_ref().and_then(Zone::index).is_none()
    }

    /// This address as somewhere a socket can be opened to.
    ///
    /// The scope id is what makes a link-local destination reachable at all;
    /// without it the kernel has no interface to send on and refuses. `None`
    /// when the address needs a zone and has none, because the alternative is a
    /// connection attempt that fails for a reason having nothing to do with the
    /// target.
    pub fn to_socket_addr(&self, port: u16) -> Option<SocketAddr> {
        if self.is_unusable() {
            return None;
        }

        match (self.addr, self.zone.as_ref().and_then(Zone::index)) {
            (IpAddr::V6(v6), Some(scope_id)) => {
                Some(SocketAddr::V6(SocketAddrV6::new(v6, port, 0, scope_id)))
            }
            (addr, _) => Some(SocketAddr::new(addr, port)),
        }
    }

    /// This address and a port as an endpoint a reader can paste back. The IPv6
    /// form is bracketed so its port is not read as one more hextet, with the
    /// zone kept inside the brackets where a shell and a URL both take it.
    pub fn endpoint(&self, port: u16) -> String {
        if self.addr.is_ipv6() {
            format!("[{self}]:{port}")
        } else {
            format!("{self}:{port}")
        }
    }
}

impl From<IpAddr> for ScopedIp {
    fn from(addr: IpAddr) -> Self {
        Self::unscoped(addr)
    }
}

/// So that an address held by reference reaches anything taking
/// `impl Into<ScopedIp>` without the caller spelling the conversion.
///
/// The address the engine keys a host under is a `ScopedIp`, and most need no
/// zone: every IPv4 address, and every IPv6 address but a link-local. A caller
/// holding one of those holds the whole key already, and this lets it pass the
/// key it has.
impl From<&IpAddr> for ScopedIp {
    fn from(addr: &IpAddr) -> Self {
        Self::unscoped(*addr)
    }
}

impl From<&ScopedIp> for ScopedIp {
    fn from(scoped: &ScopedIp) -> Self {
        scoped.clone()
    }
}

impl fmt::Display for ScopedIp {
    /// `fe80::1%en0` for a scoped address, the bare address otherwise. This is
    /// the notation every operating system's tooling accepts and the one a
    /// reader can paste back into a command.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.zone {
            Some(zone) => write!(f, "{}%{}", self.addr, zone),
            None => self.addr.fmt(f),
        }
    }
}

/// Why a scoped address could not be read from a string.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ScopedIpError {
    /// What sits before the `%`, or the whole string where there is none, is
    /// not an address in either family. Carries the input as it was written.
    #[error("not an IP address: {0}")]
    NotAnAddress(String),
    /// A zone was written on an address that has no use for one. Accepting it
    /// silently would let two spellings of the same address compare unequal.
    #[error("{0} is not a link-local address, so `%{1}` means nothing")]
    ZoneOnUnscopedAddress(IpAddr, String),
    /// The string ended at its `%`, so no interface was named for the zone.
    #[error("`%` with no interface after it")]
    EmptyZone,
}

impl FromStr for ScopedIp {
    type Err = ScopedIpError;

    /// Reads `fe80::1%en0`, or any plain address.
    ///
    /// The interface index is not resolved here: this parses text, and looking
    /// up a name requires the host's interface list. The zone comes back
    /// [`unresolved`](Zone::unresolved), which is to say it carries the name and
    /// no scope id, and the address is [`unusable`](Self::is_unusable) until
    /// something that knows the interfaces supplies one.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((addr, zone)) = s.split_once('%') else {
            return s
                .parse::<IpAddr>()
                .map(Self::unscoped)
                .map_err(|_| ScopedIpError::NotAnAddress(s.to_string()));
        };

        if zone.is_empty() {
            return Err(ScopedIpError::EmptyZone);
        }

        let addr: IpAddr = addr
            .parse()
            .map_err(|_| ScopedIpError::NotAnAddress(s.to_string()))?;
        if !Self::needs_zone(&addr) {
            return Err(ScopedIpError::ZoneOnUnscopedAddress(addr, zone.to_string()));
        }

        Ok(Self {
            addr,
            zone: Some(Zone::unresolved(zone)),
        })
    }
}

/// Which interface each of a scan's link-local ranges was named on.
///
/// A port scan addresses its targets one at a time and reaches them over the
/// routing table, which cannot carry `fe80::1` without an interface. The zone is
/// written on the range a target came from rather than on the address itself, so
/// something has to hold the pairing for the length of the scan. This is it: the
/// zoned ranges a scan was given, and the lookup that answers which interface an
/// address in one of them is valid on.
///
/// Ranges that need no zone are not held. `zone_of` answers `None` for
/// everything else, which is what a global address, an IPv4 address and a
/// link-local nobody scoped all want.
///
/// ```
/// use zond_engine::model::ip::range::Ipv6Range;
/// use zond_engine::model::ip::scoped::ZoneMap;
/// use std::net::{IpAddr, Ipv6Addr};
///
/// let addr: Ipv6Addr = "fe80::1".parse().unwrap();
/// let mut zones = ZoneMap::new();
/// zones.insert(Ipv6Range::scoped(addr, addr, Some(7)).unwrap(), &[(7, "en0")]);
///
/// assert_eq!(zones.zone_of(&IpAddr::V6(addr)), Some(7));
/// assert_eq!(zones.key(IpAddr::V6(addr)).to_string(), "fe80::1%en0");
/// assert_eq!(zones.zone_of(&"2001:db8::1".parse().unwrap()), None);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ZoneMap {
    ranges: Vec<(Ipv6Range, Zone)>,
}

impl ZoneMap {
    /// An empty map, holding no scan's zones yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Records `range` and the interface it names.
    ///
    /// A range carrying no zone is ignored, since it has nothing to answer with.
    /// The zone is taken from `interfaces`, which is the host's interface table
    /// as a list of index and name: the scope id alone reaches a socket, and the
    /// name is what a report prints and a person reads back.
    pub fn insert(&mut self, range: Ipv6Range, interfaces: &[(u32, &str)]) {
        let Some(index) = range.zone() else {
            return;
        };
        let name = interfaces
            .iter()
            .find(|(held, _)| *held == index)
            .map_or_else(|| index.to_string(), |(_, name)| (*name).to_owned());

        self.ranges.push((range, Zone::new(index, name)));
    }

    /// The interface `ip` is valid on, if this scan named one for it.
    ///
    /// An address covered by two ranges naming different interfaces answers
    /// `None`. Which segment was meant is what cannot be told in that case, and
    /// a probe sent to the first match would go to whichever range happened to
    /// be recorded first.
    pub fn zone_for(&self, ip: &IpAddr) -> Option<&Zone> {
        let IpAddr::V6(v6) = ip else {
            return None;
        };

        let mut found = None;
        for (_, zone) in self.ranges.iter().filter(|(range, _)| range.contains(v6)) {
            match found {
                None => found = Some(zone),
                Some(held) if held == zone => {}
                Some(_) => return None,
            }
        }
        found
    }

    /// The interface index `ip` is valid on, as a socket's scope id.
    pub fn zone_of(&self, ip: &IpAddr) -> Option<u32> {
        self.zone_for(ip).and_then(Zone::index)
    }

    /// `ip` as the engine keys a host under.
    ///
    /// A finding recorded against a bare `fe80::…` belongs to the host the scan
    /// named on an interface, not beside it. Completing the key here is what
    /// keeps a port scan's verdicts and a sweep's hardware address on one
    /// record. An address needing no zone comes back as itself.
    pub fn key(&self, ip: IpAddr) -> ScopedIp {
        match self.zone_for(&ip) {
            Some(zone) => ScopedIp::scoped(ip, zone.clone()),
            None => ScopedIp::unscoped(ip),
        }
    }

    /// Whether any address in `range` is also covered by a range already held
    /// under a different interface.
    ///
    /// Answers before the insertion, so a caller can refuse both rather than
    /// keep a target it cannot address.
    pub fn contests(&self, range: &Ipv6Range) -> bool {
        self.ranges
            .iter()
            .any(|(held, _)| held.zone() != range.zone() && held.overlaps(range))
    }

    /// `ip` and `port` as somewhere a socket can be opened to.
    ///
    /// A link-local destination carries the scope id the scan named it under,
    /// which is what makes it reachable: a `SocketAddrV6` with a zero scope id
    /// fails to connect however close the neighbour is. Everything else is the
    /// ordinary pairing of an address and a port.
    pub fn endpoint(&self, ip: IpAddr, port: u16) -> SocketAddr {
        match (ip, self.zone_of(&ip)) {
            (IpAddr::V6(v6), Some(zone)) => SocketAddr::V6(SocketAddrV6::new(v6, port, 0, zone)),
            _ => SocketAddr::new(ip, port),
        }
    }

    /// Whether this scan named no zoned range at all.
    pub fn is_empty(&self) -> bool {
        self.ranges.is_empty()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{Ipv4Addr, Ipv6Addr};

    fn link_local() -> IpAddr {
        IpAddr::V6(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1))
    }

    fn global() -> IpAddr {
        IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
    }

    fn en0() -> Zone {
        Zone::new(4, "en0")
    }

    fn en1() -> Zone {
        Zone::new(5, "en1")
    }

    /// The failure this type exists to prevent: the same link-local address on
    /// two segments is two machines, and merging them into one host would
    /// attribute one device's ports to another.
    #[test]
    fn the_same_link_local_on_two_interfaces_is_two_addresses() {
        assert_ne!(
            ScopedIp::scoped(link_local(), en0()),
            ScopedIp::scoped(link_local(), en1())
        );
    }

    /// And the mirror, which matters just as much: a global address is the same
    /// address however it was reached, so a host seen through two interfaces
    /// must not split into two.
    #[test]
    fn a_global_address_is_the_same_address_through_any_interface() {
        assert_eq!(
            ScopedIp::scoped(global(), en0()),
            ScopedIp::scoped(global(), en1())
        );
        assert_eq!(
            ScopedIp::scoped(global(), en0()),
            ScopedIp::unscoped(global())
        );
        assert!(ScopedIp::scoped(global(), en0()).zone().is_none());
    }

    #[test]
    fn ipv4_never_carries_a_zone() {
        let v4 = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
        assert!(!ScopedIp::needs_zone(&v4));
        assert!(ScopedIp::scoped(v4, en0()).zone().is_none());
    }

    /// A zone is identified by its index, so the same interface recorded under
    /// two spellings is still one interface.
    #[test]
    fn a_zone_is_its_index_not_its_name() {
        assert_eq!(Zone::new(4, "en0"), Zone::new(4, "utun4"));
        assert_ne!(Zone::new(4, "en0"), Zone::new(5, "en0"));
    }

    /// Until something resolves it, a parsed zone has no index, and identity by
    /// index alone made every one of them the same zone. Two link-local targets
    /// written against two interfaces would then be one address, which is the
    /// collapse this type exists to prevent, reached from the
    /// other direction.
    #[test]
    fn an_unresolved_zone_is_identified_by_the_name_it_was_written_under() {
        let en0: ScopedIp = "fe80::1%en0".parse().expect("parses");
        let en1: ScopedIp = "fe80::1%en1".parse().expect("parses");

        assert_ne!(en0, en1, "two interfaces, two addresses");
        assert_eq!(en0, "fe80::1%en0".parse().expect("parses"));

        // And an unresolved zone cannot open a socket: naming an interface is
        // not the same as having found it.
        assert!(en0.is_unusable());
        assert_eq!(en0.to_socket_addr(22), None);
    }

    /// The point of the whole exercise: a link-local destination is reachable
    /// only when the socket address carries the interface's scope id.
    #[test]
    fn a_scoped_address_produces_a_socket_address_with_its_scope_id() {
        let socket = ScopedIp::scoped(link_local(), en0())
            .to_socket_addr(443)
            .expect("a scoped link-local is usable");

        match socket {
            SocketAddr::V6(v6) => assert_eq!(v6.scope_id(), 4),
            SocketAddr::V4(_) => panic!("an IPv6 address produced a V4 socket address"),
        }
    }

    /// A scope id of zero is a lookup that failed, and it has to read as one.
    ///
    /// Zero is not an interface: it is what `if_nametoindex` returns to say
    /// there is no such name. Taken at face value it would produce a *resolved*
    /// zone whose index cannot open a socket, so `is_unusable` would answer
    /// false and `to_socket_addr` would hand back `[fe80::1]:22` with a zero
    /// scope id, which is the exact address the first paragraph of this module
    /// says the kernel refuses. A journal or a report naming index zero is
    /// enough to get one.
    #[test]
    fn a_zone_whose_index_is_zero_is_a_zone_nothing_found() {
        let failed = ScopedIp::scoped(link_local(), Zone::new(0, "en0"));

        assert_eq!(
            failed.zone().and_then(Zone::index),
            None,
            "zero is not found"
        );
        assert!(failed.is_unusable());
        assert_eq!(failed.to_socket_addr(22), None);

        // The name survives, so a report still says which interface was meant
        // and the address still renders the way it was written.
        assert_eq!(failed.to_string(), "fe80::1%en0");
        assert_eq!(failed, "fe80::1%en0".parse().expect("parses"));
    }

    /// A link-local address with no zone cannot be connected to, and saying so
    /// is better than handing back a `SocketAddr` whose connection fails with an
    /// error describing the network.
    #[test]
    fn an_unzoned_link_local_is_not_usable() {
        let bare = ScopedIp::unscoped(link_local());

        assert!(bare.is_unusable());
        assert_eq!(bare.to_socket_addr(443), None);
    }

    #[test]
    fn an_ordinary_address_is_usable_without_a_zone() {
        let host = ScopedIp::unscoped(global());

        assert!(!host.is_unusable());
        assert_eq!(
            host.to_socket_addr(443),
            Some(SocketAddr::new(global(), 443))
        );
    }

    #[test]
    fn a_scoped_address_renders_and_parses_the_way_the_operating_system_writes_it() {
        let scoped = ScopedIp::scoped(link_local(), en0());
        assert_eq!(scoped.to_string(), "fe80::1%en0");

        let parsed: ScopedIp = "fe80::1%en0".parse().unwrap();
        assert_eq!(parsed.addr(), link_local());
        assert_eq!(parsed.zone().map(Zone::name), Some("en0"));
    }

    /// The field order is load-bearing, and nothing about it is enforced by
    /// the compiler. Sorting a collection of addresses has to be by address,
    /// with the zone separating link-locals that share a number; ordered
    /// zone-first, a sorted list would be grouped by interface instead, and
    /// every consumer that walks addresses in order, whether a report, a merge
    /// or a binary search, would walk a different sequence than it reads as.
    #[test]
    fn addresses_sort_by_address_with_the_zone_breaking_ties() {
        let mut addresses = vec![
            ScopedIp::scoped(link_local(), en1()),
            ScopedIp::unscoped(global()),
            ScopedIp::scoped(link_local(), en0()),
        ];
        addresses.sort();

        assert_eq!(
            addresses,
            vec![
                ScopedIp::unscoped(global()),
                ScopedIp::scoped(link_local(), en0()),
                ScopedIp::scoped(link_local(), en1()),
            ]
        );
    }

    #[test]
    fn an_unscoped_address_renders_bare() {
        assert_eq!(ScopedIp::unscoped(global()).to_string(), "2001:db8::1");
    }

    /// A zone on an address that cannot use one is a mistake worth reporting.
    /// Dropping it silently would let `2001:db8::1%en0` and `2001:db8::1` be
    /// written for the same thing while only one of them round-trips.
    #[test]
    fn a_zone_on_an_address_that_cannot_use_one_is_rejected() {
        assert!(matches!(
            "2001:db8::1%en0".parse::<ScopedIp>(),
            Err(ScopedIpError::ZoneOnUnscopedAddress(_, _))
        ));
        assert_eq!(
            "fe80::1%".parse::<ScopedIp>(),
            Err(ScopedIpError::EmptyZone)
        );
        assert!(matches!(
            "not-an-address%en0".parse::<ScopedIp>(),
            Err(ScopedIpError::NotAnAddress(_))
        ));
    }

    /// The endpoint form a reader pastes back: an IPv6 address is bracketed so
    /// its port cannot be read as one more hextet, the zone stays inside the
    /// brackets, and an IPv4 address is left as it was.
    #[test]
    fn an_endpoint_brackets_ipv6_and_keeps_the_zone_inside() {
        assert_eq!(
            ScopedIp::unscoped(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 160))).endpoint(80),
            "192.0.2.160:80"
        );
        assert_eq!(
            ScopedIp::unscoped(global()).endpoint(80),
            "[2001:db8::1]:80"
        );
        assert_eq!(
            ScopedIp::scoped(link_local(), en0()).endpoint(80),
            "[fe80::1%en0]:80"
        );
    }
}