zond-engine 0.14.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
// 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

//! # Settings and named profiles
//!
//! Defaults a caller wants applied before a scan starts, and named sets of them
//! to switch between. A quality-of-life feature: everything here can also be
//! done by setting fields on [`ZondConfig`] directly, and this exists so a user
//! does not have to type the same six flags every time.
//!
//! ```toml
//! [defaults]
//! effort = "balanced"
//! tcp_technique = "syn"
//!
//! [profiles.stealth]
//! tcp_technique = "fin"
//! max_probe_rate = 200
//!
//! [profiles.sweep]
//! effort = "single"
//! max_probe_rate = 50000
//! ```
//!
//! ## The engine never reads the filesystem on its own
//!
//! A library that absorbs whatever is in the running account's home directory is
//! a supply-chain problem: an embedder who links this crate into a web service
//! has not agreed to have that service's behaviour changed by a file they never
//! looked at.
//!
//! So nothing here happens unless a caller asks for it, by name:
//!
//! - [`paths::user`] and [`paths::system`] compute where a settings file would
//!   live. They read environment variables and touch no disk.
//! - [`load`] opens a path the caller passes. [`read`] takes a reader and does
//!   not open anything, for a front end whose settings live in a database or an
//!   upload.
//! - [`provision`] creates a file, and only when there is none.
//! - [`Settings::apply_to`] changes a [`ZondConfig`] the caller owns.
//!
//! No scanner calls any of them. There is no lazy initialization, no static, and
//! no constructor that quietly looks somewhere.
//!
//! ## What a front end does at startup
//!
//! Four calls, in this order, none of them implicit:
//!
//! ```no_run
//! use zond_engine::config::ZondConfig;
//! use zond_engine::import::settings;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // 1. Make sure the user has a file to edit. Creates one only if there is
//! //    none, and what it writes changes nothing.
//! let (path, outcome) = settings::provision_user()?;
//! if outcome.created() {
//!     println!("wrote a settings file to {}", path.display());
//! }
//!
//! // 2. Read whatever exists, layered, under the profile the user asked for.
//! let (settings, warnings) = settings::resolve(Some("stealth"))?;
//!
//! // 3. Say what was not understood. Ignoring these is the caller's choice to
//! //    make, and they have to hold them to make it.
//! for warning in &warnings {
//!     eprintln!("{warning}");
//! }
//!
//! // 4. Apply them to a configuration the caller owns, then override with
//! //    anything the user typed on top.
//! let mut config = ZondConfig::default();
//! settings.apply_to(&mut config);
//! # Ok(())
//! # }
//! ```
//!
//! A front end that wants none of this constructs [`ZondConfig`] itself and never
//! calls into this module, which is what an embedded engine should do.
//!
//! ## TOML, and why that barely matters
//!
//! The on-disk form is TOML. It is already an unconditional dependency of this
//! crate, it has comments, which lets [`provision`] write a file that explains
//! itself, and `[profiles.<name>]` is the shape of the feature.
//!
//! The format is only a serialization, though. [`Settings`] is an ordinary struct
//! of `Option` fields, so a front end keeping its settings in Postgres, in a
//! browser's local storage or in memory constructs one directly and never touches
//! TOML or a filesystem.
//!
//! ## Every field that overrides is optional, and that is the whole design
//!
//! [`Settings`] holds `Option` for everything a later layer replaces, so unset and
//! set to the default value stay distinguishable. Without that a user file could
//! never override a system file back to a default, since doing so would be
//! indistinguishable from saying nothing.
//!
//! [`exclude`](Settings::exclude) is the exception and is a bare [`Exclusions`].
//! It is the one key that accumulates rather than overrides, so it has no silence
//! to be told apart from: an empty set adds nothing. See
//! [`overlay`](Settings::overlay) for why that key accumulates.
//!
//! Layers, each overriding the one before:
//!
//! ```text
//! ZondConfig::default()  →  system file  →  user file  →  named profile  →  the caller
//! ```
//!
//! ## Never `#[derive(Deserialize)]` on `ZondConfig`
//!
//! The same argument that keeps `Serialize` off `Host`. Deriving welds the file
//! format to the struct layout, and the first field rename becomes a breaking
//! change for every profile anybody has written. This module is the hand-written
//! boundary that costs one file and buys the freedom to move.
//!
//! ## What a settings file may not do
//!
//! It sets numbers and chooses between named alternatives, and that is the entire
//! vocabulary. There is no include directive, no key naming a path that gets
//! opened, and no key naming a command. A file synced from a team repository is
//! input nobody vouches for, so there is nothing in the grammar worth attacking.
//!
//! Nor may it be enormous. [`read`] and [`load`] refuse a document past
//! [`MAX_DOCUMENT_BYTES`], a constant rather than a parameter since there is
//! nothing here worth tuning.

pub mod paths;

use std::collections::BTreeMap;
use std::fmt;
use std::io::BufRead;
use std::num::{NonZeroU8, NonZeroU32};
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::Deserialize;

use crate::config::ZondConfig;
use crate::config::{ScanEffort, TimeoutScale};
use crate::model::exclusion::Exclusions;
use crate::model::ip::set::IpSet;
use crate::model::port::PortSet;
use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
use crate::transport::probe::SendMode;

/// The name a settings document is expected to have on disk.
pub const FILE_NAME: &str = "engine.toml";

/// The most bytes a settings document may be read from.
///
/// A constant rather than a parameter, unlike
/// [`ImportLimits`](crate::import::ImportLimits) on a target list. A target list
/// is a file whose size is the caller's business, where a settings file is a
/// handful of keys somebody typed and [`TEMPLATE`] is under four kilobytes with
/// every key in it.
///
/// [`read`] and [`load`] hold the whole document and [`parse`] then holds two
/// parsed copies, so an enormous file costs several times its own size in memory
/// before anything reads a key.
pub const MAX_DOCUMENT_BYTES: u64 = 1024 * 1024;

/// The template [`provision`] writes.
///
/// Every key is present and every key is commented out, so a freshly created file
/// documents the whole vocabulary and changes nothing. A test pins that: creating
/// a settings file must never change what a scan does.
pub const TEMPLATE: &str = include_str!("../../assets/settings/engine.toml");

/// What went wrong reading, writing or applying settings.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum SettingsError {
    /// The file could not be read or written.
    #[error("{path}: {source}")]
    Io {
        /// What was being opened.
        path: PathBuf,
        /// Why it failed.
        #[source]
        source: std::io::Error,
    },

    /// The document was not valid TOML, or a value was not of the right shape.
    #[error("settings are malformed: {0}")]
    Malformed(String),

    /// The document was longer than [`MAX_DOCUMENT_BYTES`].
    #[error("{path}: settings longer than the {limit} byte limit")]
    TooLarge {
        /// What was being read.
        path: PathBuf,
        /// The limit it passed.
        limit: u64,
    },

    /// A profile was asked for that the document does not define.
    #[error("no profile named '{wanted}'; this document defines: {}",
        if .available.is_empty() { "none".to_string() } else { .available.join(", ") })]
    UnknownProfile {
        /// The name that was asked for.
        wanted: String,
        /// The names that would have worked.
        available: Vec<String>,
    },

    /// No settings path could be computed for this host.
    #[error("no settings directory could be located for this user")]
    NoPath,
}

/// Whether [`provision`] had to create the file.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Provisioned {
    /// The file already existed and was left exactly as it was.
    Existed,
    /// The file did not exist and the commented template was written.
    Created,
}

impl Provisioned {
    /// Whether a file was written.
    pub fn created(self) -> bool {
        matches!(self, Provisioned::Created)
    }
}

/// Something a document said that this build did not understand.
///
/// Reported rather than dropped, and rather than fatal. A misspelled
/// `max_probe_rate` that does nothing means a scan runs at a rate the user
/// believes they changed, with everything appearing to work. Fatal is wrong too:
/// it would stop an
/// older engine from reading a profile a colleague wrote with a newer one.
///
/// So the caller is handed these and decides. A CLI prints them; a CI harness
/// treats them as failures.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingsWarning {
    /// The key, qualified by the table it appeared in.
    pub key: String,
    /// The closest key this build does know, when one is close enough to be
    /// worth suggesting.
    pub suggestion: Option<&'static str>,
}

impl fmt::Display for SettingsWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.suggestion {
            Some(suggestion) => {
                write!(
                    f,
                    "unknown setting '{}'; did you mean '{suggestion}'?",
                    self.key
                )
            }
            None => write!(f, "unknown setting '{}'", self.key),
        }
    }
}

/// A settings document, and everything in it this build did not recognise.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Loaded {
    /// The document.
    pub document: SettingsDocument,
    /// Keys this build does not know. Not empty-checked for the caller: one
    /// that wants to ignore them has to hold them first.
    pub warnings: Vec<SettingsWarning>,
}

/// A whole settings document: the defaults, and the profiles that override
/// them.
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SettingsDocument {
    /// Applied to every scan, before any profile.
    #[serde(default)]
    pub defaults: Settings,
    /// Named sets of overrides. Ordered by name so two runs listing them agree.
    #[serde(default)]
    pub profiles: BTreeMap<String, Settings>,
}

impl SettingsDocument {
    /// The settings for `profile`, layered onto the document's defaults.
    ///
    /// `None` asks for the defaults alone. A name the document does not define is
    /// an error listing the names that would have worked, rather than a silent
    /// fall back to the defaults. A user who asked for `stealth` and
    /// quietly got a full-rate scan has been failed badly.
    pub fn resolve(&self, profile: Option<&str>) -> Result<Settings, SettingsError> {
        let mut settings = self.defaults.clone();

        if let Some(wanted) = profile {
            let Some(overrides) = self.profiles.get(wanted) else {
                return Err(SettingsError::UnknownProfile {
                    wanted: wanted.to_string(),
                    available: self.profiles.keys().cloned().collect(),
                });
            };
            settings.overlay(overrides);
        }

        Ok(settings)
    }

    /// The profile names this document defines, in order.
    pub fn profile_names(&self) -> impl Iterator<Item = &str> {
        self.profiles.keys().map(String::as_str)
    }
}

/// One layer of settings. Every field is optional; see the module documentation
/// for why that is the design rather than a convenience.
///
/// Mirrors the fields of [`ZondConfig`] that are worth setting once and
/// forgetting, which is not all of them:
///
/// - **`segment_sweep` is missing.** It is decided by the target expression the
///   user typed and belongs to the front end that parsed it. A file must not be
///   able to turn a single-host scan into a segment sweep behind the user's back.
/// - **`exclude` is present**, which is the same argument read the other way. A
///   document may narrow a scan and may not widen one. Nothing it says here puts
///   a packet on the wire that would not otherwise have gone out, and an
///   administrator with a range that must never be scanned has nowhere else to
///   put it. Layering it unions rather than overrides; see
///   [`overlay`](Self::overlay).
/// - **Nothing about presentation is here.** No banner, no verbosity, no terminal
///   handling. This document configures a scan, and how one is displayed belongs
///   to whatever program is displaying it, in a file of its own. See
///   [`ZondConfig`] for where that line is drawn.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
#[serde(default)]
pub struct Settings {
    /// Forbids the scan from generating DNS traffic.
    pub no_dns: Option<bool>,
    /// Masks hostnames and hardware addresses in output.
    pub redact: Option<bool>,
    /// How raw probes are placed on the wire.
    #[serde(deserialize_with = "de_send_mode")]
    pub send_mode: Option<SendMode>,
    /// The fastest routed discovery may probe, in probes per second. Refused if
    /// zero, which is not a slower scan but no scan.
    #[serde(deserialize_with = "de_probe_rate")]
    pub max_probe_rate: Option<NonZeroU32>,
    /// The slowest a scan may settle at, in probes per second. Refused if zero,
    /// which is the absence of a floor rather than a floor.
    #[serde(deserialize_with = "de_min_probe_rate")]
    pub min_probe_rate: Option<NonZeroU32>,
    /// The shortest gap between two probes at one host, in whole milliseconds.
    /// Refused if zero, which is the absence of a gap rather than a gap.
    #[serde(deserialize_with = "de_millis")]
    pub host_probe_interval: Option<Duration>,
    /// How long a scan may spend on one host, in whole seconds. Refused if
    /// zero, which is a scan that asks nothing rather than a quick one.
    #[serde(deserialize_with = "de_timeout")]
    pub host_timeout: Option<Duration>,
    /// How long the whole scan may run, in whole seconds. Refused if zero, on
    /// the same reading.
    #[serde(deserialize_with = "de_timeout")]
    pub scan_timeout: Option<Duration>,
    /// Which segment a TCP port probe carries.
    #[serde(deserialize_with = "de_technique")]
    pub tcp_technique: Option<TcpScanTechnique>,
    /// Which chunk an SCTP port probe carries.
    #[serde(deserialize_with = "de_sctp_technique")]
    pub sctp_technique: Option<SctpScanTechnique>,
    /// How hard the scan tries before accepting silence as an answer.
    #[serde(deserialize_with = "de_effort")]
    pub effort: Option<ScanEffort>,
    /// Replaces the attempt budget outright. One disables retransmission, and
    /// zero is refused: a probe that is never sent is not a scan setting.
    #[serde(deserialize_with = "de_max_attempts")]
    pub max_attempts: Option<NonZeroU8>,
    /// Multiplies how long the scan is willing to wait. Refused unless positive
    /// and finite.
    #[serde(deserialize_with = "de_timeout_scale")]
    pub timeout_scale: Option<TimeoutScale>,
    /// Whether a host that answers nothing may have its probe budget cut.
    pub dampen_silent_hosts: Option<bool>,
    /// Whether to establish what each TLS port accepts, rather than only what
    /// one handshake negotiated.
    pub tls_enumeration: Option<bool>,
    /// The ports a scan covers when the caller names none.
    ///
    /// Held as written rather than parsed on the way in, since a port
    /// specification is a [`PortSet`] grammar and this struct is a document.
    /// [`ports`](Self::ports) parses it.
    pub default_ports: Option<String>,
    /// Addresses no scan reading this document may probe.
    ///
    /// Written as a list of literal addresses, ranges and CIDR blocks:
    ///
    /// ```toml
    /// exclude = ["10.0.5.0/24", "192.168.1.10-20", "2001:db8::/64"]
    /// ```
    ///
    /// Parsed on the way in, unlike [`default_ports`](Self::default_ports). A
    /// malformed port specification degrades to the built-in list, which is
    /// visible in the result and costs nothing but a wider scan. A malformed
    /// exclusion degrading the same way would scan the range somebody wrote down
    /// to keep out of, with nothing in the output saying so. So it is a document
    /// error, raised where the
    /// document is read, and there is no accessor to forget to call.
    ///
    /// Names and keywords are refused. `lan` names a different network on every
    /// machine that reads the file and `db.internal` a different address
    /// every time it is looked up, and neither belongs in a value written once
    /// and applied to every scan afterwards. A front end resolving an exclusion
    /// typed at the moment it is used has
    /// [`resolve::for_exclusion`](crate::resolve::for_exclusion), which takes
    /// the full grammar.
    #[serde(deserialize_with = "de_exclusions")]
    pub exclude: Exclusions,
}

impl Settings {
    /// Settings that change nothing.
    pub fn new() -> Self {
        Self::default()
    }

    /// Takes every value `other` sets, leaving the rest alone.
    ///
    /// This is what layering is: a later document speaks only about the keys it
    /// mentions, and silence is not an opinion.
    pub fn overlay(&mut self, other: &Settings) {
        macro_rules! take {
            ($($field:ident),+ $(,)?) => {
                $(if other.$field.is_some() {
                    self.$field = other.$field.clone();
                })+
            };
        }

        take!(
            no_dns,
            redact,
            send_mode,
            max_probe_rate,
            min_probe_rate,
            host_probe_interval,
            host_timeout,
            scan_timeout,
            tcp_technique,
            sctp_technique,
            effort,
            max_attempts,
            timeout_scale,
            dampen_silent_hosts,
            tls_enumeration,
            default_ports,
        );

        // The one key that accumulates. Every setting above says how a scan
        // should be run and the latest answer wins; `exclude` says where it may
        // not go, and a later layer overriding that would let a user's file drop
        // the range an administrator wrote into the system-wide one. Unioning
        // can only ever make a scan smaller. See `Exclusions::extend`.
        self.exclude.extend(&other.exclude);
    }

    /// The default port set this document names, if it names one.
    ///
    /// Separate from the field: a malformed specification is the caller's to
    /// report, and a document is worth loading even when one key in
    /// it is wrong.
    pub fn ports(&self) -> Option<Result<PortSet, SettingsError>> {
        self.default_ports.as_deref().map(|spec| {
            PortSet::try_from(spec).map_err(|error| {
                SettingsError::Malformed(format!("default_ports = '{spec}': {error}"))
            })
        })
    }

    /// Applies every value this sets to `config`, leaving the rest as it was.
    ///
    /// The one direction settings ever move. Nothing in this module reaches into
    /// a running scan; a caller builds its configuration, applies what it
    /// loaded, and starts.
    pub fn apply_to(&self, config: &mut ZondConfig) {
        if let Some(value) = self.no_dns {
            config.no_dns = value;
        }
        if let Some(value) = self.redact {
            config.redact = value;
        }
        if let Some(value) = self.send_mode {
            config.send_mode = value;
        }
        if self.max_probe_rate.is_some() {
            config.max_probe_rate = self.max_probe_rate;
        }
        if self.min_probe_rate.is_some() {
            config.min_probe_rate = self.min_probe_rate;
        }
        if self.host_probe_interval.is_some() {
            config.host_probe_interval = self.host_probe_interval;
        }
        if self.host_timeout.is_some() {
            config.host_timeout = self.host_timeout;
        }
        if self.scan_timeout.is_some() {
            config.scan_timeout = self.scan_timeout;
        }
        if let Some(value) = self.tcp_technique {
            config.tcp_technique = value;
        }
        if let Some(value) = self.sctp_technique {
            config.sctp_technique = value;
        }
        if let Some(value) = self.effort {
            config.retry.effort = value;
        }
        if self.max_attempts.is_some() {
            config.retry.max_attempts = self.max_attempts;
        }
        if self.timeout_scale.is_some() {
            config.retry.timeout_scale = self.timeout_scale;
        }
        if let Some(value) = self.dampen_silent_hosts {
            config.retry.dampen_silent_hosts = value;
        }
        if let Some(value) = self.tls_enumeration {
            config.tls_enumeration = value;
        }
        // Added to what the configuration already forbids rather than replacing
        // it, for the reason `overlay` gives. A caller who resolved an exclusion
        // from the command line before applying a document must not
        // lose it to one, and the reverse order must not lose the document's.
        config.exclusions.extend(&self.exclude);
    }
}

// ---------------------------------------------------------------------------
// Reading
// ---------------------------------------------------------------------------

/// Every key [`Settings`] understands, for recognising one and for suggesting a
/// correction.
///
/// Add a field to [`Settings`] and it goes here and in
/// [`TEMPLATE`](crate::import::settings::TEMPLATE) too, or a document setting
/// it is warned about while the value is quietly applied.
/// `the_template_documents_every_key_and_no_others` holds this list and the
/// template to each other in both directions; nothing can hold either to the
/// struct, so that step is by hand.
const KNOWN_KEYS: [&str; 17] = [
    "exclude",
    "no_dns",
    "redact",
    "send_mode",
    "max_probe_rate",
    "min_probe_rate",
    "host_probe_interval",
    "host_timeout",
    "scan_timeout",
    "tcp_technique",
    "sctp_technique",
    "effort",
    "max_attempts",
    "timeout_scale",
    "dampen_silent_hosts",
    "tls_enumeration",
    "default_ports",
];

/// Reads a settings document from anywhere.
///
/// Opens nothing. A front end whose settings live in a database, an upload or a
/// string hands the bytes over and gets the same parsing a file would.
pub fn read(input: &mut dyn BufRead) -> Result<Loaded, SettingsError> {
    read_bounded(input, &PathBuf::from("<reader>"))
}

/// Reads at most [`MAX_DOCUMENT_BYTES`] from `input`, naming `path` if it
/// refuses.
///
/// Bounded before the read rather than measured after, as [`crate::import::list`]
/// bounds a line: a document with no end must not be held in memory to discover
/// it is too long. One byte past
/// the ceiling is read so that a document exactly at it is still accepted.
fn read_bounded(input: &mut dyn BufRead, path: &Path) -> Result<Loaded, SettingsError> {
    use std::io::Read as _;

    let mut text = String::new();
    let read = std::io::Read::take(input, MAX_DOCUMENT_BYTES.saturating_add(1))
        .read_to_string(&mut text)
        .map_err(|source| SettingsError::Io {
            path: path.to_path_buf(),
            source,
        })?;

    if read as u64 > MAX_DOCUMENT_BYTES {
        return Err(SettingsError::TooLarge {
            path: path.to_path_buf(),
            limit: MAX_DOCUMENT_BYTES,
        });
    }

    parse(&text)
}

/// Reads a settings document from a path.
///
/// The one function in this module that opens a file, and it opens the one it was
/// handed. See the module documentation for why that distinction is the
/// whole design.
pub fn load(path: &Path) -> Result<Loaded, SettingsError> {
    let file = std::fs::File::open(path).map_err(|source| SettingsError::Io {
        path: path.to_path_buf(),
        source,
    })?;

    read_bounded(&mut std::io::BufReader::new(file), path)
}

/// Parses a document and collects the keys this build does not know.
pub fn parse(text: &str) -> Result<Loaded, SettingsError> {
    // Parsed twice on purpose. The typed pass is the document, and the untyped
    // pass is the only way to see the keys the typed one ignored, and
    // silence is exactly what makes a misspelled setting dangerous.
    let raw: toml::Table = text
        .parse()
        .map_err(|error: toml::de::Error| SettingsError::Malformed(error.to_string()))?;

    let document: SettingsDocument = toml::from_str(text)
        .map_err(|error: toml::de::Error| SettingsError::Malformed(error.to_string()))?;

    let mut warnings = Vec::new();
    collect_warnings(&raw, &mut warnings);

    Ok(Loaded { document, warnings })
}

/// Walks the untyped document for keys no layer understands.
fn collect_warnings(raw: &toml::Table, warnings: &mut Vec<SettingsWarning>) {
    for (table, value) in raw {
        match table.as_str() {
            "defaults" => warn_unknown_keys("defaults", value, warnings),
            "profiles" => {
                let Some(profiles) = value.as_table() else {
                    continue;
                };
                for (name, settings) in profiles {
                    warn_unknown_keys(&format!("profiles.{name}"), settings, warnings);
                }
            }
            other => warnings.push(SettingsWarning {
                key: other.to_string(),
                suggestion: nearest("defaults", other).or_else(|| nearest("profiles", other)),
            }),
        }
    }
}

/// Reports the keys of one settings table that this build does not know.
fn warn_unknown_keys(table: &str, value: &toml::Value, warnings: &mut Vec<SettingsWarning>) {
    let Some(settings) = value.as_table() else {
        return;
    };

    for key in settings.keys() {
        if KNOWN_KEYS.contains(&key.as_str()) {
            continue;
        }
        warnings.push(SettingsWarning {
            key: format!("{table}.{key}"),
            // The nearest key rather than the first one close enough: a user
            // who wrote `no_dn` should be pointed at `no_dns` rather than at
            // whichever candidate this list happens to name first.
            suggestion: KNOWN_KEYS
                .iter()
                .copied()
                .map(|known| (edit_distance(key, known), known))
                .filter(|(distance, _)| *distance <= 2)
                .min_by_key(|(distance, _)| *distance)
                .map(|(_, known)| known),
        });
    }
}

/// The nearest of a single candidate, if it is near enough to suggest.
fn nearest(candidate: &'static str, written: &str) -> Option<&'static str> {
    (edit_distance(written, candidate) <= 2).then_some(candidate)
}

/// Levenshtein distance, bounded by the length of the shorter word.
///
/// Only ever run against a handful of short keys when something is already
/// wrong, so the straightforward two-row implementation is the right one.
fn edit_distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();

    let mut previous: Vec<usize> = (0..=b.len()).collect();
    let mut current = vec![0usize; b.len() + 1];

    for (i, left) in a.iter().enumerate() {
        current[0] = i + 1;
        for (j, right) in b.iter().enumerate() {
            let substitution = previous[j] + usize::from(left != right);
            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
        }
        std::mem::swap(&mut previous, &mut current);
    }

    previous[b.len()]
}

// ---------------------------------------------------------------------------
// Provisioning
// ---------------------------------------------------------------------------

/// Creates a settings file at `path` if there is not one already.
///
/// The only function in this crate that writes to a filesystem, arranged so that
/// calling it cannot cost anybody their configuration:
///
/// - **It never overwrites.** The file is created with `create_new`, which fails
///   atomically if anything is already there, so two processes racing cannot both
///   decide the file was missing.
/// - **It never edits.** An existing file is not read, reformatted or extended
///   with a profile it lacks. Rewriting somebody's configuration to add a table
///   loses their comments and their ordering.
/// - **What it writes changes nothing.** [`TEMPLATE`] has every key commented
///   out, so a scan run immediately after provisioning behaves as it did before.
///   A test pins that.
///
/// Parent directories are created as needed. On Unix the directory is created
/// `0700` and the file `0600`: a settings file records which networks somebody
/// scans and how, which is nobody else's business on a shared host.
pub fn provision(path: &Path) -> Result<Provisioned, SettingsError> {
    if let Some(parent) = path.parent() {
        create_directory(parent)?;
    }

    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);

    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }

    match options.open(path) {
        Ok(mut file) => {
            use std::io::Write;
            file.write_all(TEMPLATE.as_bytes())
                .map_err(|source| SettingsError::Io {
                    path: path.to_path_buf(),
                    source,
                })?;
            Ok(Provisioned::Created)
        }
        // The one error that is not a failure: somebody else's file, or this
        // from last time, is exactly what this function wants to find.
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(Provisioned::Existed),
        Err(source) => Err(SettingsError::Io {
            path: path.to_path_buf(),
            source,
        }),
    }
}

/// Creates a directory and its parents, with restrictive permissions on Unix.
fn create_directory(path: &Path) -> Result<(), SettingsError> {
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);

    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(0o700);
    }

    builder.create(path).map_err(|source| SettingsError::Io {
        path: path.to_path_buf(),
        source,
    })
}

/// Creates the user's settings file if there is not one, and reports where it
/// is.
///
/// The convenience a front end wants at startup: one call that leaves the user
/// with a file to edit. It still has to be called; see the module
/// documentation.
pub fn provision_user() -> Result<(PathBuf, Provisioned), SettingsError> {
    let path = paths::user().ok_or(SettingsError::NoPath)?;
    let outcome = provision(&path)?;
    Ok((path, outcome))
}

/// Loads the settings a caller should run under, from the files that exist.
///
/// Reads the system file then the user file, skipping either if it is not there,
/// layers them in that order, then applies `profile`. A file that exists but
/// cannot be parsed is an error: an unreadable settings file is not an absent
/// one, and treating it as absent would run a scan under
/// settings the user believes they wrote.
///
/// Returns the resolved settings and every warning from every file. Nothing is
/// applied anywhere; hand the result to [`Settings::apply_to`].
pub fn resolve(profile: Option<&str>) -> Result<(Settings, Vec<SettingsWarning>), SettingsError> {
    let mut settings = Settings::new();
    let mut warnings = Vec::new();
    let mut found_profile = profile.is_none();
    // Gathered across every file so a name nobody defined is reported against
    // everything that was defined rather than against one file's
    // half of the picture.
    let mut available: Vec<String> = Vec::new();

    for path in paths::layered() {
        if !path.exists() {
            continue;
        }

        let loaded = load(&path)?;
        warnings.extend(loaded.warnings);

        settings.overlay(&loaded.document.defaults);

        for name in loaded.document.profile_names() {
            if !available.iter().any(|known| known == name) {
                available.push(name.to_string());
            }
        }

        if let Some(wanted) = profile
            && let Some(overrides) = loaded.document.profiles.get(wanted)
        {
            settings.overlay(overrides);
            found_profile = true;
        }
    }

    if !found_profile {
        available.sort();
        return Err(SettingsError::UnknownProfile {
            wanted: profile.unwrap_or_default().to_string(),
            available,
        });
    }

    Ok((settings, warnings))
}

// ---------------------------------------------------------------------------
// Deserialization of the fields that are named alternatives
// ---------------------------------------------------------------------------

/// Reads a value written as one of a fixed set of names.
///
/// The error names what was written and what would have worked, which is why
/// these are not plain strings in the struct. A settings file that says
/// `tcp_technique = "stealth"` should say so at load rather than scan with the
/// wrong technique.
pub(super) fn de_named<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: std::str::FromStr,
    T::Err: fmt::Display,
{
    let Some(text) = Option::<String>::deserialize(deserializer)? else {
        return Ok(None);
    };
    text.parse().map(Some).map_err(serde::de::Error::custom)
}

/// Reads a [`SendMode`] by the name a person wrote, through [`de_named`] so an
/// unknown one is refused by naming what is accepted.
fn de_send_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<SendMode>, D::Error> {
    de_named(d)
}

/// [`de_send_mode`] for the TCP technique.
fn de_technique<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Option<TcpScanTechnique>, D::Error> {
    de_named(d)
}

/// [`de_send_mode`] for the SCTP technique.
fn de_sctp_technique<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Option<SctpScanTechnique>, D::Error> {
    de_named(d)
}

/// [`de_send_mode`] for the scan effort.
fn de_effort<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<ScanEffort>, D::Error> {
    de_named(d)
}

/// Reads `max_probe_rate`, refusing a ceiling of zero.
///
/// The three numeric readers below all exist for one reason: the engine used to
/// take these values, find them unusable where the schedule is built, discard
/// them without a word, and then write them into the report as though they had
/// applied. A document is exactly where that is worth catching, since nobody is
/// watching the file being read.
fn de_probe_rate<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<NonZeroU32>, D::Error> {
    let Some(rate) = Option::<u32>::deserialize(d)? else {
        return Ok(None);
    };
    NonZeroU32::new(rate).map(Some).ok_or_else(|| {
        serde::de::Error::custom(
            "max_probe_rate = 0: a ceiling of zero probes per second is not a slower scan \
             but no scan. Remove the key to leave each scanner its own pacing.",
        )
    })
}

/// Reads `min_probe_rate`, refusing a floor of zero.
///
/// The mirror of [`de_probe_rate`]'s reason rather than the same one: a floor of
/// zero does not ask for a stalled scan, it asks for no floor, which leaving the
/// key out already says. Accepting it would write a bound into the report that
/// never bound anything.
fn de_min_probe_rate<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Option<NonZeroU32>, D::Error> {
    let Some(rate) = Option::<u32>::deserialize(d)? else {
        return Ok(None);
    };
    NonZeroU32::new(rate).map(Some).ok_or_else(|| {
        serde::de::Error::custom(
            "min_probe_rate = 0: a floor of zero probes per second is the absence of a floor. \
             Remove the key to let each scanner settle where it will.",
        )
    })
}

/// Reads a wall-clock budget written in whole seconds, refusing zero.
///
/// Seconds because that is the unit somebody writing a schedule thinks in, and
/// whole ones because no scan is bounded to a useful precision finer than that.
/// Zero is refused for the reason [`de_probe_rate`] refuses a rate of zero: a
/// budget that expires before the first probe is a scan that asks nothing, and
/// nobody writing it into a file meant that.
fn de_timeout<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
    let Some(seconds) = Option::<u64>::deserialize(d)? else {
        return Ok(None);
    };
    if seconds == 0 {
        return Err(serde::de::Error::custom(
            "a timeout of 0 seconds expires before the first probe, which is a scan \
             that asks nothing. Remove the key to leave the scan unbounded.",
        ));
    }
    Ok(Some(Duration::from_secs(seconds)))
}

/// Reads a gap written in whole milliseconds, refusing zero.
///
/// Milliseconds rather than the whole seconds [`de_timeout`] takes, because the
/// gaps worth writing down are shorter than a second: an IDS threshold of ten
/// probes a second is a hundred milliseconds, and rounding that to a whole one
/// would be a tenth of the pace the file asked for.
///
/// Zero is refused for the reason [`de_min_probe_rate`] refuses a floor of zero:
/// a gap of no time is what leaving the key out already says, and accepting it
/// would put a bound in the report that never bound anything.
fn de_millis<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
    let Some(millis) = Option::<u64>::deserialize(d)? else {
        return Ok(None);
    };
    if millis == 0 {
        return Err(serde::de::Error::custom(
            "host_probe_interval = 0: a gap of no time is the absence of a gap. \
             Remove the key to let each pass send as fast as its own pacing allows.",
        ));
    }
    Ok(Some(Duration::from_millis(millis)))
}

/// Reads `max_attempts`, refusing a budget of zero.
fn de_max_attempts<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<NonZeroU8>, D::Error> {
    let Some(attempts) = Option::<u8>::deserialize(d)? else {
        return Ok(None);
    };
    NonZeroU8::new(attempts).map(Some).ok_or_else(|| {
        serde::de::Error::custom(
            "max_attempts = 0: a probe that is never sent is not a scan setting. \
             Write 1 for a single attempt with no retransmission.",
        )
    })
}

/// Reads `timeout_scale`, refusing anything no schedule can be built from.
fn de_timeout_scale<'de, D: serde::Deserializer<'de>>(
    d: D,
) -> Result<Option<TimeoutScale>, D::Error> {
    let Some(scale) = Option::<f64>::deserialize(d)? else {
        return Ok(None);
    };
    TimeoutScale::new(scale).map(Some).ok_or_else(|| {
        serde::de::Error::custom(format!(
            "timeout_scale = {scale}: a scale multiplies how long the scan waits, \
             so it has to be a positive, finite number."
        ))
    })
}

/// Reads `exclude` as a list of address expressions, refusing anything the
/// document cannot settle by itself.
///
/// [`IpSet`]'s own grammar takes a literal address, an inclusive range and a CIDR
/// block and nothing else, so a keyword or a hostname arrives here as a parse
/// failure. See [`Settings::exclude`] for why a file is the wrong place
/// for either.
fn de_exclusions<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Exclusions, D::Error> {
    let written = Vec::<String>::deserialize(d)?;

    let mut ips = IpSet::new();
    for expression in &written {
        let parsed: IpSet = expression.parse().map_err(|error| {
            serde::de::Error::custom(format!(
                "exclude = '{expression}': {error}. A settings file takes addresses, \
                 ranges and CIDR blocks; names and keywords such as 'lan' mean something \
                 different on every machine that reads the file and are not accepted here."
            ))
        })?;
        for range in parsed.v4() {
            ips.push_v4_range(*range);
        }
        for range in parsed.v6() {
            ips.push_v6_range(*range);
        }
    }

    Ok(Exclusions::new(ips))
}

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

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

    fn document(text: &str) -> Loaded {
        parse(text).expect("the document parses")
    }

    /// Exclusions accumulate across every layer, where every other key is
    /// replaced by the one above it.
    ///
    /// An administrator's system-wide file forbids the cardholder segment, a
    /// user's file forbids a fragile appliance of their own, and a profile adds a
    /// third range. Under the ordinary overlay rule the administrator's range
    /// would be gone the moment the user named one, and the scan that followed
    /// would look like a correct one.
    /// A value the engine cannot honour is refused where the document is read,
    /// rather than accepted, discarded where the schedule is built, and then
    /// written into the report as though it had applied.
    ///
    /// A file is exactly where that is worth catching: nobody is watching it
    /// being read, so a scan runs at a pace the user believes they changed.
    #[test]
    fn a_setting_the_engine_could_not_honour_is_refused_by_name() {
        for (document, expected) in [
            ("[defaults]\nmax_probe_rate = 0\n", "max_probe_rate"),
            ("[defaults]\nmin_probe_rate = 0\n", "min_probe_rate"),
            (
                "[defaults]\nhost_probe_interval = 0\n",
                "host_probe_interval",
            ),
            ("[defaults]\nmax_attempts = 0\n", "max_attempts"),
            ("[defaults]\ntimeout_scale = 0.0\n", "timeout_scale"),
            ("[defaults]\ntimeout_scale = -1.5\n", "timeout_scale"),
            ("[defaults]\ntimeout_scale = nan\n", "timeout_scale"),
        ] {
            let refused = read(&mut document.as_bytes()).expect_err(document);
            let message = refused.to_string();
            assert!(
                message.contains(expected),
                "{document:?} was refused without naming {expected}: {message}"
            );
        }
    }

    /// And the values beside them still read, so the refusal is a bound rather
    /// than a wall.
    #[test]
    fn the_smallest_usable_values_are_accepted() {
        let mut document = &b"[defaults]\nmax_probe_rate = 1\nmin_probe_rate = 1\nmax_attempts = 1\ntimeout_scale = 0.001\n"[..];
        let loaded = read(&mut document).expect("the smallest usable values are settings");

        let settings = loaded.document.resolve(None).expect("resolves");
        assert_eq!(settings.max_probe_rate, NonZeroU32::new(1));
        assert_eq!(settings.min_probe_rate, NonZeroU32::new(1));
        assert_eq!(settings.max_attempts, NonZeroU8::new(1));
        assert_eq!(settings.timeout_scale.map(TimeoutScale::get), Some(0.001));
    }

    #[test]
    fn every_layer_adds_its_exclusions_and_none_replaces_another() {
        let mut administrator = document(
            r#"
            [defaults]
            exclude = ["10.0.5.0/24"]

            [profiles.audit]
            exclude = ["10.0.9.0/24"]
            "#,
        )
        .document;

        let user = document(
            r#"
            [defaults]
            exclude = ["192.168.1.50"]
            "#,
        )
        .document;

        administrator.defaults.overlay(&user.defaults);
        let settings = administrator.resolve(Some("audit")).expect("the profile");

        let mut config = ZondConfig::default();
        settings.apply_to(&mut config);

        for excluded in ["10.0.5.7", "192.168.1.50", "10.0.9.1"] {
            assert!(
                config
                    .exclusions
                    .excludes(&excluded.parse().expect("literal")),
                "{excluded} was named by a layer and must still be excluded"
            );
        }
        assert!(
            !config
                .exclusions
                .excludes(&"10.0.6.7".parse().expect("literal"))
        );
    }

    /// Applying a document adds to what the caller already forbade rather than
    /// replacing it, so the order the two arrive in cannot lose either.
    #[test]
    fn applying_a_document_keeps_the_exclusions_the_caller_already_had() {
        let mut from_the_command_line = IpSet::new();
        from_the_command_line.insert_range("172.16.0.0/16".parse().expect("a valid range"));

        let mut config = ZondConfig {
            exclusions: Exclusions::new(from_the_command_line),
            ..Default::default()
        };

        document(
            r#"
            [defaults]
            exclude = ["10.0.5.0/24"]
            "#,
        )
        .document
        .defaults
        .apply_to(&mut config);

        assert!(
            config
                .exclusions
                .excludes(&"172.16.4.4".parse().expect("literal"))
        );
        assert!(
            config
                .exclusions
                .excludes(&"10.0.5.7".parse().expect("literal"))
        );
    }

    /// A malformed exclusion stops the document, where a malformed port
    /// specification does not.
    ///
    /// A bad `default_ports` degrades to the built-in list and the result says
    /// what was scanned. A bad `exclude` degrading the same way would scan the
    /// range somebody wrote down to keep out of, with nothing in the output
    /// mentioning it, so the document refuses to load. The same refusal covers
    /// `lan` and hostnames, which this file is the wrong place for.
    #[test]
    fn a_malformed_exclusion_refuses_the_document() {
        for written in ["lan", "db.internal", "10.0.5.0/33"] {
            let error = parse(&format!(
                r#"
                [defaults]
                exclude = ["{written}"]
                "#
            ))
            .expect_err("the document must not load");

            assert!(
                error.to_string().contains(written),
                "the error names what was written: {error}"
            );
        }
    }

    /// The property the whole layering design rests on: a later file speaks only
    /// about the keys it mentions, and silence is not an opinion. Without
    /// `Option` everywhere, a user file could never override a system file back
    /// to a default value.
    #[test]
    fn a_later_layer_overrides_only_what_it_mentions() {
        let system = document(
            r#"
            [defaults]
            redact = true
            no_dns = true
            max_probe_rate = 1000
            "#,
        );
        let user = document(
            r#"
            [defaults]
            redact = false
            "#,
        );

        let mut settings = system.document.defaults.clone();
        settings.overlay(&user.document.defaults);

        assert_eq!(
            settings.redact,
            Some(false),
            "the user file spoke about this"
        );
        assert_eq!(settings.no_dns, Some(true), "and said nothing about this");
        assert_eq!(settings.max_probe_rate, NonZeroU32::new(1000));
    }

    #[test]
    fn a_profile_layers_onto_the_defaults() {
        let loaded = document(
            r#"
            [defaults]
            effort = "balanced"
            max_probe_rate = 20000
            no_dns = true

            [profiles.stealth]
            effort = "thorough"
            max_probe_rate = 200
            "#,
        );

        let defaults = loaded.document.resolve(None).expect("resolves");
        assert_eq!(defaults.effort, Some(ScanEffort::Balanced));
        assert_eq!(defaults.max_probe_rate, NonZeroU32::new(20000));

        let stealth = loaded.document.resolve(Some("stealth")).expect("resolves");
        assert_eq!(stealth.effort, Some(ScanEffort::Thorough));
        assert_eq!(stealth.max_probe_rate, NonZeroU32::new(200));
        assert_eq!(stealth.no_dns, Some(true), "inherited from the defaults");
    }

    /// A user who asked for `stealth` and quietly got a full-rate scan has been
    /// failed badly, so a name the document does not define is an error that
    /// lists the ones it does.
    #[test]
    fn an_unknown_profile_is_an_error_naming_the_ones_that_exist() {
        let loaded = document(
            r#"
            [profiles.stealth]
            effort = "thorough"

            [profiles.sweep]
            effort = "single"
            "#,
        );

        match loaded.document.resolve(Some("quiet")).expect_err("refused") {
            SettingsError::UnknownProfile { wanted, available } => {
                assert_eq!(wanted, "quiet");
                assert_eq!(available, vec!["stealth", "sweep"]);
            }
            other => panic!("expected an unknown profile, got {other:?}"),
        }
    }

    /// A misspelled key that silently does nothing means a scan runs at a rate
    /// the user believes they changed. Reported, not dropped - and not fatal,
    /// so an older engine can still read a colleague's newer profile.
    #[test]
    fn an_unknown_key_is_reported_with_the_nearest_one_that_exists() {
        let loaded = document(
            r#"
            [defaults]
            max_probe_rat = 500
            invented_entirely = true

            [profiles.stealth]
            tcp_techniqu = "fin"
            "#,
        );

        assert_eq!(loaded.warnings.len(), 3, "{:?}", loaded.warnings);

        // Looked up rather than indexed: the order is deterministic - the
        // untyped document is a sorted map - but it is the sorted order, not
        // the order the keys were written in, and a test that pinned the
        // latter would be pinning something this module never promised.
        let find = |key: &str| {
            loaded
                .warnings
                .iter()
                .find(|warning| warning.key == key)
                .unwrap_or_else(|| panic!("no warning for {key}: {:?}", loaded.warnings))
        };

        assert_eq!(
            find("defaults.max_probe_rat").suggestion,
            Some("max_probe_rate")
        );
        assert_eq!(
            find("defaults.invented_entirely").suggestion,
            None,
            "nothing is close enough to this to be worth suggesting"
        );
        assert_eq!(
            find("profiles.stealth.tcp_techniqu").suggestion,
            Some("tcp_technique")
        );
    }

    /// A named alternative that does not exist has to fail at load. Scanning
    /// with the wrong technique because a file said `stealth` would be a wrong
    /// answer that looks like a right one.
    #[test]
    fn a_name_outside_the_set_is_refused_at_load_and_says_what_would_have_worked() {
        let error = parse(
            r#"
            [defaults]
            tcp_technique = "stealth"
            "#,
        )
        .expect_err("refused");

        let message = error.to_string();
        assert!(message.contains("stealth"), "{message}");
        assert!(message.contains("syn"), "the accepted names: {message}");
    }

    /// Settings move in exactly one direction, and only over the keys they set.
    #[test]
    fn applying_settings_changes_only_what_they_name() {
        let loaded = document(
            r#"
            [defaults]
            no_dns = true
            redact = true
            tcp_technique = "xmas"
            effort = "thorough"
            max_attempts = 5
            max_probe_rate = 750
            send_mode = "ethernet"
            "#,
        );

        let mut config = ZondConfig::default();
        let before_sweep = config.segment_sweep;
        loaded.document.defaults.apply_to(&mut config);

        assert!(config.no_dns);
        assert!(config.redact);
        assert_eq!(config.tcp_technique, TcpScanTechnique::Xmas);
        assert_eq!(config.retry.effort, ScanEffort::Thorough);
        assert_eq!(config.retry.max_attempts, NonZeroU8::new(5));
        assert_eq!(config.max_probe_rate, NonZeroU32::new(750));
        assert_eq!(config.send_mode, SendMode::Ethernet);
        assert_eq!(
            config.segment_sweep, before_sweep,
            "a file must not be able to turn a single-host scan into a segment sweep"
        );
    }

    /// A document that sets nothing has to change nothing, which is what makes
    /// provisioning safe.
    #[test]
    fn an_empty_document_changes_no_configuration() {
        let loaded = document("");
        let mut config = ZondConfig::default();
        loaded.document.defaults.apply_to(&mut config);

        let untouched = ZondConfig::default();
        assert_eq!(config.no_dns, untouched.no_dns);
        assert_eq!(config.redact, untouched.redact);
        assert_eq!(config.tcp_technique, untouched.tcp_technique);
        assert_eq!(config.max_probe_rate, untouched.max_probe_rate);
        assert_eq!(config.retry.effort, untouched.retry.effort);
    }

    /// The property that makes creating a settings file safe: the template is
    /// entirely commented out, so a scan run straight afterwards behaves exactly
    /// as it did before.
    #[test]
    fn the_provisioned_template_parses_and_changes_nothing() {
        let loaded = parse(TEMPLATE).expect("the shipped template is valid TOML");

        assert!(
            loaded.warnings.is_empty(),
            "the template names a key this build does not know: {:?}",
            loaded.warnings
        );
        assert_eq!(
            loaded.document.defaults,
            Settings::new(),
            "the template must set nothing"
        );

        let mut config = ZondConfig::default();
        loaded.document.defaults.apply_to(&mut config);
        assert_eq!(config.redact, ZondConfig::default().redact);
        assert_eq!(config.tcp_technique, ZondConfig::default().tcp_technique);
    }

    /// The template and [`KNOWN_KEYS`] name the same settings, both ways.
    ///
    /// One direction is that the template documents everything this build reads,
    /// or a user editing the file it was handed cannot find the key they want.
    /// The other is that it documents nothing this build ignores, or the file
    /// promises a setting that does nothing, which is the failure the warnings
    /// exist to prevent arriving from the one file the engine wrote itself.
    #[test]
    fn the_template_documents_every_key_and_no_others() {
        let known: std::collections::BTreeSet<&str> = KNOWN_KEYS.into_iter().collect();

        let documented: std::collections::BTreeSet<&str> = TEMPLATE
            .lines()
            .filter_map(|line| {
                line.trim_start()
                    .strip_prefix('#')
                    .unwrap_or(line)
                    .split_once('=')
            })
            .map(|(key, _)| key.trim())
            .filter(|key| {
                !key.is_empty() && key.chars().all(|c| c.is_ascii_lowercase() || c == '_')
            })
            .collect();

        assert_eq!(
            known.difference(&documented).collect::<Vec<_>>(),
            Vec::<&&str>::new(),
            "the template does not document a key this build reads"
        );
        assert_eq!(
            documented.difference(&known).collect::<Vec<_>>(),
            Vec::<&&str>::new(),
            "the template documents a key this build ignores"
        );
    }

    #[test]
    fn a_port_specification_is_parsed_when_asked_for_and_not_before() {
        let good = document(
            r#"
            [defaults]
            default_ports = "22,80,u:53"
            "#,
        );
        let ports = good
            .document
            .defaults
            .ports()
            .expect("names ports")
            .unwrap();
        assert!(ports.has_tcp(22));
        assert!(ports.has_udp(53));

        // A malformed specification does not stop the document loading - one
        // wrong key should not cost a user every other setting in the file.
        let bad = document(
            r#"
            [defaults]
            default_ports = "http"
            "#,
        );
        assert!(bad.document.defaults.ports().expect("names ports").is_err());
    }

    #[test]
    fn a_document_that_is_not_toml_is_refused() {
        assert!(matches!(
            parse("this is not = = toml"),
            Err(SettingsError::Malformed(_))
        ));
    }

    /// Provisioning must never cost somebody their configuration, so the second
    /// call has to leave the first call's file exactly as it was - including
    /// whatever the user has since written into it.
    #[test]
    fn provisioning_creates_once_and_never_overwrites() {
        let dir = std::env::temp_dir().join(format!("zond-settings-{}", std::process::id()));
        let path = dir.join(FILE_NAME);
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(provision(&path).expect("creates"), Provisioned::Created);
        assert!(path.exists());

        // Stand in for a user editing the file they were given.
        std::fs::write(&path, "[defaults]\nredact = true\n").expect("writes");

        assert_eq!(
            provision(&path).expect("finds"),
            Provisioned::Existed,
            "a second call must not report having created anything"
        );
        assert_eq!(
            std::fs::read_to_string(&path).expect("reads"),
            "[defaults]\nredact = true\n",
            "provisioning overwrote a file somebody had edited"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The whole startup sequence a front end runs, against a directory of our
    /// own rather than the user's: provision, find it already there the second
    /// time, read it back, and apply it.
    #[test]
    fn provisioning_then_loading_produces_settings_that_change_nothing() {
        let dir = std::env::temp_dir().join(format!("zond-startup-{}", std::process::id()));
        let path = dir.join(FILE_NAME);
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(provision(&path).expect("creates"), Provisioned::Created);
        assert_eq!(provision(&path).expect("finds"), Provisioned::Existed);

        let loaded = load(&path).expect("the file it just wrote is readable");
        assert!(loaded.warnings.is_empty());

        let settings = loaded.document.resolve(None).expect("resolves");
        let mut config = ZondConfig::default();
        settings.apply_to(&mut config);

        let untouched = ZondConfig::default();
        assert_eq!(config.redact, untouched.redact);
        assert_eq!(config.tcp_technique, untouched.tcp_technique);
        assert_eq!(config.retry.effort, untouched.retry.effort);
        assert_eq!(config.max_probe_rate, untouched.max_probe_rate);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// On Unix the file records which networks somebody scans and how, which is
    /// nobody else's business on a shared host.
    #[cfg(unix)]
    #[test]
    fn a_provisioned_file_is_readable_only_by_its_owner() {
        use std::os::unix::fs::PermissionsExt;

        let dir = std::env::temp_dir().join(format!("zond-modes-{}", std::process::id()));
        let path = dir.join(FILE_NAME);
        let _ = std::fs::remove_dir_all(&dir);

        provision(&path).expect("creates");

        let file = std::fs::metadata(&path).expect("stat").permissions().mode();
        let directory = std::fs::metadata(&dir).expect("stat").permissions().mode();

        assert_eq!(file & 0o077, 0, "the file is readable by somebody else");
        assert_eq!(
            directory & 0o077,
            0,
            "the directory is traversable by somebody else"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn edit_distance_is_the_ordinary_one() {
        assert_eq!(edit_distance("quiet", "quiet"), 0);
        assert_eq!(edit_distance("quie", "quiet"), 1);
        assert_eq!(edit_distance("max_probe_rat", "max_probe_rate"), 1);
        assert_eq!(edit_distance("", "abc"), 3);
    }
}