diff --git a/src/doctor.rs b/src/doctor.rs index dd5c34f..6d13412 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -651,7 +651,12 @@ fn protocol_row( /// than a `✗`: reporting a stopped shard as a failure would train operators to ignore this line, /// which is the one line worth reading. fn shard_row(root: Result<&ServUoRoot, &anyhow::Error>, health: Option<&Health>) -> Row { - let running = root.ok().and_then(|r| servuo::find_running(&r.path)); + // Only a certain match: an unreadable-cwd process may be a different shard, and "running but + // has not dialed in" about the wrong shard would send the operator after the wrong problem. + let running = root + .ok() + .and_then(|r| servuo::find_running(&r.path)) + .filter(|s| s.certain); match (health.and_then(|h| h.plugin_connected), running) { (Some(true), _) => { diff --git a/src/servuo.rs b/src/servuo.rs index dc42072..4859e7e 100644 --- a/src/servuo.rs +++ b/src/servuo.rs @@ -180,6 +180,21 @@ pub(crate) fn strip_extended_prefix(path: PathBuf) -> PathBuf { pub struct RunningShard { pub pid: u32, pub detail: String, + /// `false` when the process names a *relative* `ServUO.exe` and its working directory could not + /// be read (another user's process, installer not run as root), so it may be a different + /// shard. Install/update still refuse — failing closed is the point — but say why. + pub certain: bool, +} + +/// How one process relates to the tree being deployed into. See [`classify`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Verdict { + /// Not a ServUO process, or one running out of a different tree. + No, + /// A ServUO process running out of this tree. + Shard, + /// A ServUO process launched with a relative path whose working directory could not be read. + Unknown, } /// Refuses to proceed if a shard is running out of `root`. @@ -190,20 +205,31 @@ pub struct RunningShard { /// running" for a shard that is very much running — the one wrong answer that corrupts a live /// `Scripts.dll`. Scoping to processes under *this* root also means a second shard on the same host /// does not block a deploy into the first. +/// +/// Every launch shape is covered (installer#47): `ServUO.exe` run directly (Windows), +/// `mono /abs/path/ServUO.exe`, and — the common one under systemd or tmux — `mono ServUO.exe` +/// started from inside the root, where the root appears only in the process's working directory. +/// The decision itself is [`classify`]; this function only gathers what it needs. pub fn find_running(root: &Path) -> Option { use sysinfo::{ProcessRefreshKind, RefreshKind, System}; let system = System::new_with_specifics( RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()), ); - let root_str = normalize_for_match(&root.to_string_lossy()); + let mut unknown = None; for (pid, process) in system.processes() { // Own process first: the installer may well have been copied into the server root, and // matching itself would make every run refuse to start. if pid.as_u32() == std::process::id() { continue; } + // On Linux the scan lists every thread (TID) beside its process (TGID). They share the + // process's exe/cmd/cwd, so a thread can match first and the refusal names a pid that + // `kill` cannot use (installer#45 item 5). Threads are skipped; the process itself matches. + if process.thread_kind().is_some() { + continue; + } let exe = process .exe() @@ -215,19 +241,101 @@ pub fn find_running(root: &Path) -> Option { .map(|a| a.to_string_lossy().to_string()) .collect(); - let hay = normalize_for_match(&format!("{exe} {}", args.join(" "))); - // Two conditions, both required: something in this process names the tree, AND it names - // the ServUO assembly. Either alone over-matches — an editor with the path open, or a - // different shard's ServUO.exe. - if hay.contains(&root_str) && hay.contains("servuo.exe") { - let detail = if exe.is_empty() { args.join(" ") } else { exe }; - return Some(RunningShard { + let found = |certain| { + let detail = if exe.is_empty() { + args.join(" ") + } else { + exe.clone() + }; + RunningShard { pid: pid.as_u32(), detail, - }); + certain, + } + }; + match classify(root, &exe, &args, process.cwd()) { + Verdict::Shard => return Some(found(true)), + // Kept looking: a certain match elsewhere is the better report. + Verdict::Unknown if unknown.is_none() => unknown = Some(found(false)), + _ => {} } } - None + unknown +} + +/// Decides whether one process is a ServUO running out of `root`. Pure, so every launch shape is +/// unit-tested without spawning anything. +/// +/// Something in the process must name the ServUO assembly — otherwise an editor or a shell sitting +/// in the root would match — and that assembly must resolve into this tree, otherwise a second +/// shard on the host would block this one. +fn classify(root: &Path, exe: &str, args: &[String], cwd: Option<&Path>) -> Verdict { + let root_str = normalize_for_match(&root.to_string_lossy()); + let names_assembly = |s: &str| normalize_for_match(s).ends_with("servuo.exe"); + + // ServUO.exe is itself the executable (Windows): its path settles it, whatever argv says. + if names_assembly(exe) { + return if in_tree(Path::new(exe), &root_str) { + Verdict::Shard + } else { + Verdict::No + }; + } + + // The original substring rule, kept so nothing it caught is lost: the tree and the assembly + // both named somewhere in the command line (`mono /opt/ServUO/ServUO.exe`, or an option of + // the form `--assembly=/opt/ServUO/ServUO.exe`). + let hay = normalize_for_match(&format!("{exe} {}", args.join(" "))); + if !hay.contains("servuo.exe") { + return Verdict::No; + } + if hay.contains(&root_str) { + return Verdict::Shard; + } + + // Hosted (`mono` / `dotnet`) with the assembly named relatively: resolve it against the + // process's working directory. `mono ServUO.exe` from the root and `mono ServUO/ServUO.exe` + // from its parent both land here. + let mut verdict = Verdict::No; + for arg in args.iter().filter(|a| names_assembly(a)) { + let path = Path::new(arg); + let resolved = if path.has_root() { + path.to_path_buf() + } else if let Some(cwd) = cwd { + cwd.join(path) + } else { + // Unreadable cwd: cannot rule this tree out. Fail closed (decided 2026-11-27). + verdict = Verdict::Unknown; + continue; + }; + if in_tree(&resolved, &root_str) { + return Verdict::Shard; + } + } + verdict +} + +/// True when `path` (lexically normalized: `.` dropped, `..` applied) lies inside the tree whose +/// normalized path is `root_str`. A component-wise prefix, so `/opt/ServUO2` is not inside +/// `/opt/ServUO`. +fn in_tree(path: &Path, root_str: &str) -> bool { + use std::path::Component; + + let mut clean = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + clean.pop(); + } + other => clean.push(other.as_os_str()), + } + } + let path_str = normalize_for_match(&clean.to_string_lossy()); + let root_str = root_str.trim_end_matches('/'); + path_str + .strip_prefix(root_str) + .is_some_and(|rest| rest.starts_with('/')) } /// Lower-cases and unifies separators so a Windows path compares equal however it was spelled. @@ -238,6 +346,18 @@ fn normalize_for_match(s: &str) -> String { /// Builds the refusal message. Separate from [`find_running`] so the wording is testable and so /// callers cannot accidentally soften it. pub fn running_error(root: &Path, shard: &RunningShard) -> anyhow::Error { + if !shard.certain { + return anyhow::anyhow!( + "A ServUO process is running (pid {} — {}) and its working directory cannot be read, \ + so the installer cannot rule out that it is running from {}.\n\ + Stop it, or re-run the installer as root (sudo) so it can check. ServUO.exe holds \ + Scripts.dll open and rewrites Saves/ on exit, so deploying underneath a live shard \ + corrupts one or both. This is not overridable.", + shard.pid, + shard.detail, + root.display() + ); + } anyhow::anyhow!( "ServUO is running from {} (pid {} — {}).\n\ Stop the shard before installing. ServUO.exe holds Scripts.dll open and rewrites Saves/ \ @@ -383,6 +503,7 @@ mod tests { let shard = RunningShard { pid: 4242, detail: "/opt/ServUO/ServUO.exe".into(), + certain: true, }; let msg = running_error(Path::new("/opt/ServUO"), &shard).to_string(); assert!(msg.contains("4242"), "{msg}"); @@ -390,6 +511,139 @@ mod tests { assert!(msg.contains("not overridable"), "{msg}"); } + #[test] + fn an_uncertain_refusal_says_it_could_not_check_and_still_offers_no_override() { + let shard = RunningShard { + pid: 4242, + detail: "mono ServUO.exe".into(), + certain: false, + }; + let msg = running_error(Path::new("/opt/ServUO"), &shard).to_string(); + assert!(msg.contains("4242"), "{msg}"); + assert!(msg.contains("cannot be read"), "{msg}"); + assert!(msg.contains("sudo"), "{msg}"); + assert!(msg.contains("not overridable"), "{msg}"); + } + + // installer#47 — every launch shape. Paths are written Unix-style; `Path` parses them on + // Windows too (root dir, no prefix), so these run on both CI legs. + const ROOT: &str = "/opt/ServUO"; + const MONO: &str = "/usr/bin/mono-sgen"; + + fn verdict(exe: &str, args: &[&str], cwd: Option<&str>) -> Verdict { + let args: Vec = args.iter().map(|a| a.to_string()).collect(); + classify(Path::new(ROOT), exe, &args, cwd.map(Path::new)) + } + + #[test] + fn a_relative_launch_from_the_root_is_the_shard() { + // `cd /opt/ServUO && mono ServUO.exe` — systemd WorkingDirectory=, or tmux. + let v = verdict(MONO, &["mono", "ServUO.exe"], Some("/opt/ServUO")); + assert_eq!(v, Verdict::Shard); + let v = verdict( + MONO, + &["mono", "--debug", "./ServUO.exe"], + Some("/opt/ServUO"), + ); + assert_eq!(v, Verdict::Shard); + } + + #[test] + fn a_relative_launch_from_elsewhere_resolves_against_its_cwd() { + let v = verdict(MONO, &["mono", "ServUO/ServUO.exe"], Some("/opt")); + assert_eq!(v, Verdict::Shard); + let v = verdict(MONO, &["mono", "../ServUO/ServUO.exe"], Some("/opt/other")); + assert_eq!(v, Verdict::Shard); + } + + #[test] + fn an_absolute_launch_is_the_shard_whatever_the_cwd() { + let v = verdict(MONO, &["mono", "/opt/ServUO/ServUO.exe"], Some("/root")); + assert_eq!(v, Verdict::Shard); + // exe unreadable (another user's process), cwd unreadable: argv alone still settles it. + let v = verdict("", &["mono", "/opt/ServUO/ServUO.exe"], None); + assert_eq!(v, Verdict::Shard); + } + + #[test] + fn servuo_as_the_executable_is_decided_by_its_path() { + // Windows: ServUO.exe runs natively; argv may be relative. + let v = verdict("/opt/ServUO/ServUO.exe", &["ServUO.exe"], None); + assert_eq!(v, Verdict::Shard); + let v = verdict("/srv/Other/ServUO.exe", &["ServUO.exe"], None); + assert_eq!(v, Verdict::No); + } + + #[test] + fn a_second_shard_on_the_host_does_not_match() { + let v = verdict(MONO, &["mono", "ServUO.exe"], Some("/srv/Other")); + assert_eq!(v, Verdict::No); + let v = verdict( + MONO, + &["mono", "/srv/Other/ServUO.exe"], + Some("/opt/ServUO"), + ); + assert_eq!(v, Verdict::No); + // A sibling whose name merely starts with the root's. + let v = verdict(MONO, &["mono", "ServUO.exe"], Some("/opt/ServUO2")); + assert_eq!(v, Verdict::No); + } + + #[test] + fn a_process_that_does_not_name_the_assembly_never_matches() { + // The tmux shell sitting in the root, or an editor with a file open. + assert_eq!( + verdict("/bin/bash", &["-bash"], Some("/opt/ServUO")), + Verdict::No + ); + let v = verdict( + "/usr/bin/vim", + &["vim", "Config/Server.cfg"], + Some("/opt/ServUO"), + ); + assert_eq!(v, Verdict::No); + } + + /// installer#47 end to end on a real `/proc`: a process started *inside* the root naming a + /// relative `ServUO.exe` — the shape of `cd root && mono ServUO.exe` — is found, under its own + /// pid (a thread id would not equal `child.id()`, installer#45 item 5). `sh -c '…' ServUO.exe` + /// puts `ServUO.exe` in argv as `$0`; the trailing `:` stops the shell exec'ing into `sleep`. + #[cfg(target_os = "linux")] + #[test] + fn a_live_relative_launch_from_the_root_is_found_by_its_pid() { + let tmp = TempDir::new("rg-test-live-shard").unwrap(); + let root = tmp.path().join("srv"); + fake_root(&root); + let root = fs::canonicalize(&root).unwrap(); + + let mut child = std::process::Command::new("sh") + .args(["-c", "sleep 30; :", "ServUO.exe"]) + .current_dir(&root) + .spawn() + .unwrap(); + // The process is listed as soon as it exists, but give /proc a moment to fill cmdline. + let mut found = None; + for _ in 0..20 { + found = find_running(&root); + if found.is_some() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let _ = child.kill(); + let _ = child.wait(); + + let shard = found.expect("a relative launch from the root must be detected"); + assert_eq!(shard.pid, child.id()); + assert!(shard.certain); + } + + #[test] + fn a_relative_launch_with_an_unreadable_cwd_fails_closed() { + let v = verdict("", &["mono", "ServUO.exe"], None); + assert_eq!(v, Verdict::Unknown); + } + #[test] fn nothing_is_running_out_of_an_empty_tree() { // Also proves the scan does not match the test binary itself, which is the failure mode