use crate::containment::dispatch::{TreeKillOutcome, TreeSignal, Unkilled};
use crate::containment::{Attached, GroupRoot, TreeKilled};
use crate::error::Error;
use crate::identity::RawPid;
use crate::signal::{RootState, Sent};
pub(crate) enum RootNumber {
Trusted,
#[cfg(target_os = "macos")]
Untrusted(RootState),
#[cfg(target_os = "macos")]
NoWalk,
Empty,
MayNameAnother { why: String, exact_root: bool },
#[cfg(target_os = "linux")]
GroupGone,
}
pub(crate) fn root_number(attached: &Attached, pid: RawPid, state: impl FnOnce() -> RootState) -> RootNumber {
use crate::identity::Resolved;
#[cfg(target_os = "macos")]
let state = {
let looked = state();
if matches!(looked, RootState::Unpinned | RootState::Unknown(_)) {
return RootNumber::Untrusted(looked);
}
move || looked
};
if !attached.needs_root_check() {
return RootNumber::Trusted;
}
let mut exact_root = false;
let why = match state() {
RootState::Unreaped => return RootNumber::Trusted,
RootState::Reaped { own: true } => match crate::child::root_identity_now(pid) {
Resolved::Gone => return own_reaped_free(attached),
Resolved::Found(_) => return RootNumber::Empty,
Resolved::Unknown => format!("this handle reaped the root, and its pid ({pid}) could not be read"),
},
RootState::Reaped { own: false } => format!("the root (pid {pid}) was reaped elsewhere"),
RootState::Unknown(e) => {
exact_root = cfg!(target_os = "linux");
format!("the root's own handle could not say whether it (pid {pid}) was reaped ({e})")
}
RootState::Unpinned => {
debug_assert!(false, "only macOS reports an unpinned root, and it is answered above");
format!("the root (pid {pid}) is not pinned by this process")
}
};
RootNumber::MayNameAnother { why, exact_root }
}
pub(crate) fn group_number_holds(pid: RawPid, state: RootState) -> Result<(), String> {
use crate::identity::Resolved;
match state {
RootState::Unreaped => Ok(()),
RootState::Reaped { own: true } => match crate::child::root_identity_now(pid) {
Resolved::Gone => Ok(()),
Resolved::Found(_) => Err(format!(
"this handle reaped the root, and another process holds its pid ({pid})"
)),
Resolved::Unknown => Err(format!(
"this handle reaped the root, and its pid ({pid}) could not be read"
)),
},
RootState::Reaped { own: false } => Err(format!("the root (pid {pid}) was reaped elsewhere")),
RootState::Unknown(e) => Err(format!(
"the root's own handle could not say whether it (pid {pid}) was reaped ({e})"
)),
RootState::Unpinned => Err(format!("the root (pid {pid}) is not pinned by this process")),
}
}
#[cfg(target_os = "linux")]
pub(crate) fn through_the_pidfd(attached: &Attached, number: RootNumber, group: &GroupRoot<'_>) -> RootNumber {
let RootNumber::MayNameAnother { why, exact_root } = &number else {
return number;
};
if !matches!(attached, Attached::ProcessGroup(_)) {
return number;
}
match group.has_member() {
Some(true) => {
log::debug!(
"{why}, but its pidfd names its process group exactly, which still has a member: it is signalled"
);
RootNumber::Trusted
}
Some(false) if !*exact_root => RootNumber::GroupGone,
_ => number,
}
}
fn own_reaped_free(attached: &Attached) -> RootNumber {
#[cfg(target_os = "macos")]
match attached.fd_marker_has_group() {
Some(true) => return RootNumber::NoWalk,
Some(false) => return RootNumber::Empty,
None => {}
}
#[cfg(not(target_os = "macos"))]
let _ = attached;
RootNumber::Trusted
}
pub(crate) struct TreeCall<'a> {
pub(crate) attached: &'a Attached,
pub(crate) pid: RawPid,
pub(crate) signal: TreeSignal,
pub(crate) op: &'static str,
pub(crate) earlier: Option<&'a str>,
pub(crate) killed: &'a TreeKilled,
}
pub(crate) enum Graceful {
Signal,
Sent {
result: Result<(), Error>,
earlier: Option<&'static str>,
},
End(Error),
#[cfg(target_os = "linux")]
RootThroughPidfd(String),
#[cfg(target_os = "macos")]
HoldersOnly(String),
}
impl TreeCall<'_> {
#[cfg_attr(not(target_os = "linux"), allow(unused_variables, reason = "only Linux has a pidfd"))]
pub(crate) fn root_number(&self, state: impl FnOnce() -> RootState, group: &GroupRoot<'_>) -> RootNumber {
let number = root_number(self.attached, self.pid, state);
#[cfg(target_os = "linux")]
let number = through_the_pidfd(self.attached, number, group);
#[cfg(test)]
crate::graceful_hooks::run_hook(crate::graceful_hooks::HookPoint::AfterRootLook);
number
}
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "only a macOS fd marker signals here")
)]
pub(crate) fn root_checked(
&self,
state: impl FnOnce() -> RootState,
signal_root: impl FnOnce() -> Result<Sent, Error>,
group: &GroupRoot<'_>,
) -> Option<Result<(), Error>> {
match self.root_number(state, group) {
RootNumber::Trusted => None,
#[cfg(target_os = "macos")]
RootNumber::Untrusted(root) => self.untrusted(&root),
#[cfg(target_os = "macos")]
RootNumber::NoWalk => Some(self.no_walk(group)),
RootNumber::Empty => Some(self.answered(self.empty_group().unwrap_or(Ok(())))),
#[cfg(target_os = "linux")]
RootNumber::GroupGone => Some(self.group_gone()),
RootNumber::MayNameAnother { why, exact_root } => {
let root = exact_root.then(signal_root);
Some(Err(self.number_skipped(&why, root)))
}
}
}
#[cfg_attr(
not(target_os = "macos"),
allow(unused_variables, reason = "only a macOS fd marker signals here")
)]
pub(crate) fn graceful(&self, state: impl FnOnce() -> RootState, group: &GroupRoot<'_>) -> Graceful {
match self.root_number(state, group) {
RootNumber::Trusted => Graceful::Signal,
#[cfg(target_os = "macos")]
RootNumber::Untrusted(root) => match self.untrusted(&root) {
Some(Err(e)) if !self.attached.names_tree_by_identity() => Graceful::End(e),
None => Graceful::Signal,
Some(result) => Graceful::Sent {
result,
earlier: Some("the SIGTERM"),
},
},
#[cfg(target_os = "macos")]
RootNumber::NoWalk => Graceful::Sent {
result: self.no_walk(group),
earlier: Some("the SIGTERM"),
},
#[cfg(target_os = "linux")]
RootNumber::GroupGone => Graceful::Sent {
result: self.group_gone(),
earlier: None,
},
RootNumber::Empty => {
let holders = self.empty_group();
Graceful::Sent {
earlier: holders.is_some().then_some("the SIGTERM to any marker holders"),
result: self.answered(holders.unwrap_or(Ok(()))),
}
}
RootNumber::MayNameAnother { why, exact_root } => {
#[cfg(target_os = "linux")]
if exact_root {
return Graceful::RootThroughPidfd(why);
}
#[cfg(not(target_os = "linux"))]
let _ = exact_root;
#[cfg(target_os = "macos")]
if self.attached.names_tree_by_identity() {
return Graceful::HoldersOnly(why);
}
Graceful::End(self.number_skipped(&why, None))
}
}
}
fn answered(&self, result: Result<(), Error>) -> Result<(), Error> {
match self.signal {
TreeSignal::Kill => self.attached.settle_for_kill_tree(
self.op,
self.killed,
TreeKillOutcome::Ran(result.map_err(Unkilled::from)),
false,
),
TreeSignal::Term => result,
}
}
#[cfg(target_os = "macos")]
fn untrusted(&self, root: &RootState) -> Option<Result<(), Error>> {
self.attached
.signal_tree_untrusted(self.signal, root, self.pid, self.op, self.earlier)
.map(|result| self.answered(result))
}
#[cfg(target_os = "macos")]
fn no_walk(&self, group: &GroupRoot<'_>) -> Result<(), Error> {
log::debug!(
"{}({}): this handle reaped the root, and its pid names no process: its group and the marker holders \
are signalled, and no walk runs from the pid, which would find none of the tree",
self.op,
self.pid
);
self.answered(
self.attached
.signal_group_and_holders(self.signal, group)
.unwrap_or_else(|| {
debug_assert!(false, "only an fd marker with a group gets here");
Ok(())
}),
)
}
#[cfg(target_os = "linux")]
fn group_gone(&self) -> Result<(), Error> {
log::debug!(
"{}({}): the root is reaped, and its pidfd shows its process group has no member left, so nothing is sent",
self.op,
self.pid
);
self.answered(Ok(()))
}
fn empty_group(&self) -> Option<Result<(), Error>> {
log::debug!(
"{}({}): this handle reaped the root, so its group is empty or it had none, a walk from its pid \
would find none of the tree, and nothing is sent by it",
self.op,
self.pid
);
self.attached.signal_holders_only(self.signal)
}
pub(crate) fn number_skipped(&self, why: &str, root: Option<Result<Sent, Error>>) -> Error {
let holders = self.attached.signal_holders_only(self.signal);
let (sent_root, failed_root) = match self.signal {
TreeSignal::Kill => (
"killed the root through its pidfd, which names it exactly, and sent nothing else",
"the kill of the root",
),
TreeSignal::Term => (
"sent the SIGTERM to the root through its pidfd, which names it exactly, and sent nothing else",
"the SIGTERM to the root",
),
};
let sent = match (&holders, &root) {
(Some(Ok(())), _) => "signalled only the marker holders".to_owned(),
(Some(Err(e)), _) => format!("signalled only the marker holders, which failed ({e})"),
(None, None) => "sent nothing".to_owned(),
(None, Some(Ok(Sent::Delivered))) => sent_root.to_owned(),
(None, Some(Ok(Sent::Gone))) => "sent nothing: the root's pidfd shows it is gone".to_owned(),
(None, Some(Ok(_))) => "sent nothing: the root's handle no longer reaches it".to_owned(),
(None, Some(Err(e))) => format!("sent nothing: {failed_root} through its pidfd failed ({e})"),
};
let detail = self.skipped_detail(why, &sent);
log::warn!("{detail}");
match (holders, root) {
(Some(Err(e)), _) | (None, Some(Err(e))) => e,
_ => Error::Unassessable { detail, source: None },
}
}
fn skipped_detail(&self, why: &str, sent: &str) -> String {
let verb = self.signal.verb();
let skipped = self
.attached
.named_by_root_number(self.pid, verb)
.unwrap_or_else(|| format!("{verb} its tree"));
let earlier = self
.earlier
.map_or_else(String::new, |sent| format!(", though {sent} was sent before it"));
format!(
"{}(): {why}, so its number may name another process; it did not {skipped}, and {sent}{earlier}",
self.op
)
}
#[cfg(target_os = "macos")]
pub(crate) fn holders_only(&self, signal: TreeSignal) -> Result<(), Error> {
self.attached.signal_holders_only(signal).unwrap_or_else(|| {
debug_assert!(false, "only a mechanism that names its tree by identity gets here");
Ok(())
})
}
#[cfg(target_os = "macos")]
pub(crate) fn holders_term(&self) -> Result<(), Error> {
self.holders_only(TreeSignal::Term)
}
#[cfg(target_os = "macos")]
pub(crate) fn holders_grace_failed(&self, e: &Error) {
log::debug!(
"{}({}): the marker holders' grace wait failed, so they are killed now: {e}",
self.op,
self.pid
);
}
#[cfg(target_os = "macos")]
pub(crate) fn holders_shutdown_error(&self, why: &str, term: Result<(), Error>) -> Error {
let kill = self.holders_only(TreeSignal::Kill);
let term = match &term {
Ok(()) => String::new(),
Err(e) => format!(", which failed ({e})"),
};
let kill_failed = match &kill {
Ok(()) => String::new(),
Err(e) => format!(", which failed ({e})"),
};
let sent = format!(
"sent the SIGTERM only to the marker holders{term}, then killed any left after the grace{kill_failed}"
);
let detail = self.skipped_detail(why, &sent);
log::warn!("{detail}");
match kill {
Err(e) => e,
Ok(()) => Error::Unassessable { detail, source: None },
}
}
}
#[cfg(target_os = "linux")]
pub(crate) struct PidfdShutdown {
term: Result<Sent, Error>,
}
#[cfg(target_os = "linux")]
impl PidfdShutdown {
pub(crate) fn start(
gate: crate::elevation::front::Gate,
term: impl FnOnce() -> Result<Sent, Error>,
) -> Result<PidfdShutdown, Error> {
if let crate::elevation::front::Gate::Closed(unkillable) = gate {
return Err(unkillable);
}
Ok(PidfdShutdown { term: term() })
}
pub(crate) fn needs_grace(&self) -> bool {
matches!(self.term, Ok(Sent::Delivered))
}
pub(crate) fn finish(
self,
call: &TreeCall<'_>,
why: &str,
exited: Option<Result<bool, impl std::fmt::Display>>,
kill_gate: impl FnOnce() -> crate::elevation::front::Gate,
kill: impl FnOnce() -> Result<Sent, Error>,
) -> Error {
use crate::elevation::front::Gate;
let kill = match exited {
None | Some(Ok(true)) => None,
Some(outcome) => {
if let Err(e) = outcome {
log::debug!(
"{}({}): the root's grace wait failed, so it is killed now: {e}",
call.op,
call.pid
);
}
Some(match kill_gate() {
Gate::Closed(unkillable) => Err(unkillable),
_ => kill(),
})
}
};
let termed = "sent the SIGTERM to the root through its pidfd, which names it exactly";
let sent = match (&self.term, &kill) {
(Err(e), _) => format!("sent nothing: the SIGTERM to the root through its pidfd failed ({e})"),
(Ok(Sent::Delivered), None) => format!("{termed}, and it exited within the grace; sent nothing else"),
(Ok(Sent::Delivered), Some(Ok(Sent::Delivered))) => {
format!("{termed}, then killed the root through its pidfd after the grace, and sent nothing else")
}
(Ok(Sent::Delivered), Some(Err(e))) => {
format!("{termed}, then the kill of the root through its pidfd failed ({e})")
}
(Ok(Sent::Delivered), Some(Ok(_))) => {
format!("{termed}, and its pidfd showed it gone after the grace; sent nothing else")
}
(Ok(Sent::Gone), _) => "sent nothing: the root's pidfd shows it is gone".to_owned(),
(Ok(_), _) => "sent nothing: the root's handle no longer reaches it".to_owned(),
};
let detail = call.skipped_detail(why, &sent);
log::warn!("{detail}");
match (self.term, kill) {
(Err(e), _) | (_, Some(Err(e))) => e,
_ => Error::Unassessable { detail, source: None },
}
}
}
pub(crate) fn status_unless_reaped_elsewhere(
waited: Result<std::process::ExitStatus, Error>,
pid: RawPid,
) -> Result<std::process::ExitStatus, Error> {
match waited {
Err(Error::Io(e)) if e.raw_os_error() == Some(libc::ECHILD) => {
log::debug!("graceful_shutdown_tree({pid}): the tree is down, and the root was reaped elsewhere");
Err(Error::Unassessable {
detail: format!(
"pid {pid}: graceful_shutdown_tree brought the tree down, but its exit status cannot be \
collected: the root was reaped elsewhere"
),
source: None,
})
}
other => other,
}
}
#[cfg(feature = "tokio")]
pub(crate) fn status_of_an_unproven_root(pid: RawPid) -> Error {
Error::Unassessable {
detail: format!(
"pid {pid}: graceful_shutdown_tree brought the tree down, but its exit status cannot be \
collected: the root's handle could not say whether it was reaped"
),
source: None,
}
}
#[cfg(test)]
#[path = "tree_call_tests.rs"]
mod tree_call_tests;