//! Internal bounded argv-only subprocess transport; never a public command API. use anyhow::{Context, Result, ensure}; use std::{ io::Read, os::{fd::AsRawFd, unix::process::CommandExt}, process::{Command, Stdio}, thread, time::{Duration, Instant}, }; #[derive(Debug, Clone)] pub struct Output { pub code: Option, pub stdout: Vec, pub stderr: Vec, pub truncated: bool, pub timed_out: bool, pub interrupted: bool, } pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize) -> Result { run_controlled(program, args, timeout, cap, || Ok(())) } pub(crate) fn run_controlled( program: &str, args: &[String], timeout: Duration, cap: usize, mut observe: impl FnMut() -> Result<()>, ) -> Result { ensure!(!timeout.is_zero() && cap > 0, "invalid process limits"); let mut command = Command::new(program); command .args(args) .env_clear() .env("PATH", "/usr/sbin:/usr/bin:/sbin:/bin") .env("LC_ALL", "C") .env("LANG", "C") .env("DEBIAN_FRONTEND", "noninteractive") .env("SYSTEMD_PAGER", "") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .process_group(0); observe()?; let mut child = command .spawn() .with_context(|| format!("spawn {program}"))?; // Keep the group leader unreaped until AFTER the last signal and cleanup. // Its reserved PID prevents the numerical PGID from becoming a foreign group. struct Group { pid: u32, reserved: bool, } impl Group { fn kill(&self) { if self.reserved { unsafe { libc::kill(-(self.pid as i32), libc::SIGKILL); } } } } impl Drop for Group { fn drop(&mut self) { self.kill(); } } let mut group = Group { pid: child.id(), reserved: true, }; let mut stdout = child.stdout.take().context("missing stdout")?; let mut stderr = child.stderr.take().context("missing stderr")?; let began = Instant::now(); let mut output = Output { code: None, stdout: vec![], stderr: vec![], truncated: false, timed_out: false, interrupted: false, }; let mut remaining = cap; let mut failure = None; for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] { let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 { failure = Some(anyhow::Error::from(std::io::Error::last_os_error())); break; } } if failure.is_none() { loop { if let Err(e) = drain( &mut stdout, &mut output.stdout, &mut remaining, &mut output.truncated, ) .and_then(|_| { drain( &mut stderr, &mut output.stderr, &mut remaining, &mut output.truncated, ) }) { failure = Some(e); break; } // WNOWAIT deliberately observes without releasing this child's PID. let mut info = std::mem::MaybeUninit::::zeroed(); let state = unsafe { libc::waitid( libc::P_PID, child.id(), info.as_mut_ptr(), libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, ) }; if state < 0 { let e = std::io::Error::last_os_error(); if e.kind() == std::io::ErrorKind::Interrupted { continue; } if e.raw_os_error() == Some(libc::ECHILD) { group.reserved = false; } failure = Some(e.into()); break; } if unsafe { info.assume_init().si_pid() } != 0 { break; } let fenced = observe().is_err(); if began.elapsed() >= timeout || fenced { output.timed_out = began.elapsed() >= timeout; output.interrupted = fenced; break; } thread::sleep(Duration::from_millis(5)); } } if !group.reserved { // An unexpected external reap destroyed the group identity proof. Never // signal/adopt a numerical replacement; caller records Unknown. return Err(failure.unwrap_or_else(|| anyhow::anyhow!("OWNED_GROUP_IDENTITY_LOST"))); } group.kill(); let cleanup = Instant::now(); loop { // A setup error may have left a blocking pipe. It must not become an // unbounded cleanup read; retain only group ownership in that path. let out_closed = if failure.is_some() { Ok(true) } else { drain( &mut stdout, &mut output.stdout, &mut remaining, &mut output.truncated, ) }; let err_closed = if failure.is_some() { Ok(true) } else { drain( &mut stderr, &mut output.stderr, &mut remaining, &mut output.truncated, ) }; if out_closed.is_err() || err_closed.is_err() { output.truncated = true; } // Only zombies may remain while the *owned* leader stays unreaped. // They cannot execute or retain pipe writers. Unclear /proc state keeps // this owner and the caller's executor lock instead of a replacement. if group_has_no_live_members(group.pid) { if out_closed.unwrap_or(true) && err_closed.unwrap_or(true) { break; } // A privileged script may deliberately give a pipe to an unrelated // process. That process is outside our ownership; never kill it. if cleanup.elapsed() >= Duration::from_millis(250) { output.truncated = true; break; } } if cleanup.elapsed() >= Duration::from_millis(250) { output.timed_out = true; } thread::sleep(Duration::from_millis(5)); } // Disarm BEFORE releasing the reserved leader PID: no later Drop can signal // a reused PGID. All assigned living members have already ended. group.reserved = false; let status = child.wait()?; if let Some(e) = failure { return Err(e); } output.interrupted |= observe().is_err(); output.code = if output.timed_out || began.elapsed() >= timeout { None } else { status.code() }; Ok(output) } fn drain( pipe: &mut impl Read, target: &mut Vec, remaining: &mut usize, truncated: &mut bool, ) -> Result { let mut bytes = [0; 4096]; for _ in 0..16 { match pipe.read(&mut bytes) { Ok(0) => return Ok(true), Ok(n) => { let keep = n.min(*remaining); target.extend_from_slice(&bytes[..keep]); *remaining -= keep; *truncated |= keep < n; } Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break, Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => return Err(e.into()), } } Ok(false) } fn group_has_no_live_members(pgid: u32) -> bool { let Ok(entries) = std::fs::read_dir("/proc") else { return false; }; for entry in entries { let Ok(entry) = entry else { return false; }; if entry.file_name().to_string_lossy().parse::().is_err() { continue; } let bytes = match std::fs::read_to_string(entry.path().join("stat")) { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, Err(_) => return false, }; let Some((_, rest)) = bytes.rsplit_once(") ") else { return false; }; let fields: Vec<_> = rest.split_whitespace().take(3).collect(); if fields.len() != 3 { return false; } let Ok(group) = fields[2].parse::() else { return false; }; if group == pgid && fields[0] != "Z" && fields[0] != "X" { return false; } } true } #[cfg(test)] mod tests { use super::*; #[test] fn cancellation_observation_terminates_only_owned_group_and_keeps_raw_bounded_output() { let began = Instant::now(); let output = run_controlled( "/bin/sh", &[ "-c".into(), "printf before; printf err >&2; sleep 10".into(), ], Duration::from_secs(5), 64, || { ensure!( began.elapsed() < Duration::from_millis(80), "TEST_CANCELLED" ); Ok(()) }, ) .unwrap(); assert!(output.interrupted); assert!(!output.timed_out); assert_eq!(output.stdout, b"before"); assert_eq!(output.stderr, b"err"); assert_ne!(output.code, Some(0)); assert!(began.elapsed() < Duration::from_secs(2)); } #[test] fn exited_leader_does_not_leave_background_effects_or_open_pipes() { let directory = std::env::temp_dir().join(format!("rmm-group-test-{}", uuid::Uuid::new_v4())); std::fs::create_dir(&directory).unwrap(); let marker = directory.join("unexpected-effect"); // The background shell inherits stdout/stderr. The leader exits without // waiting; a missing group cleanup would allow the delayed write. let script = "(sleep 0.6; printf late; printf effect > \"$1\") & printf leader; exit 0"; let started = Instant::now(); let output = run( "/bin/sh", &[ "-c".into(), script.into(), "rmm-test".into(), marker.to_str().unwrap().into(), ], Duration::from_secs(2), 128, ) .unwrap(); assert!(started.elapsed() < Duration::from_secs(2)); assert!(output.stdout.starts_with(b"leader")); assert!(!output.stdout.windows(4).any(|s| s == b"late")); thread::sleep(Duration::from_millis(750)); assert!( !marker.exists(), "background child caused an effect after return" ); std::fs::remove_dir_all(directory).unwrap(); } }