use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
pub const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2_500);
pub const MAX_CAPTURE_BYTES: usize = 8 * 1024 * 1024;
fn which_cache() -> &'static Mutex<HashMap<String, bool>> {
static CACHE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn which(binary: &str) -> bool {
if let Ok(cache) = which_cache().lock()
&& let Some(hit) = cache.get(binary)
{
return *hit;
}
let found = path_lookup(binary);
if let Ok(mut cache) = which_cache().lock() {
cache.insert(binary.to_string(), found);
}
found
}
fn path_lookup(binary: &str) -> bool {
fn is_executable_file(p: &std::path::Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}
#[cfg(not(unix))]
{
std::fs::metadata(p).is_ok_and(|m| m.is_file())
}
}
#[cfg(test)]
tests::PATH_LOOKUPS.with(|lookups| lookups.set(lookups.get().saturating_add(1)));
if binary.is_empty() {
return false;
}
if binary.contains('/') || binary.contains(std::path::MAIN_SEPARATOR) {
return is_executable_file(std::path::Path::new(binary));
}
let Some(path) = std::env::var_os("PATH") else {
return false;
};
std::env::split_paths(&path)
.filter(|dir| !dir.as_os_str().is_empty())
.any(|dir| is_executable_file(&dir.join(binary)))
}
pub fn run_capture(binary: &str, args: &[&str]) -> Result<String, String> {
run_capture_within(binary, args, DEFAULT_TIMEOUT)
}
pub fn run_capture_within(
binary: &str,
args: &[&str],
timeout: std::time::Duration,
) -> Result<String, String> {
if !which(binary) {
return Err(format!("{binary} not installed"));
}
let output = crate::run(binary, args, None, MAX_CAPTURE_BYTES, timeout)
.map_err(|error| bounded_error(binary, error))?;
if !output.status.success() {
let stderr = output.stderr_diagnostic();
return Err(format!(
"{binary} exited with status {:?}: {stderr}",
output.status.code()
));
}
String::from_utf8(output.stdout).map_err(|e| format!("{binary} stdout not utf-8: {e}"))
}
pub fn run(binary: &str, args: &[&str]) -> Result<(), String> {
let _ = run_capture(binary, args)?;
Ok(())
}
fn bounded_error(binary: &str, error: crate::Error) -> String {
match error {
crate::Error::InputTooLarge => {
format!("{binary} input exceeded the safety limit")
}
crate::Error::OutputTooLarge { limit, .. } => {
format!("{binary} output exceeded the {limit} byte safety limit")
}
crate::Error::Timeout(milliseconds) => {
format!("{binary} timed out after {milliseconds} ms")
}
other => format!("{binary} process failed: {other}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
thread_local! {
pub(super) static PATH_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[test]
fn helper_commands_are_bounded_by_output_limits_and_deadlines() {
{
assert!(which("head"), "head is required for the output-limit probe");
let bytes = (MAX_CAPTURE_BYTES + 4096).to_string();
let args = ["-c", bytes.as_str(), "/dev/zero"];
let capture = run_capture_within("head", &args, tilo_test_env::hang_bound())
.expect_err("oversized stdout must be rejected");
assert!(capture.contains("output exceeded"), "{capture}");
}
{
assert!(
which("sleep"),
"`sleep` is required to exercise the run_capture deadline"
);
let over = tilo_test_env::hang_bound().as_secs() * 2;
let arg = format!("{over}");
let started = Instant::now();
let result = run_capture("sleep", &[arg.as_str()]);
let elapsed = started.elapsed();
let err = result.expect_err("a command outliving the deadline must not report success");
assert!(
err.contains("timed out"),
"expected a timeout error, got: {err}"
);
assert!(
elapsed < tilo_test_env::hang_bound(),
"run_capture returned after {elapsed:?}; its {DEFAULT_TIMEOUT:?} kill path did \
not fire"
);
}
}
#[test]
fn which_resolves_from_path_memoised_and_reports_missing_binaries() {
{
assert!(
which("sh"),
"`sh` is on $PATH in every environment this runs in; a probe \
that cannot see it is answering about itself"
);
assert!(
!which("tilo-no-such-binary-should-ever-exist"),
"a name that is on no $PATH entry must not be reported as found"
);
assert!(which("/bin/sh") || which("/usr/bin/sh"));
assert!(!which("/definitely/not/here/sh"));
assert!(!which(""), "the empty name is not a binary");
}
{
let first = which("sh");
let looked = PATH_LOOKUPS.with(std::cell::Cell::get);
for _ in 0..200 {
assert_eq!(which("sh"), first);
}
let lookups = PATH_LOOKUPS.with(std::cell::Cell::get) - looked;
assert_eq!(
lookups, 0,
"200 memoised probes looked up $PATH {lookups} times"
);
}
{
let r = run("definitely-not-a-real-binary-tilo-test", &["--help"]);
assert!(r.is_err());
let msg = r.unwrap_err();
assert!(msg.contains("not installed"), "got: {msg}");
}
}
}