summaryrefslogtreecommitdiffstats
path: root/src/tools/shell.rs
blob: c64bab3fc04dccf554036b5b9b20cb62d14d3027 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};

use serde_json::Value;

/// Default budget per stream, split 4:1 between head and tail.
const DEFAULT_MAX_BYTES: usize = 80 * 1024;
const MIN_MAX_BYTES: usize = 1024;
const MAX_MAX_BYTES: usize = 16 * 1024 * 1024;
/// The child cannot write more than this per stream, so a runaway command cannot
/// fill /tmp and take the machine down with it.
const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;

static COUNTER: AtomicU64 = AtomicU64::new(0);

/// Removes both temp files when dropped, so an early `?` on the spawn/read paths
/// cannot leak `agent686-…-{out,err}.log` files into $TMPDIR.
struct TempGuard {
    out: PathBuf,
    err: PathBuf,
}

impl Drop for TempGuard {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.out);
        let _ = std::fs::remove_file(&self.err);
    }
}

pub fn bash(
    args: &Value,
    timeout: Duration,
    cancel: &AtomicBool,
) -> Result<String, String> {
    let cmd = match args
        .get("cmd")
        .or_else(|| args.get("command"))
        .and_then(|v| v.as_str())
    {
        Some(cmd) => cmd.to_string(),
        None => return Err("missing required argument `cmd`".into()),
    };

    let max_bytes = args
        .get("max_bytes")
        .and_then(|value| value.as_u64())
        .unwrap_or(DEFAULT_MAX_BYTES as u64)
        .clamp(MIN_MAX_BYTES as u64, MAX_MAX_BYTES as u64) as usize;
    let head_budget = max_bytes * 4 / 5;
    let tail_budget = max_bytes - head_budget;

    let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?;
    if !cwd.is_dir() {
        return Err(format!("cwd is not a directory: {}", cwd.display()));
    }

    let serial = COUNTER.fetch_add(1, Ordering::Relaxed);
    let out_path = temp_path("out", serial);
    let err_path = temp_path("err", serial);
    let _guard = TempGuard {
        out: out_path.clone(),
        err: err_path.clone(),
    };
    let mut out_file = create(&out_path)?;
    let mut err_file = create(&err_path)?;
    let stdout = out_file.try_clone().map_err(|e| e.to_string())?;
    let stderr = err_file.try_clone().map_err(|e| e.to_string())?;

    let mut command = Command::new("sh");
    command
        .arg("-c")
        .arg(&cmd)
        .current_dir(&cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::from(stdout))
        .stderr(Stdio::from(stderr))
        // The harness owns the key; no build script needs it, and a failing
        // command that dumps the environment would put it in the transcript.
        .env_remove("OPENCODE_API_KEY")
        // Own process group, so the whole tree can be killed and so terminal
        // Ctrl-C does not race our own handling.
        .process_group(0);
    unsafe {
        command.pre_exec(|| {
            // rlim_t is u32 on i686 and u64 on x86-64.
            let limit = libc::rlimit {
                rlim_cur: MAX_FILE_BYTES as libc::rlim_t,
                rlim_max: MAX_FILE_BYTES as libc::rlim_t,
            };
            if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }

    let mut child = command
        .spawn()
        .map_err(|e| format!("failed to start sh: {e}"))?;
    let group = child.id() as i32;

    let deadline = Instant::now() + timeout;
    let mut timed_out = false;
    let mut aborted = false;
    let status = loop {
        if cancel.load(Ordering::Relaxed) {
            aborted = true;
            kill_group(group);
            break child.wait().map_err(|e| e.to_string())?;
        }
        match child.try_wait().map_err(|e| e.to_string())? {
            Some(status) => break status,
            None => {
                if Instant::now() >= deadline {
                    timed_out = true;
                    kill_group(group);
                    break child.wait().map_err(|e| e.to_string())?;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
        }
    };

    // SIGXFSZ lands on whichever process crossed the limit — usually a
    // grandchild of `sh` — so `sh` exits 128+25 rather than being signalled.
    // The reliable signal is the file itself having reached the limit.
    let over_limit = status.signal() == Some(libc::SIGXFSZ)
        || out_file.metadata().map(|m| m.len()).unwrap_or(0) >= MAX_FILE_BYTES
        || err_file.metadata().map(|m| m.len()).unwrap_or(0) >= MAX_FILE_BYTES;

    let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?;
    let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?;
    drop(out_file);
    drop(err_file);

    let marker = if over_limit {
        format!(
            "[output exceeded {} MiB; command killed]",
            MAX_FILE_BYTES / (1024 * 1024)
        )
    } else if aborted {
        "[aborted by the user]".to_string()
    } else if timed_out {
        format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64())
    } else {
        match status.code() {
            Some(code) => format!("[exit {code}]"),
            None => format!(
                "[killed by signal {}]",
                status.signal().unwrap_or_default()
            ),
        }
    };

    Ok(format_result(
        &out_text, out_cut, &err_text, err_cut, &marker,
    ))
}

/// stdout and stderr are kept apart: a program that prints its real error to
/// stderr used to be indistinguishable from one that printed it to stdout.
/// Labelling only appears when it carries information.
fn format_result(
    stdout: &str,
    stdout_truncated: bool,
    stderr: &str,
    stderr_truncated: bool,
    marker: &str,
) -> String {
    let has_stdout = !stdout.trim().is_empty();
    let has_stderr = !stderr.trim().is_empty();

    let mut out = String::new();
    if has_stdout && has_stderr {
        out.push_str("[stdout]\n");
        out.push_str(stdout);
        end_line(&mut out, stdout);
        out.push_str("[stderr]\n");
        out.push_str(stderr);
        end_line(&mut out, stderr);
    } else if has_stderr {
        out.push_str("[stderr]\n");
        out.push_str(stderr);
        end_line(&mut out, stderr);
    } else if has_stdout {
        out.push_str(stdout);
        end_line(&mut out, stdout);
    }

    let truncated = stdout_truncated || stderr_truncated;
    out.push_str(marker);
    if truncated {
        out.push_str(" (output truncated; raise max_bytes or narrow the command)");
    }
    out
}

fn end_line(out: &mut String, text: &str) {
    if !text.is_empty() && !text.ends_with('\n') {
        out.push('\n');
    }
}

fn temp_path(kind: &str, serial: u64) -> PathBuf {
    std::env::temp_dir().join(format!(
        "agent686-{}-{}-{kind}.log",
        std::process::id(),
        serial
    ))
}

fn create(path: &PathBuf) -> Result<File, String> {
    std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)
        .map_err(|e| format!("{}: {e}", path.display()))
}

fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> {
    let current = std::env::current_dir().map_err(|e| e.to_string())?;
    Ok(match cwd {
        Some(dir) => {
            let path = PathBuf::from(dir);
            if path.is_absolute() {
                path
            } else {
                current.join(path)
            }
        }
        None => current,
    })
}

/// Reads at most `head` bytes from the start and `tail` from the end, noting
/// what was dropped. Returns the text and whether anything was cut.
fn read_capped(file: &mut File, head: usize, tail: usize) -> Result<(String, bool), String> {
    let len = file.metadata().map(|m| m.len()).unwrap_or(0);
    file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?;

    let mut bytes = Vec::new();
    let mut truncated = false;

    if len <= (head + tail) as u64 {
        file.read_to_end(&mut bytes).map_err(|e| e.to_string())?;
    } else {
        truncated = true;
        file.take(head as u64)
            .read_to_end(&mut bytes)
            .map_err(|e| e.to_string())?;
        let omitted = len.saturating_sub(head as u64 + tail as u64);
        bytes.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes());
        file.seek(SeekFrom::End(-(tail as i64)))
            .map_err(|e| e.to_string())?;
        let mut rest = Vec::new();
        file.read_to_end(&mut rest).map_err(|e| e.to_string())?;
        bytes.extend_from_slice(&rest);
    }

    Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated))
}

/// SIGKILL the whole process group the command created. `child.kill()` would
/// only reach `sh`, leaving `sh`'s children running on the 2-core box.
fn kill_group(pid: i32) {
    if pid > 0 {
        unsafe {
            libc::kill(-pid, libc::SIGKILL);
        }
    }
}