#![allow(unsafe_code)]
use crate::error::{Error, Result};
use deadline_machines::Deadline;
use std::ffi::CString;
use std::fmt;
use std::io::{self, Read};
use std::os::fd::AsRawFd;
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::process::{Child, ChildStderr, ChildStdout, Command, Stdio};
use std::time::{Duration, Instant};
const DEFAULT_PATH: &str = "/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin";
const TICK: Duration = Duration::from_millis(50);
const DRAIN_GRACE: Duration = Duration::from_millis(500);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Stream {
Stdout,
Stderr,
}
type Sink<'a> = Box<dyn FnMut(Stream, &[u8]) + 'a>;
enum Output<'a> {
Capture,
Stream(Sink<'a>),
Inherit,
}
enum Limit {
Timeout(Duration),
Deadline(Instant),
}
pub struct Exec<'a> {
argv: Vec<String>,
env: Vec<(String, String)>,
cwd: Option<String>,
limit: Option<Limit>,
output: Output<'a>,
}
impl<'a> Exec<'a> {
pub fn argv<I, S>(argv: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
argv: argv.into_iter().map(Into::into).collect(),
env: Vec::new(),
cwd: None,
limit: None,
output: Output::Capture,
}
}
pub fn shell(script: impl Into<String>) -> Self {
Self::argv(["/bin/sh".to_string(), "-c".to_string(), script.into()])
}
#[must_use]
pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.env.push((key.into(), value.into()));
self
}
#[must_use]
pub fn envs<I, K, V>(mut self, vars: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<String>,
{
self.env
.extend(vars.into_iter().map(|(k, v)| (k.into(), v.into())));
self
}
#[must_use]
pub fn cwd(mut self, dir: impl Into<String>) -> Self {
self.cwd = Some(dir.into());
self
}
#[must_use]
pub const fn timeout(mut self, timeout: Duration) -> Self {
self.limit = Some(Limit::Timeout(timeout));
self
}
#[must_use]
pub const fn deadline(mut self, deadline: Instant) -> Self {
self.limit = Some(Limit::Deadline(deadline));
self
}
#[must_use]
pub fn on_output(mut self, sink: impl FnMut(Stream, &[u8]) + 'a) -> Self {
self.output = Output::Stream(Box::new(sink));
self
}
#[must_use]
pub fn inherit_stdio(mut self) -> Self {
self.output = Output::Inherit;
self
}
}
impl fmt::Debug for Exec<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let output = match self.output {
Output::Capture => "capture",
Output::Stream(_) => "stream",
Output::Inherit => "inherit",
};
f.debug_struct("Exec")
.field("argv", &self.argv)
.field("env", &self.env)
.field("cwd", &self.cwd)
.field("output", &output)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Exit {
Code(i32),
Signal(i32),
TimedOut,
}
impl Exit {
#[must_use]
pub fn success(self) -> bool {
self == Self::Code(0)
}
#[must_use]
pub const fn code(self) -> Option<i32> {
match self {
Self::Code(code) => Some(code),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecOutput {
pub exit: Exit,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub duration: Duration,
}
pub fn run(jid: i32, exec: Exec<'_>) -> Result<ExecOutput> {
let Exec {
argv,
env,
cwd,
limit,
mut output,
} = exec;
let Some(program) = argv.first() else {
return Err(Error::InvalidArgument("exec needs a command".into()));
};
let cwd = CString::new(cwd.as_deref().unwrap_or("/"))?;
let inherit = matches!(output, Output::Inherit);
let mut cmd = Command::new(program);
cmd.args(&argv[1..])
.env_clear()
.env("PATH", DEFAULT_PATH)
.env("HOME", "/root")
.env("USER", "root")
.env("SHELL", "/bin/sh");
if inherit {
if let Some(term) = std::env::var_os("TERM") {
cmd.env("TERM", term);
}
cmd.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
} else {
cmd.process_group(0)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
}
cmd.envs(env);
unsafe {
cmd.pre_exec(move || {
crate::proc::close_dir_fds();
if libc::jail_attach(jid) != 0 {
return Err(io::Error::last_os_error());
}
if libc::chdir(cwd.as_ptr()) != 0 {
return Err(io::Error::last_os_error());
}
crate::proc::harden_fds();
Ok(())
});
}
let clock = crate::sys::MonotonicClock::new();
let started = Instant::now();
let deadline = match limit {
None => Deadline::never(),
Some(Limit::Timeout(timeout)) => Deadline::after(clock.now(), timeout),
Some(Limit::Deadline(at)) => {
Deadline::after(clock.now(), at.saturating_duration_since(started))
}
};
let mut child = cmd
.spawn()
.map_err(|e| Error::JailExecFailed(format!("cannot run '{program}' in jail {jid}: {e}")))?;
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let status = if inherit {
wait(&mut child, jid, &clock, deadline)?
} else {
let mut sink = |stream: Stream, bytes: &[u8]| match &mut output {
Output::Stream(callback) => callback(stream, bytes),
_ => match stream {
Stream::Stdout => stdout.extend_from_slice(bytes),
Stream::Stderr => stderr.extend_from_slice(bytes),
},
};
supervise(&mut child, jid, &clock, deadline, &mut sink)?
};
let exit = match status {
Waited::TimedOut => Exit::TimedOut,
Waited::Exited(status) => match (status.code(), status.signal()) {
(Some(code), _) => Exit::Code(code),
(None, Some(signal)) => Exit::Signal(signal),
(None, None) => Exit::Code(-1),
},
};
Ok(ExecOutput {
exit,
stdout,
stderr,
duration: started.elapsed(),
})
}
enum Waited {
Exited(std::process::ExitStatus),
TimedOut,
}
fn supervise(
child: &mut Child,
jid: i32,
clock: &crate::sys::MonotonicClock,
deadline: Deadline,
sink: &mut dyn FnMut(Stream, &[u8]),
) -> Result<Waited> {
let mut pipes = Pipes {
stdout: child.stdout.take(),
stderr: child.stderr.take(),
};
let mut exited = None;
let mut drain = Deadline::never();
while pipes.any_open() {
let now = clock.now();
if exited.is_none() {
if let Some(status) = child.try_wait()? {
exited = Some(status);
drain = Deadline::after(now, DRAIN_GRACE);
} else if deadline.is_expired(now) {
kill_everything(child, || kill_jail_processes(jid));
return Ok(Waited::TimedOut);
}
}
if drain.is_expired(now) {
break;
}
let budget = if exited.is_none() { deadline } else { drain };
let wake = budget.clamp_sleep(now, TICK);
pipes.pump(wake, sink)?;
}
drop(pipes);
match exited {
Some(status) => Ok(Waited::Exited(status)),
None => wait(child, jid, clock, deadline),
}
}
fn wait(
child: &mut Child,
jid: i32,
clock: &crate::sys::MonotonicClock,
deadline: Deadline,
) -> Result<Waited> {
if deadline.expires_at().is_none() {
return Ok(Waited::Exited(child.wait()?));
}
loop {
if let Some(status) = child.try_wait()? {
return Ok(Waited::Exited(status));
}
let now = clock.now();
if deadline.is_expired(now) {
kill_everything(child, || kill_jail_processes(jid));
return Ok(Waited::TimedOut);
}
let nap = deadline.clamp_sleep(now, TICK);
std::thread::sleep(nap);
}
}
fn kill_everything(child: &mut Child, sweep: impl FnOnce()) {
if let Ok(pgid) = libc::pid_t::try_from(child.id()) {
unsafe { libc::kill(-pgid, libc::SIGKILL) };
}
let _ = child.kill(); let _ = child.wait(); sweep();
}
pub fn kill_jail_processes(jid: i32) {
let jid = jid.to_string();
for _ in 0..50 {
let _ = Command::new("/bin/pkill")
.args(["-KILL", "-j", &jid])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
let survivors = Command::new("/bin/pgrep")
.args(["-j", &jid])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
if survivors.map_or(true, |s| s.code() == Some(1)) {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
}
struct Pipes {
stdout: Option<ChildStdout>,
stderr: Option<ChildStderr>,
}
impl Pipes {
const fn any_open(&self) -> bool {
self.stdout.is_some() || self.stderr.is_some()
}
fn pump(&mut self, wait: Duration, sink: &mut dyn FnMut(Stream, &[u8])) -> Result<()> {
let mut fds = Vec::with_capacity(2);
if let Some(out) = &self.stdout {
fds.push(pollfd(out.as_raw_fd()));
}
if let Some(err) = &self.stderr {
fds.push(pollfd(err.as_raw_fd()));
}
let timeout = libc::c_int::try_from(wait.as_millis()).unwrap_or(libc::c_int::MAX);
let nfds = libc::nfds_t::try_from(fds.len()).unwrap_or(0);
let ready = unsafe { libc::poll(fds.as_mut_ptr(), nfds, timeout) };
if ready < 0 {
let err = io::Error::last_os_error();
return if err.kind() == io::ErrorKind::Interrupted {
Ok(())
} else {
Err(err.into())
};
}
let mut buf = [0u8; 16 * 1024];
for pfd in fds {
if pfd.revents == 0 {
continue;
}
if self
.stdout
.as_ref()
.is_some_and(|p| p.as_raw_fd() == pfd.fd)
{
read_chunk(&mut self.stdout, Stream::Stdout, &mut buf, sink);
} else {
read_chunk(&mut self.stderr, Stream::Stderr, &mut buf, sink);
}
}
Ok(())
}
}
const fn pollfd(fd: libc::c_int) -> libc::pollfd {
libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
}
}
fn read_chunk<R: Read>(
pipe: &mut Option<R>,
stream: Stream,
buf: &mut [u8],
sink: &mut dyn FnMut(Stream, &[u8]),
) {
let Some(reader) = pipe else {
return;
};
match reader.read(buf) {
Ok(0) => *pipe = None,
Ok(n) => sink(stream, &buf[..n]),
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(_) => *pipe = None,
}
}
#[cfg(test)]
mod tests;