cascade_environment/
runner.rs1use std::ffi::OsString;
4use std::process::Command;
5use std::process::Stdio;
6use std::thread;
7use std::time::{Duration, Instant};
8
9use cascade_core::{CascadeError, CascadeResult};
10
11use crate::ProbeOutput;
12
13pub trait EnvironmentCommandRunner {
15 fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput>;
16}
17
18#[derive(Debug, Clone, Copy, Default)]
20pub struct ProcessEnvironmentCommandRunner;
21
22impl EnvironmentCommandRunner for ProcessEnvironmentCommandRunner {
23 fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput> {
24 let output = Command::new(program)
25 .args(args)
26 .output()
27 .map_err(|error| CascadeError::new(format!("failed to run `{program}`: {error}")))?;
28
29 Ok(ProbeOutput {
30 stdout: decode_process_output(&output.stdout),
31 stderr: decode_process_output(&output.stderr),
32 exit_code: output.status.code(),
33 })
34 }
35}
36
37#[derive(Debug, Clone, Copy, Default)]
43pub struct InteractiveEnvironmentCommandRunner;
44
45impl EnvironmentCommandRunner for InteractiveEnvironmentCommandRunner {
46 fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput> {
47 let status = Command::new(program)
48 .args(args)
49 .stdin(Stdio::inherit())
50 .stdout(Stdio::inherit())
51 .stderr(Stdio::inherit())
52 .status()
53 .map_err(|error| CascadeError::new(format!("failed to run `{program}`: {error}")))?;
54 Ok(ProbeOutput {
55 stdout: String::new(),
56 stderr: String::new(),
57 exit_code: status.code(),
58 })
59 }
60}
61
62#[derive(Debug, Clone, Copy)]
69pub struct BoundedEnvironmentCommandRunner {
70 pub timeout: Duration,
71}
72
73impl Default for BoundedEnvironmentCommandRunner {
74 fn default() -> Self {
75 Self {
76 timeout: Duration::from_secs(15 * 60),
77 }
78 }
79}
80
81impl EnvironmentCommandRunner for BoundedEnvironmentCommandRunner {
82 fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput> {
83 let mut child = Command::new(program)
84 .args(args)
85 .stdin(Stdio::null())
86 .stdout(Stdio::null())
87 .stderr(Stdio::null())
88 .spawn()
89 .map_err(|error| CascadeError::new(format!("failed to run `{program}`: {error}")))?;
90 let started = Instant::now();
91 loop {
92 if let Some(status) = child.try_wait().map_err(|error| {
93 CascadeError::new(format!("failed to inspect `{program}` status: {error}"))
94 })? {
95 return Ok(ProbeOutput {
96 stdout: String::new(),
97 stderr: String::new(),
98 exit_code: status.code(),
99 });
100 }
101 if started.elapsed() >= self.timeout {
102 let _ = child.kill();
103 let _ = child.wait();
104 return Err(CascadeError::new(format!(
105 "command `{program}` exceeded the {} second remediation timeout and was terminated",
106 self.timeout.as_secs()
107 )));
108 }
109 thread::sleep(Duration::from_millis(100));
110 }
111 }
112}
113
114fn decode_process_output(bytes: &[u8]) -> String {
116 if bytes.len() >= 2 && bytes.chunks_exact(2).any(|pair| pair[1] == 0) {
117 let utf16 = bytes
118 .chunks_exact(2)
119 .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
120 .collect::<Vec<_>>();
121 return String::from_utf16_lossy(&utf16);
122 }
123 String::from_utf8_lossy(bytes).into_owned()
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn decodes_utf8_and_utf16le_probe_output() {
132 assert_eq!(decode_process_output(b"Ubuntu\n"), "Ubuntu\n");
133 let utf16 = "Ubuntu\r\n"
134 .encode_utf16()
135 .flat_map(u16::to_le_bytes)
136 .collect::<Vec<_>>();
137 assert_eq!(decode_process_output(&utf16), "Ubuntu\r\n");
138 }
139}