use std::ffi::OsStr;
use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
use rustix::fs::OFlags;
use rustix::process::{Pid, WaitOptions};
use super::child::{self, Prepared};
use super::fds::replace_stdio;
use super::run_loop::Loop;
use super::signals;
use super::{Exit, Shim};
use crate::child::spawn::fork_exec::{Program, Spawned};
use crate::elevation::shim::codes;
use crate::elevation::shim::hooks::{Gate, Inject};
use crate::elevation::shim::protocol::{Errno, Frame, NotExecuted, ShimArgs};
use crate::elevation::shim::step::{conclude, LoopState};
use crate::os_process::linux::fork::{
clone_with_pidfd, fails_with, fallback, fork_with_pidfd, CloneKind, Fork, ForkFn,
};
unsafe fn clone3_enosys(kind: CloneKind) -> Result<Fork, i32> {
unsafe { fallback(|_| fails_with(libc::ENOSYS), clone_with_pidfd, kind) }
}
fn pipe() -> std::io::Result<(OwnedFd, OwnedFd)> {
let (reader, writer) = std::io::pipe()?;
Ok((reader.into(), writer.into()))
}
struct ReapingThread {
go: OwnedFd,
done: OwnedFd,
}
fn spawn_reaping_thread(log_fd: Option<RawFd>) -> std::io::Result<ReapingThread> {
let (go_rx, go) = pipe()?;
let (done, done_tx) = pipe()?;
std::thread::Builder::new()
.name("cosca-shim-host-reaper".into())
.spawn(move || {
let mut released = [0u8; 1];
_ = rustix::io::read(&go_rx, &mut released);
let reaped = rustix::process::wait(WaitOptions::empty());
if let Some(fd) = log_fd {
let pid = reaped.ok().flatten().map_or(-1, |(pid, _)| pid.as_raw_nonzero().get());
let line = format!("host thread: reaped pid {pid}\n");
_ = rustix::io::write(unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) }, line.as_bytes());
}
_ = rustix::io::write(&done_tx, b"r");
})?;
Ok(ReapingThread { go, done })
}
fn open_failure(path: &std::path::Path) -> OwnedFd {
rustix::fs::open(
path,
OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.unwrap_or_else(|e| {
panic!(
"the loop-failure seam: cannot open {}: {}",
path.display(),
crate::error::Report(&e)
)
})
}
pub(super) fn start_and_supervise(shim: &mut Shim, args: &ShimArgs, owner: &OwnedFd) -> Result<i32, Exit> {
let saved_mask = signals::block_all();
let inherited = shim.inherited.take().expect("the signals are caught before hello");
let pipes = (|| -> std::io::Result<_> {
if shim.injected(Inject::PipeFails) {
return Err(std::io::Error::from_raw_os_error(libc::EMFILE));
}
pipe()
})();
let (release_rx, release_tx) = match pipes {
Ok(pipes) => pipes,
Err(e) => {
return Err(shim.not_executed(
NotExecuted::SetupFailed(Errno(os_error(&e))),
"cannot create a pipe",
&e,
))
}
};
signals::reset_sigchld();
let search = args.search_path.clone().or_else(|| std::env::var_os("PATH"));
let found = match crate::resolve::posix::lookup(std::path::Path::new(&args.program), None, search.as_deref()) {
Ok(found) => found,
Err(error) => {
let errno = crate::resolve::posix::errno_of(&error);
let e = std::io::Error::from_raw_os_error(errno);
let why = args.program.to_string_lossy().into_owned();
return Err(shim.not_executed(NotExecuted::ExecFailed(Errno(errno)), &why, &e));
}
};
let argv: Vec<&OsStr> = std::iter::once(args.program.as_os_str())
.chain(args.args.iter().map(|a| a.as_os_str()))
.collect();
let paths: Vec<&OsStr> = std::iter::once(found.path.as_os_str())
.chain(found.later.iter().map(|p| p.as_os_str()))
.collect();
let program =
Program::new(&paths, &argv, std::env::vars_os()).expect("argv carries no NUL: ShimArgs::parse checked");
let gate_path = shim.hooks.and_then(|h| h.child_gate());
let prepared = Prepared::new(
inherited,
saved_mask,
(release_rx.as_raw_fd(), release_tx.as_raw_fd()),
shim.log.fd(),
gate_path.as_deref().map(|p| p.as_os_str()),
shim.hooks.is_some_and(|h| h.child_fault()),
shim.injected(Inject::ChildSetupFails),
);
let reaper = if shim.injected(Inject::ReapingHostThread) {
match spawn_reaping_thread(shim.log.fd()) {
Ok(reaper) => Some(reaper),
Err(e) => {
return Err(shim.not_executed(
NotExecuted::SetupFailed(Errno(os_error(&e))),
"cannot start the host thread",
&e,
))
}
}
} else {
None
};
shim.gate(Gate::BeforeClone);
let fork: ForkFn = if shim.injected(Inject::ForkFails) {
|_| fails_with(libc::EAGAIN)
} else if shim.injected(Inject::Clone3Enosys) {
clone3_enosys
} else {
fork_with_pidfd
};
let spawned = {
let _lock = crate::child::spawn::spawn_lock();
child::spawn(&prepared, &program, fork)
};
let Spawned { child, mut status } = match spawned {
Ok(spawned) => spawned,
Err(error) => {
let (report, what, errno) = child::not_spawned(error);
let e = std::io::Error::from_raw_os_error(errno);
return Err(shim.not_executed(report, what, &e));
}
};
drop(release_rx);
shim.log
.line(format_args!("forked child pid={} via {:?}", child.pid, child.path));
signals::restore(&saved_mask);
shim.check_owner(owner, Some(&child))?;
drop(release_tx);
if let Some(reaper) = &reaper {
_ = rustix::io::write(&reaper.go, b"g");
}
shim.gate(Gate::AfterFork);
if shim.injected(Inject::DieAfterFork) {
shim.log.line(format_args!("seam: shim exits after fork"));
return Err(Exit(codes::SUPERVISION));
}
shim.log
.line(format_args!("program pid={} (possibly started)", child.pid));
if shim.injected(Inject::StealReap) {
_ = Pid::from_raw(child.pid).map(|pid| rustix::process::waitpid(Some(pid), WaitOptions::empty()));
shim.log.line(format_args!("seam: reaped elsewhere"));
}
let failure = shim.hooks.and_then(|h| h.loop_failure()).map(|p| open_failure(&p));
replace_stdio(&shim.log);
shim.gate(Gate::BeforeLoop);
let state = LoopState::new(shim.hooks.is_some());
let finished = Loop {
log: &shim.log,
conn: shim.conn().as_fd(),
owner: owner.as_fd(),
child: &child,
wake: shim.wake().rx.as_fd(),
status: &mut status,
failure,
host_reap_done: reaper.as_ref().map(|r| r.done.as_fd()),
state,
}
.run();
let verdict = conclude(finished.report, finished.reaped, finished.lost);
match verdict.frame {
Frame::NotExecuted(n) => shim
.log
.line(format_args!("refused 117: the program was not executed ({n:?})")),
Frame::StatusLost => shim.log.line(format_args!(
"status lost: the possibly-started program's status was collected by someone else"
)),
Frame::Lost(status) => shim.log.line(format_args!(
"lost: the possibly-started program was killed, status {status}"
)),
_ => {}
}
if finished.conn_open {
shim.send(verdict.frame);
}
Ok(verdict.exit_code)
}
fn os_error(e: &std::io::Error) -> i32 {
e.raw_os_error().unwrap_or(libc::EIO)
}