//! Running a program (`std/command`, ADR 0085): the driver both back ends //! share. The native runtime parks the calling actor on the child's file //! descriptors (`louise_rt/src/command.rs`); the interpreter waits on them //! with `poll(2)`. Neither ever blocks on the child itself. //! //! - **No shell.** The program gets exactly the arguments given, and //! exactly the environment given: nothing is inherited. //! - **`posix_spawn`, not `std::process`.** The runtime blocks SIGTERM, //! SIGINT and SIGHUP in every thread (`signals.rs`), and Rust's //! `Command` hands the parent's mask down to the child, which would then //! ignore the SIGTERM of a timeout. The spawn here empties the child's //! mask, resets every disposition to its default and puts the child in //! a process group of its own, so a timeout reaches what it started. //! - **Descriptors.** The child's three pipes, a pidfd (the child's exit), //! and a timerfd (the next deadline), all non-blocking: a caller waits //! until one is ready, then calls [`Child::step`] until it is done. //! - **Deadlines.** At the timeout the group gets SIGTERM; after the grace //! period, SIGKILL. When the child ends, what is left of its group gets //! SIGKILL, and the pipes are drained for at most the grace period (a //! descendant that left the group may hold them open). //! - **No zombies.** Dropping a [`Child`] before it is done (its actor was //! killed) kills the group and reaps the child, on a reaper thread if //! the child does not die at once. A program that exits kills the groups //! still running ([`kill_all`], an `atexit` handler). use std::ffi::CString; use std::fs::{DirBuilder, OpenOptions}; use std::io::{ErrorKind, Read, Write}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use std::sync::mpsc::{Sender, channel}; use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; /// Where the program runs. pub enum Dir { /// The caller's working directory. Inherit, /// This directory. In(PathBuf), /// A fresh private directory: `inputs` are written into it first, /// `outputs` are read back (at most `max_file` bytes each) once the /// program ends, then the directory is removed. Scratch { inputs: Vec<(String, Vec)>, outputs: Vec, max_file: usize, }, } /// What to run. pub struct Spec { pub program: String, pub args: Vec, pub env: Vec<(String, String)>, pub dir: Dir, pub stdin: Vec, pub max_stdout: usize, pub max_stderr: usize, pub timeout: Duration, pub grace: Duration, } /// Why a program did not run. [`Failure::code`] numbers them in the order /// of `std/command`'s `Error` constructors. #[derive(Debug, PartialEq, Eq)] pub enum Failure { NotFound(String), Denied(String), BadArgument(String), Failed(String), } impl Failure { pub fn code(&self) -> i64 { match self { Self::NotFound(_) => 0, Self::Denied(_) => 1, Self::BadArgument(_) => 2, Self::Failed(_) => 3, } } pub fn message(&self) -> &str { match self { Self::NotFound(m) | Self::Denied(m) | Self::BadArgument(m) | Self::Failed(m) => m, } } } /// How the program ended. [`Exit::kind`] numbers them in the order of /// `std/command`'s `Exit` constructors. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Exit { Exited(i32), Signalled(i32), /// The timeout passed; the last signal the group was sent. TimedOut(i32), } impl Exit { pub fn kind(self) -> i64 { match self { Self::Exited(_) => 0, Self::Signalled(_) => 1, Self::TimedOut(_) => 2, } } pub fn value(self) -> i64 { match self { Self::Exited(n) | Self::Signalled(n) | Self::TimedOut(n) => i64::from(n), } } } /// A scratch output, read back. [`Collected::kind`] numbers them in the /// order of `std/command`'s `Collected` constructors. #[derive(Debug, PartialEq, Eq)] pub enum Collected { Found(String, Vec), TooLarge(String, u64), Absent(String), } impl Collected { pub fn kind(&self) -> i64 { match self { Self::Found(..) => 0, Self::TooLarge(..) => 1, Self::Absent(_) => 2, } } } /// A finished run. pub struct Outcome { pub exit: Exit, pub stdout: Vec, pub stderr: Vec, pub stdout_cut: bool, pub stderr_cut: bool, pub files: Vec, } /// What a [`Child::step`] found. pub enum Step { /// Wait for one of [`Child::fds`] to be ready, then step again. Pending, Done(Outcome), } /// Whether a descriptor is waited on for reading or for writing. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Interest { Read, Write, } /// Check `spec` before anything is created. pub fn validate(spec: &Spec) -> Result<(), Failure> { let bad = |m: String| Err(Failure::BadArgument(m)); if spec.program.is_empty() { return bad("the program is empty".into()); } let texts = std::iter::once(&spec.program) .chain(&spec.args) .chain(spec.env.iter().flat_map(|(k, v)| [k, v])); if let Some(t) = texts.into_iter().find(|t| t.contains('\0')) { return bad(format!("a NUL byte in {t:?}")); } if let Some((k, _)) = spec .env .iter() .find(|(k, _)| k.is_empty() || k.contains('=')) { return bad(format!("not an environment variable name: {k:?}")); } if spec.timeout.is_zero() { return bad("the timeout must be positive".into()); } match &spec.dir { Dir::In(p) if p.as_os_str().is_empty() => bad("the directory is empty".into()), Dir::Scratch { inputs, outputs, .. } => { let names = inputs.iter().map(|(n, _)| n).chain(outputs); match names.into_iter().find(|n| !plain_name(n)) { Some(n) => bad(format!("not a plain file name: {n:?}")), None => Ok(()), } } _ => Ok(()), } } /// A file name with no directory in it: not empty, no `/`, no NUL, not /// `.` or `..`. pub fn plain_name(name: &str) -> bool { !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\0']) } /// The file `program` names: itself if it has a `/`, else the first /// executable file of that name in the absolute directories of `path` /// (the `PATH` the program is given, never the caller's). pub fn resolve(program: &str, path: Option<&str>) -> Option { if program.contains('/') { return Some(PathBuf::from(program)); } path? .split(':') .filter(|d| d.starts_with('/')) .map(|d| Path::new(d).join(program)) .find(|p| executable(p)) } fn executable(p: &Path) -> bool { let Ok(c) = CString::new(p.as_os_str().as_encoded_bytes()) else { return false; }; // SAFETY: `c` is a valid C string. p.is_file() && unsafe { libc::access(c.as_ptr(), libc::X_OK) } == 0 } /// A running program. Drop it only when done, or to stop it. pub struct Child { pid: libc::pid_t, pidfd: OwnedFd, timer: OwnedFd, stdin: Option, stdout: Option, stderr: Option, input: Vec, written: usize, out: Capture, err: Capture, deadline: Instant, grace: Duration, /// The last signal the timeout sent, and when the next is due. timeout: Option<(i32, Instant)>, /// How the child ended, and until when its pipes are drained. ended: Option<(Exit, Instant)>, scratch: Option, } struct Capture { data: Vec, max: usize, cut: bool, } struct Scratch { dir: PathBuf, outputs: Vec, max_file: usize, } impl Drop for Scratch { fn drop(&mut self) { // Removing what is left is all that can be done; symlinks are // removed, never followed. let _ = std::fs::remove_dir_all(&self.dir); } } /// Start `spec`'s program (checked by [`validate`]). pub fn spawn(spec: Spec) -> Result { validate(&spec)?; let path_var = spec .env .iter() .find(|(k, _)| k == "PATH") .map(|(_, v)| v.as_str()); let program = resolve(&spec.program, path_var) .ok_or_else(|| Failure::NotFound(format!("{}: not found", spec.program)))?; let (scratch, cwd) = match spec.dir { Dir::Inherit => (None, None), Dir::In(dir) => (None, Some(dir)), Dir::Scratch { inputs, outputs, max_file, } => { let s = scratch(&inputs, outputs, max_file)?; let dir = s.dir.clone(); (Some(s), Some(dir)) } }; let c = |s: &[u8]| CString::new(s).map_err(|e| Failure::BadArgument(e.to_string())); let path = c(program.as_os_str().as_encoded_bytes())?; let argv = std::iter::once(&spec.program) .chain(&spec.args) .map(|a| c(a.as_bytes())) .collect::, _>>()?; let envp = spec .env .iter() .map(|(k, v)| c(format!("{k}={v}").as_bytes())) .collect::, _>>()?; let cwd = cwd .map(|d| c(d.as_os_str().as_encoded_bytes())) .transpose()?; let (child_in, stdin) = pipe()?; let (stdout, child_out) = pipe()?; let (stderr, child_err) = pipe()?; let pid = posix_spawn( &path, &argv, &envp, cwd.as_ref(), [&child_in, &child_out, &child_err], ) .map_err(|e| failure(&spec.program, e))?; drop((child_in, child_out, child_err)); track(pid); let pidfd = match pidfd_open(pid) { Ok(fd) => fd, Err(e) => { // SAFETY: `pid` is our unreaped child: it cannot be reused. unsafe { libc::killpg(pid, libc::SIGKILL); libc::waitpid(pid, std::ptr::null_mut(), 0); } untrack(pid); return Err(Failure::Failed(format!("pidfd_open: {e}"))); } }; let timer = timerfd().map_err(|e| Failure::Failed(format!("timerfd: {e}")))?; for fd in [&stdin, &stdout, &stderr] { nonblocking(fd).map_err(|e| Failure::Failed(format!("fcntl: {e}")))?; } let now = Instant::now(); let child = Child { pid, pidfd, timer, stdin: (!spec.stdin.is_empty()).then_some(stdin), stdout: Some(stdout), stderr: Some(stderr), input: spec.stdin, written: 0, out: Capture::new(spec.max_stdout), err: Capture::new(spec.max_stderr), deadline: now + spec.timeout, grace: spec.grace, timeout: None, ended: None, scratch, }; child.arm(child.deadline, now); Ok(child) } impl Child { /// The descriptors to wait on, and for what. pub fn fds(&self) -> Vec<(RawFd, Interest)> { let read = [ Some(&self.pidfd), Some(&self.timer), self.stdout.as_ref(), self.stderr.as_ref(), ]; read.into_iter() .flatten() .map(|fd| (fd.as_raw_fd(), Interest::Read)) .chain( self.stdin .as_ref() .map(|fd| (fd.as_raw_fd(), Interest::Write)), ) .collect() } /// Do what can be done without waiting: read the pipes, write stdin, /// notice the child's end, send the signals that are due. pub fn step(&mut self) -> Step { let mut tick = [0u8; 8]; let _ = read_fd(&self.timer, &mut tick); drain(&mut self.stdout, &mut self.out); drain(&mut self.stderr, &mut self.err); self.feed(); let now = Instant::now(); if self.ended.is_none() { if let Some(status) = self.reap() { let exit = match self.timeout { Some((signal, _)) => Exit::TimedOut(signal), None => status, }; self.ended = Some((exit, now + self.grace)); self.stdin = None; drain(&mut self.stdout, &mut self.out); drain(&mut self.stderr, &mut self.err); } else { self.signal_due(now); } } match self.ended { Some((exit, until)) if (self.stdout.is_none() && self.stderr.is_none()) || now >= until => { Step::Done(self.finish(exit)) } Some((_, until)) => { self.arm(until, now); Step::Pending } None => Step::Pending, } } fn feed(&mut self) { let Some(fd) = &self.stdin else { return }; while self.written < self.input.len() { match write_quietly(fd, &self.input[self.written..]) { Ok(n) => self.written += n, Err(e) if e.kind() == ErrorKind::WouldBlock => return, Err(e) if e.kind() == ErrorKind::Interrupted => {} // EPIPE: the program stopped reading; the rest is dropped. Err(_) => break, } } self.stdin = None; } /// The timeout's signals: SIGTERM at the deadline, SIGKILL after the /// grace period. fn signal_due(&mut self, now: Instant) { match self.timeout { None if now >= self.deadline => { self.kill_group(libc::SIGTERM); let next = now + self.grace; self.timeout = Some((libc::SIGTERM, next)); self.arm(next, now); } Some((libc::SIGTERM, next)) if now >= next => { self.kill_group(libc::SIGKILL); self.timeout = Some((libc::SIGKILL, next)); } _ => {} } } /// The child's status if it ended, reaped. What is left of its group /// is killed first, while the unreaped child keeps the group's id. fn reap(&mut self) -> Option { let mut info = waitid(&self.pidfd, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT)?; self.kill_group(libc::SIGKILL); if let Some(reaped) = waitid(&self.pidfd, libc::WEXITED | libc::WNOHANG) { info = reaped; } untrack(self.pid); self.pid = 0; Some(info) } fn kill_group(&self, signal: i32) { if self.pid > 0 { // SAFETY: an unreaped child's id names its group; failure // (the group is gone) is harmless. unsafe { libc::killpg(self.pid, signal) }; } } /// Wake the waiter at `at` (at once if it passed). fn arm(&self, at: Instant, now: Instant) { let wait = at .saturating_duration_since(now) .max(Duration::from_millis(1)); let spec = libc::itimerspec { it_interval: libc::timespec { tv_sec: 0, tv_nsec: 0, }, it_value: libc::timespec { tv_sec: wait.as_secs() as libc::time_t, tv_nsec: wait.subsec_nanos() as libc::c_long, }, }; // SAFETY: a valid timerfd and spec; a failure only delays a wake. unsafe { libc::timerfd_settime(self.timer.as_raw_fd(), 0, &spec, std::ptr::null_mut()) }; } fn finish(&mut self, exit: Exit) -> Outcome { self.stdout = None; self.stderr = None; let files = self.scratch.as_ref().map(collect).unwrap_or_default(); self.scratch = None; Outcome { exit, stdout: std::mem::take(&mut self.out.data), stderr: std::mem::take(&mut self.err.data), stdout_cut: self.out.cut, stderr_cut: self.err.cut, files, } } } impl Drop for Child { fn drop(&mut self) { if self.pid <= 0 { return; } self.kill_group(libc::SIGKILL); if waitid(&self.pidfd, libc::WEXITED | libc::WNOHANG).is_none() { // Not dead yet (in an uninterruptible wait): reaped elsewhere, // never on the caller's thread. if let Ok(fd) = self.pidfd.try_clone() { reaper().lock().map(|r| r.send(fd)).ok(); } } untrack(self.pid); } } impl Capture { fn new(max: usize) -> Self { Self { data: Vec::new(), max, cut: false, } } fn take(&mut self, chunk: &[u8]) { let room = self.max.saturating_sub(self.data.len()); self.data.extend_from_slice(&chunk[..chunk.len().min(room)]); self.cut |= chunk.len() > room; } } /// Read `fd` until it would block; close it at its end. fn drain(fd: &mut Option, into: &mut Capture) { let mut buf = [0u8; 64 * 1024]; while let Some(f) = fd { match read_fd(f, &mut buf) { Ok(0) => *fd = None, Ok(n) => into.take(&buf[..n]), Err(e) if e.kind() == ErrorKind::WouldBlock => return, Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(_) => *fd = None, } } } fn read_fd(fd: &OwnedFd, buf: &mut [u8]) -> std::io::Result { // SAFETY: `buf` is valid for its length; `fd` is open. let n = unsafe { libc::read(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; if n < 0 { Err(std::io::Error::last_os_error()) } else { Ok(n as usize) } } /// Write to a pipe without SIGPIPE: the signal is blocked on this thread /// for the write, and one it raised is taken before the mask is restored, /// so a program that stopped reading gives `EPIPE`, never the end of ours. fn write_quietly(fd: &OwnedFd, data: &[u8]) -> std::io::Result { // SAFETY: plain libc calls on valid sets, buffer and descriptor. unsafe { let mut pipe: libc::sigset_t = std::mem::zeroed(); libc::sigemptyset(&mut pipe); libc::sigaddset(&mut pipe, libc::SIGPIPE); let mut old: libc::sigset_t = std::mem::zeroed(); libc::pthread_sigmask(libc::SIG_BLOCK, &pipe, &mut old); let n = libc::write(fd.as_raw_fd(), data.as_ptr().cast(), data.len()); let result = if n < 0 { Err(std::io::Error::last_os_error()) } else { Ok(n as usize) }; if libc::sigismember(&old, libc::SIGPIPE) == 0 { let zero = libc::timespec { tv_sec: 0, tv_nsec: 0, }; while libc::sigtimedwait(&pipe, std::ptr::null_mut(), &zero) == libc::SIGPIPE {} libc::pthread_sigmask(libc::SIG_SETMASK, &old, std::ptr::null_mut()); } result } } /// The child's status, if it ended (`flags` decides whether it is reaped). fn waitid(pidfd: &OwnedFd, flags: libc::c_int) -> Option { // SAFETY: a zeroed siginfo is a valid out-parameter; `pidfd` is open. unsafe { let mut info: libc::siginfo_t = std::mem::zeroed(); let id = pidfd.as_raw_fd() as libc::id_t; if libc::waitid(libc::P_PIDFD, id, &mut info, flags) != 0 || info.si_pid() == 0 { return None; } Some(match info.si_code { libc::CLD_EXITED => Exit::Exited(info.si_status()), _ => Exit::Signalled(info.si_status()), }) } } fn failure(program: &str, errno: i32) -> Failure { let message = format!("{program}: {}", std::io::Error::from_raw_os_error(errno)); match errno { libc::ENOENT | libc::ENOTDIR => Failure::NotFound(message), libc::EACCES | libc::EPERM => Failure::Denied(message), libc::E2BIG | libc::ENAMETOOLONG => Failure::BadArgument(message), _ => Failure::Failed(message), } } /// `posix_spawn` with an empty signal mask, default dispositions and a /// process group of the child's own; `stdio` become its 0, 1 and 2. /// Everything is built before the call: the child runs no Rust. fn posix_spawn( path: &CString, argv: &[CString], envp: &[CString], cwd: Option<&CString>, stdio: [&OwnedFd; 3], ) -> Result { let argv: Vec<*mut libc::c_char> = argv .iter() .map(|a| a.as_ptr().cast_mut()) .chain([std::ptr::null_mut()]) .collect(); let envp: Vec<*mut libc::c_char> = envp .iter() .map(|a| a.as_ptr().cast_mut()) .chain([std::ptr::null_mut()]) .collect(); // SAFETY: the attributes and file actions are initialised before use // and destroyed after; every pointer outlives the call. unsafe { let mut attr: libc::posix_spawnattr_t = std::mem::zeroed(); let mut actions: libc::posix_spawn_file_actions_t = std::mem::zeroed(); libc::posix_spawnattr_init(&mut attr); libc::posix_spawn_file_actions_init(&mut actions); let mut empty: libc::sigset_t = std::mem::zeroed(); libc::sigemptyset(&mut empty); let mut all: libc::sigset_t = std::mem::zeroed(); libc::sigfillset(&mut all); libc::posix_spawnattr_setsigmask(&mut attr, &empty); libc::posix_spawnattr_setsigdefault(&mut attr, &all); libc::posix_spawnattr_setpgroup(&mut attr, 0); let flags = libc::POSIX_SPAWN_SETSIGMASK | libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETPGROUP; libc::posix_spawnattr_setflags(&mut attr, flags as libc::c_short); for (fd, target) in stdio.iter().zip(0..) { libc::posix_spawn_file_actions_adddup2(&mut actions, fd.as_raw_fd(), target); } if let Some(dir) = cwd { libc::posix_spawn_file_actions_addchdir_np(&mut actions, dir.as_ptr()); } let mut pid: libc::pid_t = 0; let err = libc::posix_spawn( &mut pid, path.as_ptr(), &actions, &attr, argv.as_ptr(), envp.as_ptr(), ); libc::posix_spawn_file_actions_destroy(&mut actions); libc::posix_spawnattr_destroy(&mut attr); if err == 0 { Ok(pid) } else { Err(err) } } } /// A pipe, both ends close-on-exec: (read end, write end). fn pipe() -> Result<(OwnedFd, OwnedFd), Failure> { let mut fds = [0; 2]; // SAFETY: `fds` holds two descriptors; on success both are ours. unsafe { if libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) != 0 { return Err(Failure::Failed(format!( "pipe: {}", std::io::Error::last_os_error() ))); } Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) } } fn pidfd_open(pid: libc::pid_t) -> std::io::Result { // SAFETY: a plain syscall; on success the descriptor is ours. let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) }; if fd < 0 { Err(std::io::Error::last_os_error()) } else { // SAFETY: a fresh descriptor. Ok(unsafe { OwnedFd::from_raw_fd(fd as RawFd) }) } } fn timerfd() -> std::io::Result { // SAFETY: a plain call; on success the descriptor is ours. let fd = unsafe { libc::timerfd_create( libc::CLOCK_MONOTONIC, libc::TFD_NONBLOCK | libc::TFD_CLOEXEC, ) }; if fd < 0 { Err(std::io::Error::last_os_error()) } else { // SAFETY: a fresh descriptor. Ok(unsafe { OwnedFd::from_raw_fd(fd) }) } } fn nonblocking(fd: &OwnedFd) -> std::io::Result<()> { // SAFETY: plain fcntl calls on an open descriptor. unsafe { let flags = libc::fcntl(fd.as_raw_fd(), libc::F_GETFL); if flags < 0 || libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 { return Err(std::io::Error::last_os_error()); } } Ok(()) } /// A fresh `0700` directory under the temporary directory, holding /// `inputs` (never through a link, never over an existing file). fn scratch( inputs: &[(String, Vec)], outputs: Vec, max_file: usize, ) -> Result { let fail = |what: &str, e: std::io::Error| Failure::Failed(format!("scratch {what}: {e}")); let dir = loop { let dir = std::env::temp_dir().join(format!("louise-command-{:016x}", random())); match DirBuilder::new().mode(0o700).create(&dir) { Ok(()) => break dir, Err(e) if e.kind() == ErrorKind::AlreadyExists => {} Err(e) => return Err(fail("directory", e)), } }; let s = Scratch { dir, outputs, max_file, }; for (name, data) in inputs { OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .custom_flags(libc::O_NOFOLLOW) .open(s.dir.join(name)) .and_then(|mut f| f.write_all(data)) .map_err(|e| fail(name, e))?; } Ok(s) } /// The outputs the program left: regular files only (never through a /// link, never a FIFO that would block), at most `max_file` bytes each. fn collect(s: &Scratch) -> Vec { s.outputs .iter() .map(|name| { let file = OpenOptions::new() .read(true) .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) .open(s.dir.join(name)); let Ok(file) = file else { return Collected::Absent(name.clone()); }; match file.metadata() { Ok(m) if m.is_file() && m.len() > s.max_file as u64 => { Collected::TooLarge(name.clone(), m.len()) } Ok(m) if m.is_file() => { let mut data = Vec::new(); match file.take(s.max_file as u64 + 1).read_to_end(&mut data) { Ok(n) if n > s.max_file => Collected::TooLarge(name.clone(), n as u64), Ok(_) => Collected::Found(name.clone(), data), Err(_) => Collected::Absent(name.clone()), } } _ => Collected::Absent(name.clone()), } }) .collect() } fn random() -> u64 { let mut n = [0u8; 8]; // SAFETY: `n` is valid for 8 bytes; a short read leaves zeros, and the // creation loop retries a name that exists. unsafe { libc::getrandom(n.as_mut_ptr().cast(), n.len(), 0) }; u64::from_ne_bytes(n) ^ u64::from(std::process::id()) } /// The process groups of the children still running. static RUNNING: Mutex> = Mutex::new(Vec::new()); fn track(pid: libc::pid_t) { static AT_EXIT: std::sync::Once = std::sync::Once::new(); // SAFETY: `kill_all` is a valid `extern "C"` function for the program's // whole life. AT_EXIT.call_once(|| unsafe { libc::atexit(kill_all); }); RUNNING .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .push(pid); } fn untrack(pid: libc::pid_t) { let mut running = RUNNING .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); running.retain(|p| *p != pid); } /// Kill every group still running: the program is exiting, and what it /// started must not outlive it. pub extern "C" fn kill_all() { let running = RUNNING .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); for pid in running.iter() { // SAFETY: an unreaped child's id names its group. unsafe { libc::killpg(*pid, libc::SIGKILL) }; } } /// The reaper thread's queue: children killed but not dead yet, reaped /// with a blocking `waitid` away from any actor's thread. fn reaper() -> &'static Mutex> { static REAPER: OnceLock>> = OnceLock::new(); REAPER.get_or_init(|| { let (tx, rx) = channel::(); std::thread::Builder::new() .name("louise-reaper".into()) .spawn(move || { for pidfd in rx { while waitid(&pidfd, libc::WEXITED).is_none() && std::io::Error::last_os_error().kind() == ErrorKind::Interrupted { } } }) .expect("louise: cannot start the reaper thread"); Mutex::new(tx) }) } #[cfg(test)] mod tests { use super::*; fn spec(program: &str, args: &[&str]) -> Spec { Spec { program: program.into(), args: args.iter().map(|a| (*a).into()).collect(), env: vec![], dir: Dir::Inherit, stdin: vec![], max_stdout: 1 << 20, max_stderr: 1 << 16, timeout: Duration::from_secs(10), grace: Duration::from_millis(500), } } /// Run to the end with `poll(2)`, as the interpreter does. fn run(s: Spec) -> Result { let mut child = spawn(s)?; loop { if let Step::Done(o) = child.step() { return Ok(o); } let mut fds: Vec = child .fds() .into_iter() .map(|(fd, i)| libc::pollfd { fd, events: if i == Interest::Read { libc::POLLIN } else { libc::POLLOUT }, revents: 0, }) .collect(); // SAFETY: `fds` is valid for its length. unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, -1) }; } } #[test] fn plain_names() { assert!(plain_name("page.html")); for bad in ["", ".", "..", "a/b", "../x", "/etc/passwd", "a\0b"] { assert!(!plain_name(bad), "{bad:?}"); } } #[test] fn resolve_uses_only_the_given_path() { assert_eq!(resolve("/bin/sh", None), Some(PathBuf::from("/bin/sh"))); assert_eq!(resolve("sh", None), None); assert_eq!(resolve("sh", Some("relative:bin")), None); assert!(resolve("sh", Some("/nowhere:/usr/bin:/bin")).is_some()); } #[test] fn validate_refuses_nul_bad_names_and_paths() { let mut s = spec("/bin/echo", &["a\0b"]); assert!(matches!(validate(&s), Err(Failure::BadArgument(_)))); s = spec("/bin/echo", &[]); s.env = vec![("A=B".into(), "c".into())]; assert!(matches!(validate(&s), Err(Failure::BadArgument(_)))); s = spec("/bin/echo", &[]); s.dir = Dir::Scratch { inputs: vec![], outputs: vec!["../x".into()], max_file: 1, }; assert!(matches!(validate(&s), Err(Failure::BadArgument(_)))); } #[test] fn arguments_reach_the_program_unchanged() { let o = run(spec( "/usr/bin/printf", &["%s|", "a b", "$HOME", "x;y", "'q'"], )) .unwrap(); assert_eq!(o.exit, Exit::Exited(0)); assert_eq!(o.stdout, b"a b|$HOME|x;y|'q'|"); } #[test] fn the_environment_is_exactly_the_one_given() { let mut s = spec("/usr/bin/env", &[]); s.env = vec![("ONLY".into(), "this".into())]; assert_eq!(run(s).unwrap().stdout, b"ONLY=this\n"); } #[test] fn a_timeout_terminates_with_sigterm() { let mut s = spec("/bin/sleep", &["10"]); s.timeout = Duration::from_millis(100); let started = Instant::now(); let o = run(s).unwrap(); assert_eq!(o.exit, Exit::TimedOut(libc::SIGTERM)); assert!(started.elapsed() < Duration::from_millis(450)); } #[test] fn a_program_that_ignores_sigterm_is_killed_after_the_grace() { let mut s = spec("/bin/sh", &["-c", "trap '' TERM; sleep 10"]); s.timeout = Duration::from_millis(100); s.grace = Duration::from_millis(200); assert_eq!(run(s).unwrap().exit, Exit::TimedOut(libc::SIGKILL)); } #[test] fn output_past_the_cap_is_cut_and_the_program_still_ends() { let mut s = spec("/usr/bin/head", &["-c", "300000", "/dev/zero"]); s.max_stdout = 1000; let o = run(s).unwrap(); assert_eq!( (o.exit, o.stdout.len(), o.stdout_cut), (Exit::Exited(0), 1000, true) ); } #[test] fn stdin_a_program_does_not_read_is_dropped_quietly() { let mut s = spec("/usr/bin/head", &["-c", "1"]); s.stdin = vec![b'x'; 4 << 20]; let o = run(s).unwrap(); assert_eq!((o.exit, o.stdout), (Exit::Exited(0), b"x".to_vec())); } #[test] fn a_background_descendant_does_not_hold_the_run() { let mut s = spec("/bin/sh", &["-c", "sleep 10 & echo hi"]); s.grace = Duration::from_millis(200); let started = Instant::now(); let o = run(s).unwrap(); assert_eq!(o.stdout, b"hi\n"); assert!(started.elapsed() < Duration::from_secs(2)); } #[test] fn scratch_inputs_go_in_and_outputs_come_back() { let mut s = spec( "/bin/sh", &[ "-c", "cat in > out; head -c 50 /dev/zero > big; ln -s /etc/passwd link", ], ); s.dir = Dir::Scratch { inputs: vec![("in".into(), b"hello".to_vec())], outputs: vec!["out".into(), "big".into(), "missing".into(), "link".into()], max_file: 10, }; let o = run(s).unwrap(); assert_eq!( o.files, vec![ Collected::Found("out".into(), b"hello".to_vec()), Collected::TooLarge("big".into(), 50), Collected::Absent("missing".into()), Collected::Absent("link".into()), ] ); } #[test] fn a_missing_program_is_not_found() { assert!(matches!( run(spec("/nowhere/at/all", &[])), Err(Failure::NotFound(_)) )); assert!(matches!(run(spec("sh", &[])), Err(Failure::NotFound(_)))); } #[test] fn dropping_a_running_child_kills_and_reaps_it() { let child = spawn(spec("/bin/sleep", &["10"])).unwrap(); let pid = child.pid; drop(child); std::thread::sleep(Duration::from_millis(100)); assert!(!Path::new(&format!("/proc/{pid}")).exists()); } }