use std::io;
use nix::sys::signal::Signal;
use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
use crate::containment::drain_edge::DrainEdge;
use crate::containment::mechanism::{Contains, Release};
use crate::containment::root::NumberLook;
use crate::containment::{check_number, Containment, Root, Skip, TerminateOutcome, TreeKill, Why};
use crate::error::{Error, Failures};
use std::sync::Arc;
#[derive(Debug)]
pub(crate) struct Group {
pgid: i32,
session: bool,
}
impl Group {
pub(crate) fn process_group(pgid: i32) -> Group {
Group { pgid, session: false }
}
pub(crate) fn session(pgid: i32) -> Group {
Group { pgid, session: true }
}
}
impl Contains for Group {
fn kill(&self, root: Option<&dyn Root>) -> TreeKill<'_> {
kill_group_tree(self.pgid, root)
}
fn send_terminate(&self, _pid: u32, root: Option<&dyn Root>) -> TerminateOutcome {
term_group_tree(self.pgid, root)
}
fn drain_edge(&self) -> Option<DrainEdge<'_>> {
None
}
fn kind(&self) -> Containment {
if self.session {
Containment::Session
} else {
Containment::ProcessGroup
}
}
fn disarm(&self) -> io::Result<()> {
Ok(())
}
fn subject(&self) -> String {
format!("ProcessGroup({})", self.pgid)
}
fn would_reach(&self, _pid: u32, _pidfd: Option<std::os::fd::BorrowedFd<'_>>) -> io::Result<bool> {
Ok(false)
}
fn reached(&self, _child: &crate::child::owned::OwnedChild) -> io::Result<bool> {
Ok(false)
}
fn release(self) -> (Release, Option<Group>) {
(Release::nothing(), Some(self))
}
#[cfg(all(feature = "tokio", target_os = "linux"))]
fn awaitable_release(&self) -> Option<crate::containment::mechanism::AwaitableRelease<'_>> {
None
}
}
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: Option<&dyn Root>,
killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<(), Error> {
#[cfg(test)]
if let Some(outcome) = fault::intercept_kill_group(pgid) {
return outcome;
}
signal_group(pgid, Signal::SIGKILL, root, killed)
}
#[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(())
})
}
}
#[cfg(test)]
pub(crate) fn term_group(pgid: i32, root: Option<&dyn Root>) -> Result<(), Error> {
term_group_sent(pgid, root).flatten()
}
pub(crate) fn term_group_sent(pgid: i32, root: Option<&dyn Root>) -> Result<Result<(), Error>, Error> {
#[cfg(test)]
if fault::intercept_term_group(pgid) {
return Ok(Ok(()));
}
signal_group_sent(pgid, Signal::SIGTERM, root, &mut Vec::new())
}
fn group_look(root: &dyn Root) -> NumberLook {
let look = crate::containment::root::look(root, true);
#[cfg(target_os = "linux")]
let look = crate::containment::root::through_the_pidfd(look, root);
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
look
}
fn skipped_group(pgid: i32, verb: &str, look: NumberLook) -> Skip {
let (why, root_alone) = match look {
NumberLook::Untrusted(state) => (Why::untrusted(&state), false),
NumberLook::MayNameAnother { refusal, exact_root } => (Why::MayNameAnother(refusal), exact_root),
NumberLook::Trusted | NumberLook::Empty | NumberLook::GroupGone => {
unreachable!("a send to a group that is not skipped has no skip to say")
}
};
Skip {
action: format!("{verb} its process group (pgid {pgid})"),
why,
root_alone,
holders: None,
}
}
fn log_empty_group(pgid: i32, look: &NumberLook) {
match look {
NumberLook::GroupGone => log::debug!(
"containment::unix: the root is reaped, and its pidfd shows process group {pgid} has no member left, so nothing is sent"
),
_ => log::debug!(
"containment::unix: this handle reaped the root, so process group {pgid} is empty, and nothing is sent by its number"
),
}
}
pub(crate) fn kill_group_tree<'a>(pgid: i32, root: Option<&dyn Root>) -> TreeKill<'a> {
let mut killed = Vec::new();
let ran = |sent: Result<(), Error>| TreeKillOutcome::Ran(sent.map_err(Unkilled::from));
let outcome = match root {
None => {
debug_assert!(false, "a group kill was given no root to look at");
ran(kill_group(pgid, None, &mut killed))
}
Some(root) => match group_look(root) {
NumberLook::Trusted => ran(kill_group(pgid, Some(root), &mut killed)),
look @ (NumberLook::Empty | NumberLook::GroupGone) => {
log_empty_group(pgid, &look);
TreeKillOutcome::Answered(Ok(()))
}
look => TreeKillOutcome::Skipped(skipped_group(pgid, "kill", look)),
},
};
TreeKill::of(outcome).reaching(killed)
}
pub(crate) fn term_group_tree(pgid: i32, root: Option<&dyn Root>) -> TerminateOutcome {
let sent = |root: Option<&dyn Root>| TerminateOutcome::of(term_group_sent(pgid, root), Some("the SIGTERM"));
let Some(root) = root else {
debug_assert!(false, "a group terminate was given no root to look at");
return sent(None);
};
match group_look(root) {
NumberLook::Trusted => sent(Some(root)),
look @ (NumberLook::Empty | NumberLook::GroupGone) => {
log_empty_group(pgid, &look);
TerminateOutcome::Sent {
result: Ok(()),
earlier: None,
}
}
look => {
let skip = skipped_group(pgid, "signal", look);
if skip.root_alone {
TerminateOutcome::RootThroughPidfd(skip)
} else {
TerminateOutcome::End(skip)
}
}
}
}
fn signal_group(
pgid: i32,
signal: Signal,
root: Option<&dyn Root>,
killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<(), Error> {
signal_group_sent(pgid, signal, root, killed).flatten()
}
fn signal_group_sent(
pgid: i32,
signal: Signal,
root: Option<&dyn Root>,
killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<Result<(), Error>, 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::Containment {
detail: format!("{signal} could not be sent to process group {pgid}"),
source: Some(Error::io_cause(io::Error::from(e))),
})
}
}
Ok(verify(pgid, signal, root, killed))
}
pub(crate) fn send_to_group(
pgid: i32,
signal: Signal,
root: Option<&dyn Root>,
) -> Result<Result<(), nix::errno::Errno>, Error> {
#[cfg(target_os = "linux")]
if let Some(pidfd) = root.and_then(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),
}
}
check_number(root).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: why.cause(),
})?;
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 {report}",
report = crate::error::Report(&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")]
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: Option<&dyn Root>,
killed: &mut Vec<crate::identity::ProcessId>,
) -> Result<(), Error> {
answer_of(group::state(pgid, signal, root, killed), pgid, signal)
}
fn answer_of(state: group::GroupState, pgid: i32, signal: Signal) -> Result<(), Error> {
let member = |pid: u32, words: &str, cause: Error, unassessed: bool| {
Arc::new(Error::of_member(pid, words, cause, unassessed))
};
match state {
group::GroupState::Cleared => Ok(()),
group::GroupState::Refused { refused, unassessable } => {
let mut detail = format!(
"{signal} did not clear {n} member(s) of process group {pgid}; the tree is still up \
and this process cannot bring it down",
n = refused.len(),
);
if !unassessable.is_empty() {
detail.push_str(&format!(
"; additionally, {n} member(s) could not be assessed at all",
n = unassessable.len(),
));
}
let members = refused
.into_iter()
.map(|(pid, cause)| member(pid, "refused the signal", cause, false))
.chain(
unassessable
.into_iter()
.map(|(pid, cause)| member(pid, "could not be assessed", cause, true)),
);
let source = Failures::collect(members).map(Failures::into_cause);
Err(Error::Containment { detail, source })
}
group::GroupState::Unassessed { members } => {
let detail = format!(
"{n} member(s) of process group {pgid} could not be assessed after {signal}",
n = members.len(),
);
let members = members
.into_iter()
.map(|(pid, cause)| member(pid, "could not be assessed", cause, true));
Err(Error::Unassessable {
detail,
source: Failures::collect(members).map(Failures::into_cause),
})
}
group::GroupState::Unlistable { source, .. } if source.kind() == io::ErrorKind::Unsupported => {
Err(Error::Unsupported {
op: format!("listing process group {pgid}"),
platform: std::env::consts::OS,
detail: "the group could not be listed".to_owned(),
source: Some(Error::io_cause(source)),
})
}
group::GroupState::Unlistable { detail, source } => Err(Error::Unassessable {
detail,
source: Some(Error::io_cause(source)),
}),
}
}
fn signal_direct(pid: i32, signal: Signal, root: Option<&dyn Root>) -> io::Result<()> {
#[cfg(target_os = "linux")]
let sent = root
.and_then(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) = check_number(root) {
log::debug!(
"containment::unix::signal_direct: {why}, so {signal} was not sent to pid {pid}",
why = crate::error::Report(&why)
);
return Err(io::Error::other(why));
}
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: {report}",
report = crate::error::Report(&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;