use std::io;
use nix::sys::signal::Signal;
use crate::containment::GroupRoot;
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(steps: &mut crate::child::spawn::in_child::InChild) {
steps.session();
}
pub(crate) fn kill_group(pgid: i32, root: &GroupRoot<'_>) -> Result<(), Error> {
#[cfg(test)]
if let Some(outcome) = fault::intercept_kill_group(pgid) {
return outcome;
}
signal_group(pgid, Signal::SIGKILL, root)
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::{Cell, RefCell};
#[cfg(target_os = "linux")]
pub(crate) use super::group::fault::{list_instead, set_after_listing};
type OnSend = Box<dyn FnMut(i32)>;
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) };
static ON_TERM: RefCell<Option<OnSend>> = const { RefCell::new(None) };
static ON_KILL: RefCell<Option<OnSend>> = const { RefCell::new(None) };
static REFUSE_GROUP: Cell<bool> = const { Cell::new(false) };
static REFUSE_FLAG: Cell<bool> = const { Cell::new(false) };
static GROUP_PROBE_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
static PROBES_REFUSED: Cell<bool> = const { Cell::new(false) };
}
#[cfg(target_os = "linux")]
pub(crate) fn refuse_probes() -> Refused {
PROBES_REFUSED.with(|r| r.set(true));
Refused(())
}
pub(super) fn probes_refused() -> bool {
PROBES_REFUSED.with(Cell::get)
}
pub(crate) fn refuse_group_sends() -> Refused {
REFUSE_GROUP.with(|r| r.set(true));
Refused(())
}
#[cfg(target_os = "linux")]
pub(crate) fn refuse_pidfd_group_flag() -> Refused {
REFUSE_FLAG.with(|r| r.set(true));
Refused(())
}
#[cfg(target_os = "linux")]
pub(crate) fn answer_group_probes_with(errno: i32) -> Refused {
GROUP_PROBE_ERRNO.with(|e| e.set(Some(errno)));
Refused(())
}
#[must_use = "the sends go out again as soon as the guard is dropped"]
pub(crate) struct Refused(());
impl Drop for Refused {
fn drop(&mut self) {
REFUSE_GROUP.with(|r| r.set(false));
REFUSE_FLAG.with(|r| r.set(false));
GROUP_PROBE_ERRNO.with(|e| e.set(None));
PROBES_REFUSED.with(|r| r.set(false));
}
}
pub(super) fn group_sends_refused() -> bool {
REFUSE_GROUP.with(Cell::get)
}
pub(super) fn group_probe_errno() -> Option<i32> {
GROUP_PROBE_ERRNO.with(Cell::get)
}
pub(super) fn pidfd_group_flag_refused() -> bool {
REFUSE_FLAG.with(Cell::get)
}
fn fire(slot: &'static std::thread::LocalKey<RefCell<Option<OnSend>>>, pgid: i32) {
let Some(mut hook) = slot.with(|h| h.borrow_mut().take()) else {
return;
};
hook(pgid);
slot.with(|h| *h.borrow_mut() = Some(hook));
}
pub(crate) fn record_kill_group() -> KillGroupRecorder {
KILLED.with(|k| *k.borrow_mut() = Some(Vec::new()));
KillGroupRecorder(())
}
pub(crate) fn record_term_group() -> TermGroupRecorder {
TERMED.with(|t| *t.borrow_mut() = Some(Vec::new()));
TermGroupRecorder(())
}
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct TermGroupRecorder(());
impl TermGroupRecorder {
pub(crate) fn termed(&self) -> Vec<i32> {
TERMED.with(|t| t.borrow().clone().expect("the recorder is live"))
}
pub(crate) fn on_send(&self, hook: impl FnMut(i32) + 'static) {
ON_TERM.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
}
}
impl Drop for TermGroupRecorder {
fn drop(&mut self) {
TERMED.with(|t| *t.borrow_mut() = None);
ON_TERM.with(|h| *h.borrow_mut() = None);
}
}
pub(super) fn intercept_term_group(pgid: i32) -> bool {
let recorded = TERMED.with(|t| t.borrow_mut().as_mut().map(|termed| termed.push(pgid)).is_some());
if recorded {
fire(&ON_TERM, pgid);
}
recorded
}
#[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"))
}
pub(crate) fn on_send(&self, hook: impl FnMut(i32) + 'static) {
ON_KILL.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
}
#[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));
ON_KILL.with(|h| *h.borrow_mut() = None);
}
}
pub(super) fn intercept_kill_group(pgid: i32) -> Option<Result<(), crate::error::Error>> {
let recorded = KILLED.with(|k| k.borrow_mut().as_mut().map(|killed| killed.push(pgid)).is_some());
if !recorded {
return None;
}
fire(&ON_KILL, pgid);
Some(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, root: &GroupRoot<'_>) -> Result<(), Error> {
#[cfg(test)]
if fault::intercept_term_group(pgid) {
return Ok(());
}
signal_group(pgid, Signal::SIGTERM, root)
}
fn signal_group(pgid: i32, signal: Signal, root: &GroupRoot<'_>) -> 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 send_to_group(pgid, signal, root)? {
Ok(()) => {}
Err(nix::errno::Errno::ESRCH) => {}
Err(nix::errno::Errno::EPERM) => {
_ = signal_direct(pgid, signal, root);
}
Err(e) => return Err(Error::Io(io::Error::from(e))),
}
verify(pgid, signal, root)
}
pub(crate) fn send_to_group(
pgid: i32,
signal: Signal,
root: &GroupRoot<'_>,
) -> Result<Result<(), nix::errno::Errno>, Error> {
#[cfg(target_os = "linux")]
if let Some(pidfd) = root.pidfd() {
match pidfd_signal(pidfd, signal, Through::Group) {
Err(nix::errno::Errno::EINVAL) => log::debug!(
"containment::unix: the kernel refused PIDFD_SIGNAL_PROCESS_GROUP (expected below Linux 6.9), so process group {pgid} is signalled by its number"
),
sent => return Ok(sent),
}
}
root.check().map_err(|why| Error::Unassessable {
detail: format!(
"process group {pgid}: {why}, so its number may name another group, and {signal} was not sent by it"
),
source: None,
})?;
Ok(send_signal(Target::Group, Sys::Group(pgid), signal))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(not(test), allow(dead_code, reason = "only a test build records it"))]
pub(crate) enum Target {
Group,
Leader,
Member(u32),
#[cfg(target_os = "linux")]
LeafMember(u32),
}
#[derive(Clone, Copy)]
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only Linux sends through a pidfd")
)]
pub(crate) enum Sys<'a> {
Pidfd(std::os::fd::BorrowedFd<'a>, libc::c_uint),
Group(i32),
Process(i32),
}
pub(crate) fn send_signal(target: Target, sys: Sys<'_>, signal: Signal) -> nix::Result<()> {
send(target, sys, signal as libc::c_int)
}
pub(crate) fn probe_signal(target: Target, sys: Sys<'_>) -> nix::Result<()> {
send(target, sys, 0)
}
fn send(target: Target, sys: Sys<'_>, signo: libc::c_int) -> nix::Result<()> {
use nix::errno::Errno;
#[cfg(test)]
let seam = match (target, sys) {
(Target::Group, Sys::Pidfd(..)) if fault::pidfd_group_flag_refused() => Some(Errno::EINVAL),
(Target::Group, Sys::Pidfd(..)) if signo == 0 => fault::group_probe_errno().map(Errno::from_raw),
(Target::Group, _) if signo != 0 && fault::group_sends_refused() => Some(Errno::EPERM),
(Target::Member(_), _) if signo == 0 && fault::probes_refused() => Some(Errno::EPERM),
_ => None,
};
#[cfg(not(test))]
let seam: Option<Errno> = None;
let sent = match (seam, sys) {
(Some(errno), _) => Err(errno),
#[cfg(target_os = "linux")]
(None, Sys::Pidfd(pidfd, flags)) => pidfd_send_syscall(pidfd, signo, flags),
#[cfg(not(target_os = "linux"))]
(None, Sys::Pidfd(..)) => unreachable!("only Linux sends through a pidfd"),
(None, Sys::Group(pgid)) => Errno::result(unsafe { libc::killpg(pgid, signo) }).map(drop),
(None, Sys::Process(pid)) => Errno::result(unsafe { libc::kill(pid, signo) }).map(drop),
};
#[cfg(test)]
{
use crate::send_log::{GroupStep, Route};
let route = match sys {
Sys::Pidfd(..) => Route::Pidfd,
Sys::Group(_) | Sys::Process(_) => Route::Number,
};
match target {
Target::Group => crate::send_log::record_group(GroupStep::Group(route, signo)),
Target::Leader => crate::send_log::record_group(GroupStep::Leader(route, signo)),
Target::Member(pid) => crate::send_log::record_group(GroupStep::Member(route, pid, signo)),
#[cfg(target_os = "linux")]
Target::LeafMember(pid) => crate::containment::cgroup::fault::record_member_term(sys, pid, signo),
}
}
#[cfg(not(test))]
let _ = target;
sent
}
#[cfg(target_os = "linux")]
pub(crate) fn pidfd_signal_group(pidfd: std::os::fd::BorrowedFd<'_>, signal: Signal) -> Result<(), nix::errno::Errno> {
pidfd_signal(pidfd, signal, Through::Group)
}
#[cfg(target_os = "linux")]
#[derive(Clone, Copy, PartialEq, Eq)]
enum Through {
Group,
Leader,
}
#[cfg(target_os = "linux")]
pub(crate) fn pidfd_group_has_member(pidfd: std::os::fd::BorrowedFd<'_>) -> Option<bool> {
match probe_signal(Target::Group, Sys::Pidfd(pidfd, libc::PIDFD_SIGNAL_PROCESS_GROUP)) {
Ok(()) => Some(true),
Err(nix::errno::Errno::ESRCH) => Some(false),
Err(nix::errno::Errno::EINVAL) => None,
Err(e) => {
log::debug!("containment::unix: a signal-0 send to a process group through its root's pidfd answered {e}");
None
}
}
}
#[cfg(target_os = "linux")]
fn pidfd_signal(pidfd: std::os::fd::BorrowedFd<'_>, signal: Signal, through: Through) -> Result<(), nix::errno::Errno> {
let (target, flags) = match through {
Through::Group => (Target::Group, libc::PIDFD_SIGNAL_PROCESS_GROUP),
Through::Leader => (Target::Leader, 0),
};
send_signal(target, Sys::Pidfd(pidfd, flags), signal)
}
#[cfg(target_os = "linux")]
pub(crate) fn pidfd_signal_member(
pidfd: std::os::fd::BorrowedFd<'_>,
pid: crate::identity::RawPid,
signal: Signal,
) -> Result<(), nix::errno::Errno> {
send_signal(Target::Member(pid), Sys::Pidfd(pidfd, 0), signal)
}
#[cfg(target_os = "linux")]
fn pidfd_send_syscall(
pidfd: std::os::fd::BorrowedFd<'_>,
signo: libc::c_int,
flags: libc::c_uint,
) -> Result<(), nix::errno::Errno> {
use std::os::fd::AsRawFd as _;
let rc = unsafe {
libc::syscall(
libc::SYS_pidfd_send_signal,
pidfd.as_raw_fd(),
signo,
std::ptr::null::<libc::siginfo_t>(),
flags,
)
};
if rc == 0 {
Ok(())
} else {
Err(nix::errno::Errno::last())
}
}
fn verify(pgid: i32, signal: Signal, root: &GroupRoot<'_>) -> Result<(), Error> {
match group::state(pgid, signal, root) {
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, root: &GroupRoot<'_>) -> io::Result<()> {
#[cfg(target_os = "linux")]
let sent = root.pidfd().map(|pidfd| pidfd_signal(pidfd, signal, Through::Leader));
#[cfg(not(target_os = "linux"))]
let sent = None;
let sent = match sent {
Some(sent) => sent,
None => {
if let Err(why) = root.check() {
log::debug!("containment::unix::signal_direct: {why}, so {signal} was not sent to pid {pid}");
return Err(io::Error::other(why.to_string()));
}
send_signal(Target::Leader, Sys::Process(pid), signal)
}
};
match sent {
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;
#[cfg(test)]
#[path = "unix_send_tests.rs"]
mod unix_send_tests;