use std::env;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use serde_json::Value;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;
use crate::nmap_xml;
#[derive(Debug)]
pub struct RunOutput {
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Clone)]
pub struct NmapRunner {
bin: PathBuf,
}
impl Default for NmapRunner {
fn default() -> Self {
Self::new()
}
}
impl NmapRunner {
pub fn new() -> Self {
let bin = env::var("NMAP_MCP_BIN")
.ok()
.filter(|p| !p.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("nmap"));
Self { bin }
}
pub fn bin(&self) -> String {
self.bin.to_string_lossy().into_owned()
}
pub async fn run(&self, args: &[&str], timeout_secs: u64) -> Result<RunOutput, String> {
let mut cmd = Command::new(&self.bin);
cmd.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| {
format!(
"failed to start nmap ({e}); install nmap or set NMAP_MCP_BIN to the executable path"
)
})?;
let stdout = child.stdout.take().expect("stdout piped");
let stderr = child.stderr.take().expect("stderr piped");
let deadline = Duration::from_secs(timeout_secs.clamp(1, 3600));
let result = timeout(deadline, async {
let (out, err) = tokio::join!(read_all(stdout), read_all_err(stderr));
let status = child
.wait()
.await
.map_err(|e| format!("wait failed: {e}"))?;
Ok::<RunOutput, String>(RunOutput {
exit_code: status.code(),
stdout: out,
stderr: err,
})
})
.await;
match result {
Ok(Ok(output)) => Ok(output),
Ok(Err(e)) => Err(e),
Err(_) => Err(format!(
"nmap timed out after {timeout_secs}s (command: {} {})",
self.bin(),
args.join(" ")
)),
}
}
pub async fn scan(&self, args: &[String], timeout_secs: u64) -> Result<Value, String> {
let mut full: Vec<String> = Vec::with_capacity(args.len() + 2);
full.push("-oX".to_string());
full.push("-".to_string());
full.extend_from_slice(args);
let refs: Vec<&str> = full.iter().map(|s| s.as_str()).collect();
let out = self.run(&refs, timeout_secs).await?;
if out.stdout.trim().is_empty() {
let detail = if out.stderr.trim().is_empty() {
String::new()
} else {
format!(": {}", out.stderr.trim())
};
return Err(format!(
"nmap produced no output (exit {:?}){detail}",
out.exit_code
));
}
if !out.stdout.trim_start().starts_with('<') {
return Err(format!(
"nmap output is not XML (exit {:?}): {}",
out.exit_code,
preview(&out.stdout, 400)
));
}
let mut value = nmap_xml::parse_nmap_xml(&out.stdout)?;
if let Some(obj) = value.as_object_mut() {
if !out.stderr.trim().is_empty() {
obj.insert(
"stderr".to_string(),
Value::String(out.stderr.trim().to_string()),
);
}
if let Some(code) = out.exit_code {
obj.insert("exit_code".to_string(), Value::from(code));
}
}
Ok(value)
}
pub async fn version(&self) -> Result<(String, String), String> {
let out = self.run(&["--version"], 30).await?;
let first = out.stdout.lines().next().unwrap_or("").trim().to_string();
if first.starts_with("Nmap version") {
let version = first
.trim_start_matches("Nmap version")
.split_whitespace()
.next()
.unwrap_or("unknown")
.to_string();
Ok((version, first))
} else {
Err(format!(
"unexpected nmap --version output: {}",
preview(&out.stdout, 200)
))
}
}
pub async fn script_help(&self, names: &[&str], timeout_secs: u64) -> Result<String, String> {
let mut args = vec!["--script-help"];
args.extend_from_slice(names);
let out = self.run(&args, timeout_secs).await?;
if out.stdout.trim().is_empty() {
return Err(format!(
"nmap --script-help produced no output: {}",
out.stderr.trim()
));
}
Ok(out.stdout)
}
}
async fn read_all(mut r: tokio::process::ChildStdout) -> String {
let mut s = String::new();
let _ = r.read_to_string(&mut s).await;
s
}
async fn read_all_err(mut r: tokio::process::ChildStderr) -> String {
let mut s = String::new();
let _ = r.read_to_string(&mut s).await;
s
}
fn preview(s: &str, max: usize) -> String {
let mut out = s.trim().chars().take(max).collect::<String>();
if s.trim().chars().count() > max {
out.push_str("...");
}
out
}
pub fn script_db_path(runner: &NmapRunner) -> Option<PathBuf> {
if let Ok(p) = env::var("NMAP_MCP_SCRIPT_DB") {
if !p.is_empty() && Path::new(&p).is_file() {
return Some(PathBuf::from(p));
}
}
let bin_path = Path::new(&runner.bin);
if bin_path.is_absolute() {
let mut dir = bin_path.parent();
while let Some(d) = dir {
let candidate = d
.join("share")
.join("nmap")
.join("scripts")
.join("script.db");
if candidate.is_file() {
return Some(candidate);
}
dir = d.parent();
}
}
for cand in [
"/usr/share/nmap/scripts/script.db",
"/usr/local/share/nmap/scripts/script.db",
"/opt/homebrew/share/nmap/scripts/script.db",
] {
if Path::new(cand).is_file() {
return Some(PathBuf::from(cand));
}
}
None
}
pub fn scripts_dir(runner: &NmapRunner) -> Option<PathBuf> {
if let Some(db) = script_db_path(runner) {
if let Some(dir) = db.parent() {
if dir.join("script.db").is_file() {
return Some(dir.to_path_buf());
}
}
}
let bin_path = Path::new(&runner.bin);
if bin_path.is_absolute() {
let mut dir = bin_path.parent();
while let Some(d) = dir {
let candidate = d.join("share").join("nmap").join("scripts");
if candidate.is_dir() {
return Some(candidate);
}
dir = d.parent();
}
}
None
}
pub fn script_file_count(runner: &NmapRunner) -> Option<usize> {
let dir = scripts_dir(runner)?;
let entries = std::fs::read_dir(dir).ok()?;
let count = entries
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|x| x == "nse").unwrap_or(false))
.count();
Some(count)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preview_truncates() {
let s = "a".repeat(500);
let p = preview(&s, 400);
assert_eq!(p.chars().count(), 403);
assert!(p.ends_with("..."));
assert_eq!(preview("short", 400), "short");
}
#[tokio::test]
async fn runner_reports_missing_binary() {
let runner = NmapRunner {
bin: PathBuf::from("/nonexistent/nmap-xyz"),
};
let err = runner.run(&["--version"], 5).await.unwrap_err();
assert!(err.contains("failed to start nmap"));
}
}