diff options
Diffstat (limited to 'src/tools/shell.rs')
| -rw-r--r-- | src/tools/shell.rs | 185 |
1 files changed, 127 insertions, 58 deletions
diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 6f095c6..91f2dd9 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs | |||
| @@ -8,11 +8,14 @@ use std::time::{Duration, Instant}; | |||
| 8 | 8 | ||
| 9 | use serde_json::Value; | 9 | use serde_json::Value; |
| 10 | 10 | ||
| 11 | const HEAD_BYTES: usize = 64 * 1024; | 11 | /// Default budget per stream, split 4:1 between head and tail. |
| 12 | const TAIL_BYTES: i64 = 16 * 1024; | 12 | const DEFAULT_MAX_BYTES: usize = 80 * 1024; |
| 13 | /// The child cannot write more than this, so a runaway command cannot fill /tmp | 13 | const MIN_MAX_BYTES: usize = 1024; |
| 14 | /// and take the machine down with it. | 14 | const MAX_MAX_BYTES: usize = 16 * 1024 * 1024; |
| 15 | const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; | 15 | /// The child cannot write more than this per stream, so a runaway command cannot |
| 16 | /// fill /tmp and take the machine down with it. | ||
| 17 | const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; | ||
| 18 | |||
| 16 | static COUNTER: AtomicU64 = AtomicU64::new(0); | 19 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 17 | 20 | ||
| 18 | pub fn bash( | 21 | pub fn bash( |
| @@ -25,25 +28,26 @@ pub fn bash( | |||
| 25 | None => return Err("missing required argument `cmd`".into()), | 28 | None => return Err("missing required argument `cmd`".into()), |
| 26 | }; | 29 | }; |
| 27 | 30 | ||
| 31 | let max_bytes = args | ||
| 32 | .get("max_bytes") | ||
| 33 | .and_then(|value| value.as_u64()) | ||
| 34 | .unwrap_or(DEFAULT_MAX_BYTES as u64) | ||
| 35 | .clamp(MIN_MAX_BYTES as u64, MAX_MAX_BYTES as u64) as usize; | ||
| 36 | let head_budget = max_bytes * 4 / 5; | ||
| 37 | let tail_budget = max_bytes - head_budget; | ||
| 38 | |||
| 28 | let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; | 39 | let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; |
| 29 | if !cwd.is_dir() { | 40 | if !cwd.is_dir() { |
| 30 | return Err(format!("cwd is not a directory: {}", cwd.display())); | 41 | return Err(format!("cwd is not a directory: {}", cwd.display())); |
| 31 | } | 42 | } |
| 32 | 43 | ||
| 33 | let path = std::env::temp_dir().join(format!( | 44 | let serial = COUNTER.fetch_add(1, Ordering::Relaxed); |
| 34 | "agent686-{}-{}.out", | 45 | let out_path = temp_path("out", serial); |
| 35 | std::process::id(), | 46 | let err_path = temp_path("err", serial); |
| 36 | COUNTER.fetch_add(1, Ordering::Relaxed) | 47 | let mut out_file = create(&out_path)?; |
| 37 | )); | 48 | let mut err_file = create(&err_path)?; |
| 38 | let mut file = std::fs::OpenOptions::new() | 49 | let stdout = out_file.try_clone().map_err(|e| e.to_string())?; |
| 39 | .read(true) | 50 | let stderr = err_file.try_clone().map_err(|e| e.to_string())?; |
| 40 | .write(true) | ||
| 41 | .create(true) | ||
| 42 | .truncate(true) | ||
| 43 | .open(&path) | ||
| 44 | .map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 45 | let stdout = file.try_clone().map_err(|e| e.to_string())?; | ||
| 46 | let stderr = file.try_clone().map_err(|e| e.to_string())?; | ||
| 47 | 51 | ||
| 48 | let mut command = Command::new("sh"); | 52 | let mut command = Command::new("sh"); |
| 49 | command | 53 | command |
| @@ -63,8 +67,8 @@ pub fn bash( | |||
| 63 | command.pre_exec(|| { | 67 | command.pre_exec(|| { |
| 64 | // rlim_t is u32 on i686 and u64 on x86-64. | 68 | // rlim_t is u32 on i686 and u64 on x86-64. |
| 65 | let limit = libc::rlimit { | 69 | let limit = libc::rlimit { |
| 66 | rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t, | 70 | rlim_cur: MAX_FILE_BYTES as libc::rlim_t, |
| 67 | rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t, | 71 | rlim_max: MAX_FILE_BYTES as libc::rlim_t, |
| 68 | }; | 72 | }; |
| 69 | if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { | 73 | if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { |
| 70 | return Err(std::io::Error::last_os_error()); | 74 | return Err(std::io::Error::last_os_error()); |
| @@ -103,38 +107,97 @@ pub fn bash( | |||
| 103 | // A child that blew the file-size limit was killed by SIGXFSZ. | 107 | // A child that blew the file-size limit was killed by SIGXFSZ. |
| 104 | let over_limit = status.signal() == Some(libc::SIGXFSZ); | 108 | let over_limit = status.signal() == Some(libc::SIGXFSZ); |
| 105 | 109 | ||
| 106 | let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; | 110 | let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?; |
| 107 | drop(file); | 111 | let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?; |
| 108 | let _ = std::fs::remove_file(&path); | 112 | drop(out_file); |
| 113 | drop(err_file); | ||
| 114 | let _ = std::fs::remove_file(&out_path); | ||
| 115 | let _ = std::fs::remove_file(&err_path); | ||
| 109 | 116 | ||
| 110 | let mut out = output; | 117 | let marker = if over_limit { |
| 111 | if !out.is_empty() && !out.ends_with('\n') { | 118 | format!( |
| 112 | out.push('\n'); | ||
| 113 | } | ||
| 114 | if over_limit { | ||
| 115 | out.push_str(&format!( | ||
| 116 | "[output exceeded {} MiB; command killed]", | 119 | "[output exceeded {} MiB; command killed]", |
| 117 | MAX_OUTPUT_BYTES / (1024 * 1024) | 120 | MAX_FILE_BYTES / (1024 * 1024) |
| 118 | )); | 121 | ) |
| 119 | } else if aborted { | 122 | } else if aborted { |
| 120 | out.push_str("[aborted by the user]"); | 123 | "[aborted by the user]".to_string() |
| 121 | } else if timed_out { | 124 | } else if timed_out { |
| 122 | out.push_str(&format!( | 125 | format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64()) |
| 123 | "[timed out after {:.1}s; process killed]", | ||
| 124 | timeout.as_secs_f64() | ||
| 125 | )); | ||
| 126 | } else { | 126 | } else { |
| 127 | match status.code() { | 127 | match status.code() { |
| 128 | Some(code) => out.push_str(&format!("[exit {code}]")), | 128 | Some(code) => format!("[exit {code}]"), |
| 129 | None => { | 129 | None => format!( |
| 130 | out.push_str(&format!( | 130 | "[killed by signal {}]", |
| 131 | "[killed by signal {}]", | 131 | status.signal().unwrap_or_default() |
| 132 | status.signal().unwrap_or_default() | 132 | ), |
| 133 | )); | ||
| 134 | } | ||
| 135 | } | 133 | } |
| 134 | }; | ||
| 135 | |||
| 136 | Ok(format_result( | ||
| 137 | &out_text, out_cut, &err_text, err_cut, &marker, | ||
| 138 | )) | ||
| 139 | } | ||
| 140 | |||
| 141 | /// stdout and stderr are kept apart: a program that prints its real error to | ||
| 142 | /// stderr used to be indistinguishable from one that printed it to stdout. | ||
| 143 | /// Labelling only appears when it carries information. | ||
| 144 | fn format_result( | ||
| 145 | stdout: &str, | ||
| 146 | stdout_truncated: bool, | ||
| 147 | stderr: &str, | ||
| 148 | stderr_truncated: bool, | ||
| 149 | marker: &str, | ||
| 150 | ) -> String { | ||
| 151 | let has_stdout = !stdout.trim().is_empty(); | ||
| 152 | let has_stderr = !stderr.trim().is_empty(); | ||
| 153 | |||
| 154 | let mut out = String::new(); | ||
| 155 | if has_stdout && has_stderr { | ||
| 156 | out.push_str("[stdout]\n"); | ||
| 157 | out.push_str(stdout); | ||
| 158 | end_line(&mut out, stdout); | ||
| 159 | out.push_str("[stderr]\n"); | ||
| 160 | out.push_str(stderr); | ||
| 161 | end_line(&mut out, stderr); | ||
| 162 | } else if has_stderr { | ||
| 163 | out.push_str("[stderr]\n"); | ||
| 164 | out.push_str(stderr); | ||
| 165 | end_line(&mut out, stderr); | ||
| 166 | } else if has_stdout { | ||
| 167 | out.push_str(stdout); | ||
| 168 | end_line(&mut out, stdout); | ||
| 136 | } | 169 | } |
| 137 | Ok(out) | 170 | |
| 171 | let truncated = stdout_truncated || stderr_truncated; | ||
| 172 | out.push_str(marker); | ||
| 173 | if truncated { | ||
| 174 | out.push_str(" (output truncated; raise max_bytes or narrow the command)"); | ||
| 175 | } | ||
| 176 | out | ||
| 177 | } | ||
| 178 | |||
| 179 | fn end_line(out: &mut String, text: &str) { | ||
| 180 | if !text.is_empty() && !text.ends_with('\n') { | ||
| 181 | out.push('\n'); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | |||
| 185 | fn temp_path(kind: &str, serial: u64) -> PathBuf { | ||
| 186 | std::env::temp_dir().join(format!( | ||
| 187 | "agent686-{}-{}-{kind}.log", | ||
| 188 | std::process::id(), | ||
| 189 | serial | ||
| 190 | )) | ||
| 191 | } | ||
| 192 | |||
| 193 | fn create(path: &PathBuf) -> Result<File, String> { | ||
| 194 | std::fs::OpenOptions::new() | ||
| 195 | .read(true) | ||
| 196 | .write(true) | ||
| 197 | .create(true) | ||
| 198 | .truncate(true) | ||
| 199 | .open(path) | ||
| 200 | .map_err(|e| format!("{}: {e}", path.display())) | ||
| 138 | } | 201 | } |
| 139 | 202 | ||
| 140 | fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { | 203 | fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { |
| @@ -152,26 +215,32 @@ fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { | |||
| 152 | }) | 215 | }) |
| 153 | } | 216 | } |
| 154 | 217 | ||
| 155 | fn read_capped(file: &mut File) -> Result<String, String> { | 218 | /// Reads at most `head` bytes from the start and `tail` from the end, noting |
| 219 | /// what was dropped. Returns the text and whether anything was cut. | ||
| 220 | fn read_capped(file: &mut File, head: usize, tail: usize) -> Result<(String, bool), String> { | ||
| 156 | let len = file.metadata().map(|m| m.len()).unwrap_or(0); | 221 | let len = file.metadata().map(|m| m.len()).unwrap_or(0); |
| 157 | file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; | 222 | file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; |
| 158 | 223 | ||
| 159 | let mut out = Vec::new(); | 224 | let mut bytes = Vec::new(); |
| 160 | if len <= HEAD_BYTES as u64 { | 225 | let mut truncated = false; |
| 161 | file.read_to_end(&mut out).map_err(|e| e.to_string())?; | 226 | |
| 227 | if len <= (head + tail) as u64 { | ||
| 228 | file.read_to_end(&mut bytes).map_err(|e| e.to_string())?; | ||
| 162 | } else { | 229 | } else { |
| 163 | file.take(HEAD_BYTES as u64) | 230 | truncated = true; |
| 164 | .read_to_end(&mut out) | 231 | file.take(head as u64) |
| 232 | .read_to_end(&mut bytes) | ||
| 165 | .map_err(|e| e.to_string())?; | 233 | .map_err(|e| e.to_string())?; |
| 166 | let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); | 234 | let omitted = len.saturating_sub(head as u64 + tail as u64); |
| 167 | out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); | 235 | bytes.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); |
| 168 | file.seek(SeekFrom::End(-TAIL_BYTES)) | 236 | file.seek(SeekFrom::End(-(tail as i64))) |
| 169 | .map_err(|e| e.to_string())?; | 237 | .map_err(|e| e.to_string())?; |
| 170 | let mut tail = Vec::new(); | 238 | let mut rest = Vec::new(); |
| 171 | file.read_to_end(&mut tail).map_err(|e| e.to_string())?; | 239 | file.read_to_end(&mut rest).map_err(|e| e.to_string())?; |
| 172 | out.extend_from_slice(&tail); | 240 | bytes.extend_from_slice(&rest); |
| 173 | } | 241 | } |
| 174 | Ok(String::from_utf8_lossy(&out).into_owned()) | 242 | |
| 243 | Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated)) | ||
| 175 | } | 244 | } |
| 176 | 245 | ||
| 177 | /// SIGKILL the whole process group the command created. `child.kill()` would | 246 | /// SIGKILL the whole process group the command created. `child.kill()` would |
