use std::io::{BufRead as _, BufReader};
use crate::test_child::Console;
use std::time::Duration;
use crate::error::Error;
use crate::log_capture::warns_since;
use crate::os_process::child::{Foreign, PeekOutcome};
use crate::os_process::fake::FakeProcess;
use crate::send_log::{Capture, Via};
use crate::signal::Sig;
use crate::ContainMode;
fn blocker(
mode: ContainMode,
elevation: Option<crate::elevation::ElevationReport>,
) -> (crate::Child, crate::PipeWriter) {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
cmd.contain_with(mode);
cmd.set_elevation_report(elevation);
(cmd.spawn().expect("spawn"), writer)
}
fn degraded_blocker(
mode: ContainMode,
elevation: Option<crate::elevation::ElevationReport>,
) -> (crate::Child, crate::PipeWriter) {
use crate::containment::fdmarker::fault::{lock_for_log_assertion, set_fault, Fault};
let _serialize = lock_for_log_assertion();
set_fault(Some(Fault::Pipe));
let spawned = blocker(mode, elevation);
set_fault(None);
spawned
}
pub(crate) fn walked_blocker() -> (crate::Child, crate::PipeWriter) {
walked_blocker_reporting(None)
}
fn walked_blocker_reporting(elevation: Option<crate::elevation::ElevationReport>) -> (crate::Child, crate::PipeWriter) {
let (child, writer) = degraded_blocker(ContainMode::TreeWalk, elevation);
assert!(
child.containment() == crate::containment::Containment::TreeWalk,
"the test needs a tree walk"
);
(child, writer)
}
pub(crate) fn session_blocker() -> (crate::Child, crate::PipeWriter) {
let (child, writer) = blocker(ContainMode::Session, None);
assert!(
child.containment() == crate::containment::Containment::FdMarker,
"the test needs an fd marker"
);
(child, writer)
}
pub(crate) fn group_blocker() -> (crate::Child, crate::PipeWriter) {
let (child, writer) = degraded_blocker(ContainMode::Session, None);
assert!(
child.containment() == crate::containment::Containment::Session,
"the test needs a session's process group"
);
(child, writer)
}
pub(crate) fn session_tree() -> (crate::Child, crate::PipeWriter, u32, crate::PipeReader) {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args([
"sh",
"-c",
"exec 3<&0; cat <&3 3<&- >/dev/null & echo $!; exec 3<&- 4>&-; exec cat",
]);
cmd.stdin(stdin).expect("set stdin");
cmd.stdout(crate::Stdio::pipe()).expect("set stdout");
cmd.fd(4, crate::Stdio::pipe_out()).expect("set the descendant's pipe");
cmd.contain_with(ContainMode::Session);
let mut child = cmd.spawn().expect("spawn");
let mut line = String::new();
BufReader::new(child.stdout().expect("piped stdout"))
.read_line(&mut line)
.expect("the descendant's pid");
let gone = child.fd_read_end(4.into()).expect("the descendant's pipe");
(child, writer, line.trim().parse().expect("a pid"), gone)
}
pub(crate) fn assert_descendant_dies(mut gone: crate::PipeReader) {
let mut rest = Vec::new();
std::io::Read::read_to_end(&mut gone, &mut rest).expect("the descendant's pipe reaches EOF");
assert!(rest.is_empty(), "unexpected output from the descendant: {rest:?}");
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Untrusted {
Unpinned,
Unknown,
}
pub(crate) const BOTH: [Untrusted; 2] = [Untrusted::Unpinned, Untrusted::Unknown];
impl Untrusted {
pub(crate) fn script(self, child: &mut crate::Child) -> FakeProcess {
child.proc.script_over(|f| f.peeks([self.result()]))
}
pub(crate) fn result(self) -> std::io::Result<PeekOutcome> {
match self {
Untrusted::Unpinned => Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
Untrusted::Unknown => Err(std::io::Error::other("unreadable")),
}
}
pub(crate) fn why(self) -> &'static str {
match self {
Untrusted::Unpinned => "launchd holds its zombie",
Untrusted::Unknown => "RootState::Unknown",
}
}
pub(crate) fn cause(self) -> Cause {
match self {
Untrusted::Unpinned => Cause::None,
Untrusted::Unknown => Cause::Unreadable,
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Cause {
None,
Unreadable,
ForcedTerm,
}
impl Cause {
#[track_caller]
pub(crate) fn assert(self, source: &Option<std::sync::Arc<Error>>) {
match (self, source) {
(Cause::None, None) => {}
(Cause::None, Some(cause)) => panic!("expected no source, got {cause:?}"),
(_, None) => panic!("expected {self:?} as the source, got none"),
(Cause::Unreadable, Some(cause)) => {
let said = crate::error::said(&**cause);
assert!(said.contains("unreadable"), "{said}");
}
(Cause::ForcedTerm, Some(cause)) => assert!(
matches!(&**cause, Error::Containment { detail, .. } if detail.contains("forced term_group refusal")),
"{cause:?}"
),
}
}
}
pub(crate) fn orphan(child: &mut crate::Child) -> FakeProcess {
Untrusted::Unpinned.script(child)
}
#[track_caller]
pub(crate) fn assert_refused(err: &Error, op: &str) {
assert_refused_caused_by(err, op, Cause::None);
}
#[track_caller]
pub(crate) fn assert_refused_caused_by(err: &Error, op: &str, cause: Cause) {
match err {
Error::Unassessable { detail, source } => {
assert!(
detail.contains("launchd")
&& detail.contains(&format!("{op} sent nothing"))
&& !detail.contains("(launchd"),
"{detail}"
);
cause.assert(source);
}
other => panic!("expected Unassessable, got {other:?}"),
}
}
#[track_caller]
pub(crate) fn assert_tree_refused(err: &Error, op: &str, state: Untrusted) {
assert_tree_refused_caused_by(err, op, state, state.cause());
}
#[track_caller]
pub(crate) fn assert_tree_refused_caused_by(err: &Error, op: &str, state: Untrusted, cause: Cause) {
match err {
Error::Unassessable { detail, source } => {
assert!(
detail.contains(state.why())
&& detail.contains(&format!("{op} sent nothing"))
&& detail.contains("named by the root's number"),
"{state:?}: {detail}"
);
cause.assert(source);
}
other => panic!("{state:?}: expected Unassessable, got {other:?}"),
}
}
#[track_caller]
pub(crate) fn assert_holders_only(err: &Error, op: &str, state: Untrusted) {
match err {
Error::Unassessable { detail, source } => {
assert!(
detail.contains(state.why()) && detail.contains(&format!("{op} signalled the marker holders")),
"{state:?}: {detail}"
);
state.cause().assert(source);
}
other => panic!("{state:?}: expected Unassessable, got {other:?}"),
}
}
#[track_caller]
pub(crate) fn assert_nothing_sent(sends: &Capture) {
assert_eq!(sends.entries(), vec![], "nothing may be sent to a root we do not pin");
assert_eq!(sends.by_identity(), vec![], "nothing may be sent by identity either");
}
#[track_caller]
pub(crate) fn sorted(mut pids: Vec<u32>) -> Vec<u32> {
pids.sort_unstable();
pids.dedup();
pids
}
#[track_caller]
pub(crate) fn assert_sent_by_identity(sends: &Capture, signo: i32, want: &[u32], what: impl std::fmt::Debug) {
let sent: Vec<u32> = sends
.by_identity()
.into_iter()
.filter(|&(_, sent)| sent == signo)
.map(|(pid, _)| pid)
.collect();
for pid in want {
assert!(
sent.contains(pid),
"{what:?}: signal {signo} never went to pid {pid}: {sent:?}"
);
}
}
#[skuld::test]
fn kill_of_an_orphaned_root_sends_nothing() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = orphan(&mut child);
let err = child
.kill()
.expect_err("a root this process does not pin is not killed");
fake.assert_peeks_exhausted();
assert_refused(&err, "kill");
assert_nothing_sent(&sends);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
child.kill().expect("an unreaped root is killed");
assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Identity)]);
drop(writer);
}
#[skuld::test]
fn kill_of_an_unknown_root_is_sent_through_its_handle() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let fake = Untrusted::Unknown.script(&mut child);
child.kill().expect("an unknown root is killed through its handle");
fake.assert_peeks_exhausted();
assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Identity)]);
drop(writer);
}
#[skuld::test]
fn terminate_of_an_orphaned_root_sends_nothing() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = orphan(&mut child);
let err = child
.terminate()
.expect_err("a root this process does not pin is not signalled");
fake.assert_peeks_exhausted();
assert_refused(&err, "terminate");
assert_nothing_sent(&sends);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
child.terminate().expect("an unreaped root is signalled");
assert_eq!(sends.by_identity(), vec![(pid, libc::SIGTERM)]);
drop(writer);
}
#[skuld::test]
fn terminate_of_an_unknown_root_is_sent_through_its_handle() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let fake = Untrusted::Unknown.script(&mut child);
child.terminate().expect("an unknown root is signalled");
fake.assert_peeks_exhausted();
assert_eq!(sends.by_identity(), vec![(pid, libc::SIGTERM)]);
drop(writer);
}
#[skuld::test]
fn kill_tree_of_an_untrusted_walked_root_sends_nothing() {
crate::log_capture::install();
for state in BOTH {
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let walks = crate::containment::treewalk::fault::record_walks();
let mark = crate::log_capture::mark();
let fake = state.script(&mut child);
let err = child
.kill_tree()
.expect_err("the walk names the tree by the root's number");
fake.assert_peeks_exhausted();
assert_tree_refused(&err, "kill_tree", state);
assert_nothing_sent(&sends);
assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
child.kill_tree().expect("an unreaped root is killed with its tree");
assert!(
sends.by_identity().contains(&(pid, libc::SIGKILL)),
"{state:?}: {:?}",
sends.by_identity()
);
drop(writer);
}
}
#[skuld::test]
fn kill_tree_of_an_untrusted_group_root_sends_no_killpg() {
crate::log_capture::install();
for state in BOTH {
let groups = crate::containment::unix::fault::record_kill_group();
let (mut child, writer) = group_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = state.script(&mut child);
let err = child.kill_tree().expect_err("the group is named by the root's number");
fake.assert_peeks_exhausted();
assert_tree_refused(&err, "kill_tree", state);
assert_nothing_sent(&sends);
assert_eq!(groups.killed(), Vec::<i32>::new(), "{state:?}");
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
child.kill_tree().expect("an unreaped root is killed with its group");
assert_eq!(
groups.killed(),
vec![pid as i32],
"{state:?}: the group call was reached"
);
drop(writer);
}
}
#[skuld::test]
fn kill_tree_of_an_untrusted_session_root_kills_its_holders_only() {
crate::log_capture::install();
for state in BOTH {
let groups = crate::containment::unix::fault::record_kill_group();
let walks = crate::containment::treewalk::fault::record_walks();
let holders = crate::containment::fdmarker::fault::record_holder_kills();
let (mut child, writer, descendant, gone) = session_tree();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = state.script(&mut child);
let err = child
.kill_tree()
.expect_err("every holder was reached, but the kill skipped the rest of the tree");
assert_holders_only(&err, "kill_tree", state);
fake.assert_peeks_exhausted();
assert_eq!(groups.killed(), Vec::<i32>::new(), "{state:?}");
assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
assert_eq!(sends.entries(), vec![], "{state:?}: nothing by pid");
let want = match state {
Untrusted::Unpinned => vec![descendant],
Untrusted::Unknown => sorted(vec![pid, descendant]),
};
assert_eq!(sorted(holders.killed()), want, "{state:?}");
assert_sent_by_identity(&sends, libc::SIGKILL, &want, state);
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
assert_descendant_dies(gone);
drop(writer);
}
}
#[skuld::test]
fn kill_tree_kills_a_trusted_session_root() {
let (child, writer) = session_blocker();
child.kill_tree().expect("a trusted root is killed with its group");
drop(writer);
crate::test_child::assert_killed("the session root", child.wait().expect("wait"));
}
#[skuld::test]
fn terminate_tree_of_an_untrusted_walked_root_sends_nothing() {
crate::log_capture::install();
for state in BOTH {
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let walks = crate::containment::treewalk::fault::record_walks();
let mark = crate::log_capture::mark();
let fake = state.script(&mut child);
let err = child
.terminate_tree()
.expect_err("the walk names the tree by the root's number");
fake.assert_peeks_exhausted();
assert_tree_refused(&err, "terminate_tree", state);
assert_nothing_sent(&sends);
assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
child
.terminate_tree()
.expect("an unreaped root is signalled with its tree");
assert!(
sends.by_identity().contains(&(pid, libc::SIGTERM)),
"{state:?}: {:?}",
sends.by_identity()
);
drop(writer);
}
}
#[skuld::test]
fn terminate_tree_of_an_untrusted_group_root_sends_no_killpg() {
crate::log_capture::install();
for state in BOTH {
let groups = crate::containment::unix::fault::record_term_group();
let (mut child, writer) = group_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = state.script(&mut child);
let err = child
.terminate_tree()
.expect_err("the group is named by the root's number");
fake.assert_peeks_exhausted();
assert_tree_refused(&err, "terminate_tree", state);
assert_nothing_sent(&sends);
assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}");
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
child
.terminate_tree()
.expect("an unreaped root is signalled with its group");
assert_eq!(
groups.termed(),
vec![pid as i32],
"{state:?}: the group call was reached"
);
drop(writer);
}
}
#[skuld::test]
fn terminate_tree_of_an_untrusted_session_root_signals_its_holders_only() {
crate::log_capture::install();
for state in BOTH {
let groups = crate::containment::unix::fault::record_term_group();
let walks = crate::containment::treewalk::fault::record_walks();
let holders = crate::containment::fdmarker::fault::record_holder_kills();
let (mut child, writer, descendant, gone) = session_tree();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = state.script(&mut child);
child
.terminate_tree()
.expect("every holder was reached, so the tree was asked to stop");
fake.assert_peeks_exhausted();
assert_eq!(groups.termed(), Vec::<i32>::new(), "{state:?}");
assert_eq!(walks.walked(), Vec::<u32>::new(), "{state:?}");
assert_eq!(sends.entries(), vec![], "{state:?}: nothing by pid");
let want = match state {
Untrusted::Unpinned => vec![descendant],
Untrusted::Unknown => sorted(vec![pid, descendant]),
};
assert_eq!(sorted(holders.killed()), want, "{state:?}");
assert_sent_by_identity(&sends, libc::SIGTERM, &want, state);
assert_eq!(warns_since(mark, ""), Vec::<String>::new(), "{state:?}");
assert_descendant_dies(gone);
drop(writer);
}
}
#[skuld::test]
fn terminate_tree_terminates_a_trusted_session_root() {
use std::os::unix::process::ExitStatusExt as _;
let (child, writer) = session_blocker();
child
.terminate_tree()
.expect("a trusted root is signalled with its group");
drop(writer);
assert_eq!(child.wait().expect("wait").signal(), Some(libc::SIGTERM));
}
#[skuld::test]
fn terminate_tree_decides_on_one_look_at_the_root() {
let groups = crate::containment::unix::fault::record_term_group();
let (mut child, writer) = group_blocker();
let pid = child.pid();
let fake = child
.proc
.script_over(|f| f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));
child.terminate_tree().expect("a running root's group is signalled");
assert_eq!(fake.peeks_left(), 1, "the decision looked at the root twice");
drop(fake.peeks([]));
assert_eq!(groups.termed(), vec![pid as i32]);
drop(writer);
}
#[skuld::test]
fn kill_tree_decides_on_one_look_at_the_root() {
let groups = crate::containment::unix::fault::record_kill_group();
let (mut child, writer) = group_blocker();
let pid = child.pid();
let fake = child.proc.script_over(|f| {
f.peeks([
Ok(PeekOutcome::Running),
Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
])
});
child.kill_tree().expect("a running root's group is killed");
assert_eq!(fake.peeks_left(), 1, "the decision looked at the root twice");
drop(fake.peeks([]));
assert_eq!(groups.killed(), vec![pid as i32]);
drop(writer);
}
#[skuld::test]
fn kill_tree_skips_its_backstop_for_a_root_orphaned_during_the_sweep() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let mark = crate::log_capture::mark();
let fake = child
.proc
.script_over(|f| f.peeks([Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));
child
.kill_tree()
.expect("the sweep killed the tree; the backstop has nothing to do");
fake.assert_peeks_exhausted();
assert_eq!(
sends.entries(),
vec![(pid, Sig::Kill, Via::Identity)],
"the backstop must send nothing after the walk's own kill of the root"
);
assert!(
sends.by_identity().contains(&(pid, libc::SIGKILL)),
"the sweep ran first"
);
assert_eq!(warns_since(mark, ""), Vec::<String>::new());
drop(writer);
}
#[skuld::test]
fn kill_tree_keeps_its_backstop_for_an_unknown_root() {
crate::log_capture::install();
let (mut child, writer) = walked_blocker();
let pid = child.pid();
let sends = Capture::start();
let fake = child
.proc
.script_over(|f| f.peeks([Ok(PeekOutcome::Running), Err(std::io::Error::other("unreadable"))]));
child.kill_tree().expect("the backstop kills through the handle");
fake.assert_peeks_exhausted();
assert_eq!(
sends.entries(),
vec![(pid, Sig::Kill, Via::Identity), (pid, Sig::Kill, Via::Identity)]
);
drop(writer);
}
#[skuld::test]
fn an_uncontained_child_hears_why_it_has_no_tree_not_why_its_root_is_unpinned() {
let (stdin, writer) = crate::test_child::held_writer_stdin();
let mut cmd = crate::test_child::command(Console::Hidden);
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(stdin).expect("set stdin");
let mut child = cmd.spawn().expect("spawn");
let fake = child
.proc
.script_over(|f| f.peeks([Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));
for (op, result) in [
("kill_tree", child.kill_tree()),
("terminate_tree", child.terminate_tree()),
(
"graceful_shutdown_tree",
child.graceful_shutdown_tree(Duration::ZERO).map(drop),
),
] {
assert!(
matches!(result, Err(Error::Unsupported { .. })),
"{op}: expected the containment error, got {result:?}"
);
}
assert_eq!(fake.peeks_left(), 1, "the root's state was read");
drop(fake.peeks([]));
drop(writer);
}
#[skuld::test]
fn a_closed_front_gate_outranks_an_unpinned_root() {
use crate::elevation::{Backend, ElevatedVia};
for op in ["kill", "terminate", "kill_tree"] {
let (mut child, writer) =
walked_blocker_reporting(Some(crate::elevation::elevation_tests::report(if op == "terminate" {
ElevatedVia::MacosOsascript
} else {
ElevatedVia::Wrapped(Backend::Sudo)
})));
let peeks = if op == "terminate" {
vec![Ok(PeekOutcome::Running), Ok(PeekOutcome::Foreign(Foreign::Orphaned))]
} else {
vec![
Ok(PeekOutcome::Running),
Ok(PeekOutcome::Running),
Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
]
};
let fake = child.proc.script_over(|f| f.peeks(peeks));
let err = match op {
"kill" => child.kill(),
"terminate" => child.terminate(),
_ => child.kill_tree(),
}
.expect_err("the front is not signalled");
assert!(
matches!(
err,
Error::Elevation {
kind: crate::error::ElevationErrorKind::Unkillable,
..
}
),
"{op}: {err:?}"
);
assert_eq!(
fake.peeks_left(),
1,
"{op}: the root's state was read before the gate, or the gate was not"
);
drop(fake.peeks([]));
drop(writer);
}
}