use std::io;
use nix::sys::signal::{kill, killpg, Signal};
use nix::unistd::Pid;
use crate::error::Error;
pub(crate) fn set_process_group(std_cmd: &mut std::process::Command) {
use std::os::unix::process::CommandExt;
std_cmd.process_group(0); }
pub(crate) fn set_session(std_cmd: &mut std::process::Command) {
unsafe {
use std::os::unix::process::CommandExt;
std_cmd.pre_exec(|| {
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
pub(crate) fn kill_group(pgid: i32) -> Result<(), Error> {
#[cfg(test)]
if let Some(outcome) = fault::intercept_kill_group(pgid) {
return outcome;
}
signal_group(pgid, Signal::SIGKILL)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::{Cell, RefCell};
thread_local! {
static TERMED: RefCell<Option<Vec<i32>>> = const { RefCell::new(None) };
static KILLED: RefCell<Option<Vec<i32>>> = const { RefCell::new(None) };
static FAIL: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn record_kill_group() -> KillGroupRecorder {
KILLED.with(|k| *k.borrow_mut() = Some(Vec::new()));
KillGroupRecorder(())
}
#[cfg(target_os = "macos")]
pub(crate) fn record_term_group() -> TermGroupRecorder {
TERMED.with(|t| *t.borrow_mut() = Some(Vec::new()));
TermGroupRecorder(())
}
#[cfg(target_os = "macos")]
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct TermGroupRecorder(());
#[cfg(target_os = "macos")]
impl TermGroupRecorder {
pub(crate) fn termed(&self) -> Vec<i32> {
TERMED.with(|t| t.borrow().clone().expect("the recorder is live"))
}
}
#[cfg(target_os = "macos")]
impl Drop for TermGroupRecorder {
fn drop(&mut self) {
TERMED.with(|t| *t.borrow_mut() = None);
}
}
pub(super) fn intercept_term_group(pgid: i32) -> bool {
TERMED.with(|t| t.borrow_mut().as_mut().map(|termed| termed.push(pgid)).is_some())
}
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct KillGroupRecorder(());
impl KillGroupRecorder {
pub(crate) fn fail_with_unassessable(&self) {
FAIL.with(|f| f.set(true));
}
pub(crate) fn killed(&self) -> Vec<i32> {
KILLED.with(|k| k.borrow().clone().expect("the recorder is live"))
}
#[track_caller]
pub(crate) fn assert_killed_only(&self, pgid: i32) {
let killed = self.killed();
assert!(
!killed.is_empty() && killed.iter().all(|g| *g == pgid),
"expected only killpg({pgid}), at least once, got {killed:?}"
);
}
}
impl Drop for KillGroupRecorder {
fn drop(&mut self) {
KILLED.with(|k| *k.borrow_mut() = None);
FAIL.with(|f| f.set(false));
}
}
pub(super) fn intercept_kill_group(pgid: i32) -> Option<Result<(), crate::error::Error>> {
KILLED.with(|k| {
k.borrow_mut().as_mut().map(|killed| {
killed.push(pgid);
if FAIL.with(|f| f.get()) {
Err(crate::error::Error::Unassessable {
detail: "forced by a test".into(),
source: None,
})
} else {
Ok(())
}
})
})
}
}
pub(crate) fn term_group(pgid: i32) -> Result<(), Error> {
#[cfg(test)]
if fault::intercept_term_group(pgid) {
return Ok(());
}
signal_group(pgid, Signal::SIGTERM)
}
fn signal_group(pgid: i32, signal: Signal) -> Result<(), Error> {
if pgid <= 0 {
return Err(Error::Unassessable {
detail: format!(
"process group {pgid} is not a valid group id to signal (0 addresses this \
process's own group; negative wraps to a broadcast or double-negation hazard)"
),
source: None,
});
}
match killpg(Pid::from_raw(pgid), signal) {
Ok(()) => {}
Err(nix::errno::Errno::ESRCH) => {}
Err(nix::errno::Errno::EPERM) => {
_ = signal_direct(pgid, signal);
}
Err(e) => return Err(Error::Io(io::Error::from(e))),
}
verify(pgid, signal)
}
fn verify(pgid: i32, signal: Signal) -> Result<(), Error> {
match group::state(pgid, signal) {
group::GroupState::Cleared => Ok(()),
group::GroupState::Refused { refused, unassessable } => {
let list = |pids: &[u32]| pids.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(", ");
let mut detail = format!(
"{signal} did not clear {n} member(s) of process group {pgid} (pid {list}); the \
tree is still up and this process cannot bring it down",
n = refused.len(),
list = list(&refused),
);
if !unassessable.is_empty() {
detail.push_str(&format!(
"; additionally, {n} member(s) could not be assessed at all (pid {list})",
n = unassessable.len(),
list = list(&unassessable),
));
}
Err(Error::Containment { detail })
}
group::GroupState::Unlistable {
source: Some(source), ..
} if source.kind() == io::ErrorKind::Unsupported => Err(Error::Unsupported {
op: format!("listing process group {pgid}"),
platform: std::env::consts::OS,
detail: source.to_string(),
}),
group::GroupState::Unlistable { detail, source } => Err(Error::Unassessable { detail, source }),
}
}
fn signal_direct(pid: i32, signal: Signal) -> io::Result<()> {
match kill(Pid::from_raw(pid), signal) {
Ok(()) | Err(nix::errno::Errno::ESRCH) => Ok(()),
Err(e) => {
log::debug!("containment::unix::signal_direct: kill({pid}, {signal}) failed: {e}");
Err(io::Error::from(e))
}
}
}
#[path = "unix/group.rs"]
mod group;
#[cfg(test)]
#[path = "unix_tests.rs"]
mod unix_tests;