use std::io;
use crate::error::{ElevationErrorKind, Error, Failures};
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)]
pub(crate) 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)
}
}
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 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", 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(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, io::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)| Error::io_cause(e)))?.into_cause();
Some(Reason {
words,
cause: Some(cause),
})
}
pub(crate) fn cgroup_kill_reached(
front: Front,
pid: u32,
exited: impl Fn() -> io::Result<bool>,
under_leaf: impl FnOnce() -> io::Result<bool>,
) -> Result<(), Error> {
let exited = || {
#[cfg(test)]
if seams::reach_reads_running() {
return Ok(false);
}
exited()
};
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", 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(("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)))
}
pub(crate) fn cgroup_kill_failed(front: Front, pid: 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))
}
pub(crate) fn cgroup_not_killed(front: Front, pid: u32) -> Error {
refused(
front,
pid,
Signal::Kill,
Some(Reason::words("its cgroup was not killed")),
)
}
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,
unread_reason(vec![("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, 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)]
#[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;