zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
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
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
// 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

//! # Reading nmap's XML as a report
//!
//! The same `-oX` file [`import::nmap`](crate::import::nmap) reads as targets,
//! read instead as what that scan found: hosts with their reachability, ports
//! with their states, services with their versions, and the operating system
//! nmap settled on. What comes back is a [`ScanReport`], so an nmap scan from
//! last quarter and a scan this engine ran tonight are the same input to
//! [`diff`](crate::diff).
//!
//! The parsing is `xml`'s, refusals and bounds included. This module is the
//! mapping.
//!
//! ## Nmap's vocabulary is not this engine's, and the gaps are where the care is
//!
//! Four places where a literal translation would record something the scan did
//! not establish.
//!
//! A host nmap calls `down` is [`Unknown`](HostStatus::Unknown) unless
//! something said otherwise. Nmap uses one word both for an intermediary
//! reporting an address unreachable and for nothing coming back, where
//! [`HostStatus::Down`] refuses to be inferred from silence. So the `reason`
//! attribute decides: `host-unreach` and its relatives give
//! [`Down`](HostStatus::Down), `admin-prohibited` and its relatives give
//! [`Filtered`](HostStatus::Filtered), and everything else, a bare `no-response`
//! included, gives `Unknown`.
//!
//! A host nmap calls `up` for the reason `user-set` is `Unknown`. That is
//! what nmap records when it was told to skip host discovery: no probe was sent
//! and nothing answered, so `up` there is an instruction echoed back rather than
//! a finding. Where such a host has a port that answered, the port proves the
//! stack is alive and the status is promoted on that evidence, which is the
//! inference this engine's own port scanner makes.
//!
//! A service nmap identified by `method="table"` is recorded at confidence
//! zero. That method means nmap looked the port number up in a file, which is
//! what this engine's own
//! [`baseline_service`](crate::fingerprint::baseline_service) does to every
//! classified port. Recording it the same way keeps the two symmetrical, and
//! [`Service::is_inferred`](crate::model::port::Service::is_inferred) tells
//! either apart from an identification. A comparison ignores both, so two tools
//! with different port catalogues do not appear to disagree about every port on
//! the network.
//!
//! The hostname is the first `<hostname>` nmap names the address by, whichever
//! its type, except that a `user` name in a document this engine wrote is not
//! read as one. Nmap types a name the operator gave as a target `user`; this
//! engine's exporter types the DNS names a host gave for itself that way, and
//! those are not the name a lookup resolved.
//!
//! ## What the report says it covered
//!
//! [`TargetScope`] is what lets a comparison tell a host that went away from one
//! nobody looked for, and nmap's XML does not record its resolved target set.
//! What it does record is a `<host>` element per address it accounted for, and
//! whether that accounting is complete is knowable: nmap lists the addresses that
//! did not answer only when asked to, so a document containing any host that is
//! not `up` lists everything it considered.
//!
//! So the scope is the addresses the document accounts for, claimed only when
//! such a host appears. A document of nothing but live hosts states no scope at
//! all, and every question a comparison asks of it answers
//! [`Unstated`](crate::diff::Coverage::Unstated). Under-claiming costs a
//! comparison some confirmations. Over-claiming would have it report hosts as
//! gone on the strength of a scan that never looked.
//!
//! ## What is not read
//!
//! Traceroute hops, `<distance>`, `<times>`, `<uptime>`, the sequence
//! predictions, `<owner>`, the raw service fingerprints, and every `<script>`
//! element on a port or under `<hostscript>`. None of them bears on what
//! [`diff`](crate::diff) compares.
//!
//! Two of those are worth stating separately, because this engine's own nmap
//! exporter writes them. A report exported to nmap XML and read back here has no
//! findings and no path: nmap's format carries a finding as `<script output>`
//! text meant for a person, and a rebuilt `Finding` needs the detection identity,
//! version and content hash that text does not hold. `<distance>` and `<times>`
//! are recoverable and are not read yet. [`json`](super::json) is the round trip
//! that keeps everything.
//!
//! Read against the shape of that list: `<extraports>` and the
//! `<extrareasons ports="…">` beneath it. Nmap names the ports it summarised
//! there whenever it was asked to, and those hundreds of closed ports are the
//! difference between a readable comparison and a wall of endpoints that appear
//! to have opened.

use std::collections::BTreeMap;
use std::io::BufRead;
use std::net::IpAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use crate::config::{OsDetection, ServiceDetection, ZondConfig};
use crate::import::report::{ReportOptions, ReportReader};
use crate::import::xml::{Element, Event, Parser, elements_within};
use crate::import::{ImportError, ImportOrigin};
use crate::model::exclusion::Exclusions;
use crate::model::host::os::OsFingerprint;
use crate::model::host::{Host, HostStatus, IpProtocolState, StatusProtocol, StatusReason};
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::discovery::{Discovery, ScanResponse};
use crate::model::port::{self, Port, PortSet, PortState, Protocol, Service};
use crate::model::technique::TcpScanTechnique;
use crate::report::{
    PhaseParts, PortScope, ScanKind, ScanPhase, ScanReport, ScanSettings, ScopeParts, TargetScope,
};

/// The format's name in errors.
const FORMAT: &str = "nmap XML";

/// The attributes this reader keeps. Everything else is skipped unbuffered.
///
/// Longer than the target reader's four, since a finding is more than an address.
/// Several names appear on more than one element, `version` on both `<nmaprun>`
/// and `<service>` and `name` on three, and which is meant is decided
/// by the element the parser is inside, never by the name alone.
///
/// `args` is deliberately absent: it runs to kilobytes and nothing reads it.
/// `services` and `ports` are kept despite doing the same, since between them
/// they are what nmap knows and its port list does not say: which ports were
/// walked, and which of them it found uninteresting enough to leave out. Both are
/// [lossy](crate::import::xml::Parser::with_lossy), since a sparse sweep of every
/// port could write several hundred kilobytes of either and neither is worth
/// refusing a file over.
const KEPT: &[&[u8]] = &[
    b"addr",
    b"addrtype",
    b"portid",
    b"protocol",
    b"state",
    b"reason",
    b"name",
    b"product",
    b"version",
    b"extrainfo",
    b"tunnel",
    b"conf",
    b"method",
    b"accuracy",
    b"osfamily",
    b"osgen",
    b"vendor",
    b"type",
    b"start",
    b"starttime",
    b"endtime",
    b"elapsed",
    b"numservices",
    b"services",
    b"ports",
    b"proto",
    b"scanner",
];

/// The attributes dropped rather than refused when they run long.
///
/// Both are port lists, and both only ever enrich: without them a comparison
/// falls back to saying it cannot tell whether an endpoint was probed, which is
/// the honest answer rather than a wrong one.
const LOSSY: &[&[u8]] = &[b"services", b"ports"];

/// The longest attribute value kept, in bytes.
///
/// Well past the parser's default, because of `services`. Nmap writes its default
/// port set out as an explicit list of a thousand entries, which runs to
/// several kilobytes. Every other kept value here is free text a service
/// reported about itself and runs to a few dozen bytes. The element's whole
/// markup is still bounded by
/// [`ImportLimits::max_line_bytes`](crate::import::ImportLimits::max_line_bytes),
/// and the document by [`ReportOptions::max_document_bytes`], which is where an
/// unbounded one is actually stopped.
const MAX_VALUE_BYTES: usize = 16 * 1024;

/// nmap's `conf` runs 0 to 10, and this engine's confidence runs 0 to 100.
const CONFIDENCE_SCALE: u8 = 10;

/// Reads an nmap XML document as the report of the scan that produced it.
#[derive(Debug, Clone, Copy, Default)]
pub struct NmapXmlReportReader {
    options: ReportOptions,
}

impl NmapXmlReportReader {
    /// A reader bounded by `options`.
    pub fn new(options: ReportOptions) -> Self {
        Self { options }
    }
}

impl ReportReader for NmapXmlReportReader {
    fn read(&self, input: &mut dyn BufRead) -> Result<ScanReport, ImportError> {
        let max_document_bytes = self.options.max_document_bytes;
        crate::import::bounded::within(input, max_document_bytes, |input| self.read_within(input))
    }
}

impl NmapXmlReportReader {
    /// The parser a document is read with, bounded as this reader's options
    /// say: the element ceiling is the one the document ceiling implies, so a
    /// caller who raises the byte ceiling for a large scan is not refused its
    /// document by a fixed element count.
    fn parser<'a>(&self, input: &'a mut dyn BufRead) -> Parser<'a> {
        Parser::new(input, self.options.limits.max_line_bytes, FORMAT, KEPT)
            .with_max_value_bytes(MAX_VALUE_BYTES)
            .with_lossy(LOSSY)
            .with_max_elements(elements_within(self.options.max_document_bytes))
    }

    /// [`read`](ReportReader::read), over an input already cut off at the
    /// document ceiling.
    fn read_within(&self, input: &mut dyn BufRead) -> Result<ScanReport, ImportError> {
        crate::import::skip_bom(input)?;

        let mut parser = self.parser(input);
        let mut state = State::new(self.options.limits.max_addresses);

        loop {
            match parser.next_event()? {
                Event::Eof => break,

                Event::Start { self_closing } => {
                    let tag = Tag::of(&parser.element.name);
                    state.on_start(tag, self_closing, &mut parser)?;

                    // A self-closing `<host/>` or `<port/>` opens and closes in
                    // one event and never sees an `End`.
                    if self_closing {
                        state.close_element(tag)?;
                    }
                }

                Event::End => {
                    let tag = Tag::of(&parser.element.name);
                    state.on_end(tag, &mut parser)?;
                }
            }
        }

        let run = state.run;
        if !run.saw_root {
            return Err(ImportError::Malformed {
                format: FORMAT,
                origin: ImportOrigin::unknown(),
                message: "no <nmaprun> element: this is not an nmap document".to_string(),
            });
        }

        // The host ceiling is checked as each `<host>` closes instead. A
        // ceiling on what a document may make the process allocate has to refuse
        // before the allocation rather than describe it
        // afterwards.
        Ok(run.into_report())
    }
}

// ---------------------------------------------------------------------------
// The walk
// ---------------------------------------------------------------------------

/// Everything the document has said so far, as the parser walks it.
///
/// The run being assembled, the host and port an element is currently being
/// read into, and the two pieces of context that decide what a nested element
/// belongs to.
#[derive(Debug, Default)]
struct State {
    run: Run,
    host: Option<HostAcc>,
    port: Option<PortAcc>,
    /// The state an `<extraports>` block is reporting, while inside one.
    bulk: Option<String>,
    inside: Inside,
    /// The most hosts the document may name, checked as each one closes.
    max_hosts: u128,
}

impl State {
    /// A walk bounded by how many hosts the document may name.
    fn new(max_hosts: u128) -> Self {
        Self {
            max_hosts,
            ..Self::default()
        }
    }

    /// Takes one opening element and folds what it carries in.
    ///
    /// `self_closing` is here because an element with no content opens nothing.
    /// The arms that record what the parser is inside of, and the one that begins
    /// capturing text, skip that for such an element.
    /// [`close_element`](Self::close_element) decides what it closes.
    fn on_start(
        &mut self,
        tag: Tag,
        self_closing: bool,
        parser: &mut Parser<'_>,
    ) -> Result<(), ImportError> {
        match tag {
            Tag::NmapRun => {
                self.run.saw_root = true;
                self.run.scanner = attr(&parser.element, b"scanner");
                self.run.scanner_version = attr(&parser.element, b"version");
                self.run.started = attr(&parser.element, b"start").and_then(|s| epoch(&s));
            }
            Tag::ScanInfo => self.run.scan_info(&parser.element),
            Tag::Host => {
                self.host = Some(HostAcc {
                    started: attr(&parser.element, b"starttime").and_then(|s| epoch(&s)),
                    ended: attr(&parser.element, b"endtime").and_then(|s| epoch(&s)),
                    ..HostAcc::default()
                });
            }
            Tag::Status => {
                if let Some(host) = self.host.as_mut() {
                    host.state = attr(&parser.element, b"state");
                    host.reason = attr(&parser.element, b"reason");
                }
            }
            Tag::Address => self.record_address(parser)?,
            // The first name for the address is the hostname, except a
            // `user` name in this engine's own document: that is a DNS name
            // the host gave for itself, which this format cannot carry back as
            // one, and taking it for the resolved name would have a document
            // read back disagree with the report it was written from.
            Tag::HostName => {
                let stated = self.run.scanner.as_deref() == Some(crate::format::NMAP_SCANNER)
                    && attr(&parser.element, b"type").as_deref() == Some("user");
                if let Some(host) = self.host.as_mut()
                    && host.hostname.is_none()
                    && !stated
                {
                    host.hostname = attr(&parser.element, b"name");
                }
            }
            Tag::Port => self.port = Some(PortAcc::open(&parser.element, parser)?),
            // The ports nmap did not think worth listing one by one. It still
            // probed them and still knows what it found, and both are here.
            Tag::ExtraPorts => self.bulk = attr(&parser.element, b"state"),
            Tag::ExtraReasons => {
                if let (Some(host), Some(state)) = (self.host.as_mut(), self.bulk.as_deref()) {
                    let state = PortAcc::state_named(state, parser)?;
                    host.extend(state, &parser.element);
                }
            }
            Tag::State => self.settle_port(parser)?,
            Tag::Service => {
                if let Some(port) = self.port.as_mut() {
                    port.identify(&parser.element);
                    self.run.probed_services |= port.service.is_some();
                }
                if !self_closing {
                    self.inside = Inside::Service;
                }
            }
            Tag::OsMatch => {
                if let Some(host) = self.host.as_mut() {
                    host.match_os(&parser.element);
                    self.run.identified_os |= host.os.is_some();
                }
                if !self_closing {
                    self.inside = Inside::Os;
                }
            }
            Tag::OsClass => {
                if let Some(host) = self.host.as_mut() {
                    host.classify_os(&parser.element);
                }
                if !self_closing {
                    self.inside = Inside::Os;
                }
            }
            Tag::Cpe => {
                if !self_closing && self.inside != Inside::Nothing {
                    parser.begin_text();
                }
            }
            Tag::Finished => {
                self.run.elapsed = attr(&parser.element, b"elapsed")
                    .and_then(|s| s.parse::<f64>().ok())
                    .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok());
            }
            Tag::Other => {}
        }

        Ok(())
    }

    /// Takes one closing element.
    fn on_end(&mut self, tag: Tag, parser: &mut Parser<'_>) -> Result<(), ImportError> {
        match tag {
            Tag::ExtraPorts => self.bulk = None,
            Tag::Host | Tag::Port => self.close_element(tag)?,
            Tag::Cpe => self.record_cpe(parser.take_text()?),
            Tag::Service | Tag::OsMatch => self.inside = Inside::Nothing,
            _ => {}
        }

        Ok(())
    }

    /// Folds a finished element into what holds it: a `<host>` into the run, a
    /// `<port>` into the host it was found on.
    ///
    /// A port found outside a host is dropped, since there is nothing to record
    /// it against.
    fn close_element(&mut self, tag: Tag) -> Result<(), ImportError> {
        match tag {
            Tag::Host => {
                self.run.close(self.host.take());
                // Checked as the host closes rather than over the finished
                // list. The document decides how many of these there are, and a
                // ceiling reporting the overrun afterwards has already paid
                // for it.
                if self.run.hosts.len() as u128 > self.max_hosts {
                    return Err(ImportError::TooManyHosts {
                        limit: self.max_hosts,
                    });
                }
            }
            Tag::Port => {
                if let (Some(host), Some(port)) = (self.host.as_mut(), self.port.take()) {
                    match port.ip_protocol {
                        true => host.ip_protocols.push(port.into_ip_protocol()),
                        false => port::fold(&mut host.ports, port.into_port()),
                    }
                }
            }
            _ => {}
        }

        Ok(())
    }

    /// Records what an `<address>` names on the host being read.
    ///
    /// One outside a `<host>` is skipped without being read at all, so an
    /// address nmap could not have written refuses the document only where
    /// there is a host it would have belonged to.
    fn record_address(&mut self, parser: &Parser<'_>) -> Result<(), ImportError> {
        if self.host.is_none() {
            return Ok(());
        }

        let address = HostAcc::read_address(&parser.element, parser)?;
        if let (Some(host), Some(address)) = (self.host.as_mut(), address) {
            host.record(address);
        }

        Ok(())
    }

    /// Settles the port being read on the verdict its `<state>` names.
    ///
    /// One outside a `<port>` is skipped without being read, for the reason
    /// [`record_address`](Self::record_address) gives.
    fn settle_port(&mut self, parser: &Parser<'_>) -> Result<(), ImportError> {
        if self.port.is_none() {
            return Ok(());
        }

        let settled = PortAcc::read_state(&parser.element, parser)?;
        if let (Some(port), Some((state, reason))) = (self.port.as_mut(), settled) {
            port.state = state;
            port.reason = reason;
        }

        Ok(())
    }

    /// Files a `<cpe>` under the identification it qualifies.
    ///
    /// An empty one, and one that appeared outside a `<service>` or an
    /// `<osmatch>`, qualifies nothing and is dropped.
    fn record_cpe(&mut self, cpe: String) {
        if cpe.is_empty() {
            return;
        }

        match self.inside {
            Inside::Service => {
                if let Some(service) = self.port.as_mut().and_then(|port| port.service.as_mut()) {
                    service.add_cpe(cpe);
                }
            }
            Inside::Os => {
                if let Some(os) = self.host.as_mut().and_then(|host| host.os.as_mut()) {
                    os.add_cpe(cpe);
                }
            }
            Inside::Nothing => {}
        }
    }
}

/// Which element the parser is inside, for the ones whose text belongs to
/// something further out.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Inside {
    #[default]
    Nothing,
    Service,
    Os,
}

/// The elements this reader acts on. Everything else is `Other` and is skipped
/// without its content being examined.
///
/// Resolved from the name once per element, so nothing borrows the parser across
/// the work of handling one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tag {
    NmapRun,
    ScanInfo,
    Host,
    Status,
    Address,
    HostName,
    Port,
    ExtraPorts,
    ExtraReasons,
    State,
    Service,
    Cpe,
    OsMatch,
    OsClass,
    Finished,
    Other,
}

impl Tag {
    fn of(name: &[u8]) -> Self {
        match name {
            b"nmaprun" => Tag::NmapRun,
            b"scaninfo" => Tag::ScanInfo,
            b"host" => Tag::Host,
            b"status" => Tag::Status,
            b"address" => Tag::Address,
            b"hostname" => Tag::HostName,
            b"port" => Tag::Port,
            b"extraports" => Tag::ExtraPorts,
            b"extrareasons" => Tag::ExtraReasons,
            b"state" => Tag::State,
            b"service" => Tag::Service,
            b"cpe" => Tag::Cpe,
            b"osmatch" => Tag::OsMatch,
            b"osclass" => Tag::OsClass,
            b"finished" => Tag::Finished,
            _ => Tag::Other,
        }
    }
}

/// One attribute as an owned string, which ends the parser borrow before
/// anything is done with the value.
fn attr(element: &Element, name: &[u8]) -> Option<String> {
    element.value(name).map(str::to_owned)
}

/// The port set a `<scaninfo>` names, in this engine's specification grammar.
///
/// Nmap writes a bare list of numbers and ranges and says which transport it
/// means in a sibling attribute; this grammar carries the transport in the
/// specification itself, so a UDP list is rewritten with the prefix each entry
/// needs.
fn services(spec: &str, protocol: Protocol) -> Option<PortSet> {
    let prefix = protocol.spec_prefix();
    let spec = spec
        .split(',')
        .map(|entry| format!("{prefix}{}", entry.trim()))
        .collect::<Vec<_>>()
        .join(",");

    PortSet::try_from(spec.as_str()).ok()
}

/// Seconds since the epoch, as nmap writes every time in its document.
///
/// `None` for a count no clock can name. A `u64` of seconds reaches five
/// hundred billion years and a [`SystemTime`] does not, so the addition is
/// checked: `+` panics on the difference, and a panic belongs to the process
/// that embedded this engine rather than to the file it was handed.
/// `start="16847805878974283974"` is such a count.
fn epoch(seconds: &str) -> Option<SystemTime> {
    let seconds = seconds.parse::<u64>().ok()?;
    SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(seconds))
}

// ---------------------------------------------------------------------------
// The run
// ---------------------------------------------------------------------------

/// Everything the document says about the scan as a whole.
#[derive(Debug, Default)]
struct Run {
    saw_root: bool,
    scanner: Option<String>,
    scanner_version: Option<String>,
    started: Option<SystemTime>,
    elapsed: Option<Duration>,
    technique: Option<TcpScanTechnique>,
    probes: Option<u128>,
    /// The port set every `<scaninfo>` between them named.
    ports: Option<PortSet>,
    protocols: Vec<Protocol>,
    probed_services: bool,
    identified_os: bool,
    hosts: Vec<Host>,
    /// Every address the document accounted for with a `<host>` element.
    accounted: IpSet,
    /// Whether the accounting is complete; see the module documentation.
    exhaustive: bool,
}

impl Run {
    /// Takes a `<scaninfo>`, which is where nmap says which probe it sent and
    /// which ports it sent it to.
    fn scan_info(&mut self, element: &Element) {
        // `ip` names no transport, since a protocol scan walks protocol
        // numbers rather than ports. Ignored rather than refused, as anything
        // else unreadable is: an unreadable `<scaninfo>` is not a reason to
        // refuse the findings under it.
        let protocol = element
            .value(b"protocol")
            .and_then(crate::record::wire::protocol);
        if let Some(protocol) = protocol {
            // Nmap writes one `<scaninfo>` per scan type, so `-sS -sA` names TCP
            // twice. The scope is a set of transports and the document says it is
            // ascending, so the second mention adds nothing.
            if !self.protocols.contains(&protocol) {
                self.protocols.push(protocol);
            }

            // The resolved port set, which nmap applies to every host it scans.
            if let Some(ports) = element
                .value(b"services")
                .and_then(|spec| services(spec, protocol))
            {
                self.ports = Some(match self.ports.take() {
                    Some(existing) => existing.union(&ports),
                    None => ports,
                });
            }
        }

        // Saturating, because nothing bounds how many `<scaninfo>` elements a
        // document may carry and each one names its own count. Two naming
        // `u128::MAX` would panic a debug build and wrap a release one into a
        // probe count of nearly zero, which is the worse of the two: a wrapped
        // total reads as a plausible number. A saturated one is visibly the
        // ceiling.
        if let Some(count) = element
            .value(b"numservices")
            .and_then(|n| n.parse::<u128>().ok())
        {
            let probes = self.probes.get_or_insert(0);
            *probes = probes.saturating_add(count);
        }

        // The scan type says both which segment went out and whether it took a
        // raw socket to send it.
        match element.value(b"type") {
            Some("syn") => self.raw(Some(TcpScanTechnique::Syn)),
            Some("ack") => self.raw(Some(TcpScanTechnique::Ack)),
            Some("fin") => self.raw(Some(TcpScanTechnique::Fin)),
            Some("null") => self.raw(Some(TcpScanTechnique::Null)),
            Some("xmas") => self.raw(Some(TcpScanTechnique::Xmas)),
            Some("maimon") => self.raw(Some(TcpScanTechnique::Maimon)),
            Some("window") => self.raw(Some(TcpScanTechnique::Window)),
            Some("udp" | "ipproto" | "sctpinit" | "sctpcookieecho") => self.raw(None),
            // A connect scan is the one nmap performs without privileges, and
            // this engine records the same fallback the same way.
            _ => {}
        }
    }

    /// Records that a raw probe was sent, and which one where this engine has a
    /// word for it.
    ///
    /// The technique and nothing else. That nmap sent raw probes says nmap was
    /// privileged, which is a fact about nmap's run: see the phase's own
    /// `privileged`, which stays `None` for exactly that reason.
    fn raw(&mut self, technique: Option<TcpScanTechnique>) {
        if let Some(technique) = technique {
            self.technique.get_or_insert(technique);
        }
    }

    /// Folds a finished `<host>` in.
    fn close(&mut self, host: Option<HostAcc>) {
        let Some(accumulated) = host else {
            return;
        };

        for ip in &accumulated.addresses {
            self.accounted.insert(*ip);
        }

        // An address nmap listed as anything but up is one it was asked to
        // account for whether or not it answered, which is what makes the
        // listing a statement of scope.
        if accumulated
            .state
            .as_deref()
            .is_some_and(|state| state != "up")
        {
            self.exhaustive = true;
        }

        if let Some(host) = accumulated.into_host(self.started) {
            self.hosts.push(host);
        }
    }

    /// The report the scan would have produced.
    fn into_report(mut self) -> ScanReport {
        let kind = if self.hosts.iter().any(|host| host.port_count() > 0) {
            ScanKind::PortScan
        } else {
            ScanKind::Discovery
        };

        // Nmap gives every host it scans the same port set, so what
        // `<scaninfo>` names is true of every address the scan covered.
        let ports = match self.ports.take() {
            Some(ports) if !ports.is_empty() => PortScope::Every(ports),
            _ => PortScope::NoPorts,
        };

        let targets = if self.exhaustive {
            let mut scope = TargetScope::from_ip_set(&mut self.accounted, &Exclusions::none());
            scope = TargetScope::from_parts(ScopeParts {
                // Nmap sends probes; it has no notion of a phase that only listens.
                listened: Vec::new(),
                ranges: scope.ranges().to_vec(),
                // Nmap's document names no interface, so it cannot say it swept
                // a link whole even where it did.
                links: Vec::new(),
                addresses: scope.addresses(),
                probes: self.probes,
                ports,
                protocols: self.protocols.clone(),
                excluded: Vec::new(),
                withheld: 0,
            });
            scope
        } else {
            TargetScope::from_parts(ScopeParts {
                // Nmap sends probes; it has no notion of a phase that only listens.
                listened: Vec::new(),
                ranges: Vec::new(),
                links: Vec::new(),
                addresses: 0,
                probes: self.probes,
                ports,
                protocols: self.protocols.clone(),
                excluded: Vec::new(),
                withheld: 0,
            })
        };

        let phase = ScanPhase::from_parts(PhaseParts {
            // Nmap's format has no place for one, and a scan it ran was not run
            // from here.
            attachments: Vec::new(),
            kind,
            started_at: self.started.unwrap_or(SystemTime::UNIX_EPOCH),
            elapsed: self.elapsed.unwrap_or_default(),
            // Not this engine's question to answer. A scan another program ran
            // says nothing about whether these strategies held the sockets they
            // need, and answering `false` claimed a sweep nmap performed over
            // ARP as root had none, putting this engine's advice about running
            // as root under findings that contradicted it.
            privilege: None,
            targets,
            settings: self.settings(),
            failures: Vec::new(),
            // Nothing in nmap's output distinguishes ground it declined from
            // ground it covered, so nothing is invented here.
            refusals: Vec::new(),
            unroutable: Vec::new(),
            refused_by_route: Vec::new(),
            timed_out: Vec::new(),
            icmp_rate_limited: Vec::new(),
            reached_by_connect: Vec::new(),
            // The scope holds only addresses the document gave a verdict on, up
            // or down, so none of it is left undecided.
            undecided: Vec::new(),
            // An nmap document does not say whether host discovery ran, only
            // what it concluded, so no reason is claimed.
            liveness_skipped: None,
            silent: Vec::new(),
            stopped: None,
            passes_cut: Vec::new(),
            unreached: 0,
            unheard_probes: 0,
            probes: Vec::new(),
            origin: None,
            // Nmap writes its document once the scan is done.
            open: false,
        });

        ScanReport::recorded(self.attribution(), vec![phase], self.hosts)
    }

    /// The settings, as far as the document states them.
    ///
    /// Nmap records which probe it sent and whether it looked for services and an
    /// operating system. It does not record a retransmission budget, a rate
    /// ceiling or a redaction policy, and those keep this engine's defaults, so
    /// read this for what nmap stated rather than as how nmap was tuned.
    fn settings(&self) -> ScanSettings {
        let mut settings = ScanSettings::from(&ZondConfig::default());
        if let Some(technique) = self.technique {
            settings.tcp_technique = technique;
        }
        settings.service_detection = if self.probed_services {
            ServiceDetection::default()
        } else {
            ServiceDetection::Off
        };
        settings.os_detection = if self.identified_os {
            OsDetection::default()
        } else {
            OsDetection::Off
        };
        settings.traceroute = false;
        settings
    }

    /// What produced the document, as it named itself.
    fn attribution(&self) -> String {
        let scanner = self.scanner.as_deref().unwrap_or("nmap");
        match self.scanner_version.as_deref() {
            Some(version) => format!("{scanner} {version}"),
            None => scanner.to_string(),
        }
    }
}

// ---------------------------------------------------------------------------
// One host
// ---------------------------------------------------------------------------

/// An `<address>`, once it has been recognised.
enum Address {
    Ip(IpAddr),
    Hardware(MacAddr),
}

/// One `<host>`, gathered until its element closes.
#[derive(Debug, Default)]
struct HostAcc {
    addresses: Vec<IpAddr>,
    macs: Vec<MacAddr>,
    hostname: Option<String>,
    state: Option<String>,
    reason: Option<String>,
    /// Keyed as the host keys them, and folded as they are read, so a
    /// document naming one endpoint many times, in `<port>` elements or in
    /// an `<extrareasons>` list, builds it once rather than growing a list
    /// the host would have collapsed anyway.
    ports: BTreeMap<(u16, Protocol), Port>,
    ip_protocols: Vec<(u8, IpProtocolState)>,
    os: Option<OsFingerprint>,
    started: Option<SystemTime>,
    ended: Option<SystemTime>,
}

impl HostAcc {
    /// Reads an `<address>`, which is an IP address or a hardware one.
    fn read_address(
        element: &Element,
        parser: &Parser<'_>,
    ) -> Result<Option<Address>, ImportError> {
        let Some(addr) = element.value(b"addr") else {
            return Ok(None);
        };

        Ok(match element.value(b"addrtype") {
            Some("ipv4" | "ipv6") => {
                let ip = addr.parse::<IpAddr>().map_err(|_| {
                    parser.malformed(format!(
                        "'{addr}' is not an address nmap could have written"
                    ))
                })?;
                Some(Address::Ip(ip))
            }
            // A hardware address that will not parse is not a reason to refuse
            // the host: the addresses and ports under it are the finding, and
            // this is decoration on top of them.
            Some("mac") => MacAddr::from_str(addr).ok().map(Address::Hardware),
            _ => None,
        })
    }

    fn record(&mut self, address: Address) {
        match address {
            Address::Ip(ip) => self.addresses.push(ip),
            Address::Hardware(mac) => self.macs.push(mac),
        }
    }

    /// Takes an `<extrareasons>`, which names every port nmap left out of its
    /// list along with what it found there.
    ///
    /// This is the difference between a readable comparison and a wall. Nmap
    /// lists the interesting ports and summarises the rest, where this engine's
    /// own scans record every port they probed. Without this the hundreds nmap
    /// summarised read as ports that appeared the moment the two were compared,
    /// when both scans found them closed.
    ///
    /// A `ports` attribute that ran past the parser's bound is absent, and then
    /// nothing is recorded, which reads as not probed rather than as a wrong
    /// verdict. See [`LOSSY`].
    fn extend(&mut self, state: PortState, element: &Element) {
        let Some(list) = element.value(b"ports") else {
            return;
        };
        // TCP where the attribute is absent, as it is from the nmap releases
        // that predate it, and anything this engine has no word for is left
        // alone rather than recorded as TCP.
        let protocol = match element.value(b"proto") {
            Some(name) => match crate::record::wire::protocol(name) {
                Some(protocol) => protocol,
                None => return,
            },
            None => Protocol::Tcp,
        };

        let Some(ports) = services(list, protocol) else {
            return;
        };
        let reason = element.value(b"reason").map(str::to_owned);

        for (number, protocol) in ports.iter() {
            let mut port = Port::new(number, protocol, state);
            if let Some(reason) = &reason {
                port = port.with_discovery(Discovery::new(scan_response(reason)));
            }
            port::fold(&mut self.ports, port);
        }
    }

    /// Takes an `<osmatch>`, keeping only the first.
    ///
    /// Nmap lists every candidate it considered, best first. Keeping the rest
    /// would make a comparison report a change every time the also-rans
    /// reshuffled beneath an unchanged winner.
    fn match_os(&mut self, element: &Element) {
        if self.os.is_some() {
            return;
        }
        let Some(name) = element.value(b"name") else {
            return;
        };
        let accuracy = element
            .value(b"accuracy")
            .and_then(|a| a.parse::<u8>().ok())
            .unwrap_or(0);

        self.os = Some(OsFingerprint::new(name, accuracy));
    }

    /// Takes an `<osclass>`, which carries the family, generation, vendor and
    /// device type the match above it does not. Only the first class of the first match contributes,
    /// for the reason [`match_os`](Self::match_os) gives.
    fn classify_os(&mut self, element: &Element) {
        let Some(os) = self.os.take() else {
            return;
        };
        if os.family().is_some() {
            self.os = Some(os);
            return;
        }

        // An empty value is one the writer had to give and did not know, which
        // is what this engine's own exporter writes for a vendor it did not
        // establish: absent, not named "".
        let value = |name: &[u8]| element.value(name).filter(|value| !value.is_empty());
        let mut os = os;
        if let Some(family) = value(b"osfamily") {
            os = os.with_family(family);
        }
        if let Some(generation) = value(b"osgen") {
            os = os.with_generation(generation);
        }
        if let Some(vendor) = value(b"vendor") {
            os = os.with_vendor(vendor);
        }
        if let Some(device) = value(b"type") {
            os = os.with_device(device);
        }
        self.os = Some(os);
    }

    /// The host this record describes, or `None` if it named no address.
    fn into_host(self, run_started: Option<SystemTime>) -> Option<Host> {
        let (primary, rest) = self.addresses.split_first()?;

        let mut host = Host::new(*primary);
        host.extend_ips(rest.iter().copied());

        if let Some(hostname) = self.hostname {
            host.set_hostname(Some(hostname));
        }

        for mac in self.macs {
            host.record_mac(mac);
        }

        let status = status_of(self.state.as_deref(), self.reason.as_deref());
        match self.reason.as_deref() {
            Some(reason) if status != HostStatus::Unknown => {
                host.record_evidence(status, StatusReason::new(status_protocol(reason), reason));
            }
            _ => host.set_status(status),
        }

        let answered = self
            .ports
            .values()
            .any(|port| matches!(port.state(), PortState::Open | PortState::Closed));
        for port in self.ports.into_values() {
            host.add_port(port);
        }
        for (number, state) in self.ip_protocols {
            host.record_ip_protocol(number, state);
        }

        // A port that accepted a connection or refused one was answered by the
        // host's own stack, whatever the discovery phase concluded. This is the
        // inference that recovers a host nmap was told not to probe.
        if answered {
            host.record_evidence(
                HostStatus::Up,
                StatusReason::new(StatusProtocol::Tcp, "a probed port answered for the host"),
            );
        }

        if let Some(os) = self.os {
            host.set_os(os);
        }

        // Last, because every mutator above stamps the current time and this is
        // the record of when the scan saw the host.
        let first = self.started.or(run_started);
        let last = self.ended.or(first);
        if let (Some(first), Some(last)) = (first, last) {
            host.restore_seen(first, last);
        }

        Some(host)
    }
}

/// What a `<status>` establishes, in this engine's four states.
fn status_of(state: Option<&str>, reason: Option<&str>) -> HostStatus {
    match state {
        // `user-set` is what nmap records when it was told to skip discovery.
        // Nothing was sent and nothing answered, so the word is an instruction
        // echoed back rather than a finding.
        Some("up") if reason == Some("user-set") => HostStatus::Unknown,
        // This engine's own word for a host it found filtered, which nmap's
        // vocabulary has no state for and which its exporter writes `up`.
        Some("up") if reason == Some("probes-filtered") => HostStatus::Filtered,
        Some("up") => HostStatus::Up,
        Some("down") => match reason {
            Some(reason) if reason.ends_with("-prohibited") => HostStatus::Filtered,
            Some(reason) if reason.ends_with("-unreach") => HostStatus::Down,
            // Including `no-response`, which is silence, and silence is not
            // evidence of absence.
            _ => HostStatus::Unknown,
        },
        Some("filtered") => HostStatus::Filtered,
        _ => HostStatus::Unknown,
    }
}

/// Which protocol carried the evidence nmap named.
fn status_protocol(reason: &str) -> StatusProtocol {
    match reason {
        "arp-response" => StatusProtocol::Arp,
        "nd-response" => StatusProtocol::Ndp,
        "echo-reply" | "netmask-reply" | "addressmask-reply" => StatusProtocol::IcmpEcho,
        "timestamp-reply" => StatusProtocol::IcmpTimestamp,
        "syn-ack" => StatusProtocol::TcpSyn,
        "reset" | "tcp-response" => StatusProtocol::Tcp,
        "conn-refused" => StatusProtocol::TcpConnect,
        "udp-response" => StatusProtocol::Udp,
        "init-ack" | "abort" | "sctp-response" => StatusProtocol::Sctp,
        "dhcp-response" => StatusProtocol::Dhcp,
        reason if reason.ends_with("-unreach") || reason.ends_with("-prohibited") => {
            StatusProtocol::IcmpUnreachable
        }
        other => StatusProtocol::Custom(Arc::from(other)),
    }
}

// ---------------------------------------------------------------------------
// One port
// ---------------------------------------------------------------------------

/// One `<port>`, gathered until its element closes.
#[derive(Debug)]
struct PortAcc {
    number: u16,
    protocol: Protocol,
    state: PortState,
    reason: Option<String>,
    service: Option<Service>,
    /// Whether this element was `protocol="ip"`, which is a protocol verdict
    /// wearing a port's shape rather than a port. [`protocol`](Self::protocol)
    /// is then meaningless and is not read.
    ip_protocol: bool,
}

impl PortAcc {
    /// Takes a `<port>`, which names the endpoint and nothing about it.
    fn open(element: &Element, parser: &Parser<'_>) -> Result<Self, ImportError> {
        let number = element
            .value(b"portid")
            .and_then(|id| id.parse::<u16>().ok())
            .ok_or_else(|| parser.malformed("a port with no readable number".to_string()))?;

        // An unrecognised transport is refused rather than guessed at, for the
        // reason the target reader gives: it is not a field a reader can skip,
        // it is the value that decides what the record says.
        let protocol = match element.value(b"protocol") {
            // Not a transport at all. Nmap reports a protocol scan by reusing
            // this element with `protocol="ip"`, where `portid` is an IP
            // protocol number rather than a port; this engine keeps the two
            // apart and reads it into the host's protocol verdicts instead. See
            // `export::nmap::write_ip_protocols`, which writes the same shape.
            Some("ip") => {
                let number = u8::try_from(number).map_err(|_| {
                    parser.malformed(format!(
                        "'{number}' is not an IP protocol number, which is a byte"
                    ))
                })?;
                return Ok(Self {
                    number: u16::from(number),
                    protocol: Protocol::Tcp,
                    state: PortState::Filtered,
                    reason: None,
                    service: None,
                    ip_protocol: true,
                });
            }
            Some(name) => crate::record::wire::protocol(name).ok_or_else(|| {
                parser.malformed(format!(
                    "port {number} names transport '{name}', which this engine cannot scan"
                ))
            })?,
            None => return Err(parser.malformed(format!("port {number} names no transport"))),
        };

        Ok(Self {
            number,
            protocol,
            state: PortState::Filtered,
            reason: None,
            service: None,
            ip_protocol: false,
        })
    }

    /// Reads the `<state>` inside a port, which is the verdict.
    fn read_state(
        element: &Element,
        parser: &Parser<'_>,
    ) -> Result<Option<(PortState, Option<String>)>, ImportError> {
        let Some(state) = element.value(b"state") else {
            return Ok(None);
        };

        Ok(Some((
            Self::state_named(state, parser)?,
            attr(element, b"reason"),
        )))
    }

    /// One of nmap's six verdicts, in this engine's terms.
    ///
    /// An unrecognised one is refused rather than guessed at, for the reason the
    /// target reader gives: it is the value that decides what the record says.
    fn state_named(state: &str, parser: &Parser<'_>) -> Result<PortState, ImportError> {
        Ok(match state {
            "open" => PortState::Open,
            "closed" => PortState::Closed,
            "filtered" => PortState::Filtered,
            "unfiltered" => PortState::Unfiltered,
            "open|filtered" => PortState::OpenFiltered,
            "closed|filtered" => PortState::ClosedFiltered,
            other => {
                return Err(parser.malformed(format!(
                    "a port is in state '{other}', which this engine has no verdict for"
                )));
            }
        })
    }

    /// Takes the `<service>` inside a port, unless nmap only looked the number
    /// up.
    fn identify(&mut self, element: &Element) {
        let Some(name) = element.value(b"name") else {
            return;
        };

        // `table` means nmap read the port number out of a file rather than
        // asking the service. Confidence zero is how this engine records the
        // same thing about its own port-number labels, and what a comparison
        // reads to know it is not a finding.
        let confidence = if element.value(b"method") == Some("probed") {
            element
                .value(b"conf")
                .and_then(|c| c.parse::<u8>().ok())
                .unwrap_or(0)
                .saturating_mul(CONFIDENCE_SCALE)
        } else {
            0
        };

        // Nmap names a protocol read through TLS by the protocol, with the
        // tunnel in an attribute of its own. This engine's label carries both,
        // `ssl/http`, and it is the label that decides whether a later probe of
        // the port speaks through a handshake, so the two are joined here.
        let mut service = match element.value(b"tunnel") {
            Some("ssl") => Service::new(format!("ssl/{name}"), confidence),
            _ => Service::new(name, confidence),
        };
        if let Some(product) = element.value(b"product") {
            service = service.with_product(product);
        }
        if let Some(version) = element.value(b"version") {
            service = service.with_version(version);
        }
        if let Some(extra) = element.value(b"extrainfo") {
            service = service.with_extrainfo(extra);
        }

        self.service = Some(service);
    }

    /// The port this record describes.
    fn into_port(self) -> Port {
        let mut port = Port::new(self.number, self.protocol, self.state);

        if let Some(service) = self.service {
            port.set_service(service);
        }

        if let Some(reason) = self.reason {
            port = port.with_discovery(Discovery::new(scan_response(&reason)));
        }

        port
    }

    /// The protocol verdict this record describes, for an element that was
    /// `protocol="ip"`.
    ///
    /// The state comes back through the port vocabulary it was written in, since
    /// nmap has one set of words for both questions. `unfiltered` and
    /// `closed|filtered` cannot be reached by a protocol scan and are read as the
    /// nearest thing a protocol verdict can say rather than refused, because a
    /// document is a foreign tool's and refusing a whole host over one word
    /// nmap's own scan would not have written is the wrong trade.
    fn into_ip_protocol(self) -> (u8, IpProtocolState) {
        let state = match self.state {
            PortState::Open => IpProtocolState::Open,
            PortState::Closed => IpProtocolState::Closed,
            PortState::Filtered => IpProtocolState::Filtered,
            PortState::OpenFiltered => IpProtocolState::OpenFiltered,
            // Neither is a conclusion a protocol scan draws. `unfiltered` says a
            // probe arrived and nothing more, and `closed|filtered` says the two
            // could not be told apart; both amount to the same silence here.
            PortState::Unfiltered | PortState::ClosedFiltered => IpProtocolState::OpenFiltered,
            PortState::Unasked => IpProtocolState::Unasked,
        };

        // Held to a byte on the way in, which is what `open` checked.
        (self.number as u8, state)
    }
}

/// The packet nmap says settled a port's state.
fn scan_response(reason: &str) -> ScanResponse {
    match reason {
        "syn-ack" => ScanResponse::TcpSynAck,
        "reset" => ScanResponse::TcpRst,
        "conn-refused" => ScanResponse::ConnectionRefused,
        "no-response" => ScanResponse::NoResponse,
        "udp-response" | "proto-response" => ScanResponse::UdpResponse,
        "init-ack" => ScanResponse::SctpInitAck,
        "abort" => ScanResponse::SctpAbort,
        reason if reason.ends_with("-prohibited") => ScanResponse::IcmpProhibited,
        reason if reason.ends_with("-unreach") => ScanResponse::IcmpUnreachable,
        other => ScanResponse::Custom(other.to_string()),
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝
#[cfg(test)]
mod tests {
    use std::io::Cursor;
    use std::net::Ipv4Addr;

    use super::*;
    use crate::diff::{Coverage, Presence, ScanDiff};

    fn read(document: &str) -> Result<ScanReport, ImportError> {
        let reader = NmapXmlReportReader::default();
        reader.read(&mut Cursor::new(document))
    }

    fn ip(last: u8) -> IpAddr {
        IpAddr::V4(Ipv4Addr::new(192, 0, 2, last))
    }

    /// The element ceiling follows the document ceiling, at its default and at
    /// one a caller set.
    ///
    /// Only a document past the parser's fixed count, some 134 MB of the
    /// smallest element, could show the difference by reading it, which is too
    /// much for a test to stream; so the parser the reader builds is asked
    /// directly. Without the wiring, a caller who raised the byte ceiling to
    /// read a full-range scan of a few hundred hosts would be refused it.
    #[test]
    fn the_element_ceiling_is_the_one_the_document_ceiling_implies() {
        for reader in [
            NmapXmlReportReader::default(),
            NmapXmlReportReader::new(ReportOptions::default().with_max_document_bytes(1 << 36)),
        ] {
            let mut input = Cursor::new(Vec::new());
            let parser = reader.parser(&mut input);
            let implied = elements_within(reader.options.max_document_bytes);
            assert_ne!(
                implied,
                crate::import::xml::MAX_ELEMENTS,
                "a ceiling that shows it"
            );
            assert_eq!(parser.max_elements(), implied);
        }
    }

    /// A timestamp no clock can name is a field to drop, not a process to end.
    ///
    /// `SystemTime + Duration` panics on overflow and a `u64` of seconds reaches
    /// far past what a `SystemTime` holds, so unchecked, a document carrying
    /// twenty digits in `start` would take down whatever had embedded the
    /// engine.
    #[test]
    fn a_time_past_what_a_clock_can_hold_is_dropped_rather_than_fatal() {
        for seconds in ["16847805878974283974", "18446744073709551615"] {
            let document = format!(
                r#"<nmaprun scanner="nmap" start="{seconds}" version="7.94">
<host starttime="{seconds}" endtime="{seconds}">
<status state="up" reason="arp-response" reason_ttl="0"/>
<address addr="192.0.2.10" addrtype="ipv4"/>
</host>
</nmaprun>"#
            );

            let report = read(&document).expect("a time it cannot hold is not a broken document");
            assert_eq!(report.host_count(), 1, "the host survived the bad stamp");
        }

        // And a time it can hold is still read, so the guard is not refusing
        // every document that carries one.
        assert!(read(SWEEP).is_ok());
    }

    /// What nmap writes for `-sS -sV -O --reason` over two addresses, one of
    /// which did not answer.
    const SWEEP: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<nmaprun scanner="nmap" args="nmap -sS -sV" start="1690000000" version="7.94">
<scaninfo type="syn" protocol="tcp" numservices="1000" services="1-1024"/>
<host starttime="1690000001" endtime="1690000009">
<status state="up" reason="arp-response" reason_ttl="0"/>
<address addr="192.0.2.10" addrtype="ipv4"/>
<address addr="2C:CF:67:00:00:01" addrtype="mac" vendor="Raspberry Pi"/>
<hostnames><hostname name="pi.local" type="PTR"/></hostnames>
<ports>
<extraports state="closed" count="998"><extrareasons reason="resets" count="998"/></extraports>
<port protocol="tcp" portid="22">
<state state="open" reason="syn-ack" reason_ttl="64"/>
<service name="ssh" product="OpenSSH" version="8.9p1" extrainfo="Ubuntu" method="probed" conf="10">
<cpe>cpe:/a:openbsd:openssh:8.9p1</cpe>
</service>
</port>
<port protocol="tcp" portid="80">
<state state="closed" reason="reset" reason_ttl="64"/>
<service name="http" method="table" conf="3"/>
</port>
</ports>
<os><osmatch name="Linux 5.0 - 5.14" accuracy="97">
<osclass type="general purpose" vendor="Linux" osfamily="Linux" osgen="5.X" accuracy="97">
<cpe>cpe:/o:linux:linux_kernel:5</cpe>
</osclass></osmatch></os>
</host>
<host starttime="1690000001" endtime="1690000009">
<status state="down" reason="no-response" reason_ttl="0"/>
<address addr="192.0.2.11" addrtype="ipv4"/>
</host>
<runstats><finished time="1690000010" elapsed="9.42"/></runstats>
</nmaprun>"#;

    #[test]
    fn a_scan_reads_back_as_its_hosts_ports_and_services() {
        let report = read(SWEEP).expect("a readable document");

        assert_eq!(report.engine_version(), "nmap 7.94");
        assert_eq!(report.host_count(), 2);

        let host = report.host(&ip(10)).expect("the host that answered");
        assert_eq!(host.status(), HostStatus::Up);
        assert_eq!(host.hostname(), Some("pi.local"));
        assert_eq!(
            host.mac(),
            Some(MacAddr::new(0x2c, 0xcf, 0x67, 0x00, 0x00, 0x01))
        );

        let ssh = host.ports().find(|port| port.number() == 22).expect("22");
        assert_eq!(ssh.state(), PortState::Open);
        let service = ssh.service().expect("a probed service");
        assert_eq!(service.name(), "ssh");
        assert_eq!(service.product(), Some("OpenSSH"));
        assert_eq!(service.version(), Some("8.9p1"));
        assert_eq!(service.extrainfo(), Some("Ubuntu"));
        assert!(
            service
                .cpes()
                .iter()
                .any(|cpe| &**cpe == "cpe:/a:openbsd:openssh:8.9p1"),
            "the CPE is element text, not an attribute: {:?}",
            service.cpes()
        );

        let os = host.os().expect("an operating system");
        assert_eq!(os.name(), "Linux 5.0 - 5.14");
        assert_eq!(os.family(), Some("Linux"));
        assert_eq!(os.generation(), Some("5.X"));
        assert_eq!(os.device(), Some("general purpose"));
        assert_eq!(os.accuracy(), 97);
        assert!(
            os.cpes()
                .iter()
                .any(|cpe| &**cpe == "cpe:/o:linux:linux_kernel:5")
        );
    }

    /// A service nmap found inside TLS reads as this engine labels one, with
    /// the tunnel in its name.
    ///
    /// Nmap writes HTTPS as `name="http" tunnel="ssl"`. Read by the name alone
    /// it is plain HTTP, which a comparison against this engine's own scan
    /// reports as a changed service and a detection speaks to in the clear.
    #[test]
    fn a_service_nmap_found_inside_tls_keeps_its_tunnel() {
        let document = r#"<nmaprun scanner="nmap" version="7.94">
<host><status state="up" reason="syn-ack" reason_ttl="0"/>
<address addr="192.0.2.10" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="443">
<state state="open" reason="syn-ack" reason_ttl="64"/>
<service name="http" product="nginx" tunnel="ssl" method="probed" conf="10"/>
</port></ports></host></nmaprun>"#;

        let report = read(document).expect("a readable document");
        let host = report.host(&ip(10)).expect("the host");
        let https = host.ports().next().expect("443");
        assert_eq!(https.service_name(), Some("ssl/http"));
    }

    /// A port-number lookup is recorded, and recorded as the guess it is.
    ///
    /// This engine seeds the same label on every classified port of its own, so
    /// dropping nmap's would make the two asymmetrical and a comparison would
    /// report a service on every well-known port the moment an nmap scan entered
    /// one.
    #[test]
    fn a_service_nmap_looked_up_in_a_table_is_marked_as_inferred() {
        let report = read(SWEEP).expect("a readable document");
        let host = report.host(&ip(10)).expect("the host");
        let http = host.ports().find(|port| port.number() == 80).expect("80");

        assert_eq!(http.state(), PortState::Closed);
        let service = http.service().expect("the label is kept");
        assert_eq!(service.name(), "http");
        assert!(
            service.is_inferred(),
            "nothing asked the port what it was running"
        );

        // And a probed one is not.
        let ssh = host.ports().find(|port| port.number() == 22).expect("22");
        assert!(!ssh.service().expect("a probed service").is_inferred());
    }

    /// The property the one above exists to protect.
    #[test]
    fn a_port_number_label_never_reaches_a_comparison() {
        let report = read(SWEEP).expect("a readable document");

        // The same scan with nmap's table label changed to another one, which is
        // what a different port catalogue amounts to.
        let renamed = SWEEP.replace(
            r#"<service name="http" method="table" conf="3"/>"#,
            r#"<service name="www" method="table" conf="3"/>"#,
        );
        let other = read(&renamed).expect("a readable document");

        assert!(
            ScanDiff::between(&report, &other).is_empty(),
            "two port catalogues disagreeing is not a change to the network"
        );
    }

    // -----------------------------------------------------------------------
    // Nmap's `down` is not this engine's
    // -----------------------------------------------------------------------

    #[test]
    fn a_host_that_merely_did_not_answer_is_unknown_not_down() {
        let report = read(SWEEP).expect("a readable document");
        let quiet = report.host(&ip(11)).expect("the host that did not answer");

        assert_eq!(
            quiet.status(),
            HostStatus::Unknown,
            "silence is not evidence that an address is unreachable"
        );
    }

    #[test]
    fn a_host_an_intermediary_reported_unreachable_is_down() {
        let document = SWEEP.replace(
            r#"<status state="down" reason="no-response" reason_ttl="0"/>"#,
            r#"<status state="down" reason="host-unreach" reason_ttl="61"/>"#,
        );

        let report = read(&document).expect("a readable document");
        assert_eq!(
            report.host(&ip(11)).expect("the host").status(),
            HostStatus::Down
        );
    }

    #[test]
    fn a_host_a_policy_rejected_is_filtered() {
        let document = SWEEP.replace(
            r#"<status state="down" reason="no-response" reason_ttl="0"/>"#,
            r#"<status state="down" reason="admin-prohibited" reason_ttl="61"/>"#,
        );

        let report = read(&document).expect("a readable document");
        assert_eq!(
            report.host(&ip(11)).expect("the host").status(),
            HostStatus::Filtered
        );
    }

    #[test]
    fn a_host_up_only_because_discovery_was_skipped_is_unknown() {
        // What `-Pn --reason` writes: nmap was told the host is up and repeats
        // it back, having sent nothing.
        let document = r#"<nmaprun scanner="nmap" start="1690000000" version="7.94">
<host><status state="up" reason="user-set"/>
<address addr="192.0.2.11" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="80">
<state state="filtered" reason="no-response"/>
</port></ports></host></nmaprun>"#;

        let report = read(document).expect("a readable document");
        assert_eq!(
            report.host(&ip(11)).expect("the host").status(),
            HostStatus::Unknown,
            "an instruction echoed back is not evidence the host answered"
        );
    }

    #[test]
    fn a_port_that_answered_proves_the_host_is_up_whatever_discovery_said() {
        let document = r#"<nmaprun scanner="nmap" start="1690000000" version="7.94">
<host><status state="up" reason="user-set"/>
<address addr="192.0.2.11" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="443">
<state state="open" reason="syn-ack"/>
</port></ports></host></nmaprun>"#;

        let report = read(document).expect("a readable document");
        assert_eq!(
            report.host(&ip(11)).expect("the host").status(),
            HostStatus::Up,
            "a SYN+ACK requires a live stack, whether or not discovery ran"
        );
    }

    // -----------------------------------------------------------------------
    // What the document says it covered
    // -----------------------------------------------------------------------

    #[test]
    fn a_document_listing_an_address_that_did_not_answer_states_its_scope() {
        let report = read(SWEEP).expect("a readable document");
        let scope = report.phases()[0].targets();

        assert_eq!(
            scope.addresses(),
            2,
            "both addresses were accounted for, so both were walked"
        );
        assert!(scope.ranges().iter().any(|range| range.contains(&ip(10))));
        assert!(scope.ranges().iter().any(|range| range.contains(&ip(11))));
    }

    #[test]
    fn a_document_of_nothing_but_live_hosts_claims_no_scope() {
        let document = r#"<nmaprun scanner="nmap" start="1690000000" version="7.94">
<host><status state="up" reason="echo-reply"/>
<address addr="192.0.2.10" addrtype="ipv4"/></host></nmaprun>"#;

        let report = read(document).expect("a readable document");
        assert!(
            report.phases()[0].targets().ranges().is_empty(),
            "nmap lists the addresses that did not answer only when asked to, so \
             a document without one cannot say what it walked"
        );

        // And a comparison against it therefore confirms nothing.
        let baseline = ScanReport::recorded("test", Vec::new(), vec![Host::new(ip(99))]);
        let diff = ScanDiff::between(&baseline, &report);
        let gone = diff
            .hosts()
            .iter()
            .find(|delta| delta.address() == ip(99))
            .expect("the host only the baseline has");
        assert_eq!(
            gone.presence(),
            Presence::Removed {
                after: Coverage::Unstated
            }
        );
    }

    // -----------------------------------------------------------------------
    // Refusals
    // -----------------------------------------------------------------------

    #[test]
    fn a_port_state_this_engine_has_no_verdict_for_is_refused() {
        let document = r#"<nmaprun><host><address addr="192.0.2.10" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="80"><state state="perhaps"/></port></ports>
</host></nmaprun>"#;

        let error = read(document).expect_err("refused");
        assert!(error.to_string().contains("perhaps"), "{error}");
    }

    #[test]
    fn a_document_that_is_not_nmaps_is_refused() {
        let error = read("<other><host/></other>").expect_err("refused");
        assert!(error.to_string().contains("nmaprun"), "{error}");
    }

    #[test]
    fn an_entity_declaration_is_refused_here_too() {
        let document = r#"<?xml version="1.0"?>
<!DOCTYPE nmaprun [<!ENTITY x "boom">]>
<nmaprun><host><address addr="192.0.2.10" addrtype="ipv4"/></host></nmaprun>"#;

        let error = read(document).expect_err("refused");
        assert!(error.to_string().contains("DOCTYPE"), "{error}");
    }

    /// A connect scan's refusal keeps its own name rather than becoming a
    /// reset.
    ///
    /// nmap records `conn-refused` for the error a connect is handed, which
    /// is a reset or an ICMP port unreachable, and the engine's own connect
    /// scan records the same thing under the same meaning. Read as a reset,
    /// an imported connect scan would claim a packet nobody saw, and a
    /// comparison with the engine's own would differ where the two agree.
    #[test]
    fn a_refused_connect_is_read_as_a_refusal_rather_than_a_reset() {
        assert_eq!(
            scan_response("conn-refused"),
            ScanResponse::ConnectionRefused
        );
        assert_eq!(scan_response("reset"), ScanResponse::TcpRst);
    }

    // -----------------------------------------------------------------------
    // The whole point: comparing an nmap scan with something else
    // -----------------------------------------------------------------------

    #[test]
    fn two_nmap_scans_compare_as_a_network_that_changed() {
        let later = SWEEP
            .replace(r#"version="8.9p1""#, r#"version="9.6p1""#)
            .replace(
                r#"<state state="closed" reason="reset" reason_ttl="64"/>"#,
                r#"<state state="open" reason="syn-ack" reason_ttl="64"/>"#,
            );

        let before = read(SWEEP).expect("a readable document");
        let after = read(&later).expect("a readable document");

        let diff = ScanDiff::between(&before, &after);
        let summary = diff.summary();

        assert_eq!(
            summary.ports_opened.total, 1,
            "port 80 went from closed to open"
        );
        assert_eq!(
            summary.ports_opened.confirmed, 1,
            "both scans hold a record for it"
        );
        assert_eq!(summary.services_changed, 1, "OpenSSH moved a version");
        assert_eq!(summary.hosts_added.total, 0);
        assert_eq!(summary.hosts_removed.total, 0);
    }

    #[test]
    fn an_unchanged_nmap_document_compares_as_unchanged() {
        let before = read(SWEEP).expect("a readable document");
        let after = read(SWEEP).expect("a readable document");

        assert!(
            ScanDiff::between(&before, &after).is_empty(),
            "reading the same file twice must not manufacture a change"
        );
    }
}