#![allow(unsafe_code)]
use std::io;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
use std::thread;
use std::time::Duration;
use deadline_machines::Deadline;
pub fn wait_exited(pid: nix::unistd::Pid, block: bool) -> nix::Result<bool> {
use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid};
let mut flags = WaitPidFlag::WEXITED | WaitPidFlag::WNOWAIT;
if !block {
flags |= WaitPidFlag::WNOHANG;
}
Ok(!matches!(
waitid(Id::Pid(pid), flags)?,
WaitStatus::StillAlive
))
}
const POLL_INTERVAL: Duration = Duration::from_millis(100);
#[derive(Debug)]
pub struct Output {
pub success: bool,
pub exit_code: Option<i32>,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug)]
pub enum Outcome {
Exited(Output),
TimedOut,
}
pub fn run_supervised(cmd: &mut Command, timeout: Duration) -> io::Result<Outcome> {
let mut child = unsafe {
cmd.stdout(Stdio::piped())
.stderr(Stdio::piped())
.pre_exec(|| {
if libc::setpgid(0, 0) == -1 {
return Err(io::Error::last_os_error());
}
harden_fds();
Ok(())
})
.spawn()?
};
let mut stdout_thread = child.stdout.take().map(spawn_reader);
let mut stderr_thread = child.stderr.take().map(spawn_reader);
let pid = child.id() as libc::pid_t;
let clock = crate::sys::MonotonicClock::new();
let deadline = Deadline::after(clock.now(), timeout);
loop {
match wait_exited(nix::unistd::Pid::from_raw(pid), false) {
Ok(true) => {
unsafe { libc::kill(-pid, libc::SIGKILL) };
let status = child.wait();
let (stdout, stderr) = join_pipes(&mut stdout_thread, &mut stderr_thread);
let status = status?;
return Ok(Outcome::Exited(Output {
success: status.success(),
exit_code: status.code(),
stdout,
stderr,
}));
}
Ok(false) => {
if deadline.is_expired(clock.now()) {
reap_group(&mut child, pid);
join_pipes(&mut stdout_thread, &mut stderr_thread);
return Ok(Outcome::TimedOut);
}
thread::sleep(POLL_INTERVAL);
}
Err(e) => {
reap_group(&mut child, pid);
join_pipes(&mut stdout_thread, &mut stderr_thread);
return Err(io::Error::from(e));
}
}
}
}
const FD_GAP: libc::c_int = 1024;
pub fn close_dir_fds() {
let mut fd = 3;
let mut closed_run = 0;
while closed_run < FD_GAP {
unsafe {
let mut st: libc::stat = std::mem::zeroed();
if libc::fstat(fd, &raw mut st) == 0 {
closed_run = 0;
if st.st_mode & libc::S_IFMT == libc::S_IFDIR {
libc::close(fd);
}
} else {
closed_run += 1;
}
}
fd += 1;
}
}
pub fn harden_fds() {
let marked = unsafe {
libc::close_range(
3,
libc::c_uint::MAX,
libc::CLOSE_RANGE_CLOEXEC.cast_signed(),
)
};
if marked == -1 {
unsafe { libc::closefrom(3) };
}
}
fn reap_group(child: &mut std::process::Child, pid: libc::pid_t) {
let killed_group = unsafe { libc::kill(-pid, libc::SIGKILL) };
if killed_group == -1 {
unsafe { libc::kill(pid, libc::SIGKILL) };
}
let _ = child.wait();
}
fn spawn_reader(mut pipe: impl io::Read + Send + 'static) -> thread::JoinHandle<String> {
thread::spawn(move || {
let mut buf = String::new();
let _ = pipe.read_to_string(&mut buf);
buf
})
}
fn join_pipes(
stdout_thread: &mut Option<thread::JoinHandle<String>>,
stderr_thread: &mut Option<thread::JoinHandle<String>>,
) -> (String, String) {
let stdout = stdout_thread
.take()
.map(|t| t.join().unwrap_or_default())
.unwrap_or_default();
let stderr = stderr_thread
.take()
.map(|t| t.join().unwrap_or_default())
.unwrap_or_default();
(stdout, stderr)
}
#[cfg(test)]
mod tests;