use crate::error::Error;
use crate::identity::RawPid;
#[cfg(unix)]
use crate::signal::RootState;
use crate::signal::{Sent, Sig};
pub(crate) trait Root {
fn pid(&self) -> u32;
fn signal(&self, sig: Sig) -> Result<Sent, Error>;
#[cfg(unix)]
fn state(&self) -> RootState;
#[cfg(unix)]
fn look_state(&self) -> RootState {
self.state()
}
#[cfg(target_os = "linux")]
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>>;
}
#[cfg(unix)]
pub(crate) struct Seen<'a> {
root: &'a dyn Root,
look: RootState,
}
#[cfg(unix)]
impl<'a> Seen<'a> {
pub(crate) fn new(root: &'a dyn Root, look: RootState) -> Seen<'a> {
Seen { root, look }
}
}
#[cfg(unix)]
impl Root for Seen<'_> {
fn pid(&self) -> u32 {
self.root.pid()
}
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
self.root.signal(sig)
}
fn state(&self) -> RootState {
self.root.state()
}
fn look_state(&self) -> RootState {
self.look.clone()
}
#[cfg(target_os = "linux")]
fn pidfd(&self) -> Option<std::os::fd::BorrowedFd<'_>> {
self.root.pidfd()
}
}
#[cfg(target_os = "linux")]
pub(crate) fn group_has_member(root: Option<&dyn Root>) -> Result<Option<bool>, nix::errno::Errno> {
match root.and_then(Root::pidfd) {
Some(pidfd) => crate::containment::unix::pidfd_group_has_member(pidfd),
None => Ok(None),
}
}
#[cfg(unix)]
pub(crate) fn check_number(root: Option<&dyn Root>) -> Result<(), NotItsGroup> {
#[cfg(test)]
crate::send_log::record_group(crate::send_log::GroupStep::Check);
let (has_member, probe) = probe_group(root, "the root's state decides");
match has_member {
Some(true) => return Ok(()),
Some(false) => return Err(NotItsGroup::Empty),
None => {}
}
match root {
Some(root) => number_holds(root, root.state()).map_err(|refusal| NotItsGroup::unproven(refusal, probe)),
None => {
debug_assert!(false, "a send by the root's number was given no root to check");
Err(NotItsGroup::NoRoot)
}
}
}
#[cfg(target_os = "linux")]
fn probe_group(root: Option<&dyn Root>, then: &str) -> (Option<bool>, Option<i32>) {
match group_has_member(root) {
Ok(has_member) => (has_member, None),
Err(errno) => {
log::debug!(
"a signal-0 send to a process group through its root's pidfd answered {report}, so {then}",
report = crate::error::Report(&errno)
);
(None, Some(errno as i32))
}
}
}
#[cfg(all(unix, not(target_os = "linux")))]
fn probe_group(_root: Option<&dyn Root>, _then: &str) -> (Option<bool>, Option<i32>) {
(None, None)
}
#[cfg(unix)]
fn probe_error(errno: i32) -> Error {
Error::Unassessable {
detail: "a signal-0 send to the root's process group through its pidfd failed".to_owned(),
source: Some(Error::io_cause(std::io::Error::from_raw_os_error(errno))),
}
}
#[derive(Debug)]
#[cfg_attr(not(unix), allow(dead_code, reason = "only Unix sends by the root's pid"))]
pub(crate) enum Refusal {
ReapedElsewhere(RawPid),
Unsure(RawPid, std::sync::Arc<std::io::Error>),
Unpinned(RawPid),
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Refusal::ReapedElsewhere(pid) => write!(f, "the root (pid {pid}) was reaped elsewhere"),
Refusal::Unsure(pid, _) => write!(
f,
"the root's own handle could not say whether it (pid {pid}) was reaped"
),
Refusal::Unpinned(pid) => write!(f, "the root (pid {pid}) is not pinned by this process"),
}
}
}
impl std::error::Error for Refusal {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Refusal::Unsure(_, e) => Some(&**e),
_ => None,
}
}
}
#[cfg(unix)]
impl Refusal {
pub(crate) fn cause(&self) -> Option<std::sync::Arc<crate::error::Error>> {
match self {
Refusal::Unsure(_, e) => Some(crate::error::shared_io_cause(e)),
_ => None,
}
}
pub(crate) fn cause_after(&self, probe: Option<i32>) -> Option<std::sync::Arc<Error>> {
match probe {
None => self.cause(),
Some(errno) => Some(Error::joined_cause(
self.cause(),
[std::sync::Arc::new(probe_error(errno))],
)),
}
}
}
#[cfg(unix)]
pub(crate) fn number_holds(root: &dyn Root, state: RootState) -> Result<(), Refusal> {
let pid = root.pid();
match state {
RootState::Unreaped => Ok(()),
RootState::Reaped => Err(Refusal::ReapedElsewhere(pid)),
RootState::Unknown(e) => Err(Refusal::Unsure(pid, e)),
RootState::Unpinned => Err(Refusal::Unpinned(pid)),
}
}
#[cfg(unix)]
pub(crate) enum NumberLook {
Trusted,
#[cfg_attr(not(target_os = "macos"), allow(dead_code, reason = "only macOS reports it"))]
Untrusted(RootState),
MayNameAnother {
refusal: Refusal,
exact_root: bool,
probe: Option<i32>,
},
#[cfg_attr(not(target_os = "linux"), allow(dead_code, reason = "only Linux has a pidfd"))]
GroupGone,
}
#[cfg(unix)]
pub(crate) fn look(root: &dyn Root) -> NumberLook {
let state = root.look_state();
#[cfg(target_os = "macos")]
if matches!(state, RootState::Unpinned | RootState::Unknown(_)) {
return NumberLook::Untrusted(state);
}
let handle_unsure = matches!(state, RootState::Unknown(_));
match number_holds(root, state) {
Ok(()) => NumberLook::Trusted,
Err(refusal) => {
debug_assert!(
cfg!(target_os = "macos") || !matches!(refusal, Refusal::Unpinned(_)),
"only macOS reports an unpinned root, and it is answered above"
);
NumberLook::MayNameAnother {
refusal,
exact_root: handle_unsure && cfg!(target_os = "linux"),
probe: None,
}
}
}
}
#[cfg(target_os = "linux")]
pub(crate) fn through_the_pidfd(look: NumberLook, root: &dyn Root) -> NumberLook {
let NumberLook::MayNameAnother {
refusal,
exact_root,
probe,
} = look
else {
return look;
};
let (has_member, failed) = probe_group(Some(root), "the look keeps its refusal");
match has_member {
Some(true) => {
log::debug!(
"{refusal}, but its pidfd names its process group exactly, which still has a member: it is signalled",
refusal = crate::error::Report(&refusal)
);
return NumberLook::Trusted;
}
Some(false) if !exact_root => return NumberLook::GroupGone,
_ => {}
}
NumberLook::MayNameAnother {
refusal,
exact_root,
probe: failed.or(probe),
}
}
#[cfg(unix)]
#[derive(Debug)]
pub(crate) enum NotItsGroup {
#[cfg_attr(not(target_os = "linux"), allow(dead_code, reason = "only Linux has a pidfd"))]
Empty,
Unproven(Refusal, Option<i32>, std::sync::OnceLock<Option<std::sync::Arc<Error>>>),
NoRoot,
}
#[cfg(unix)]
impl std::fmt::Display for NotItsGroup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotItsGroup::Empty => f.write_str("the root's process group has no member left"),
NotItsGroup::Unproven(why, ..) => std::fmt::Display::fmt(why, f),
NotItsGroup::NoRoot => f.write_str("no root was given to check"),
}
}
}
#[cfg(unix)]
impl std::error::Error for NotItsGroup {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
NotItsGroup::Unproven(why, None, _) => std::error::Error::source(why),
NotItsGroup::Unproven(..) => self
.joined()
.map(|cause| &**cause as &(dyn std::error::Error + 'static)),
NotItsGroup::Empty | NotItsGroup::NoRoot => None,
}
}
}
#[cfg(unix)]
impl NotItsGroup {
pub(crate) fn unproven(refusal: Refusal, probe: Option<i32>) -> NotItsGroup {
NotItsGroup::Unproven(refusal, probe, std::sync::OnceLock::new())
}
pub(crate) fn cause(&self) -> Option<std::sync::Arc<Error>> {
self.joined().cloned()
}
fn joined(&self) -> Option<&std::sync::Arc<Error>> {
match self {
NotItsGroup::Unproven(why, probe, joined) => joined.get_or_init(|| why.cause_after(*probe)).as_ref(),
NotItsGroup::Empty | NotItsGroup::NoRoot => None,
}
}
}
#[cfg(all(test, unix))]
#[path = "root_tests.rs"]
mod root_tests;