#[cfg(unix)]
use std::io;
#[cfg(unix)]
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sig {
Kill,
#[cfg(unix)]
Term,
}
#[cfg(target_os = "linux")]
impl Sig {
fn as_rustix(self) -> rustix::process::Signal {
match self {
Sig::Kill => rustix::process::Signal::KILL,
Sig::Term => rustix::process::Signal::TERM,
}
}
}
#[cfg(any(target_os = "macos", all(test, target_os = "linux")))]
impl Sig {
pub(crate) fn as_libc(self) -> libc::c_int {
match self {
Sig::Kill => libc::SIGKILL,
Sig::Term => libc::SIGTERM,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sent {
Delivered,
Gone,
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS's audit-token send cannot verify a process")
)]
Unverified,
}
#[cfg(unix)]
#[derive(Debug, Clone)]
pub(crate) enum RootState {
Unreaped,
Reaped,
Unknown(Arc<io::Error>),
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS reports an unpinned root")
)]
Unpinned,
}
#[cfg(unix)]
#[cfg_attr(
not(target_os = "macos"),
allow(dead_code, reason = "only macOS reports an unpinned root")
)]
pub(crate) const UNPINNED_WHY: &str = "launchd holds its zombie (its tracer died), so it is not ours to reap";
#[cfg(target_os = "macos")]
pub(crate) fn unpinned_refusal(pid: u32, op: &str, earlier: Option<&str>) -> crate::error::Error {
let earlier = earlier.map_or_else(String::new, |sent| format!(", though {sent} was sent before it"));
crate::error::Error::Unassessable {
detail: format!("pid {pid}: the child cannot be shown to be ours: {UNPINNED_WHY}; {op} sent nothing{earlier}"),
source: None,
}
}
#[cfg(unix)]
pub(crate) fn is_unpinned(state: impl FnOnce() -> RootState) -> bool {
#[cfg(target_os = "macos")]
return matches!(state(), RootState::Unpinned);
#[cfg(not(target_os = "macos"))]
{
let _ = state;
false
}
}
#[cfg(target_os = "macos")]
pub(crate) fn unpinned_status(pid: u32, op: &str) -> crate::error::Error {
crate::error::Error::Unassessable {
detail: format!("pid {pid}: {op} sent its signals, but its exit status cannot be collected: {UNPINNED_WHY}"),
source: None,
}
}
#[cfg(unix)]
pub(crate) fn refuse_unpinned(
pid: u32,
op: &str,
earlier: Option<&str>,
state: impl FnOnce() -> RootState,
) -> Result<(), crate::error::Error> {
#[cfg(target_os = "macos")]
if is_unpinned(state) {
return Err(unpinned_refusal(pid, op, earlier));
}
#[cfg(not(target_os = "macos"))]
let _ = (pid, op, earlier, state);
Ok(())
}
#[cfg(unix)]
pub(crate) fn why_untrusted(state: &RootState) -> String {
match state {
RootState::Unpinned => format!("the root is not pinned by this process (RootState::Unpinned: {UNPINNED_WHY})"),
RootState::Unknown(_) => "the root could not be shown to be unreaped (RootState::Unknown)".to_owned(),
RootState::Unreaped | RootState::Reaped => {
debug_assert!(false, "{state:?} leaves the root's number trusted");
"the root's number is trusted".to_owned()
}
}
}
#[cfg(unix)]
pub(crate) fn why_untrusted_with_cause(state: &RootState) -> String {
match state {
RootState::Unknown(e) => format!("{}: {}", why_untrusted(state), crate::error::Report(e)),
_ => why_untrusted(state),
}
}
#[cfg(unix)]
impl RootState {
pub(crate) fn of_peek(peeked: io::Result<crate::os_process::child::PeekOutcome>) -> RootState {
use crate::os_process::child::PeekOutcome;
match peeked {
Ok(PeekOutcome::Running | PeekOutcome::Exit(_)) => RootState::Unreaped,
Ok(PeekOutcome::Foreign(crate::os_process::child::Foreign::Orphaned)) => RootState::Unpinned,
Ok(PeekOutcome::Foreign(_)) => RootState::Reaped,
Err(e) => RootState::Unknown(Arc::new(e)),
}
}
pub(crate) fn unheld() -> RootState {
RootState::Unknown(Arc::new(io::Error::other(
"the root is held by a handle that does not show whether it was reaped",
)))
}
}
#[cfg(target_os = "linux")]
pub(crate) fn send_pidfd(
pidfd: std::os::fd::BorrowedFd<'_>,
pid: Option<u32>,
sig: Sig,
) -> Result<Sent, rustix::io::Errno> {
#[cfg(test)]
let seam = seams::kills_refused();
#[cfg(not(test))]
let seam: Option<i32> = None;
let sent = match seam {
Some(errno) => Err(rustix::io::Errno::from_raw_os_error(errno)),
None => rustix::process::pidfd_send_signal(pidfd, sig.as_rustix()),
};
#[cfg(test)]
crate::send_log::record(pid.unwrap_or(0), sig, crate::send_log::Via::Pidfd);
match sent {
Ok(()) => Ok(Sent::Delivered),
Err(rustix::io::Errno::SRCH) => {
log::debug!(
"pidfd_send_signal({sig:?}) to {}: it is already gone",
crate::os_process::child_named(pid)
);
Ok(Sent::Gone)
}
Err(e) => Err(e),
}
}
#[cfg(all(target_os = "macos", test))]
pub(crate) fn read_identity(kernel: &dyn crate::identity::Kernel, pid: u32) -> Result<Option<u64>, i32> {
use crate::identity::UniqRead;
match kernel.unique_info(pid) {
UniqRead::Found(info) => Ok(Some(info.unique_id)),
UniqRead::Gone => Ok(None),
UniqRead::Refused(errno) => Err(errno),
}
}
#[cfg(all(target_os = "macos", test))]
pub(crate) fn identity_unreadable(pid: u32, errno: i32) -> crate::error::Error {
crate::error::Error::Unassessable {
detail: format!("pid {pid}: its identity could not be read; the child was not adopted"),
source: Some(crate::error::Error::io_cause(io::Error::from_raw_os_error(errno))),
}
}
#[cfg(target_os = "macos")]
pub(crate) fn via_audit_token(
kernel: &dyn crate::identity::Kernel,
pid: u32,
identity: Option<u64>,
sig: Sig,
) -> io::Result<Sent> {
use crate::os_process::macos::{read_version, signal_by_token, SignalByTokenOutcome};
let Some(unique) = identity else {
log::debug!("child {pid} holds no unique id; {sig:?} not sent");
return Ok(Sent::Unverified);
};
let Some(mut idversion) = read_version(kernel, pid, unique, sig)? else {
log::debug!("child {pid} is gone or its pid names another process; {sig:?} not sent");
return Ok(Sent::Gone);
};
let sent = signal_by_token(kernel, pid, unique, &mut idversion, sig);
#[cfg(test)]
crate::send_log::record(pid, sig, crate::send_log::Via::Identity);
Ok(match sent? {
SignalByTokenOutcome::Delivered | SignalByTokenOutcome::ExitedUnreaped | SignalByTokenOutcome::Exiting => {
Sent::Delivered
}
SignalByTokenOutcome::Gone => Sent::Gone,
})
}
#[cfg(all(test, unix))]
pub(crate) mod seams {
use std::cell::Cell;
thread_local! {
static REFUSED: Cell<Option<i32>> = const { Cell::new(None) };
}
pub(crate) fn refuse_kills() -> RefusedKills {
fail_kills_with(libc::EPERM)
}
pub(crate) fn fail_kills_with(errno: i32) -> RefusedKills {
REFUSED.with(|r| r.set(Some(errno)));
RefusedKills(())
}
#[must_use = "kills are sent again as soon as the guard is dropped"]
pub(crate) struct RefusedKills(());
impl Drop for RefusedKills {
fn drop(&mut self) {
REFUSED.with(|r| r.set(None));
}
}
pub(crate) fn kills_refused() -> Option<i32> {
REFUSED.with(Cell::get)
}
}
#[cfg(all(test, unix))]
#[path = "signal_tests.rs"]
mod signal_tests;