use std::io;
use super::{Backend, ElevatedVia};
use crate::error::{ElevationErrorKind, Error};
#[derive(Debug)]
pub(crate) enum Gate {
Open,
Exited,
CgroupOnly,
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)
}
}
pub(crate) fn front(via: Option<&ElevatedVia>) -> Option<Front> {
match via? {
ElevatedVia::Wrapped(Backend::Sudo) => Some(Front::Sudo),
ElevatedVia::Wrapped(Backend::Doas) => Some(Front::Doas),
ElevatedVia::MacosOsascript => Some(Front::Osascript),
ElevatedVia::Wrapped(_) | ElevatedVia::WindowsUac | ElevatedVia::AlreadyElevated => None,
}
}
pub(crate) fn kill_gate(
front: Option<Front>,
pid: u32,
running: impl Fn() -> io::Result<bool>,
in_cgroup: impl FnOnce() -> io::Result<bool>,
) -> Gate {
#[cfg(test)]
seams::note_kill_gate();
let Some(front) = front else {
return Gate::Open;
};
let unread = match running() {
Ok(false) => return Gate::Exited,
Ok(true) => None,
Err(e) => Some(format!("whether it had exited could not be read: {e}")),
};
#[cfg(test)]
seams::run_between_gate_reads();
let placed = in_cgroup();
if !matches!(placed, Ok(true)) && matches!(running(), Ok(false)) {
return Gate::Exited;
}
match placed {
Ok(true) => Gate::CgroupOnly,
Ok(false) => Gate::Closed(refused(front, pid, Signal::Kill, unread)),
Err(e) => {
let why = format!("whether its cgroup kill reaches it could not be read: {e}");
let why = unread.map_or(why.clone(), |r| format!("{r}; {why}"));
Gate::Closed(refused(front, pid, Signal::Kill, Some(why)))
}
}
}
pub(crate) fn cgroup_kill_reached(
front: Option<Front>,
pid: u32,
exited: impl Fn() -> io::Result<bool>,
under_leaf: impl FnOnce() -> io::Result<bool>,
) -> Result<(), Error> {
let Some(front) = front else {
debug_assert!(false, "only a front's cgroup kill is checked");
return Err(Error::Containment {
detail: format!("pid {pid}'s cgroup kill is not shown to have reached it: it is no front"),
});
};
let exited = || {
#[cfg(test)]
if seams::reach_reads_running() {
return Ok(false);
}
exited()
};
let mut unread = Vec::new();
match exited() {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => unread.push(format!("whether it had exited could not be read: {e}")),
}
#[cfg(test)]
seams::run_between_reach_reads();
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(format!("its cgroup could not be read: {e}"));
"nothing shows the cgroup kill reached it".to_owned()
}
};
let why = if unread.is_empty() {
why
} else {
format!("{why} ({})", unread.join("; "))
};
Err(refused(front, pid, Signal::Kill, Some(why)))
}
pub(crate) fn cgroup_kill_failed(front: Option<Front>, pid: u32, error: Error) -> Error {
let Some(front) = front else {
debug_assert!(false, "only a front's cgroup kill is refused so");
return error;
};
cgroup_not_killed(front, pid, Some(&error.to_string()))
}
pub(crate) fn cgroup_not_killed_of(front: Option<Front>, pid: u32, failure: Option<&str>) -> Error {
let Some(front) = front else {
debug_assert!(false, "only a front's gate is CgroupOnly");
return Error::Containment {
detail: format!(
"pid {pid}'s cgroup was not killed{}",
failure.map_or(String::new(), |f| format!(": {f}"))
),
};
};
cgroup_not_killed(front, pid, failure)
}
pub(crate) fn cgroup_not_killed(front: Front, pid: u32, failure: Option<&str>) -> Error {
let why = match failure {
Some(failure) => format!("its cgroup kill failed: {failure}"),
None => "its cgroup was not killed".to_owned(),
};
refused(front, pid, Signal::Kill, Some(why))
}
pub(crate) fn terminate_gate(front: Option<Front>, pid: u32, running: impl FnOnce() -> io::Result<bool>) -> Gate {
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,
Some(format!("whether it had exited could not be read: {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: u32, signal: Signal, unread: Option<String>) -> 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.");
}
if let Some(why) = unread {
detail.push_str(&format!(" ({why})"));
}
Error::Elevation {
kind: ElevationErrorKind::Unkillable,
detail,
}
}
#[cfg(test)]
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux cgroup lane's tests count gates")
)]
pub(crate) mod seams {
use std::cell::Cell;
thread_local! {
static GATES: Cell<Option<u32>> = const { Cell::new(None) };
static BETWEEN_GATE_READS: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static BETWEEN_REACH_READS: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
static REACH_READS_RUNNING: Cell<u32> = const { Cell::new(0) };
}
pub(crate) fn read_front_running_at_the_first_reach_read() -> ReachReadsRunning {
REACH_READS_RUNNING.with(|f| f.set(1));
ReachReadsRunning(())
}
pub(crate) fn read_front_running_at_every_reach_read() -> ReachReadsRunning {
REACH_READS_RUNNING.with(|f| f.set(u32::MAX));
ReachReadsRunning(())
}
#[must_use = "fronts are read as they are again as soon as the guard is dropped"]
pub(crate) struct ReachReadsRunning(());
impl Drop for ReachReadsRunning {
fn drop(&mut self) {
REACH_READS_RUNNING.with(|f| f.set(0));
}
}
pub(super) fn reach_reads_running() -> bool {
REACH_READS_RUNNING.with(|f| {
let remaining = f.get();
if remaining != u32::MAX {
f.set(remaining.saturating_sub(1));
}
remaining > 0
})
}
pub(crate) fn set_between_gate_reads(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BETWEEN_GATE_READS, hook)
}
pub(super) fn run_between_gate_reads() {
crate::oneshot_hook::fire(&BETWEEN_GATE_READS);
}
pub(crate) fn set_between_reach_reads(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BETWEEN_REACH_READS, hook)
}
pub(super) fn run_between_reach_reads() {
crate::oneshot_hook::fire(&BETWEEN_REACH_READS);
}
pub(crate) fn count_kill_gates() -> GateCounter {
GATES.with(|g| g.set(Some(0)));
GateCounter(())
}
#[must_use = "counting stops as soon as the counter is dropped"]
pub(crate) struct GateCounter(());
impl GateCounter {
pub(crate) fn count(&self) -> u32 {
GATES.with(|g| g.get().expect("the counter is live"))
}
}
impl Drop for GateCounter {
fn drop(&mut self) {
GATES.with(|g| g.set(None));
}
}
pub(super) fn note_kill_gate() {
GATES.with(|g| {
if let Some(n) = g.get() {
g.set(Some(n + 1));
}
});
}
}
#[cfg(test)]
#[path = "front_tests.rs"]
mod front_tests;