diff options
| author | salmonik <salmonik@tuta.io> | 2026-11-15 15:38:57 +0100 |
|---|---|---|
| committer | salmonik <salmonik@tuta.io> | 2026-11-15 15:38:57 +0100 |
| commit | c7afd1ea752aeff0310ac7c6b78d091ac360c760 (patch) | |
| tree | 461f22fc3633ea1ea0e23ccbf330d7a55a92bea8 /src/tools/shell.rs | |
| parent | 0.4.1 + 0.4.2: abort integrity, stream completeness, tool-call indexing (diff) | |
| download | agent686-c7afd1ea752aeff0310ac7c6b78d091ac360c760.tar.gz agent686-c7afd1ea752aeff0310ac7c6b78d091ac360c760.zip | |
0.4.3: kill process groups, bound bash output, keep the key out of tool env
- setsid-style process group kill on timeout and on Ctrl-C
- 64 MiB RLIMIT_FSIZE so a runaway command cannot fill /tmp
- OPENCODE_API_KEY removed from child environment
- sessions 0600/0700, history 0600 and trimmed
Diffstat (limited to '')
| -rw-r--r-- | src/tools/shell.rs | 67 |
1 files changed, 61 insertions, 6 deletions
diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 9c214fb..29d2375 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs | |||
| @@ -1,17 +1,25 @@ | |||
| 1 | use std::fs::File; | 1 | use std::fs::File; |
| 2 | use std::io::{Read, Seek, SeekFrom}; | 2 | use std::io::{Read, Seek, SeekFrom}; |
| 3 | use std::os::unix::process::{CommandExt, ExitStatusExt}; | ||
| 3 | use std::path::PathBuf; | 4 | use std::path::PathBuf; |
| 4 | use std::process::{Command, Stdio}; | 5 | use std::process::{Command, Stdio}; |
| 5 | use std::sync::atomic::{AtomicU64, Ordering}; | 6 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 6 | use std::time::{Duration, Instant}; | 7 | use std::time::{Duration, Instant}; |
| 7 | 8 | ||
| 8 | use serde_json::Value; | 9 | use serde_json::Value; |
| 9 | 10 | ||
| 10 | const HEAD_BYTES: usize = 64 * 1024; | 11 | const HEAD_BYTES: usize = 64 * 1024; |
| 11 | const TAIL_BYTES: i64 = 16 * 1024; | 12 | const TAIL_BYTES: i64 = 16 * 1024; |
| 13 | /// The child cannot write more than this, so a runaway command cannot fill /tmp | ||
| 14 | /// and take the machine down with it. | ||
| 15 | const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; | ||
| 12 | static COUNTER: AtomicU64 = AtomicU64::new(0); | 16 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 13 | 17 | ||
| 14 | pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | 18 | pub fn bash( |
| 19 | args: &Value, | ||
| 20 | timeout: Duration, | ||
| 21 | cancel: &AtomicBool, | ||
| 22 | ) -> Result<String, String> { | ||
| 15 | let cmd = match args.get("cmd").and_then(|v| v.as_str()) { | 23 | let cmd = match args.get("cmd").and_then(|v| v.as_str()) { |
| 16 | Some(cmd) => cmd.to_string(), | 24 | Some(cmd) => cmd.to_string(), |
| 17 | None => return Err("missing required argument `cmd`".into()), | 25 | None => return Err("missing required argument `cmd`".into()), |
| @@ -37,25 +45,53 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | |||
| 37 | let stdout = file.try_clone().map_err(|e| e.to_string())?; | 45 | let stdout = file.try_clone().map_err(|e| e.to_string())?; |
| 38 | let stderr = file.try_clone().map_err(|e| e.to_string())?; | 46 | let stderr = file.try_clone().map_err(|e| e.to_string())?; |
| 39 | 47 | ||
| 40 | let mut child = Command::new("sh") | 48 | let mut command = Command::new("sh"); |
| 49 | command | ||
| 41 | .arg("-c") | 50 | .arg("-c") |
| 42 | .arg(&cmd) | 51 | .arg(&cmd) |
| 43 | .current_dir(&cwd) | 52 | .current_dir(&cwd) |
| 44 | .stdin(Stdio::null()) | 53 | .stdin(Stdio::null()) |
| 45 | .stdout(Stdio::from(stdout)) | 54 | .stdout(Stdio::from(stdout)) |
| 46 | .stderr(Stdio::from(stderr)) | 55 | .stderr(Stdio::from(stderr)) |
| 56 | // The harness owns the key; no build script needs it, and a failing | ||
| 57 | // command that dumps the environment would put it in the transcript. | ||
| 58 | .env_remove("OPENCODE_API_KEY") | ||
| 59 | // Own process group, so the whole tree can be killed and so terminal | ||
| 60 | // Ctrl-C does not race our own handling. | ||
| 61 | .process_group(0); | ||
| 62 | unsafe { | ||
| 63 | command.pre_exec(|| { | ||
| 64 | let limit = libc::rlimit { | ||
| 65 | rlim_cur: MAX_OUTPUT_BYTES, | ||
| 66 | rlim_max: MAX_OUTPUT_BYTES, | ||
| 67 | }; | ||
| 68 | if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { | ||
| 69 | return Err(std::io::Error::last_os_error()); | ||
| 70 | } | ||
| 71 | Ok(()) | ||
| 72 | }); | ||
| 73 | } | ||
| 74 | |||
| 75 | let mut child = command | ||
| 47 | .spawn() | 76 | .spawn() |
| 48 | .map_err(|e| format!("failed to start sh: {e}"))?; | 77 | .map_err(|e| format!("failed to start sh: {e}"))?; |
| 78 | let group = child.id() as i32; | ||
| 49 | 79 | ||
| 50 | let deadline = Instant::now() + timeout; | 80 | let deadline = Instant::now() + timeout; |
| 51 | let mut timed_out = false; | 81 | let mut timed_out = false; |
| 82 | let mut aborted = false; | ||
| 52 | let status = loop { | 83 | let status = loop { |
| 84 | if cancel.load(Ordering::Relaxed) { | ||
| 85 | aborted = true; | ||
| 86 | kill_group(group); | ||
| 87 | break child.wait().map_err(|e| e.to_string())?; | ||
| 88 | } | ||
| 53 | match child.try_wait().map_err(|e| e.to_string())? { | 89 | match child.try_wait().map_err(|e| e.to_string())? { |
| 54 | Some(status) => break status, | 90 | Some(status) => break status, |
| 55 | None => { | 91 | None => { |
| 56 | if Instant::now() >= deadline { | 92 | if Instant::now() >= deadline { |
| 57 | let _ = child.kill(); | ||
| 58 | timed_out = true; | 93 | timed_out = true; |
| 94 | kill_group(group); | ||
| 59 | break child.wait().map_err(|e| e.to_string())?; | 95 | break child.wait().map_err(|e| e.to_string())?; |
| 60 | } | 96 | } |
| 61 | std::thread::sleep(Duration::from_millis(20)); | 97 | std::thread::sleep(Duration::from_millis(20)); |
| @@ -63,6 +99,9 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | |||
| 63 | } | 99 | } |
| 64 | }; | 100 | }; |
| 65 | 101 | ||
| 102 | // A child that blew the file-size limit was killed by SIGXFSZ. | ||
| 103 | let over_limit = status.signal() == Some(libc::SIGXFSZ); | ||
| 104 | |||
| 66 | let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; | 105 | let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; |
| 67 | drop(file); | 106 | drop(file); |
| 68 | let _ = std::fs::remove_file(&path); | 107 | let _ = std::fs::remove_file(&path); |
| @@ -71,7 +110,14 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | |||
| 71 | if !out.is_empty() && !out.ends_with('\n') { | 110 | if !out.is_empty() && !out.ends_with('\n') { |
| 72 | out.push('\n'); | 111 | out.push('\n'); |
| 73 | } | 112 | } |
| 74 | if timed_out { | 113 | if over_limit { |
| 114 | out.push_str(&format!( | ||
| 115 | "[output exceeded {} MiB; command killed]", | ||
| 116 | MAX_OUTPUT_BYTES / (1024 * 1024) | ||
| 117 | )); | ||
| 118 | } else if aborted { | ||
| 119 | out.push_str("[aborted by the user]"); | ||
| 120 | } else if timed_out { | ||
| 75 | out.push_str(&format!( | 121 | out.push_str(&format!( |
| 76 | "[timed out after {:.1}s; process killed]", | 122 | "[timed out after {:.1}s; process killed]", |
| 77 | timeout.as_secs_f64() | 123 | timeout.as_secs_f64() |
| @@ -80,7 +126,6 @@ pub fn bash(args: &Value, timeout: Duration) -> Result<String, String> { | |||
| 80 | match status.code() { | 126 | match status.code() { |
| 81 | Some(code) => out.push_str(&format!("[exit {code}]")), | 127 | Some(code) => out.push_str(&format!("[exit {code}]")), |
| 82 | None => { | 128 | None => { |
| 83 | use std::os::unix::process::ExitStatusExt; | ||
| 84 | out.push_str(&format!( | 129 | out.push_str(&format!( |
| 85 | "[killed by signal {}]", | 130 | "[killed by signal {}]", |
| 86 | status.signal().unwrap_or_default() | 131 | status.signal().unwrap_or_default() |
| @@ -127,3 +172,13 @@ fn read_capped(file: &mut File) -> Result<String, String> { | |||
| 127 | } | 172 | } |
| 128 | Ok(String::from_utf8_lossy(&out).into_owned()) | 173 | Ok(String::from_utf8_lossy(&out).into_owned()) |
| 129 | } | 174 | } |
| 175 | |||
| 176 | /// SIGKILL the whole process group the command created. `child.kill()` would | ||
| 177 | /// only reach `sh`, leaving `sh`'s children running on the 2-core box. | ||
| 178 | fn kill_group(pid: i32) { | ||
| 179 | if pid > 0 { | ||
| 180 | unsafe { | ||
| 181 | libc::kill(-pid, libc::SIGKILL); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | } | ||
