208 lines
7.0 KiB
Rust
208 lines
7.0 KiB
Rust
//! 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<i32>,
|
|
pub stdout: Vec<u8>,
|
|
pub stderr: Vec<u8>,
|
|
pub truncated: bool,
|
|
pub timed_out: bool,
|
|
}
|
|
|
|
// Nonblocking pipes avoid both unbounded output and reader threads held open by
|
|
// grandchildren. The child has a separate process group, cleaned even on success.
|
|
pub(crate) fn run(program: &str, args: &[String], timeout: Duration, cap: usize) -> Result<Output> {
|
|
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);
|
|
let mut child = command
|
|
.spawn()
|
|
.with_context(|| format!("spawn {program}"))?;
|
|
struct Group(u32);
|
|
impl Drop for Group {
|
|
fn drop(&mut self) {
|
|
// SAFETY: negative PID addresses only the group created for this child.
|
|
unsafe {
|
|
libc::kill(-(self.0 as i32), libc::SIGKILL);
|
|
}
|
|
}
|
|
}
|
|
let group = Group(child.id());
|
|
let mut stdout = child.stdout.take().context("missing stdout")?;
|
|
let mut stderr = child.stderr.take().context("missing stderr")?;
|
|
for fd in [stdout.as_raw_fd(), stderr.as_raw_fd()] {
|
|
// SAFETY: these are live owned pipe descriptors; flags are not pointers.
|
|
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
|
|
if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
|
|
drop(group);
|
|
let _ = child.wait();
|
|
return Err(std::io::Error::last_os_error().into());
|
|
}
|
|
}
|
|
fn drain(
|
|
pipe: &mut impl Read,
|
|
target: &mut Vec<u8>,
|
|
remaining: &mut usize,
|
|
truncated: &mut bool,
|
|
) -> Result<bool> {
|
|
let mut bytes = [0; 4096];
|
|
// Bound each pass too: a continuously writing child cannot starve timeout.
|
|
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)
|
|
}
|
|
let started = Instant::now();
|
|
let mut result = Output {
|
|
code: None,
|
|
stdout: vec![],
|
|
stderr: vec![],
|
|
truncated: false,
|
|
timed_out: false,
|
|
};
|
|
let mut remaining = cap;
|
|
let status = loop {
|
|
let drained = drain(
|
|
&mut stdout,
|
|
&mut result.stdout,
|
|
&mut remaining,
|
|
&mut result.truncated,
|
|
)
|
|
.and_then(|_| {
|
|
drain(
|
|
&mut stderr,
|
|
&mut result.stderr,
|
|
&mut remaining,
|
|
&mut result.truncated,
|
|
)
|
|
});
|
|
if let Err(e) = drained {
|
|
drop(group);
|
|
let _ = child.wait();
|
|
return Err(e);
|
|
}
|
|
match child.try_wait() {
|
|
Ok(Some(status)) => break status,
|
|
Ok(None) => {}
|
|
Err(e) => {
|
|
drop(group);
|
|
let _ = child.wait();
|
|
return Err(e.into());
|
|
}
|
|
}
|
|
if started.elapsed() >= timeout {
|
|
result.timed_out = true;
|
|
// SAFETY: this is the dedicated group created for this child.
|
|
unsafe {
|
|
libc::kill(-(child.id() as i32), libc::SIGKILL);
|
|
}
|
|
break child.wait()?;
|
|
}
|
|
thread::sleep(Duration::from_millis(5));
|
|
};
|
|
let pgid = child.id();
|
|
drop(group);
|
|
// SIGKILL delivery is asynchronous. A single WouldBlock is not EOF and
|
|
// does not prove that descendants have stopped. Bound both cleanup waiting
|
|
// and output draining, and withhold a successful exit code if unconfirmed.
|
|
let cleanup_started = Instant::now();
|
|
loop {
|
|
let stdout_closed = drain(
|
|
&mut stdout,
|
|
&mut result.stdout,
|
|
&mut remaining,
|
|
&mut result.truncated,
|
|
)?;
|
|
let stderr_closed = drain(
|
|
&mut stderr,
|
|
&mut result.stderr,
|
|
&mut remaining,
|
|
&mut result.truncated,
|
|
)?;
|
|
// SAFETY: signal zero only probes the dedicated process group.
|
|
let absent = unsafe { libc::kill(-(pgid as i32), 0) } == -1
|
|
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
|
|
if stdout_closed && stderr_closed && absent {
|
|
result.code = status.code();
|
|
break;
|
|
}
|
|
if cleanup_started.elapsed() >= Duration::from_millis(250) {
|
|
result.truncated |= !stdout_closed || !stderr_closed;
|
|
// None explicitly means no confirmed successful completion. This
|
|
// can also occur for lingering zombies: never guess their state.
|
|
result.code = None;
|
|
break;
|
|
}
|
|
thread::sleep(Duration::from_millis(5));
|
|
}
|
|
Ok(result)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[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();
|
|
}
|
|
}
|