use std::io;
use crate::child::owned::teardown::Reach;
use crate::child::owned::OwnedChild;
use crate::error::{ElevationErrorKind, Error, Failures};
use crate::os_process::child::PeekOutcome;
use crate::signal::{Sent, Sig};
pub(crate) fn front_named(pid: Option<u32>) -> String {
pid.map_or_else(
|| "the elevation front (pid unknown)".to_owned(),
|pid| format!("elevation front pid {pid}"),
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TrackedKind {
Own,
AnotherUser,
Front(Front),
}
impl TrackedKind {
pub(crate) fn front(self) -> Option<Front> {
match self {
TrackedKind::Front(front) => Some(front),
TrackedKind::Own | TrackedKind::AnotherUser => None,
}
}
fn runs_as_another_user(self) -> bool {
match self {
TrackedKind::Own => false,
TrackedKind::AnotherUser => true,
TrackedKind::Front(front) => front.may_be_the_program(),
}
}
fn refusal(self, err: io::Error) -> Error {
if self.runs_as_another_user() && err.kind() == io::ErrorKind::PermissionDenied {
Error::Elevation {
kind: ElevationErrorKind::Unkillable,
detail: "could not signal the elevated child".into(),
source: Some(Error::io_cause(err)),
}
} else {
Error::Io(err)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KillNeed {
ThenRoot,
Exited,
}
pub(crate) enum AloneStep<K, A> {
Killed { result: Result<(), Error>, carry: K },
NotKilled(K),
Answered(A),
}
pub(crate) enum RootStep<R, A> {
ThenRoot(R),
Answered(A),
}
pub(crate) enum KillRootOutcome<K, R, A> {
Refused(Error),
Contained { reached: Result<(), Error>, carry: K },
Root { sent: Result<Sent, Error>, carry: R },
Answered(A),
}
impl OwnedChild {
pub(crate) fn kill_root<K, R, A>(
&self,
reach: Option<&dyn Reach>,
alone: impl FnOnce(Front) -> AloneStep<K, A>,
then_root: impl FnOnce(KillNeed) -> RootStep<R, A>,
) -> KillRootOutcome<K, R, A> {
let pid = self.pid();
let placed = || reach.map_or(Ok(false), |reach| reach.would_reach(self));
let need = match kill_gate(self.tracked_kind().front(), pid, || self.running(), placed) {
Gate::Closed(refusal) => return KillRootOutcome::Refused(refusal),
Gate::CgroupOnly(front) => {
let (reached, carry) = match alone(front) {
AloneStep::Answered(answer) => return KillRootOutcome::Answered(answer),
AloneStep::Killed { result: Ok(()), carry } => (
cgroup_kill_reached(front, pid, || self.running().map(|running| !running), placed),
carry,
),
AloneStep::Killed { result: Err(e), carry } => (Err(cgroup_kill_failed(front, pid, e)), carry),
AloneStep::NotKilled(carry) => (Err(cgroup_not_killed(front, pid)), carry),
};
return KillRootOutcome::Contained { reached, carry };
}
Gate::Open => KillNeed::ThenRoot,
Gate::Exited => KillNeed::Exited,
};
match then_root(need) {
RootStep::Answered(answer) => KillRootOutcome::Answered(answer),
RootStep::ThenRoot(carry) => KillRootOutcome::Root {
sent: self.send_kill(need == KillNeed::Exited),
carry,
},
}
}
#[cfg(any(target_os = "linux", not(unix)))]
pub(crate) fn kill_root_only(&self, reach: Option<&dyn Reach>) -> Result<Sent, Error> {
let pid = self.pid();
let killed = self.kill_root(
reach,
|front| {
AloneStep::<std::convert::Infallible, _>::Answered(refused(
front,
pid,
Signal::Kill,
Some(Reason::words("this call kills through no cgroup")),
))
},
|_| RootStep::ThenRoot(()),
);
match killed {
KillRootOutcome::Refused(refusal) | KillRootOutcome::Answered(refusal) => Err(refusal),
KillRootOutcome::Root { sent, .. } => sent,
KillRootOutcome::Contained { carry, .. } => match carry {},
}
}
pub(crate) fn terminate_by<T>(&self, send: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
match terminate_gate(self.tracked_kind().front(), self.pid(), || self.running()) {
Gate::Closed(refusal) => Err(refusal),
Gate::Open | Gate::Exited => send(),
Gate::CgroupOnly(_) => {
debug_assert!(false, "a SIGTERM's gate never leaves a front to a cgroup kill");
send()
}
}
}
fn running(&self) -> io::Result<bool> {
let peeked = self.peek().map_err(Error::into_io)?;
Ok(matches!(peeked, PeekOutcome::Running))
}
fn send_kill(&self, exited_front: bool) -> Result<Sent, Error> {
match self.signal(Sig::Kill).map_err(Error::into_io) {
Ok(sent) => Ok(sent),
Err(e) if exited_front && e.kind() == io::ErrorKind::PermissionDenied => {
log::debug!(
"the kill of the exited {} was refused ({report})",
front_named(self.pid()),
report = crate::error::Report(&e)
);
Ok(Sent::Delivered)
}
Err(e) if exited_front => Err(Error::Io(e)),
Err(e) => Err(self.tracked_kind().refusal(e)),
}
}
}
#[derive(Debug)]
enum Gate {
Open,
Exited,
CgroupOnly(Front),
Closed(Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Front {
Sudo,
Doas,
Osascript,
}
impl Front {
pub(crate) fn name(self) -> &'static str {
match self {
Front::Sudo => "sudo",
Front::Doas => "doas",
Front::Osascript => "osascript",
}
}
fn may_be_the_program(self) -> bool {
!matches!(self, Front::Osascript)
}
fn relays_term(self) -> bool {
!matches!(self, Front::Osascript)
}
}
fn kill_gate(
front: Option<Front>,
pid: impl Into<Option<u32>>,
running: impl Fn() -> io::Result<bool>,
in_cgroup: impl FnOnce() -> Result<bool, Error>,
) -> Gate {
let pid = pid.into();
let Some(front) = front else {
return Gate::Open;
};
let mut unread = Unread::new();
match running() {
Ok(false) => return Gate::Exited,
Ok(true) => {}
Err(e) => unread.push(("whether it had exited could not be read", Error::Io(e))),
}
let placed = in_cgroup();
if !matches!(placed, Ok(true)) && matches!(running(), Ok(false)) {
return Gate::Exited;
}
match placed {
Ok(true) => Gate::CgroupOnly(front),
Ok(false) => Gate::Closed(refused(front, pid, Signal::Kill, unread_reason(unread))),
Err(e) => {
unread.push(("whether its cgroup kill reaches it could not be read", e));
Gate::Closed(refused(front, pid, Signal::Kill, unread_reason(unread)))
}
}
}
type Unread = Vec<(&'static str, Error)>;
struct Reason {
words: String,
cause: Option<std::sync::Arc<Error>>,
}
impl Reason {
fn words(words: impl Into<String>) -> Reason {
Reason {
words: words.into(),
cause: None,
}
}
}
fn unread_reason(unread: Unread) -> Option<Reason> {
let words = unread.iter().map(|(what, _)| *what).collect::<Vec<_>>().join("; ");
let cause = Failures::collect(unread.into_iter().map(|(_, e)| std::sync::Arc::new(e)))?.into_cause();
Some(Reason {
words,
cause: Some(cause),
})
}
fn cgroup_kill_reached(
front: Front,
pid: impl Into<Option<u32>>,
exited: impl Fn() -> io::Result<bool>,
under_leaf: impl FnOnce() -> Result<bool, Error>,
) -> Result<(), Error> {
let pid = pid.into();
let mut unread = Unread::new();
match exited() {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => unread.push(("whether it had exited could not be read", Error::Io(e))),
}
let placed = under_leaf();
if !matches!(placed, Ok(true)) && matches!(exited(), Ok(true)) {
return Ok(());
}
let why = match placed {
Ok(true) => return Ok(()),
Ok(false) => "it reads as having left the cgroup before its kill, which did not reach it".to_owned(),
Err(e) => {
unread.push(("its cgroup could not be read", e));
"nothing shows the cgroup kill reached it".to_owned()
}
};
let reason = match unread_reason(unread) {
None => Reason::words(why),
Some(Reason { words, cause }) => Reason {
words: format!("{why} ({words})"),
cause,
},
};
Err(refused(front, pid, Signal::Kill, Some(reason)))
}
fn cgroup_kill_failed(front: Front, pid: impl Into<Option<u32>>, error: Error) -> Error {
let reason = Reason {
words: "its cgroup kill failed".to_owned(),
cause: Some(std::sync::Arc::new(error)),
};
refused(front, pid, Signal::Kill, Some(reason))
}
fn cgroup_not_killed(front: Front, pid: impl Into<Option<u32>>) -> Error {
refused(
front,
pid,
Signal::Kill,
Some(Reason::words("its cgroup was not killed")),
)
}
fn terminate_gate(
front: Option<Front>,
pid: impl Into<Option<u32>>,
running: impl FnOnce() -> io::Result<bool>,
) -> Gate {
let pid = pid.into();
let Some(front) = front.filter(|f| !f.relays_term()) else {
return Gate::Open;
};
match running() {
Ok(false) => Gate::Open,
Ok(true) => Gate::Closed(refused(front, pid, Signal::Term, None)),
Err(e) => Gate::Closed(refused(
front,
pid,
Signal::Term,
unread_reason(vec![("whether it had exited could not be read", Error::Io(e))]),
)),
}
}
pub(crate) fn describe(front: Front, pid: impl Into<Option<u32>>) -> String {
let subject = pid
.into()
.map_or_else(|| "the spawned child".to_owned(), |pid| format!("pid {pid}"));
if front.may_be_the_program() {
format!(
"{subject} is what {name} left this process tracking: {name} itself, which runs as this user and \
outlives the elevated program it launched, so a kill would orphan the program, or, with direct exec, \
the root program itself, whose kill is refused",
name = front.name()
)
} else {
format!(
"{subject} is {name}, which runs as this user and outlives the elevated program it launched, so a signal \
would end {name} and orphan the program",
name = front.name()
)
}
}
#[derive(Clone, Copy)]
enum Signal {
Kill,
Term,
}
fn refused(front: Front, pid: impl Into<Option<u32>>, signal: Signal, why: Option<Reason>) -> Error {
let what = match signal {
Signal::Kill => "no kill",
Signal::Term => "no SIGTERM",
};
let mut detail = format!("{}; {what} was sent.", describe(front, pid));
if matches!(signal, Signal::Kill) && !matches!(front, Front::Osascript) {
detail.push_str(" Only a cgroup (Linux containment) that holds it reaches the program.");
}
let mut source = None;
if let Some(Reason { words, cause }) = why {
detail.push_str(&format!(" ({words})"));
source = cause;
}
Error::Elevation {
kind: ElevationErrorKind::Unkillable,
detail,
source,
}
}
#[cfg(test)]
#[path = "front_tests.rs"]
mod front_tests;