Skip to main content

bounded_command/
command.rs

1//! The `Command` helpers Tilo's domains share: bounded subprocess execution, so every shell-out
2//! shares one error vocabulary (missing binary, non-zero exit, spawn failure) and hands it
3//! straight to `tracing::warn!`.
4
5use std::collections::HashMap;
6use std::sync::{Mutex, OnceLock};
7
8/// Applies to every shell-out that names no deadline of its own: a tool that exceeds it is killed
9/// and reported as a timeout.
10pub const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2_500);
11
12/// Eight MiB is far above legitimate status or list output, and bounds what a compromised daemon or a
13/// network-derived response can make the caller hold.
14pub const MAX_CAPTURE_BYTES: usize = 8 * 1024 * 1024;
15
16/// A binary does not appear on or vanish from `$PATH` during a session, so the probe is memoised: one
17/// spawn per binary per session.
18fn which_cache() -> &'static Mutex<HashMap<String, bool>> {
19    static CACHE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
20    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
21}
22
23/// Walks `$PATH` in-process rather than shelling out to `which(1)`, which the image does not carry.
24pub fn which(binary: &str) -> bool {
25    if let Ok(cache) = which_cache().lock()
26        && let Some(hit) = cache.get(binary)
27    {
28        return *hit;
29    }
30    let found = path_lookup(binary);
31    if let Ok(mut cache) = which_cache().lock() {
32        cache.insert(binary.to_string(), found);
33    }
34    found
35}
36
37/// A name with a separator is a path, not a `$PATH` lookup, as `execvp` treats it.
38fn path_lookup(binary: &str) -> bool {
39    /// Whether `p` names something this system runs: an executable file on Unix, and on Windows
40    /// a file, whose extension `CreateProcess` takes from `PATHEXT` when the name carries none.
41    fn is_executable_file(p: &std::path::Path) -> bool {
42        #[cfg(unix)]
43        {
44            use std::os::unix::fs::PermissionsExt as _;
45            std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
46        }
47        #[cfg(not(unix))]
48        {
49            std::fs::metadata(p).is_ok_and(|m| m.is_file())
50        }
51    }
52
53    #[cfg(test)]
54    tests::PATH_LOOKUPS.with(|lookups| lookups.set(lookups.get().saturating_add(1)));
55
56    if binary.is_empty() {
57        return false;
58    }
59    if binary.contains('/') || binary.contains(std::path::MAIN_SEPARATOR) {
60        return is_executable_file(std::path::Path::new(binary));
61    }
62    let Some(path) = std::env::var_os("PATH") else {
63        return false;
64    };
65    std::env::split_paths(&path)
66        .filter(|dir| !dir.as_os_str().is_empty())
67        .any(|dir| is_executable_file(&dir.join(binary)))
68}
69
70/// Runs `binary args...` under [`DEFAULT_TIMEOUT`], capturing stdout. A wedged or restarting daemon
71/// otherwise leaves its client blocked with no bound, and on the compositor's thread that stops the
72/// desktop painting; a deadline turns it into a stale reading, which callers already handle. stdout and
73/// stderr are drained on their own threads, because polling while the child writes into an unread pipe
74/// deadlocks once the pipe buffer fills.
75pub fn run_capture(binary: &str, args: &[&str]) -> Result<String, String> {
76    run_capture_within(binary, args, DEFAULT_TIMEOUT)
77}
78
79pub fn run_capture_within(
80    binary: &str,
81    args: &[&str],
82    timeout: std::time::Duration,
83) -> Result<String, String> {
84    if !which(binary) {
85        return Err(format!("{binary} not installed"));
86    }
87    let output = crate::run(binary, args, None, MAX_CAPTURE_BYTES, timeout)
88        .map_err(|error| bounded_error(binary, error))?;
89    if !output.status.success() {
90        let stderr = output.stderr_diagnostic();
91        return Err(format!(
92            "{binary} exited with status {:?}: {stderr}",
93            output.status.code()
94        ));
95    }
96    String::from_utf8(output.stdout).map_err(|e| format!("{binary} stdout not utf-8: {e}"))
97}
98
99pub fn run(binary: &str, args: &[&str]) -> Result<(), String> {
100    let _ = run_capture(binary, args)?;
101    Ok(())
102}
103
104fn bounded_error(binary: &str, error: crate::Error) -> String {
105    match error {
106        crate::Error::InputTooLarge => {
107            format!("{binary} input exceeded the safety limit")
108        }
109        crate::Error::OutputTooLarge { limit, .. } => {
110            format!("{binary} output exceeded the {limit} byte safety limit")
111        }
112        crate::Error::Timeout(milliseconds) => {
113            format!("{binary} timed out after {milliseconds} ms")
114        }
115        other => format!("{binary} process failed: {other}"),
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use std::time::Instant;
123
124    thread_local! {
125        pub(super) static PATH_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
126    }
127
128    #[test]
129    fn helper_commands_are_bounded_by_output_limits_and_deadlines() {
130        {
131            assert!(which("head"), "head is required for the output-limit probe");
132            let bytes = (MAX_CAPTURE_BYTES + 4096).to_string();
133            let args = ["-c", bytes.as_str(), "/dev/zero"];
134            // The output ceiling is under test; the deadline only catches a hang.
135            let capture = run_capture_within("head", &args, tilo_test_env::hang_bound())
136                .expect_err("oversized stdout must be rejected");
137            assert!(capture.contains("output exceeded"), "{capture}");
138        }
139        // A command that never exits is killed at the deadline and reported as a timeout rather than
140        // blocking its caller.
141        {
142            // No `sleep` binary means the deadline cannot be exercised. Fail rather than skip: a check
143            // that cannot look is not a check that passed.
144            assert!(
145                which("sleep"),
146                "`sleep` is required to exercise the run_capture deadline"
147            );
148            // The child outlives the hang bound, so returning within it proves the kill fired at
149            // `run_capture`'s own deadline.
150            let over = tilo_test_env::hang_bound().as_secs() * 2;
151            let arg = format!("{over}");
152            let started = Instant::now();
153            let result = run_capture("sleep", &[arg.as_str()]);
154            let elapsed = started.elapsed();
155
156            let err = result.expect_err("a command outliving the deadline must not report success");
157            assert!(
158                err.contains("timed out"),
159                "expected a timeout error, got: {err}"
160            );
161            assert!(
162                elapsed < tilo_test_env::hang_bound(),
163                "run_capture returned after {elapsed:?}; its {DEFAULT_TIMEOUT:?} kill path did \
164                 not fire"
165            );
166        }
167    }
168
169    #[test]
170    fn which_resolves_from_path_memoised_and_reports_missing_binaries() {
171        // The probe answers from `$PATH` itself: asserting on `sh`, which is always present, keeps a
172        // third binary out of the question.
173        {
174            assert!(
175                which("sh"),
176                "`sh` is on $PATH in every environment this runs in; a probe \
177                 that cannot see it is answering about itself"
178            );
179            assert!(
180                !which("tilo-no-such-binary-should-ever-exist"),
181                "a name that is on no $PATH entry must not be reported as found"
182            );
183            // A name containing a separator is a path, not a $PATH lookup.
184            assert!(which("/bin/sh") || which("/usr/bin/sh"));
185            assert!(!which("/definitely/not/here/sh"));
186            assert!(!which(""), "the empty name is not a binary");
187        }
188        // `which` answers from its memo after the first probe, so repeated shell-outs do not pay a
189        // second spawn.
190        {
191            let first = which("sh");
192            let looked = PATH_LOOKUPS.with(std::cell::Cell::get);
193            for _ in 0..200 {
194                assert_eq!(which("sh"), first);
195            }
196            let lookups = PATH_LOOKUPS.with(std::cell::Cell::get) - looked;
197            assert_eq!(
198                lookups, 0,
199                "200 memoised probes looked up $PATH {lookups} times"
200            );
201        }
202        // Setters that shell out never panic when the binary is missing: they return a `"<binary> not
203        // installed"` error.
204        {
205            let r = run("definitely-not-a-real-binary-tilo-test", &["--help"]);
206            assert!(r.is_err());
207            let msg = r.unwrap_err();
208            assert!(msg.contains("not installed"), "got: {msg}");
209        }
210    }
211}