Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

23.0 KB
Raw Blame
// ©AngelaMos | 2026
// process.rs

use std::io::{BufRead, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

pub const MAX_CAPTURED_BYTES: usize = 512 * 1024;
pub const DEFAULT_STEP_TIMEOUT_SECS: u64 = 1800;

const POLL_MS: u64 = 25;
const ENV_PATH: &str = "PATH";
const EXECUTABLE_BITS: u32 = 0o111;
const DRAIN_CHUNK_BYTES: usize = 16 * 1024;
pub const DRAIN_GRACE_MS: u64 = 2000;
const KILL_BIN: &str = "kill";
const SIGNAL_KILL: &str = "-KILL";
const SCRUBBED_PREFIXES: [&str; 4] = ["AFL_", "ASAN_", "UBSAN_", "MSAN_"];
const SCRUBBED_NAMES: [&str; 8] = [
    "CC", "CXX", "AR", "RANLIB", "NM", "AS", "CFLAGS", "CXXFLAGS",
];
const STREAM_SEPARATOR: &str = "\n--- stderr ---\n";
const TRUNCATION_NOTICE: &str = "\n[lisdex] output truncated\n";

#[derive(Debug, thiserror::Error)]
pub enum ProcessError {
    #[error("could not launch {program}: {source}")]
    Launch {
        program: String,
        source: std::io::Error,
    },
    #[error("io error while running {program}: {source}")]
    Io {
        program: String,
        source: std::io::Error,
    },
    #[error("output reader thread for {program} panicked")]
    ReaderPanicked { program: String },
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CommandSpec {
    pub program: String,
    pub args: Vec<String>,
    pub cwd: Option<PathBuf>,
    pub envs: Vec<(String, String)>,
}

impl CommandSpec {
    #[must_use]
    pub fn new(program: impl Into<String>) -> Self {
        Self {
            program: program.into(),
            args: Vec::new(),
            cwd: None,
            envs: Vec::new(),
        }
    }

    #[must_use]
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    #[must_use]
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    #[must_use]
    pub fn path_arg(self, arg: &Path) -> Self {
        self.arg(arg.display().to_string())
    }

    #[must_use]
    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        self.cwd = Some(cwd.into());
        self
    }

    #[must_use]
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.envs.push((key.into(), value.into()));
        self
    }

    #[must_use]
    pub fn envs<I, K, V>(mut self, envs: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        self.envs
            .extend(envs.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    #[must_use]
    pub fn has_env(&self, key: &str) -> bool {
        self.envs.iter().any(|(name, _)| name == key)
    }

    #[must_use]
    pub fn env_value(&self, key: &str) -> Option<&str> {
        self.envs
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value.as_str())
    }

    #[must_use]
    pub fn command_line(&self) -> String {
        let mut line = self.program.clone();
        for arg in &self.args {
            line.push(' ');
            line.push_str(arg);
        }
        line
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Execution {
    pub command_line: String,
    pub code: Option<i32>,
    pub success: bool,
    pub timed_out: bool,
    pub truncated: bool,
    pub output: String,
    pub stderr: String,
    pub duration: Duration,
}

impl Execution {
    #[must_use]
    pub fn tail(&self, lines: usize) -> String {
        let collected: Vec<&str> = self.output.lines().collect();
        let start = collected.len().saturating_sub(lines);
        collected[start..].join("\n")
    }

    // A tool writes progress to stdout and its verdict to stderr, so a window over the
    // combined capture is mostly chatter. Measured on a build that fails for a missing
    // dependency: of the fifteen lines reported, thirteen were `checking for stdio.h... yes`
    // and the two naming the cause were last. This reports what the tool actually
    // diagnosed. The whole capture is still written to the step's log either way, so
    // nothing is lost - only the failure LINE gets shorter and truer.
    #[must_use]
    pub fn diagnosis(&self, lines: usize) -> String {
        let collected: Vec<&str> = self
            .stderr
            .lines()
            .filter(|line| !line.trim().is_empty())
            .collect();
        if collected.is_empty() {
            return self.tail(lines);
        }
        let start = collected.len().saturating_sub(lines);
        collected[start..].join("\n")
    }
}

#[must_use]
pub fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path)
        .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & EXECUTABLE_BITS != 0)
}

#[must_use]
pub fn resolve_on_path(program: &str) -> Option<PathBuf> {
    if program.contains('/') {
        let path = PathBuf::from(program);
        return is_executable(&path).then_some(path);
    }
    let paths = std::env::var_os(ENV_PATH)?;
    std::env::split_paths(&paths).find_map(|dir| {
        let candidate = dir.join(program);
        is_executable(&candidate).then_some(candidate)
    })
}

pub type Captured = std::sync::Arc<std::sync::Mutex<Vec<u8>>>;

pub fn drain(
    mut stream: impl Read + Send + 'static,
    limit: usize,
) -> (Captured, std::thread::JoinHandle<()>) {
    let captured: Captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let sink = std::sync::Arc::clone(&captured);
    let handle = std::thread::spawn(move || {
        let mut chunk = [0u8; DRAIN_CHUNK_BYTES];
        loop {
            match stream.read(&mut chunk) {
                Ok(0) | Err(_) => break,
                Ok(read) => {
                    let Ok(mut buffer) = sink.lock() else { break };
                    let room = limit.saturating_sub(buffer.len());
                    if room > 0 {
                        buffer.extend_from_slice(&chunk[..read.min(room)]);
                    }
                }
            }
        }
    });
    (captured, handle)
}

pub fn fold_lines<T, F>(
    stream: impl Read + Send + 'static,
    init: T,
    mut fold: F,
) -> std::thread::JoinHandle<T>
where
    T: Send + 'static,
    F: FnMut(&mut T, &str) + Send + 'static,
{
    std::thread::spawn(move || {
        let mut accumulator = init;
        let reader = std::io::BufReader::new(stream);
        for line in reader.lines() {
            let Ok(line) = line else { break };
            fold(&mut accumulator, &line);
        }
        accumulator
    })
}

pub fn run_folding<T, F>(
    spec: &CommandSpec,
    timeout: Duration,
    init: T,
    fold: F,
) -> Result<(Execution, T), ProcessError>
where
    T: Send + 'static,
    F: FnMut(&mut T, &str) + Send + 'static,
{
    use std::os::unix::process::CommandExt;

    let started = Instant::now();
    let mut command = Command::new(&spec.program);
    command.args(&spec.args);
    if let Some(cwd) = &spec.cwd {
        command.current_dir(cwd);
    }
    for name in scrubbed_names(spec) {
        command.env_remove(name);
    }
    for (key, value) in &spec.envs {
        command.env(key, value);
    }

    let mut child = command
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|source| ProcessError::Launch {
            program: spec.program.clone(),
            source,
        })?;

    let folded = child
        .stdout
        .take()
        .map(|stream| fold_lines(stream, init, fold));
    let stderr = child
        .stderr
        .take()
        .map(|stream| drain(stream, MAX_CAPTURED_BYTES));

    let mut timed_out = false;
    let status = loop {
        if let Some(status) = child.try_wait().map_err(|source| ProcessError::Io {
            program: spec.program.clone(),
            source,
        })? {
            break status;
        }
        if started.elapsed() >= timeout {
            terminate(&mut child);
            timed_out = true;
            break child.wait().map_err(|source| ProcessError::Io {
                program: spec.program.clone(),
                source,
            })?;
        }
        std::thread::sleep(Duration::from_millis(POLL_MS));
    };

    let accumulator = match folded {
        Some(handle) => handle.join().map_err(|_| ProcessError::ReaderPanicked {
            program: spec.program.clone(),
        })?,
        None => {
            return Err(ProcessError::ReaderPanicked {
                program: spec.program.clone(),
            });
        }
    };

    let deadline = Instant::now() + Duration::from_millis(DRAIN_GRACE_MS);
    let mut diagnostic = Vec::new();
    if let Some((buffer, handle)) = stderr {
        while !handle.is_finished() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(POLL_MS));
        }
        diagnostic = take_captured(&buffer);
    }
    let stderr_text = String::from_utf8_lossy(&diagnostic).into_owned();

    Ok((
        Execution {
            command_line: spec.command_line(),
            code: status.code(),
            success: status.success() && !timed_out,
            timed_out,
            truncated: false,
            output: stderr_text.clone(),
            stderr: stderr_text,
            duration: started.elapsed(),
        },
        accumulator,
    ))
}

#[must_use]
pub fn take_captured(captured: &Captured) -> Vec<u8> {
    captured
        .lock()
        .map(|buffer| buffer.clone())
        .unwrap_or_default()
}

#[must_use]
pub fn scrubbed_names(spec: &CommandSpec) -> Vec<String> {
    std::env::vars()
        .map(|(name, _)| name)
        .filter(|name| {
            SCRUBBED_PREFIXES
                .iter()
                .any(|prefix| name.starts_with(prefix))
                || SCRUBBED_NAMES.contains(&name.as_str())
        })
        .filter(|name| !spec.has_env(name))
        .collect()
}

fn terminate(child: &mut std::process::Child) {
    let group = format!("-{}", child.id());
    let _ = Command::new(KILL_BIN)
        .arg(SIGNAL_KILL)
        .arg("--")
        .arg(&group)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
    let _ = child.kill();
}

pub fn run(spec: &CommandSpec, timeout: Duration) -> Result<Execution, ProcessError> {
    use std::os::unix::process::CommandExt;

    let started = Instant::now();
    let mut command = Command::new(&spec.program);
    command.args(&spec.args);
    if let Some(cwd) = &spec.cwd {
        command.current_dir(cwd);
    }
    for name in scrubbed_names(spec) {
        command.env_remove(name);
    }
    for (key, value) in &spec.envs {
        command.env(key, value);
    }

    let mut child = command
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|source| ProcessError::Launch {
            program: spec.program.clone(),
            source,
        })?;

    let stdout = child
        .stdout
        .take()
        .map(|stream| drain(stream, MAX_CAPTURED_BYTES));
    let stderr = child
        .stderr
        .take()
        .map(|stream| drain(stream, MAX_CAPTURED_BYTES));

    let mut timed_out = false;
    let status = loop {
        if let Some(status) = child.try_wait().map_err(|source| ProcessError::Io {
            program: spec.program.clone(),
            source,
        })? {
            break status;
        }
        if started.elapsed() >= timeout {
            terminate(&mut child);
            timed_out = true;
            break child.wait().map_err(|source| ProcessError::Io {
                program: spec.program.clone(),
                source,
            })?;
        }
        std::thread::sleep(Duration::from_millis(POLL_MS));
    };

    let deadline = Instant::now() + Duration::from_millis(DRAIN_GRACE_MS);
    let mut captured = Vec::new();
    let mut diagnostic = Vec::new();
    let mut truncated = false;
    for (drained, separator, is_stderr) in [(stdout, "", false), (stderr, STREAM_SEPARATOR, true)] {
        let Some((buffer, handle)) = drained else {
            continue;
        };
        while !handle.is_finished() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(POLL_MS));
        }
        let bytes = take_captured(&buffer);
        if bytes.is_empty() {
            continue;
        }
        truncated = truncated || bytes.len() >= MAX_CAPTURED_BYTES;
        if is_stderr {
            diagnostic.clone_from(&bytes);
        }
        // B79. The separator only separates when there is something in front of it. A compiler
        // writes its errors to stderr and nothing at all to stdout, so leading with the banner
        // put a BLANK FIRST LINE on the capture - and `tail` keeps that blank line whenever the
        // whole output is shorter than the window, which rendered `does not compile: ` with
        // seemingly nothing after the colon. The real text was on the following lines all along.
        if !captured.is_empty() {
            captured.extend_from_slice(separator.as_bytes());
        }
        captured.extend_from_slice(&bytes);
    }

    let mut output = String::from_utf8_lossy(&captured).into_owned();
    if truncated {
        output.push_str(TRUNCATION_NOTICE);
    }

    Ok(Execution {
        command_line: spec.command_line(),
        code: status.code(),
        success: status.success() && !timed_out,
        timed_out,
        truncated,
        output,
        stderr: String::from_utf8_lossy(&diagnostic).into_owned(),
        duration: started.elapsed(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn spec_builds_a_readable_command_line() {
        let spec = CommandSpec::new("cmake")
            .arg("-S")
            .arg("/src")
            .args(["-B", "/build"]);
        assert_eq!(spec.command_line(), "cmake -S /src -B /build");
    }

    #[test]
    fn spec_records_environment_lookups() {
        let spec = CommandSpec::new("make").env("CC", "afl-clang-lto");
        assert!(spec.has_env("CC"));
        assert_eq!(spec.env_value("CC"), Some("afl-clang-lto"));
        assert_eq!(spec.env_value("CXX"), None);
    }

    #[test]
    fn path_arg_renders_a_path_without_quoting() {
        let spec = CommandSpec::new("sh").path_arg(Path::new("/src/configure"));
        assert_eq!(spec.args, vec!["/src/configure".to_owned()]);
    }

    #[test]
    fn successful_command_captures_stdout() {
        let spec = CommandSpec::new("echo").arg("instrumented");
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(run.success);
        assert_eq!(run.code, Some(0));
        assert!(run.output.contains("instrumented"));
        assert!(!run.timed_out);
    }

    #[test]
    fn failing_command_reports_its_exit_code_and_stderr() {
        let spec = CommandSpec::new("sh").args(["-c", "echo boom >&2; exit 3"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(!run.success);
        assert_eq!(run.code, Some(3));
        assert!(run.output.contains("boom"));
    }

    #[test]
    fn stderr_is_captured_separately_from_stdout() {
        let spec = CommandSpec::new("sh").args(["-c", "echo out; echo err >&2"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert_eq!(run.stderr.trim(), "err");
        assert!(run.output.contains("out"));
        assert!(run.output.contains("err"));
    }

    #[test]
    fn a_silent_command_reports_empty_stderr() {
        let spec = CommandSpec::new("sh").args(["-c", "echo out"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(run.stderr.is_empty());
    }

    // B79. A compiler writes its errors to stderr and nothing to stdout, which is the shape
    // every failed harness build has. Leading the capture with the stream banner put a BLANK
    // FIRST LINE in front of the only text anyone wants, and `tail` keeps that blank whenever
    // the whole output is shorter than its window - which is how `does not compile: ` came to
    // render with seemingly nothing after the colon while the errors sat on the next lines.
    #[test]
    fn a_command_that_writes_only_to_stderr_does_not_lead_its_capture_with_a_blank_line() {
        let spec = CommandSpec::new("sh").args(["-c", "echo 'cannot find -lcrypto' >&2; exit 1"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(
            !run.output.starts_with('\n'),
            "capture led with a blank line: {:?}",
            run.output
        );
        assert_eq!(run.tail(12), "cannot find -lcrypto");
    }

    // The isolating control for the arm above: with BOTH streams written, the banner still has
    // to be there, or two interleaved streams read as one. Drop the separator entirely and this
    // goes red while the test above stays green.
    #[test]
    fn the_stream_banner_survives_when_there_is_stdout_in_front_of_it() {
        let spec = CommandSpec::new("sh").args(["-c", "echo out; echo err >&2"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(
            run.output.contains(STREAM_SEPARATOR.trim()),
            "the two streams ran together: {:?}",
            run.output
        );
        assert!(run.output.starts_with("out"));
    }

    #[test]
    fn a_hung_command_is_killed_at_the_timeout() {
        let spec = CommandSpec::new("sleep").arg("30");
        let run = run(&spec, Duration::from_millis(200)).unwrap();
        assert!(run.timed_out);
        assert!(!run.success);
    }

    #[test]
    fn large_output_is_captured_without_deadlocking_and_marked_truncated() {
        let spec = CommandSpec::new("sh").args([
            "-c",
            "i=0; while [ $i -lt 40000 ]; do echo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; i=$((i+1)); done",
        ]);
        let run = run(&spec, Duration::from_mins(1)).unwrap();
        assert!(run.success);
        assert!(run.truncated);
        assert!(run.output.len() >= MAX_CAPTURED_BYTES);
    }

    #[test]
    fn cwd_is_honoured() {
        let dir = crate::scratch::path("process-cwd");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("marker.txt"), "here").unwrap();
        let spec = CommandSpec::new("ls").cwd(&dir);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(run.output.contains("marker.txt"));
    }

    #[test]
    fn environment_reaches_the_child() {
        let spec = CommandSpec::new("sh")
            .args(["-c", "printf %s \"$LISDEX_PROBE\""])
            .env("LISDEX_PROBE", "present");
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert_eq!(run.output, "present");
    }

    #[test]
    fn missing_program_is_a_launch_error() {
        let spec = CommandSpec::new("lisdex-no-such-program-exists");
        assert!(matches!(
            run(&spec, Duration::from_secs(10)),
            Err(ProcessError::Launch { .. })
        ));
    }

    #[test]
    fn tail_returns_the_last_lines_only() {
        let spec = CommandSpec::new("sh").args(["-c", "printf 'one\\ntwo\\nthree\\n'"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert_eq!(run.tail(2), "two\nthree");
    }

    #[test]
    fn a_diagnosis_reports_what_the_tool_wrote_to_stderr_not_its_progress() {
        let spec = CommandSpec::new("sh").args([
            "-c",
            "for i in 1 2 3 4 5 6 7 8 9; do echo \"checking for header $i... yes\"; done; \
             echo 'configure: error: liblzma is required' >&2; exit 1",
        ]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert!(!run.success);
        assert_eq!(
            run.diagnosis(15),
            "configure: error: liblzma is required",
            "a window over the combined capture buries the cause under nine successful \
             probes, which is what a missing dependency looked like before"
        );
        assert!(
            run.tail(15).contains("checking for header 9"),
            "the whole capture is still there for the step log"
        );
    }

    #[test]
    fn a_tool_that_says_nothing_on_stderr_still_reports_its_output() {
        let spec = CommandSpec::new("sh").args(["-c", "printf 'only\\nstdout\\nhere\\n'; exit 1"]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert_eq!(
            run.diagnosis(2),
            "stdout\nhere",
            "some tools report their failure on stdout, and reporting nothing at all would \
             be worse than reporting chatter"
        );
    }

    #[test]
    fn blank_stderr_lines_do_not_crowd_out_the_diagnosis() {
        let spec = CommandSpec::new("sh").args([
            "-c",
            "printf 'progress\\n'; printf '\\n\\n\\nld: cannot find -lz\\n' >&2; exit 1",
        ]);
        let run = run(&spec, Duration::from_secs(10)).unwrap();
        assert_eq!(run.diagnosis(2), "ld: cannot find -lz");
    }

    #[test]
    fn capturing_output_larger_than_the_limit_truncates_and_says_so() {
        let spec = CommandSpec::new("seq").args(["1", "200000"]);
        let run = run(&spec, Duration::from_mins(1)).unwrap();
        assert!(run.success);
        assert!(
            run.truncated,
            "seq 1 200000 emits more than the capture limit, so the capped path must flag it"
        );
        assert!(run.output.len() <= MAX_CAPTURED_BYTES + TRUNCATION_NOTICE.len());
    }

    #[test]
    fn folding_reads_every_line_of_output_larger_than_the_limit() {
        let spec = CommandSpec::new("seq").args(["1", "200000"]);
        let (execution, counted) = run_folding(
            &spec,
            Duration::from_mins(1),
            0usize,
            |total: &mut usize, _line: &str| *total += 1,
        )
        .unwrap();
        assert!(execution.success);
        assert!(!execution.truncated);
        assert_eq!(
            counted, 200_000,
            "the folding path must see every line, not the first {MAX_CAPTURED_BYTES} bytes of them"
        );
    }

    #[test]
    fn folding_reports_a_failing_command_and_keeps_its_stderr() {
        let spec = CommandSpec::new("sh").args([
            "-c",
            "printf 'a\\nb\\n'; printf 'llvm-nm: error: unreadable\\n' >&2; exit 3",
        ]);
        let (execution, counted) = run_folding(
            &spec,
            Duration::from_secs(10),
            0usize,
            |total: &mut usize, _line: &str| *total += 1,
        )
        .unwrap();
        assert!(!execution.success);
        assert_eq!(execution.code, Some(3));
        assert_eq!(counted, 2);
        assert_eq!(execution.diagnosis(1), "llvm-nm: error: unreadable");
    }

    #[test]
    fn folding_kills_a_command_that_outruns_its_timeout() {
        let spec = CommandSpec::new("sh").args(["-c", "printf 'one\\n'; sleep 30"]);
        let (execution, counted) = run_folding(
            &spec,
            Duration::from_millis(500),
            0usize,
            |total: &mut usize, _line: &str| *total += 1,
        )
        .unwrap();
        assert!(execution.timed_out);
        assert!(!execution.success);
        assert_eq!(counted, 1);
    }
}