zond-engine 0.12.0

A lightweight, fast, and highly concurrent networking backend for packet crafting, protocol fingerprinting, and host discovery.
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
// 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

use std::fmt;
use std::str::FromStr;

use crate::model::technique::TcpScanTechnique;

/// How the privileged (raw) scanners put probe packets on the wire.
///
/// Only affects the raw-socket SYN paths; the unprivileged TCP-connect
/// fallback and the on-link ARP/ICMPv6 [`LocalScanner`](crate::scanner)
/// discovery are unaffected.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SendMode {
    /// Pick per platform: a raw Layer-4 socket on Unix - which the kernel
    /// routes, ARPs, and fragments for us, and which works through VPN
    /// tunnels - and self-built Layer-2 Ethernet frames on Windows, where the
    /// OS blocks raw-socket TCP sends outright.
    #[default]
    Auto,
    /// Force a raw Layer-4 socket regardless of platform.
    RawSocket,
    /// Force self-built Layer-2 Ethernet frames, bypassing the host IP stack
    /// (and the local firewall / connection tracking that a raw-socket send
    /// still traverses). Requires an Ethernet-capable interface and can't
    /// reach loopback or tunnel-only destinations.
    Ethernet,
}

impl SendMode {
    /// Every mode, in the order a front end should offer them.
    pub const ALL: [SendMode; 3] = [SendMode::Auto, SendMode::RawSocket, SendMode::Ethernet];

    /// The name this mode is written under, wherever it arrives as text.
    pub const fn name(self) -> &'static str {
        match self {
            SendMode::Auto => "auto",
            SendMode::RawSocket => "raw_socket",
            SendMode::Ethernet => "ethernet",
        }
    }
}

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

/// The error [`SendMode::from_str`] returns, carrying the names that would have
/// worked so a front end can print it verbatim.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown send mode '{input}', expected one of: auto, raw_socket, ethernet")]
pub struct UnknownSendMode {
    /// What the caller wrote.
    pub input: String,
}

impl FromStr for SendMode {
    type Err = UnknownSendMode;

    /// Parses a mode name, ignoring case and surrounding whitespace, so a choice
    /// arriving as text - from an argument, a form field, a settings file -
    /// needs no mapping table of its own.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::config::SendMode;
    ///
    /// assert_eq!("Ethernet".parse(), Ok(SendMode::Ethernet));
    /// assert!("layer2".parse::<SendMode>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_ascii_lowercase();
        Self::ALL
            .into_iter()
            .find(|mode| mode.name() == name)
            .ok_or_else(|| UnknownSendMode {
                input: s.to_string(),
            })
    }
}

/// How much effort a scan spends before accepting silence as an answer.
///
/// Every probing path has its own tuned
/// [`RetryPolicy`](crate::scanner::pacing::retry::RetryPolicy), set against what its
/// protocol actually requires - a SYN is answered as fast as the path allows, an
/// ICMP error only as fast as the host is permitted to send one. This scales
/// that starting point rather than replacing it, so choosing "fast" does not
/// quietly hand the UDP scanner a schedule its protocol cannot satisfy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ScanEffort {
    /// One probe per target and no repeats.
    ///
    /// A first-class choice rather than a disabled feature: it is what an
    /// address-space-scale sweep wants, where per-probe state cannot be afforded
    /// and coverage is bought with a second pass instead.
    Single,
    /// Fewer attempts and less patience. For a network already known to be
    /// healthy, where a missed host is cheaper than the time spent confirming
    /// one is absent.
    Fast,
    #[default]
    Balanced,
    /// More attempts, more patience, and no shortcuts on hosts that stay
    /// silent. For a lossy path, or a result someone is going to act on.
    Thorough,
}

impl ScanEffort {
    /// Every level, ordered from least effort to most.
    pub const ALL: [ScanEffort; 4] = [
        ScanEffort::Single,
        ScanEffort::Fast,
        ScanEffort::Balanced,
        ScanEffort::Thorough,
    ];

    /// The name this level is written under, wherever it arrives as text.
    pub const fn name(self) -> &'static str {
        match self {
            ScanEffort::Single => "single",
            ScanEffort::Fast => "fast",
            ScanEffort::Balanced => "balanced",
            ScanEffort::Thorough => "thorough",
        }
    }
}

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

/// The error parsing a [`ScanEffort`] returns, carrying the names that would
/// have worked so a front end can print it verbatim.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown scan effort '{input}', expected one of: single, fast, balanced, thorough")]
pub struct UnknownScanEffort {
    /// What the caller wrote.
    pub input: String,
}

impl std::str::FromStr for ScanEffort {
    type Err = UnknownScanEffort;

    /// Parses an effort name, ignoring case and surrounding whitespace, so a
    /// choice arriving as text - from an argument, a form field, a settings
    /// file - needs no mapping table of its own.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::config::ScanEffort;
    ///
    /// assert_eq!("Thorough".parse(), Ok(ScanEffort::Thorough));
    /// assert!("maximum".parse::<ScanEffort>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_ascii_lowercase();
        Self::ALL
            .into_iter()
            .find(|effort| effort.name() == name)
            .ok_or_else(|| UnknownScanEffort {
                input: s.to_string(),
            })
    }
}

/// How far a scan goes to identify the operating system behind a host.
///
/// Four levels, ordered by what they put on the wire. The ordering is the point:
/// each level is a superset of the one below it, so raising the level only ever
/// adds evidence and never trades one technique for another. That is what makes
/// [`is_active`](Self::is_active) — "may this send packets of its own?" — a
/// question with a single answer, and what lets a front end offer this as a dial
/// rather than a menu.
///
/// # Why the default is on
///
/// [`Passive`](Self::Passive) sends **nothing at all**. Every signal it reads is
/// already in a reply the scan drew for another reason: the hop count, the
/// fragmentation policy and the identifier in an IP header the capture used to
/// arrive at, and the window and options of a segment the port scanner was
/// waiting for anyway. A scan with it on and a scan with it off emit
/// byte-identical traffic and take the same time, so there is nothing for a
/// caller to weigh, and defaulting it off would mean a finding thrown away for
/// no consideration.
///
/// [`Off`](Self::Off) exists all the same, for the caller who wants a report to
/// contain only what was asked for, and for reproducing a run that predates any
/// of this.
///
/// # Why the higher levels are not
///
/// From [`Active`](Self::Active) upward this costs packets, and unusual ones:
/// probes exist to be identified by how a stack mishandles them, so they are by
/// construction the traffic an intrusion-detection system was written to notice.
/// Sending them has to be asked for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OsDetection {
    /// Level 0. Identify nothing, and record nothing about the stacks that
    /// answered.
    Off,

    /// Level 1, and the default. Read the operating system out of replies the
    /// scan already drew, and send nothing extra.
    ///
    /// Answers at the level of a family — the shape of a stack, not its version
    /// — and answers only for hosts that replied to something. A host that
    /// answered no probe at all leaves nothing to read.
    #[default]
    Passive,

    /// Level 2. Everything [`Passive`](Self::Passive) reads, plus probes of this
    /// engine's own aimed at the hosts whose replies were not enough.
    ///
    /// Ordinary, well-formed packets that stacks are simply known to answer
    /// differently. The traffic is unremarkable in shape but it is extra, it is
    /// addressed at hosts the caller may only have meant to enumerate, and it is
    /// spent on the hosts where passive evidence was thin rather than on
    /// everything.
    Active,

    /// Level 3. Everything [`Active`](Self::Active) sends, plus probes that are
    /// deliberately malformed.
    ///
    /// Reserved fields set, flag combinations no connection produces, headers
    /// that disagree with their own lengths. These separate stacks that agree on
    /// everything legal, which is what version-level identification comes down
    /// to — and they are the packets most likely to be logged, most likely to be
    /// dropped by anything in the path, and the only ones here with any chance of
    /// upsetting what receives them.
    Aggressive,
}

impl OsDetection {
    /// Every level, ordered from least effort to most. The index of a level in
    /// this array is its [`level`](Self::level) number.
    pub const ALL: [OsDetection; 4] = [
        OsDetection::Off,
        OsDetection::Passive,
        OsDetection::Active,
        OsDetection::Aggressive,
    ];

    /// The name this level is written under, wherever it arrives as text.
    pub const fn name(self) -> &'static str {
        match self {
            OsDetection::Off => "off",
            OsDetection::Passive => "passive",
            OsDetection::Active => "active",
            OsDetection::Aggressive => "aggressive",
        }
    }

    /// The number this level is written as, for a front end that offers it as a
    /// dial rather than a word.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::config::OsDetection;
    ///
    /// assert_eq!(OsDetection::default().level(), 1);
    /// ```
    pub const fn level(self) -> u8 {
        match self {
            OsDetection::Off => 0,
            OsDetection::Passive => 1,
            OsDetection::Active => 2,
            OsDetection::Aggressive => 3,
        }
    }

    /// The level with this number, or `None` past the highest there is.
    ///
    /// Deliberately not saturating. A caller who writes `9` meaning "as much as
    /// possible" has written something this engine does not offer, and silently
    /// giving them the top level would hide it — the same reasoning that makes
    /// [`from_str`](Self::from_str) refuse a name it does not know rather than
    /// fall back to the default.
    pub const fn from_level(level: u8) -> Option<Self> {
        match level {
            0 => Some(OsDetection::Off),
            1 => Some(OsDetection::Passive),
            2 => Some(OsDetection::Active),
            3 => Some(OsDetection::Aggressive),
            _ => None,
        }
    }

    /// Whether identification happens at all.
    pub const fn is_enabled(self) -> bool {
        !matches!(self, OsDetection::Off)
    }

    /// Whether this level may put probes of its own on the wire.
    ///
    /// The question every caller with a reason to care is actually asking. A
    /// scan that must add no traffic of its own, and a report that has to say
    /// whether it did, both turn on this and not on which level was chosen.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::config::OsDetection;
    ///
    /// assert!(!OsDetection::Passive.is_active(), "the default sends nothing");
    /// assert!(OsDetection::Aggressive.is_active());
    /// ```
    pub const fn is_active(self) -> bool {
        matches!(self, OsDetection::Active | OsDetection::Aggressive)
    }
}

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

/// The error parsing an [`OsDetection`] returns, carrying the values that would
/// have worked so a front end can print it verbatim.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "unknown OS detection level '{input}', expected one of: off, passive, active, aggressive \
     (or 0, 1, 2, 3)"
)]
pub struct UnknownOsDetection {
    /// What the caller wrote.
    pub input: String,
}

impl FromStr for OsDetection {
    type Err = UnknownOsDetection;

    /// Parses a level by name or by number, ignoring case and surrounding
    /// whitespace, so a choice arriving as text - from an argument, a form
    /// field, a settings file - needs no mapping table of its own.
    ///
    /// Both spellings are accepted because both are how this is written in
    /// practice: a settings file says `passive`, and a command line says `2`.
    /// Splitting them across two entry points would put the correspondence
    /// between the word and the number in whoever called this, and two front ends
    /// would eventually disagree about it.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::config::OsDetection;
    ///
    /// assert_eq!("Aggressive".parse(), Ok(OsDetection::Aggressive));
    /// assert_eq!("0".parse(), Ok(OsDetection::Off));
    /// assert!("maximum".parse::<OsDetection>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let written = s.trim().to_ascii_lowercase();

        if let Ok(level) = written.parse::<u8>()
            && let Some(detection) = Self::from_level(level)
        {
            return Ok(detection);
        }

        Self::ALL
            .into_iter()
            .find(|detection| detection.name() == written)
            .ok_or_else(|| UnknownOsDetection {
                input: s.to_string(),
            })
    }
}

/// User control over retransmission, applied on top of each scanner's own
/// profile.
///
/// Comparable so a report can state whether two runs were asked for the same
/// effort. Not [`Eq`]: `timeout_scale` is a float, and a scale nobody can write
/// down exactly is not a scale two runs should be claimed to share.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RetryConfig {
    pub effort: ScanEffort,
    /// Replaces the attempt budget outright, whatever `effort` implies. One
    /// disables retransmission.
    pub max_attempts: Option<u8>,
    /// Multiplies how long the scan is willing to wait.
    ///
    /// Deliberately does not touch the shortest timeout a policy allows. That
    /// floor is not a preference to be traded away, it is what the protocol
    /// costs: retrying a UDP probe sooner than the target is permitted to answer
    /// is not a faster scan, it is a wasted packet.
    pub timeout_scale: Option<f64>,
    /// Whether a host that answers nothing at all may have its budget cut.
    /// Turning this off spends the full budget on every port of every silent
    /// address, which is thorough and expensive.
    pub dampen_silent_hosts: bool,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            effort: ScanEffort::default(),
            max_attempts: None,
            timeout_scale: None,
            dampen_silent_hosts: true,
        }
    }
}

/// The knobs a probing strategy is built from, carried together so adding one
/// does not mean threading another parameter through every constructor.
///
/// Not every strategy reads every field: local discovery builds its own
/// Ethernet frames and so has no use for [`SendMode`], while every strategy that
/// sends a probe at all has a use for [`RetryConfig`]. `max_probe_rate` is read
/// by routed host discovery; the other paths pace themselves by other means or,
/// where they burst, have not been measured to need it.
#[derive(Debug, Clone, Copy, Default)]
pub struct ProbeTuning {
    pub send_mode: SendMode,
    pub retry: RetryConfig,
    pub max_probe_rate: Option<u32>,
    /// Which segment a TCP port probe carries. Read only by the raw TCP port
    /// scanner: host discovery asks whether anything is there, which every one
    /// of these techniques answers equally badly, so it stays on SYN.
    pub tcp_technique: TcpScanTechnique,

    /// How far a strategy may go to identify the operating system behind a host.
    ///
    /// Read by the raw TCP port scanner, which is where the replies that carry a
    /// stack's shape arrive. At [`OsDetection::Passive`] it changes no packet and
    /// no timing — it reads a reply the scan already drew — so it is here rather
    /// than in a phase of its own.
    pub os_detection: OsDetection,
}

/// What a scan does, and what it is allowed to put on the wire.
///
/// **Every field here changes packets or timing.** Nothing about rendering — no
/// banner, no verbosity, no terminal or keyboard handling — because none of that
/// is the engine's business: it emits `tracing` events and installs no
/// subscriber, so what a run looks like is decided entirely by whoever embeds
/// the crate. A front end's own settings belong to the front end; the engine
/// carries them nowhere and holds no opinion about them.
///
/// That boundary is worth keeping because this type is also the record of *how a
/// scan was run*. [`ScanSettings`](crate::scanner::report::ScanSettings) is derived
/// from it into every report, and a field that cannot change a finding has no
/// business in the record of one.
#[derive(Debug, Clone, Default)]
pub struct ZondConfig {
    /// Forbids the scan from generating any DNS traffic of its own: no A, AAAA
    /// or PTR queries, and no name resolution to go with the addresses it finds.
    ///
    /// Set when the traffic itself is the problem — a query to a resolver the
    /// target operates announces the scan to whoever runs it, and on an
    /// engagement that can be the whole of what goes wrong. The cost is hosts
    /// reported by address alone.
    ///
    /// It governs what this engine sends and nothing else. Traffic the host's
    /// own stack generates for its own reasons is outside anything this crate
    /// can promise.
    pub no_dns: bool,

    /// Whether discovery may probe the whole segment rather than only the
    /// addresses it was given.
    ///
    /// A segment sweep sends the ICMPv6 all-nodes echo, which every IPv6
    /// neighbour may answer, and records the ones that do even though nobody
    /// named them. That is the right behaviour for `zond lan` — the caller asked
    /// about a network, and an IPv6 neighbour with no address in the IPv4 range
    /// is found through this and nothing else. It is the wrong behaviour for
    /// `zond <address>`: scanning one host should not wake its neighbours, and a
    /// report listing eight machines when one was asked about is both surprising
    /// and, on someone else's network, indiscreet.
    ///
    /// Off by default, so the surprising behaviour is the one that has to be
    /// asked for. Only the front end knows which the user meant — the engine
    /// receives an already-resolved set of addresses and cannot tell `lan` from
    /// the range it expanded to — so this has to be set by whoever parsed the
    /// target expression.
    pub segment_sweep: bool,

    /// Whether a port scan should take its targets on trust rather than probing
    /// them for liveness first.
    ///
    /// Off by default, so [`scan`](crate::scan) establishes that a target is
    /// there before spending a probe on each of its ports. An address nothing
    /// answers for otherwise comes back with every port filtered, which is a
    /// thousand lines of the scan reporting its own silence — and on a wide port
    /// range it is most of the run's cost.
    ///
    /// Set it when the liveness probe is the thing that is wrong: a host behind
    /// a firewall that drops ICMP and answers nothing on the discovery ports is
    /// reported down and never scanned, and it may well be up. That is the
    /// trade — the check is what stops a dead address costing a full scan, and
    /// turning it off is what reaches a host that will not answer a knock.
    ///
    /// The liveness phase probes the addresses it was given and nothing else. It
    /// is not a segment sweep; see [`segment_sweep`](Self::segment_sweep).
    pub assume_up: bool,

    /// Whether identifying detail should be masked wherever the scan's findings
    /// leave the process: hostnames, hardware addresses, and the host part of an
    /// IPv6 address.
    ///
    /// For a report going somewhere that needs to know a network's shape without
    /// knowing which device is which — a client, an auditor, a screenshot in an
    /// issue.
    ///
    /// The engine does not mask anything itself; a scan holds what it found. This
    /// records the caller's intent, and it reaches the point of use through
    /// [`ScanSettings`](crate::scanner::report::ScanSettings) and the export layer's
    /// own [`Redaction`](crate::export::Redaction) policy. Masking on the way out
    /// rather than on the way in is deliberate: the alternative is a report that
    /// has quietly lost data nobody can recover.
    pub redact: bool,

    /// How raw SYN probes are placed on the wire. Defaults to
    /// [`SendMode::Auto`], which is correct on every supported platform;
    /// override it only to force Layer-2 sends for host-stack-bypass scanning.
    pub send_mode: SendMode,

    /// The fastest routed discovery may put probes on the wire, in probes per
    /// second. `None` leaves the scanner's own default in force.
    ///
    /// This is a coverage control before it is a politeness one. A probe's
    /// chance of being answered falls as the rate rises: on a policed path a
    /// burst loses most of its first attempt and the loss is recovered, if at
    /// all, by retransmitting into a quieter moment. Lowering the rate buys
    /// coverage on the first attempt instead, and raising it trades coverage
    /// for the time a large range takes to emit.
    pub max_probe_rate: Option<u32>,

    /// Which segment a TCP port probe carries, and so what its answers mean.
    ///
    /// Defaults to [`TcpScanTechnique::Syn`], which is the only technique that
    /// identifies an open port positively and the only one the unprivileged
    /// connect fallback can approximate. The rest need raw sockets; asking for
    /// one without them records a failure rather than quietly substituting a
    /// connect scan, because the two answer different questions.
    ///
    /// Affects the port-scan phase only. [`discover`](crate::scanner::discover)
    /// is unaffected.
    pub tcp_technique: TcpScanTechnique,

    /// How hard the scan tries before accepting silence as an answer.
    ///
    /// Every probing path has its own schedule, tuned to what its protocol
    /// requires; this scales those rather than replacing them, so raising or
    /// lowering the effort cannot hand a scanner a schedule its protocol cannot
    /// satisfy. Defaults to
    /// [`ScanEffort::Balanced`].
    pub retry: RetryConfig,

    /// How far the scan goes to identify the operating system behind each host.
    ///
    /// Defaults to [`OsDetection::Passive`], which reads what the replies the
    /// scan already drew happen to say and emits nothing of its own. The higher
    /// levels send probes and have to be asked for; see [`OsDetection`] for what
    /// each one puts on the wire.
    pub os_detection: OsDetection,
}

impl ZondConfig {
    /// The probe-level knobs, bundled for the strategies that need them.
    pub fn probe_tuning(&self) -> ProbeTuning {
        ProbeTuning {
            send_mode: self.send_mode,
            retry: self.retry,
            max_probe_rate: self.max_probe_rate,
            tcp_technique: self.tcp_technique,
            os_detection: self.os_detection,
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    /// A level's number is written down in three places — the position in
    /// [`OsDetection::ALL`], the arm in `level`, and the arm in `from_level` —
    /// and a fifth level added to two of them would leave a name and a number
    /// that quietly disagree. Nothing else would notice: both spellings would
    /// still parse, and a front end offering the dial would simply select the
    /// wrong thing.
    #[test]
    fn every_os_detection_level_agrees_with_its_number() {
        for (index, detection) in OsDetection::ALL.into_iter().enumerate() {
            assert_eq!(usize::from(detection.level()), index);
            assert_eq!(OsDetection::from_level(detection.level()), Some(detection));
        }

        let past_the_end = OsDetection::ALL.len() as u8;
        assert_eq!(
            OsDetection::from_level(past_the_end),
            None,
            "a level this engine does not offer is refused, not rounded down to the highest"
        );
    }

    /// Where the wire cost begins. The default level promises to emit nothing at
    /// all, and that promise is what makes it safe to leave on for every scan —
    /// so which levels answer `true` here is a behavioural contract, not an
    /// implementation detail.
    #[test]
    fn os_detection_sends_nothing_below_the_active_level() {
        assert!(!OsDetection::Off.is_active());
        assert!(!OsDetection::Passive.is_active());
        assert!(OsDetection::Active.is_active());
        assert!(OsDetection::Aggressive.is_active());

        assert!(!OsDetection::default().is_active(), "the default is silent");
        assert!(OsDetection::default().is_enabled(), "and it is still on");
    }

    /// The two spellings are one setting, so a name and its number have to parse
    /// to the same level. A front end reading `2` from a flag and `active` from a
    /// settings file must not get two different scans.
    #[test]
    fn an_os_detection_level_parses_the_same_by_name_and_by_number() {
        for detection in OsDetection::ALL {
            assert_eq!(detection.name().parse(), Ok(detection));
            assert_eq!(detection.level().to_string().parse(), Ok(detection));
        }

        assert!("4".parse::<OsDetection>().is_err());
        assert!("passive-ish".parse::<OsDetection>().is_err());
    }
}