nmap-mcp 0.1.0

Nmap network scanner and NSE scripting engine control for AI assistants via MCP
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
//! Parser for nmap XML output (`nmap -oX -`), turning the document into a
//! structured `serde_json::Value`.
//!
//! The parser is intentionally a streaming, event-driven reader over the
//! documented nmap XML schema (xmloutputversion 1.05). Every parse function is
//! pure: input XML string in, `serde_json::Value` out, no I/O. That makes the
//! whole module unit-testable with realistic fixtures, without ever running
//! nmap itself.
//!
//! Document shape produced by [`parse_nmap_xml`]:
//!
//! ```json
//! {
//!   "scanner": "nmap",
//!   "version": "7.95",
//!   "args": "nmap -oX - 127.0.0.1",
//!   "start": "1786216804",
//!   "hosts": [
//!     {
//!       "status": {"state": "up", "reason": "conn-refused"},
//!       "addresses": [{"addr": "127.0.0.1", "addrtype": "ipv4"}],
//!       "hostnames": [{"name": "localhost", "type": "PTR"}],
//!       "ports": [
//!         {
//!           "protocol": "tcp",
//!           "portid": 22,
//!           "state": "open",
//!           "service": {"name": "ssh", "method": "table", "conf": "3"},
//!           "scripts": [{"id": "ssh-hostkey", "output": "...", "data": {...}}]
//!         }
//!       ],
//!       "os_matches": [{"name": "...", "accuracy": "100", "classes": [...]}],
//!       "uptime": {"seconds": "123", "lastboot": "..."},
//!       "traceroute": [{"ttl": "1", "ipaddr": "...", "rtt": "..."}],
//!       "extraports": {"state": "closed", "count": "5"}
//!     }
//!   ],
//!   "runstats": {"finished": {...}, "hosts": {"up": "1", "down": "0", "total": "1"}}
//! }
//! ```
//!
//! NSE script output (the `<script>` element) follows the format documented
//! in the Nmap Scripting Engine API: `<elem>` and `<table>` children carry an
//! optional `key` attribute. Keyed entries become object fields, unkeyed
//! entries become array items, matching how a Lua `stdnse.output_table()`
//! serializes to XML.

use quick_xml::events::{BytesStart, Event};
use quick_xml::Reader;
use serde_json::{Map, Value};

/// Parse a full nmap XML document into a JSON value.
pub fn parse_nmap_xml(input: &str) -> Result<Value, String> {
    let mut reader = Reader::from_str(input);
    reader.config_mut().trim_text(true);
    let mut buf = Vec::new();

    let mut doc = Map::new();
    let mut hosts: Vec<Value> = Vec::new();
    let mut host: Option<HostAcc> = None;
    let mut port: Option<PortAcc> = None;
    let mut osmatch: Option<OsMatchAcc> = None;
    let mut osclass: Option<Map<String, Value>> = None;
    let mut runstats = Map::new();
    let mut text: Option<String> = None;

    loop {
        match reader.read_event_into(&mut buf) {
            Err(e) => return Err(format!("nmap XML parse error: {e}")),
            Ok(Event::Eof) => break,

            Ok(Event::Start(e)) => {
                let name = e.name().as_ref().to_vec();
                match name.as_slice() {
                    b"nmaprun" => {
                        attrs_into(&e, &mut doc)?;
                    }
                    b"host" => host = Some(HostAcc::default()),
                    b"port" => port = Some(PortAcc::from_attrs(&e)?),
                    b"service" => {
                        if let Some(p) = port.as_mut() {
                            p.service_attrs = Some(ServiceAcc::from_attrs(&e)?);
                        }
                    }
                    b"osmatch" => osmatch = Some(OsMatchAcc::from_attrs(&e)?),
                    b"osclass" => osclass = Some(attrs_map(&e)?),
                    b"script" => {
                        if let Some(p) = port.as_mut() {
                            let attrs = owned_attrs(&e)?;
                            p.scripts.push(parse_script(&mut reader, &mut buf, attrs)?);
                        }
                    }
                    // Containers and elements whose attributes we keep are
                    // handled as Start/End pairs or Empty events below.
                    _ => {}
                }
            }

            Ok(Event::Empty(e)) => {
                let name = e.name().as_ref().to_vec();
                let m = attrs_map(&e)?;
                match name.as_slice() {
                    b"status" => {
                        if let Some(h) = host.as_mut() {
                            h.status = Some(m);
                        }
                    }
                    b"address" => {
                        if let Some(h) = host.as_mut() {
                            h.addresses.push(m);
                        }
                    }
                    b"hostname" => {
                        if let Some(h) = host.as_mut() {
                            h.hostnames.push(m);
                        }
                    }
                    b"state" => {
                        if let Some(p) = port.as_mut() {
                            p.state = Some(m);
                        }
                    }
                    b"uptime" => {
                        if let Some(h) = host.as_mut() {
                            h.uptime = Some(m);
                        }
                    }
                    b"hop" => {
                        if let Some(h) = host.as_mut() {
                            h.traceroute.push(m);
                        }
                    }
                    b"extraports" => {
                        if let Some(h) = host.as_mut() {
                            h.extraports = Some(m);
                        }
                    }
                    b"service" => {
                        // Self-closing service elements arrive as Empty.
                        if let Some(p) = port.as_mut() {
                            p.service_attrs = Some(ServiceAcc::from_attrs(&e)?);
                        }
                    }
                    b"finished" => {
                        runstats.insert("finished".to_string(), Value::Object(m));
                    }
                    b"hosts" => {
                        runstats.insert("hosts".to_string(), Value::Object(m));
                    }
                    b"script" => {
                        // Self-closing script element: keep id/output only.
                        if let Some(p) = port.as_mut() {
                            p.scripts.push(Value::Object(m));
                        }
                    }
                    _ => {}
                }
            }

            Ok(Event::Text(t)) => {
                text = Some(t.xml_content().map_err(|e| e.to_string())?.into_owned());
            }

            Ok(Event::End(e)) => {
                let name = e.name().as_ref().to_vec();
                match name.as_slice() {
                    b"host" => {
                        if let Some(h) = host.take() {
                            hosts.push(h.finish());
                        }
                    }
                    b"port" => {
                        if let Some(p) = port.take() {
                            if let Some(h) = host.as_mut() {
                                h.ports.push(p.finish());
                            }
                        }
                    }
                    b"osmatch" => {
                        if let Some(o) = osmatch.take() {
                            if let Some(h) = host.as_mut() {
                                h.os_matches.push(o.finish());
                            }
                        }
                    }
                    b"osclass" => {
                        if let Some(cls) = osclass.take() {
                            if let Some(o) = osmatch.as_mut() {
                                o.classes.push(Value::Object(cls));
                            }
                        }
                    }
                    b"cpe" => {
                        let t = text.take().unwrap_or_default();
                        if let Some(p) = port.as_mut() {
                            if let Some(s) = p.service_attrs.as_mut() {
                                s.cpes.push(t.clone());
                            }
                        }
                        if let Some(o) = osclass.as_mut() {
                            o.entry("cpe").or_insert_with(|| Value::Array(Vec::new()));
                            if let Some(Value::Array(arr)) = o.get_mut("cpe") {
                                arr.push(Value::String(t));
                            }
                        }
                    }
                    _ => {}
                }
            }

            Ok(_) => {}
        }
    }

    doc.insert("hosts".to_string(), Value::Array(hosts));
    if !runstats.is_empty() {
        doc.insert("runstats".to_string(), Value::Object(runstats));
    }
    Ok(Value::Object(doc))
}

/// Parse the children of a `<script>` element: `<elem>` and `<table>` entries
/// per the NSE structured-output XML format. Consumes events until the
/// matching `</script>` (or `</table>` for nested tables). `attrs` is the
/// owned attribute list of the opening tag.
fn parse_script(
    reader: &mut Reader<&[u8]>,
    buf: &mut Vec<u8>,
    attrs: Vec<(Vec<u8>, String)>,
) -> Result<Value, String> {
    let mut map = Map::new();
    let mut id = None;
    let mut output = None;
    for (key, val) in attrs {
        match key.as_slice() {
            b"id" => id = Some(val),
            b"output" => output = Some(val),
            _ => {}
        }
    }
    if let Some(id) = id {
        map.insert("id".to_string(), Value::String(id));
    }
    if let Some(output) = output {
        map.insert("output".to_string(), Value::String(output));
    }

    let bucket = parse_script_children(reader, buf)?;
    let data = bucket.finish();
    if !data.is_null() {
        map.insert("data".to_string(), data);
    }
    Ok(Value::Object(map))
}

/// Recursive reader for `<table>` / `<elem>` content inside a script.
/// Returns a [`ScriptBucket`]; the caller converts it to JSON.
fn parse_script_children(
    reader: &mut Reader<&[u8]>,
    buf: &mut Vec<u8>,
) -> Result<ScriptBucket, String> {
    let mut bucket = ScriptBucket::default();
    loop {
        match reader.read_event_into(buf) {
            Ok(Event::Start(e)) => {
                let name = e.name().as_ref().to_vec();
                let key = key_attr(&e)?;
                match name.as_slice() {
                    b"elem" => {
                        let value = read_text_until(reader, buf, b"elem")?;
                        bucket.insert(key, Value::String(value));
                    }
                    b"table" => {
                        let child = parse_script_children(reader, buf)?;
                        bucket.insert(key, child.finish());
                    }
                    _ => {
                        skip_until(reader, buf, &name)?;
                    }
                }
            }
            Ok(Event::Empty(e)) => {
                let name = e.name().as_ref().to_vec();
                if name.as_slice() == b"elem" {
                    let key = key_attr(&e)?;
                    bucket.insert(key, Value::String(String::new()));
                }
            }
            Ok(Event::End(e)) => {
                let name = e.name().as_ref().to_vec();
                if name.as_slice() == b"table" || name.as_slice() == b"script" {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(e) => return Err(format!("nmap XML parse error: {e}")),
        }
    }
    Ok(bucket)
}

/// Accumulator for one `<table>`/`<script>` element's children: keyed entries
/// become object fields, unkeyed entries become array items.
#[derive(Default)]
struct ScriptBucket {
    map: Map<String, Value>,
    list: Vec<Value>,
}

impl ScriptBucket {
    fn insert(&mut self, key: Option<String>, value: Value) {
        match key {
            Some(k) => {
                self.map.insert(k, value);
            }
            None => self.list.push(value),
        }
    }

    fn finish(self) -> Value {
        match (self.map.is_empty(), self.list.is_empty()) {
            (true, true) => Value::Null,
            (false, true) => Value::Object(self.map),
            (true, false) => Value::Array(self.list),
            (false, false) => {
                let mut m = self.map;
                m.insert("_list".to_string(), Value::Array(self.list));
                Value::Object(m)
            }
        }
    }
}

/// Read text events until the matching end tag `name`; returns the text.
fn read_text_until(
    reader: &mut Reader<&[u8]>,
    buf: &mut Vec<u8>,
    name: &[u8],
) -> Result<String, String> {
    let mut out = String::new();
    loop {
        match reader.read_event_into(buf) {
            Ok(Event::Text(t)) => {
                out.push_str(&t.xml_content().map_err(|e| e.to_string())?);
            }
            Ok(Event::CData(t)) => {
                out.push_str(&t.xml_content().map_err(|e| e.to_string())?);
            }
            Ok(Event::End(e)) if e.name().as_ref() == name => break,
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(e) => return Err(format!("nmap XML parse error: {e}")),
        }
    }
    Ok(out)
}

/// Consume events until the matching end tag `name` (for elements we do not
/// care about inside a script, e.g. unknown future extensions).
fn skip_until(reader: &mut Reader<&[u8]>, buf: &mut Vec<u8>, name: &[u8]) -> Result<(), String> {
    loop {
        match reader.read_event_into(buf) {
            Ok(Event::End(e)) if e.name().as_ref() == name => return Ok(()),
            Ok(Event::Eof) => return Ok(()),
            Ok(_) => {}
            Err(e) => return Err(format!("nmap XML parse error: {e}")),
        }
    }
}

/// Read the `key` attribute of an elem/table element, if present.
fn key_attr(e: &BytesStart<'_>) -> Result<Option<String>, String> {
    for attr in e.attributes() {
        let attr = attr.map_err(|err| format!("bad attribute: {err}"))?;
        if attr.key.as_ref() == b"key" {
            return Ok(Some(
                attr.unescape_value()
                    .map_err(|err| err.to_string())?
                    .into_owned(),
            ));
        }
    }
    Ok(None)
}

/// Copy all attributes of an element into owned `(key, value)` pairs so the
/// event borrow can be dropped before recursive parsing continues.
fn owned_attrs(e: &BytesStart<'_>) -> Result<Vec<(Vec<u8>, String)>, String> {
    let mut out = Vec::new();
    for attr in e.attributes() {
        let attr = attr.map_err(|err| format!("bad attribute: {err}"))?;
        let key = attr.key.as_ref().to_vec();
        let val = attr.unescape_value().map_err(|err| err.to_string())?;
        out.push((key, val.into_owned()));
    }
    Ok(out)
}

fn attrs_map(e: &BytesStart<'_>) -> Result<Map<String, Value>, String> {
    let mut m = Map::new();
    attrs_into(e, &mut m)?;
    Ok(m)
}

fn attrs_into(e: &BytesStart<'_>, m: &mut Map<String, Value>) -> Result<(), String> {
    for attr in e.attributes() {
        let attr = attr.map_err(|err| format!("bad attribute: {err}"))?;
        let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
        let val = attr.unescape_value().map_err(|err| err.to_string())?;
        m.insert(key, Value::String(val.into_owned()));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Accumulators
// ---------------------------------------------------------------------------

#[derive(Default)]
struct HostAcc {
    status: Option<Map<String, Value>>,
    addresses: Vec<Map<String, Value>>,
    hostnames: Vec<Map<String, Value>>,
    ports: Vec<Value>,
    os_matches: Vec<Value>,
    uptime: Option<Map<String, Value>>,
    traceroute: Vec<Map<String, Value>>,
    extraports: Option<Map<String, Value>>,
}

impl HostAcc {
    fn finish(self) -> Value {
        let mut m = Map::new();
        if let Some(s) = self.status {
            m.insert("status".to_string(), Value::Object(s));
        }
        if !self.addresses.is_empty() {
            m.insert(
                "addresses".to_string(),
                Value::Array(self.addresses.into_iter().map(Value::Object).collect()),
            );
        }
        if !self.hostnames.is_empty() {
            m.insert(
                "hostnames".to_string(),
                Value::Array(self.hostnames.into_iter().map(Value::Object).collect()),
            );
        }
        if !self.ports.is_empty() {
            m.insert("ports".to_string(), Value::Array(self.ports));
        }
        if !self.os_matches.is_empty() {
            m.insert("os_matches".to_string(), Value::Array(self.os_matches));
        }
        if let Some(u) = self.uptime {
            m.insert("uptime".to_string(), Value::Object(u));
        }
        if !self.traceroute.is_empty() {
            m.insert(
                "traceroute".to_string(),
                Value::Array(self.traceroute.into_iter().map(Value::Object).collect()),
            );
        }
        if let Some(e) = self.extraports {
            m.insert("extraports".to_string(), Value::Object(e));
        }
        Value::Object(m)
    }
}

struct PortAcc {
    protocol: Option<String>,
    portid: Option<String>,
    state: Option<Map<String, Value>>,
    service_attrs: Option<ServiceAcc>,
    scripts: Vec<Value>,
}

impl PortAcc {
    fn from_attrs(e: &BytesStart<'_>) -> Result<Self, String> {
        let m = attrs_map(e)?;
        Ok(Self {
            protocol: m
                .get("protocol")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            portid: m.get("portid").and_then(|v| v.as_str()).map(str::to_string),
            state: None,
            service_attrs: None,
            scripts: Vec::new(),
        })
    }

    fn finish(mut self) -> Value {
        let mut m = Map::new();
        if let Some(p) = self.protocol {
            m.insert("protocol".to_string(), Value::String(p));
        }
        if let Some(pid) = self.portid {
            // Keep the numeric string from nmap; clients can parse as needed.
            m.insert("portid".to_string(), Value::String(pid));
        }
        if let Some(s) = self.state {
            m.insert("state".to_string(), Value::Object(s));
        }
        if let Some(s) = self.service_attrs.take() {
            m.insert("service".to_string(), s.finish());
        }
        if !self.scripts.is_empty() {
            m.insert("scripts".to_string(), Value::Array(self.scripts));
        }
        Value::Object(m)
    }
}

struct ServiceAcc {
    attrs: Map<String, Value>,
    cpes: Vec<String>,
}

impl ServiceAcc {
    fn from_attrs(e: &BytesStart<'_>) -> Result<Self, String> {
        Ok(Self {
            attrs: attrs_map(e)?,
            cpes: Vec::new(),
        })
    }

    fn finish(mut self) -> Value {
        if !self.cpes.is_empty() {
            self.attrs.insert(
                "cpe".to_string(),
                Value::Array(self.cpes.into_iter().map(Value::String).collect()),
            );
        }
        Value::Object(self.attrs)
    }
}

struct OsMatchAcc {
    name: Option<String>,
    accuracy: Option<String>,
    classes: Vec<Value>,
}

impl OsMatchAcc {
    fn from_attrs(e: &BytesStart<'_>) -> Result<Self, String> {
        let m = attrs_map(e)?;
        Ok(Self {
            name: m.get("name").and_then(|v| v.as_str()).map(str::to_string),
            accuracy: m
                .get("accuracy")
                .and_then(|v| v.as_str())
                .map(str::to_string),
            classes: Vec::new(),
        })
    }

    fn finish(self) -> Value {
        let mut m = Map::new();
        if let Some(n) = self.name {
            m.insert("name".to_string(), Value::String(n));
        }
        if let Some(a) = self.accuracy {
            m.insert("accuracy".to_string(), Value::String(a));
        }
        if !self.classes.is_empty() {
            m.insert("classes".to_string(), Value::Array(self.classes));
        }
        Value::Object(m)
    }
}

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

    const PORT_SCAN_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.95 scan initiated Sat Aug  8 21:20:04 2026 as: nmap -sT -p 22 -oX - 127.0.0.1 -->
<nmaprun scanner="nmap" args="nmap -sT -p 22 -oX - 127.0.0.1" start="1786216804" startstr="Sat Aug  8 21:20:04 2026" version="7.95" xmloutputversion="1.05">
<scaninfo type="connect" protocol="tcp" numservices="1" services="22"/>
<verbose level="0"/>
<debugging level="0"/>
<hosthint><status state="up" reason="unknown-response" reason_ttl="0"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<hostnames>
</hostnames>
</hosthint>
<host starttime="1786216804" endtime="1786216804"><status state="up" reason="conn-refused" reason_ttl="0"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<hostnames>
<hostname name="localhost" type="PTR"/>
</hostnames>
<ports><port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
</ports>
<times srtt="40" rttvar="2128" to="100000"/>
</host>
<runstats><finished time="1786216804" timestr="Sat Aug  8 21:20:04 2026" summary="Nmap done at Sat Aug  8 21:20:04 2026; 1 IP address (1 host up) scanned in 0.01 seconds" elapsed="0.01" exit="success"/><hosts up="1" down="0" total="1"/>
</runstats>
</nmaprun>"#;

    #[test]
    fn parses_host_and_port_scan() {
        let v = parse_nmap_xml(PORT_SCAN_XML).expect("parses");
        assert_eq!(v["version"], "7.95");
        assert_eq!(v["scanner"], "nmap");
        let hosts = v["hosts"].as_array().expect("hosts array");
        assert_eq!(hosts.len(), 1);
        let h = &hosts[0];
        assert_eq!(h["status"]["state"], "up");
        assert_eq!(h["addresses"][0]["addr"], "127.0.0.1");
        assert_eq!(h["hostnames"][0]["name"], "localhost");
        let port = &h["ports"][0];
        assert_eq!(port["protocol"], "tcp");
        assert_eq!(port["portid"], "22");
        assert_eq!(port["state"]["state"], "open");
        assert_eq!(port["service"]["name"], "ssh");
        assert_eq!(port["service"]["method"], "table");
        let rs = &v["runstats"];
        assert_eq!(rs["hosts"]["up"], "1");
        assert_eq!(rs["hosts"]["total"], "1");
        assert_eq!(rs["finished"]["exit"], "success");
    }

    const NO_HOST_UP_XML: &str = r#"<nmaprun scanner="nmap" args="nmap -sn -oX - 10.0.0.99" start="1" version="7.95" xmloutputversion="1.05">
<scaninfo type="syn" protocol="tcp" numservices="0" services=""/>
<verbose level="0"/>
<debugging level="0"/>
<hosthint><status state="up" reason="unknown-response" reason_ttl="0"/>
<address addr="10.0.0.99" addrtype="ipv4"/>
<hostnames>
</hostnames>
</hosthint>
<runstats><finished time="1" timestr="" summary="Nmap done at ...; 1 IP address (0 hosts up) scanned in 0.01 seconds" elapsed="0.01" exit="success"/><hosts up="0" down="1" total="1"/>
</runstats>
</nmaprun>"#;

    #[test]
    fn parses_zero_hosts_up() {
        let v = parse_nmap_xml(NO_HOST_UP_XML).expect("parses");
        assert_eq!(v["hosts"].as_array().unwrap().len(), 0);
        assert_eq!(v["runstats"]["hosts"]["up"], "0");
        assert_eq!(v["runstats"]["hosts"]["down"], "1");
    }

    const SCRIPT_SCAN_XML: &str = r#"<nmaprun scanner="nmap" args="nmap -sT --script ssh-hostkey -p 22 -oX - 127.0.0.1" start="1" version="7.95" xmloutputversion="1.05">
<host><status state="up" reason="conn-refused"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="22"><state state="open" reason="syn-ack"/>
<service name="ssh" product="OpenSSH" version="9.2p1" method="probed" conf="10"><cpe>cpe:/a:openbsd:openssh:9.2p1</cpe></service>
<script id="ssh-hostkey" output="&#xa;  ssh-ed25519 SHA256:AAAA&#xa;  ssh-rsa SHA256:BBBB">
  <table key="algorithm">
    <elem key="type">ssh-ed25519</elem>
    <elem key="bits">256</elem>
  </table>
  <table key="fingerprints">
    <elem>SHA256:AAAA</elem>
    <elem>SHA256:BBBB</elem>
  </table>
</script>
<script id="ssh2-enum-algos"/>
</port>
</ports>
</host>
</nmaprun>"#;

    #[test]
    fn parses_service_version_cpe_and_script_structured_output() {
        let v = parse_nmap_xml(SCRIPT_SCAN_XML).expect("parses");
        let port = &v["hosts"][0]["ports"][0];
        let svc = &port["service"];
        assert_eq!(svc["name"], "ssh");
        assert_eq!(svc["product"], "OpenSSH");
        assert_eq!(svc["version"], "9.2p1");
        assert_eq!(svc["method"], "probed");
        assert_eq!(svc["cpe"][0], "cpe:/a:openbsd:openssh:9.2p1");

        let scripts = port["scripts"].as_array().expect("scripts");
        assert_eq!(scripts.len(), 2);

        // Structured script: keyed tables become objects.
        let hostkey = &scripts[0];
        assert_eq!(hostkey["id"], "ssh-hostkey");
        assert!(hostkey["output"].as_str().unwrap().contains("SHA256:AAAA"));
        assert_eq!(hostkey["data"]["algorithm"]["type"], "ssh-ed25519");
        assert_eq!(hostkey["data"]["algorithm"]["bits"], "256");
        // Unkeyed elems become array items.
        assert_eq!(hostkey["data"]["fingerprints"][0], "SHA256:AAAA");
        assert_eq!(hostkey["data"]["fingerprints"][1], "SHA256:BBBB");

        // Self-closing script keeps id/output only.
        let empty = &scripts[1];
        assert_eq!(empty["id"], "ssh2-enum-algos");
        assert!(empty.get("data").is_none());
    }

    const OS_SCAN_XML: &str = r#"<nmaprun scanner="nmap" args="nmap -O -oX - 192.168.1.1" start="1" version="7.95" xmloutputversion="1.05">
<host><status state="up" reason="arp-response"/>
<address addr="192.168.1.1" addrtype="ipv4"/>
<address addr="AA:BB:CC:DD:EE:FF" addrtype="mac" vendor="Router Co"/>
<os>
<osmatch name="Linux 2.6.32 - 3.2" accuracy="100" line="123">
<osclass type="general purpose" vendor="Linux" osfamily="Linux" osgen="2.6.X" accuracy="100"><cpe>cpe:/o:linux:linux_kernel:2.6</cpe></osclass>
</osmatch>
</os>
<uptime seconds="12345" lastboot="Sat Aug  1 12:00:00 2026"/>
<traceroute>
<hop ttl="1" ipaddr="192.168.1.254" rtt="0.50"/>
<hop ttl="2" ipaddr="10.0.0.1" rtt="1.20"/>
</traceroute>
</host>
</nmaprun>"#;

    #[test]
    fn parses_os_detection_uptime_and_traceroute() {
        let v = parse_nmap_xml(OS_SCAN_XML).expect("parses");
        let h = &v["hosts"][0];
        let m = &h["os_matches"][0];
        assert_eq!(m["name"], "Linux 2.6.32 - 3.2");
        assert_eq!(m["accuracy"], "100");
        let cls = &m["classes"][0];
        assert_eq!(cls["vendor"], "Linux");
        assert_eq!(cls["osfamily"], "Linux");
        assert_eq!(cls["osgen"], "2.6.X");
        assert_eq!(cls["type"], "general purpose");
        assert_eq!(cls["cpe"][0], "cpe:/o:linux:linux_kernel:2.6");
        assert_eq!(h["uptime"]["seconds"], "12345");
        assert_eq!(h["traceroute"][0]["ttl"], "1");
        assert_eq!(h["traceroute"][1]["ipaddr"], "10.0.0.1");
    }

    #[test]
    fn rejects_malformed_xml() {
        let err = parse_nmap_xml("<nmaprun><host></nmaprun>").expect_err("bad xml");
        assert!(err.contains("parse error") || err.contains("unexpected"));
    }

    #[test]
    fn handles_entities_in_attributes_and_text() {
        let xml = r#"<nmaprun scanner="nmap" args="a &amp; b" version="7.95" xmloutputversion="1.05">
<host><status state="up" reason="conn-refused"/>
<address addr="127.0.0.1" addrtype="ipv4"/>
<ports><port protocol="tcp" portid="80"><state state="open" reason="syn-ack"/>
<script id="http-title" output="&#xa;Title: A &amp; B"></script>
</port>
</ports>
</host>
</nmaprun>"#;
        let v = parse_nmap_xml(xml).expect("parses");
        assert_eq!(v["args"], "a & b");
        let script = &v["hosts"][0]["ports"][0]["scripts"][0];
        assert!(script["output"].as_str().unwrap().contains("A & B"));
    }
}