Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-drive/src/command.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-drive / src / command.rs` 980 lines ยท 33387 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Operator policy for `run_command`. 17 //! 18 //! The model supplies `command` and `cwd` only. This policy is filled from 19 //! code or from the operator environment, never from tool arguments. 20 //! 21 //! Extending [`CommandPolicy::allowlist`] is an operator-trusted action, and 22 //! for any program that can run code (an interpreter, `git`, `make`, `awk`, 23 //! a compiler) it is shell-equivalent: the model can write a script with the 24 //! file tools and pass its path. A name that is accepted is executed with the 25 //! model's arguments. Shells and exec wrappers (`sh`, `bash`, `nice`, 26 //! `timeout`, `env`, `xargs`, `nohup`, `setsid`, `stdbuf`, and the rest of 27 //! [`SHELLS`] / [`EXEC_WRAPPERS`]) are rejected when the allowlist is built 28 //! and again at execution, even if a caller puts them on the list. 29 //! Interpreters in [`INTERPRETERS`] reject their inline-code options, including 30 //! inside short clusters (`perl -le`, `python3 -Bc`) and versioned names 31 //! (`python3.12`, `php8.2`). `git` rejects global `-c` / `--exec-path` / 32 //! `--config-env`, `git config` writes, and the options and subcommands that 33 //! run a program (`--upload-pack`, `rebase -x`, `bisect run`, ...). These 34 //! checks remove one-line escalation; they do not make such a program safe. 35 36 use serde_json::{json, Value}; 37 use std::io::Read; 38 use std::os::unix::io::AsRawFd; 39 use std::path::{Component, Path, PathBuf}; 40 use std::process::{Child, Command, Stdio}; 41 use std::sync::atomic::{AtomicBool, Ordering}; 42 use std::sync::Arc; 43 use std::thread::JoinHandle; 44 use std::time::{Duration, Instant}; 45 46 use std::os::unix::process::CommandExt; 47 48 /// Programs the crate itself has been shown to need, and nothing that reads 49 /// or writes the filesystem. `echo` is the loop-stub round trip. `printf` is 50 /// the historical output-size fixture. `true` is the bad-cwd probe. `false` 51 /// and `pwd` are the same class of program: they do not take a shell and they 52 /// do not open files. File inspection stays on `view_file`, `list_dir`, and 53 /// `grep_search`. Operators add other names with 54 /// `AIEN_DRIVE_COMMAND_ALLOWLIST`. That extension is trusted: see the module 55 /// docs. Shells and exec wrappers in the value are dropped. 56 pub const DEFAULT_COMMAND_ALLOWLIST: &[&str] = &["echo", "printf", "true", "false", "pwd"]; 57 58 /// Limits and the program allowlist for one driver process. 59 #[derive(Clone, Debug, PartialEq, Eq)] 60 pub struct CommandPolicy { 61 /// Bare program names that may be executed. The model cannot extend this. 62 pub allowlist: Vec, 63 /// When true, the command string is passed to `/bin/sh -c`. 64 /// Off by default. Tool arguments cannot turn this on. 65 pub allow_shell: bool, 66 /// `cwd` must canonicalize inside this directory. An absolute `cwd` 67 /// inside the root is accepted. An absolute `cwd` outside the root is 68 /// rejected. The default is empty, which fails closed. Set 69 /// `AIEN_DRIVE_COMMAND_ROOT`, or assign this field. The process cwd is 70 /// not used as the root. 71 pub root: PathBuf, 72 pub timeout: Duration, 73 /// Stdout characters returned to the model (the tail, matching the 74 /// previous driver). 75 pub max_stdout: usize, 76 /// Stderr characters returned to the model. 77 pub max_stderr: usize, 78 /// Bytes read from one stream before the process is killed. 79 pub max_capture: usize, 80 } 81 82 impl Default for CommandPolicy { 83 fn default() -> Self { 84 Self { 85 allowlist: DEFAULT_COMMAND_ALLOWLIST 86 .iter() 87 .map(|s| (*s).to_string()) 88 .collect(), 89 allow_shell: false, 90 // Not the process cwd. The operator sets `AIEN_DRIVE_COMMAND_ROOT` 91 // or assigns this field. An empty root fails closed. 92 root: PathBuf::new(), 93 timeout: Duration::from_secs(120), 94 max_stdout: 4000, 95 max_stderr: 2000, 96 max_capture: 1024 * 1024, 97 } 98 } 99 } 100 101 impl CommandPolicy { 102 /// Operator environment of the `aien-drive` process. Unset variables keep 103 /// the defaults. `AIEN_DRIVE_ALLOW_SHELL` must be the exact string `1`. 104 pub fn from_operator_env() -> Self { 105 Self::from_operator_values( 106 std::env::var("AIEN_DRIVE_COMMAND_ALLOWLIST") 107 .ok() 108 .as_deref(), 109 std::env::var("AIEN_DRIVE_ALLOW_SHELL").ok().as_deref(), 110 std::env::var("AIEN_DRIVE_COMMAND_ROOT").ok().as_deref(), 111 std::env::var("AIEN_DRIVE_COMMAND_TIMEOUT_SECS") 112 .ok() 113 .as_deref(), 114 ) 115 } 116 117 pub fn from_operator_values( 118 allowlist: Option<&str>, 119 allow_shell: Option<&str>, 120 root: Option<&str>, 121 timeout_secs: Option<&str>, 122 ) -> Self { 123 let mut policy = Self::default(); 124 if let Some(raw) = allowlist { 125 // Shells and exec wrappers are dropped here so an operator string 126 // cannot reintroduce them. Direct struct assignment is checked 127 // again in `reject_dangerous_invocation`. 128 policy.allowlist = raw 129 .split(',') 130 .map(str::trim) 131 .filter(|s| !s.is_empty() && !is_shell_or_wrapper(s)) 132 .map(str::to_string) 133 .collect(); 134 } 135 policy.allow_shell = matches!(allow_shell.map(str::trim), Some("1")); 136 if let Some(root) = root.map(str::trim).filter(|s| !s.is_empty()) { 137 policy.root = PathBuf::from(root); 138 } 139 if let Some(secs) = timeout_secs { 140 if let Ok(secs) = secs.trim().parse::() { 141 if secs > 0 { 142 policy.timeout = Duration::from_secs(secs); 143 } 144 } 145 } 146 policy 147 } 148 } 149 150 /// Shells. Rejected on the allowlist and at execution. Use `allow_shell`. 151 const SHELLS: &[&str] = &[ 152 "sh", "bash", "dash", "zsh", "ksh", "ash", "csh", "tcsh", "fish", "busybox", "elvish", 153 ]; 154 155 /// Programs whose job is to exec another program. Rejected on the allowlist 156 /// and at execution so `nice bash -c id` cannot undo the confinement. 157 const EXEC_WRAPPERS: &[&str] = &[ 158 "env", "nice", "timeout", "xargs", "nohup", "setsid", "stdbuf", "ionice", "taskset", "chrt", 159 "numactl", "setarch", "setpriv", "unshare", "nsenter", "watch", "time", "find", "flock", 160 ]; 161 162 /// An interpreter's inline-code options. Short options are scanned as a 163 /// cluster: an eval letter is rejected unless an earlier letter in the same 164 /// cluster takes the rest of the argument as its value. 165 struct Interpreter { 166 names: &'static [&'static str], 167 eval_short: &'static str, 168 value_short: &'static str, 169 eval_long: &'static [&'static str], 170 } 171 172 /// Interpreters whose eval options run model text as code. 173 const INTERPRETERS: &[Interpreter] = &[ 174 Interpreter { 175 names: &["perl"], 176 eval_short: "eE", 177 value_short: "IMmxdDF", 178 eval_long: &[], 179 }, 180 Interpreter { 181 names: &["python", "pypy"], 182 eval_short: "c", 183 value_short: "WXm", 184 eval_long: &[], 185 }, 186 Interpreter { 187 names: &["ruby"], 188 eval_short: "e", 189 value_short: "IrCEFxK", 190 eval_long: &[], 191 }, 192 Interpreter { 193 names: &["node", "nodejs", "bun"], 194 eval_short: "epc", 195 value_short: "r", 196 eval_long: &["--eval", "--print"], 197 }, 198 Interpreter { 199 names: &["lua", "luajit"], 200 eval_short: "e", 201 value_short: "l", 202 eval_long: &[], 203 }, 204 Interpreter { 205 names: &["php"], 206 eval_short: "rBRFE", 207 value_short: "dcz", 208 eval_long: &[ 209 "--run", 210 "--process-begin", 211 "--process-code", 212 "--process-file", 213 "--process-end", 214 ], 215 }, 216 Interpreter { 217 names: &["awk", "gawk", "mawk", "nawk"], 218 eval_short: "eE", 219 value_short: "fvF", 220 eval_long: &["--source", "--exec"], 221 }, 222 ]; 223 224 /// The interpreter for an argv[0], ignoring a version suffix (`python3.12`). 225 fn interpreter(name: &str) -> Option<&'static Interpreter> { 226 let base = name.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.'); 227 INTERPRETERS.iter().find(|i| i.names.contains(&base)) 228 } 229 230 fn is_shell_or_wrapper(name: &str) -> bool { 231 SHELLS.contains(&name) || EXEC_WRAPPERS.contains(&name) 232 } 233 234 const SEARCH_DIRS: &[&str] = &["/bin", "/usr/bin"]; 235 236 /// Run the model `command` under `policy`. Failures are strings for the model. 237 pub(crate) fn execute(policy: &CommandPolicy, args: &Value) -> Result { 238 let command = args.get("command").and_then(Value::as_str).unwrap_or(""); 239 if command.trim().is_empty() { 240 return Err("run_command rejected: empty command".into()); 241 } 242 if command.contains('\0') { 243 return Err("run_command rejected: shell metacharacter NUL is not allowed".into()); 244 } 245 let cwd_arg = args.get("cwd").and_then(Value::as_str).unwrap_or("."); 246 let cwd = resolve_cwd(&policy.root, cwd_arg)?; 247 let (program, argv) = if policy.allow_shell { 248 let program = PathBuf::from("/bin/sh"); 249 if !program.is_file() { 250 return Err( 251 "run_command rejected: /bin/sh is not available for the operator shell opt-in" 252 .into(), 253 ); 254 } 255 (program, vec!["-c".to_string(), command.to_string()]) 256 } else { 257 reject_metacharacters(command)?; 258 let argv = parse_argv(command)?; 259 reject_dangerous_invocation(&argv)?; 260 let program = resolve_program(&argv[0], &policy.allowlist)?; 261 (program, argv[1..].to_vec()) 262 }; 263 let (code, stdout, stderr) = run_captured( 264 &program, 265 &argv, 266 &cwd, 267 policy.timeout, 268 policy.max_capture, 269 &short_label(command), 270 )?; 271 Ok(json!({ 272 "exit_code": code, 273 "stdout": crate::last_chars(&stdout, policy.max_stdout), 274 "stderr": crate::last_chars(&stderr, policy.max_stderr), 275 })) 276 } 277 278 fn reject_metacharacters(command: &str) -> Result<(), String> { 279 for c in command.chars() { 280 if is_shell_meta(c) { 281 return Err(format!( 282 "run_command rejected: shell metacharacter {} is not allowed. Pass one allowlisted program and its arguments.", 283 meta_label(c) 284 )); 285 } 286 } 287 Ok(()) 288 } 289 290 fn is_shell_meta(c: char) -> bool { 291 matches!( 292 c, 293 ';' | '|' 294 | '&' 295 | '$' 296 | '`' 297 | '<' 298 | '>' 299 | '(' 300 | ')' 301 | '{' 302 | '}' 303 | '\\' 304 | '!' 305 | '*' 306 | '?' 307 | '~' 308 | '#' 309 | '\n' 310 | '\r' 311 | '\0' 312 ) 313 } 314 315 fn meta_label(c: char) -> String { 316 match c { 317 '\n' => "newline".to_string(), 318 '\r' => "carriage return".to_string(), 319 '\0' => "NUL".to_string(), 320 _ => format!("'{c}'"), 321 } 322 } 323 324 fn parse_argv(command: &str) -> Result, String> { 325 let mut args = Vec::new(); 326 let mut cur = String::new(); 327 let mut in_single = false; 328 let mut in_double = false; 329 let mut any = false; 330 for c in command.chars() { 331 match c { 332 '\'' if !in_double => { 333 in_single = !in_single; 334 any = true; 335 } 336 '"' if !in_single => { 337 in_double = !in_double; 338 any = true; 339 } 340 ' ' | '\t' if !in_single && !in_double => { 341 if any { 342 args.push(std::mem::take(&mut cur)); 343 any = false; 344 } 345 } 346 _ => { 347 cur.push(c); 348 any = true; 349 } 350 } 351 } 352 if in_single || in_double { 353 return Err("run_command rejected: unmatched quote".into()); 354 } 355 if any { 356 args.push(cur); 357 } 358 if args.is_empty() { 359 return Err("run_command rejected: empty command".into()); 360 } 361 Ok(args) 362 } 363 364 fn reject_dangerous_invocation(argv: &[String]) -> Result<(), String> { 365 let name = argv.first().map(String::as_str).unwrap_or(""); 366 if is_shell_or_wrapper(name) { 367 return Err(format!( 368 "run_command rejected: '{name}' is a shell or exec wrapper and cannot be allowlisted. Shell execution requires the operator allow_shell opt-in, which is off." 369 )); 370 } 371 if let Some(interp) = interpreter(name) { 372 // Every argument is scanned, not just options before the script: 373 // value-taking options make "stop at the first operand" unsafe. 374 if let Some(arg) = argv.iter().skip(1).find(|a| is_eval_flag(interp, a)) { 375 return Err(format!( 376 "run_command rejected: '{name}' option '{arg}' is an eval flag and runs inline code." 377 )); 378 } 379 } 380 if name == "git" { 381 if let Some(why) = git_override(&argv[1..]) { 382 return Err(format!("run_command rejected: git {why} is not allowed.")); 383 } 384 } 385 Ok(()) 386 } 387 388 fn is_eval_flag(interp: &Interpreter, arg: &str) -> bool { 389 if let Some(long) = arg.strip_prefix("--") { 390 let long = long.split('=').next().unwrap_or(""); 391 return interp.eval_long.iter().any(|e| &e[2..] == long); 392 } 393 let Some(cluster) = arg.strip_prefix('-') else { 394 return false; 395 }; 396 for c in cluster.chars() { 397 if interp.eval_short.contains(c) { 398 return true; 399 } 400 if interp.value_short.contains(c) { 401 return false; 402 } 403 } 404 false 405 } 406 407 /// Global options that take the next argument as their value. 408 const GIT_GLOBAL_VALUE: &[&str] = &[ 409 "-C", 410 "--git-dir", 411 "--work-tree", 412 "--namespace", 413 "--super-prefix", 414 "--attr-source", 415 ]; 416 417 /// Options that name a program for git to run. 418 const GIT_RUNS_PROGRAM: &[&str] = &[ 419 "--upload-pack", 420 "--receive-pack", 421 "--exec", 422 "--extcmd", 423 "--template", 424 "--config", 425 ]; 426 427 /// Why this git invocation can run a program or rewrite config, if it can. 428 /// `args` excludes `git` itself. 429 fn git_override(args: &[String]) -> Option { 430 let mut i = 0; 431 while i < args.len() { 432 let arg = args[i].as_str(); 433 if arg == "-c" 434 || arg.starts_with("-c") 435 || arg == "--exec-path" 436 || arg.starts_with("--exec-path=") 437 || arg.starts_with("--config-env") 438 { 439 return Some(format!("'{arg}' (global config or exec-path override)")); 440 } 441 if !arg.starts_with('-') { 442 break; 443 } 444 i += if GIT_GLOBAL_VALUE.contains(&arg) { 445 2 446 } else { 447 1 448 }; 449 } 450 let sub = args.get(i).map(String::as_str)?; 451 let rest = &args[i + 1..]; 452 for arg in rest { 453 let long = arg.split('=').next().unwrap_or(""); 454 if GIT_RUNS_PROGRAM.contains(&long) { 455 return Some(format!("'{arg}' (runs a program or sets config)")); 456 } 457 } 458 // Short options that run a program or set config in one subcommand only; 459 // elsewhere the same letter is harmless (`git log -c`, `git add -u`). 460 let short_runs = match sub { 461 "clone" => "cu", 462 "rebase" | "difftool" => "x", 463 _ => "", 464 }; 465 if let Some(arg) = rest.iter().find(|a| { 466 a.strip_prefix('-') 467 .is_some_and(|c| !c.starts_with('-') && c.chars().any(|c| short_runs.contains(c))) 468 }) { 469 return Some(format!("{sub} '{arg}' (runs a program or sets config)")); 470 } 471 let first = rest 472 .iter() 473 .find(|a| !a.starts_with('-')) 474 .map(String::as_str); 475 match (sub, first) { 476 ("bisect", Some("run")) | ("submodule", Some("foreach")) | ("filter-branch", _) => { 477 return Some(format!("{sub} (runs a program)")); 478 } 479 ("config", _) => { 480 const READ: &[&str] = &[ 481 "--get", 482 "--get-all", 483 "--get-regexp", 484 "--get-urlmatch", 485 "--get-color", 486 "--get-colorbool", 487 "--list", 488 "-l", 489 ]; 490 const WRITE: &[&str] = &[ 491 "--add", 492 "--replace-all", 493 "--unset", 494 "--unset-all", 495 "--rename-section", 496 "--remove-section", 497 "--edit", 498 "-e", 499 ]; 500 let read = matches!(first, Some("get" | "list")) 501 || rest.iter().any(|a| READ.contains(&a.as_str())); 502 let write = matches!( 503 first, 504 Some("set" | "unset" | "rename-section" | "remove-section" | "edit") 505 ) || rest.iter().any(|a| WRITE.contains(&a.as_str())); 506 if write || !read { 507 return Some("config write".into()); 508 } 509 } 510 _ => {} 511 } 512 None 513 } 514 515 fn resolve_program(name: &str, allowlist: &[String]) -> Result { 516 if name.contains('/') || name.contains('\\') { 517 return Err(format!( 518 "run_command rejected: program path '{name}' is not allowed; pass a bare name" 519 )); 520 } 521 if is_shell_or_wrapper(name) { 522 return Err(format!( 523 "run_command rejected: '{name}' is a shell or exec wrapper and cannot be allowlisted. Shell execution requires the operator allow_shell opt-in, which is off." 524 )); 525 } 526 let bare = !name.is_empty() 527 && name 528 .chars() 529 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-')); 530 if !bare { 531 return Err(format!( 532 "run_command rejected: program '{name}' is not a bare name" 533 )); 534 } 535 if !allowlist.iter().any(|allowed| allowed == name) { 536 return Err(format!( 537 "run_command rejected: program '{name}' is not in the allowlist" 538 )); 539 } 540 for dir in SEARCH_DIRS { 541 let path = Path::new(dir).join(name); 542 if path.is_file() { 543 return Ok(path); 544 } 545 } 546 Err(format!( 547 "run_command rejected: program '{name}' was not found in /bin or /usr/bin" 548 )) 549 } 550 551 fn resolve_cwd(root: &Path, requested: &str) -> Result { 552 let root = root.canonicalize().map_err(|e| { 553 format!( 554 "run_command rejected: command root '{}' is not available: {e}", 555 root.display() 556 ) 557 })?; 558 let requested_path = PathBuf::from(requested); 559 let joined = if requested_path.is_absolute() { 560 requested_path 561 } else { 562 root.join(requested_path) 563 }; 564 let lexical = normalize_lexical(&joined); 565 if !lexical.starts_with(&root) { 566 return Err(format!( 567 "run_command rejected: working directory '{requested}' is outside the command root '{}'", 568 root.display() 569 )); 570 } 571 let canon = joined.canonicalize().map_err(|e| { 572 format!("run_command rejected: working directory '{requested}' is not available: {e}") 573 })?; 574 if !canon.starts_with(&root) { 575 return Err(format!( 576 "run_command rejected: working directory '{requested}' is outside the command root '{}'", 577 root.display() 578 )); 579 } 580 Ok(canon) 581 } 582 583 fn normalize_lexical(path: &Path) -> PathBuf { 584 let mut out = PathBuf::new(); 585 for component in path.components() { 586 match component { 587 Component::CurDir => {} 588 Component::ParentDir => { 589 out.pop(); 590 } 591 other => out.push(other.as_os_str()), 592 } 593 } 594 out 595 } 596 597 fn run_captured( 598 program: &Path, 599 args: &[String], 600 cwd: &Path, 601 timeout: Duration, 602 max_capture: usize, 603 label: &str, 604 ) -> Result<(i32, String, String), String> { 605 let deadline = Instant::now() + timeout; 606 let mut cmd = Command::new(program); 607 cmd.args(args) 608 .current_dir(cwd) 609 .env_clear() 610 .env("PATH", "/usr/bin:/bin") 611 .env("LANG", "C") 612 .env("LC_ALL", "C") 613 .stdin(Stdio::null()) 614 .stdout(Stdio::piped()) 615 .stderr(Stdio::piped()) 616 // Own process group so a background grandchild shares this pgid 617 // and `kill_group` reaches it. 618 .process_group(0); 619 let mut child = cmd.spawn().map_err(|e| { 620 format!( 621 "run_command rejected: failed to start '{}': {e}", 622 program.display() 623 ) 624 })?; 625 let pgid = child.id(); 626 let out = child 627 .stdout 628 .take() 629 .ok_or_else(|| "run_command rejected: stdout pipe was not created".to_string())?; 630 let err = child 631 .stderr 632 .take() 633 .ok_or_else(|| "run_command rejected: stderr pipe was not created".to_string())?; 634 let stdout_hit = Arc::new(AtomicBool::new(false)); 635 let stderr_hit = Arc::new(AtomicBool::new(false)); 636 let stop = Arc::new(AtomicBool::new(false)); 637 let stdout_thread = spawn_reader(out, max_capture, &stdout_hit, deadline, &stop); 638 let stderr_thread = spawn_reader(err, max_capture, &stderr_hit, deadline, &stop); 639 let status: Result = loop { 640 match child.try_wait() { 641 Ok(Some(status)) => { 642 // The leader exited. A grandchild may still hold the pipes. 643 kill_group(pgid); 644 break Ok(status); 645 } 646 Ok(None) => {} 647 Err(e) => { 648 reap_group(&mut child, pgid); 649 stop.store(true, Ordering::Release); 650 let _ = join_readers(stdout_thread, stderr_thread); 651 return Err(e.to_string()); 652 } 653 } 654 if stdout_hit.load(Ordering::Acquire) || stderr_hit.load(Ordering::Acquire) { 655 reap_group(&mut child, pgid); 656 stop.store(true, Ordering::Release); 657 let _ = join_readers(stdout_thread, stderr_thread); 658 let stream = if stdout_hit.load(Ordering::Acquire) { 659 "stdout" 660 } else { 661 "stderr" 662 }; 663 return Err(format!( 664 "run_command rejected: {stream} exceeded the {max_capture} byte capture cap" 665 )); 666 } 667 if Instant::now() >= deadline { 668 reap_group(&mut child, pgid); 669 stop.store(true, Ordering::Release); 670 let _ = join_readers(stdout_thread, stderr_thread); 671 return Err(format!( 672 "Command '{label}' timed out after {:.3} seconds", 673 timeout.as_secs_f64() 674 )); 675 } 676 std::thread::sleep(Duration::from_millis(20)); 677 }; 678 // A grandchild that left the group with `setsid` is out of `kill_group`'s 679 // reach and can hold the pipes open. Give the readers a short grace to 680 // take what the leader wrote, then stop them; they still drain whatever 681 // is already buffered. 682 let grace = (Instant::now() + DRAIN_AFTER_EXIT).min(deadline); 683 while !(stdout_thread.is_finished() && stderr_thread.is_finished()) && Instant::now() < grace { 684 std::thread::sleep(Duration::from_millis(10)); 685 } 686 stop.store(true, Ordering::Release); 687 let (stdout, stderr) = join_readers(stdout_thread, stderr_thread); 688 let status = status?; 689 if stdout_hit.load(Ordering::Acquire) { 690 return Err(format!( 691 "run_command rejected: stdout exceeded the {max_capture} byte capture cap" 692 )); 693 } 694 if stderr_hit.load(Ordering::Acquire) { 695 return Err(format!( 696 "run_command rejected: stderr exceeded the {max_capture} byte capture cap" 697 )); 698 } 699 Ok((status.code().unwrap_or(-1), stdout, stderr)) 700 } 701 702 /// How long the readers may wait for more output after the leader exited. 703 const DRAIN_AFTER_EXIT: Duration = Duration::from_millis(500); 704 705 /// Longest single poll, so a reader notices `stop` promptly. 706 const POLL_SLICE_MS: i32 = 50; 707 708 fn spawn_reader( 709 reader: R, 710 cap: usize, 711 hit: &Arc, 712 deadline: Instant, 713 stop: &Arc, 714 ) -> JoinHandle> 715 where 716 R: Read + AsRawFd + Send + 'static, 717 { 718 let (hit, stop) = (Arc::clone(hit), Arc::clone(stop)); 719 std::thread::spawn(move || read_bounded(reader, cap, &hit, deadline, &stop)) 720 } 721 722 /// Read until EOF, `cap`, `deadline`, or `stop`. After `stop` the reader 723 /// takes only what is already buffered, so a grandchild holding the pipe 724 /// cannot block the drain. 725 fn read_bounded( 726 mut reader: impl Read + AsRawFd, 727 cap: usize, 728 hit: &AtomicBool, 729 deadline: Instant, 730 stop: &AtomicBool, 731 ) -> Vec { 732 let fd = reader.as_raw_fd(); 733 set_nonblock(fd); 734 let mut buf = Vec::new(); 735 let mut tmp = [0u8; 8192]; 736 loop { 737 if buf.len() >= cap { 738 if extra_byte(&mut reader, fd, deadline, stop) { 739 hit.store(true, Ordering::Release); 740 } 741 return buf; 742 } 743 let want = (cap - buf.len()).min(tmp.len()); 744 match reader.read(&mut tmp[..want]) { 745 Ok(0) => return buf, 746 Ok(n) => buf.extend_from_slice(&tmp[..n]), 747 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, 748 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { 749 if !wait_readable(fd, deadline, stop) { 750 return buf; 751 } 752 } 753 Err(_) => return buf, 754 } 755 } 756 } 757 758 fn extra_byte(reader: &mut impl Read, fd: i32, deadline: Instant, stop: &AtomicBool) -> bool { 759 loop { 760 let mut extra = [0u8; 1]; 761 match reader.read(&mut extra) { 762 Ok(0) => return false, 763 Ok(_) => return true, 764 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, 765 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { 766 if !wait_readable(fd, deadline, stop) { 767 return false; 768 } 769 } 770 Err(_) => return false, 771 } 772 } 773 } 774 775 /// Wait for input in slices of at most [`POLL_SLICE_MS`]. Once `stop` is 776 /// set, one zero-timeout poll reports whether data is already buffered. 777 fn wait_readable(fd: i32, deadline: Instant, stop: &AtomicBool) -> bool { 778 loop { 779 let stopping = stop.load(Ordering::Acquire); 780 let now = Instant::now(); 781 if now >= deadline { 782 return false; 783 } 784 let wait_ms = if stopping { 785 0 786 } else { 787 deadline 788 .saturating_duration_since(now) 789 .as_millis() 790 .clamp(1, POLL_SLICE_MS as u128) as i32 791 }; 792 let mut pfd = PollFd { 793 fd, 794 events: POLLIN, 795 revents: 0, 796 }; 797 let rc = unsafe { poll(&mut pfd, 1, wait_ms) }; 798 if rc > 0 { 799 return true; 800 } 801 if rc == 0 && stopping { 802 return false; 803 } 804 if rc < 0 && std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted { 805 return false; 806 } 807 } 808 } 809 810 fn set_nonblock(fd: i32) { 811 let flags = unsafe { fcntl(fd, F_GETFL, 0) }; 812 if flags >= 0 { 813 let _ = unsafe { fcntl(fd, F_SETFL, flags | O_NONBLOCK) }; 814 } 815 } 816 817 fn short_label(command: &str) -> String { 818 let mut out = String::new(); 819 for (i, c) in command.chars().enumerate() { 820 if i == 120 { 821 out.push_str("..."); 822 break; 823 } 824 out.push(c); 825 } 826 out 827 } 828 829 fn join_readers(stdout: JoinHandle>, stderr: JoinHandle>) -> (String, String) { 830 let stdout = String::from_utf8_lossy(&stdout.join().unwrap_or_default()).into_owned(); 831 let stderr = String::from_utf8_lossy(&stderr.join().unwrap_or_default()).into_owned(); 832 (stdout, stderr) 833 } 834 835 fn reap_group(child: &mut Child, pgid: u32) { 836 kill_group(pgid); 837 let _ = child.kill(); 838 let _ = child.wait(); 839 } 840 841 fn kill_group(pgid: u32) { 842 if pgid == 0 { 843 return; 844 } 845 let _ = unsafe { 846 // SAFETY: `pgid` is the spawned child's pid. `process_group(0)` made 847 // that pid the process group id. A negative pid signals only that 848 // group, not the driver. 849 kill(-(pgid as i32), 9) 850 }; 851 } 852 853 const POLLIN: i16 = 1; 854 const F_GETFL: i32 = 3; 855 const F_SETFL: i32 = 4; 856 const O_NONBLOCK: i32 = 0o4000; 857 858 #[repr(C)] 859 struct PollFd { 860 fd: i32, 861 events: i16, 862 revents: i16, 863 } 864 865 unsafe extern "C" { 866 fn kill(pid: i32, sig: i32) -> i32; 867 fn poll(fds: *mut PollFd, nfds: usize, timeout: i32) -> i32; 868 fn fcntl(fd: i32, cmd: i32, arg: i32) -> i32; 869 } 870 871 #[cfg(test)] 872 mod tests { 873 use super::*; 874 use std::os::unix::fs::PermissionsExt; 875 876 #[test] 877 fn grandchild_holding_the_pipe_does_not_hang_the_drain() { 878 let dir = std::env::temp_dir().join(format!( 879 "aien-drive-bg-{}-{}", 880 std::process::id(), 881 std::time::SystemTime::now() 882 .duration_since(std::time::UNIX_EPOCH) 883 .unwrap() 884 .as_nanos() 885 )); 886 std::fs::create_dir_all(&dir).unwrap(); 887 let script = dir.join("bg.sh"); 888 let pidfile = dir.join("pid"); 889 std::fs::write(&script, "#!/bin/sh\nsleep 30 &\necho $! > \"$1\"\nexit 0\n").unwrap(); 890 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); 891 let started = Instant::now(); 892 let result = run_captured( 893 &script, 894 &[pidfile.display().to_string()], 895 &dir, 896 Duration::from_secs(2), 897 1024 * 1024, 898 "bg", 899 ); 900 let elapsed = started.elapsed(); 901 let pid_txt = std::fs::read_to_string(&pidfile).unwrap_or_default(); 902 let pid: i32 = pid_txt.trim().parse().unwrap_or(0); 903 let mut alive = pid > 0; 904 if alive { 905 for _ in 0..50 { 906 if !std::path::Path::new(&format!("/proc/{pid}")).exists() { 907 alive = false; 908 break; 909 } 910 std::thread::sleep(Duration::from_millis(10)); 911 } 912 } 913 if alive { 914 // Direct signal to the recorded pid. `kill_group` uses a negative 915 // pgid, and this pid is the sleeper, not the group leader. 916 let _ = unsafe { kill(pid, 9) }; 917 } 918 let _ = std::fs::remove_dir_all(&dir); 919 assert!( 920 elapsed < Duration::from_secs(3), 921 "drain hung for {elapsed:?}: {result:?}" 922 ); 923 assert!(result.is_ok(), "{result:?}"); 924 assert!(pid > 0, "helper did not record the grandchild pid"); 925 assert!(!alive, "grandchild {pid} survived kill_group"); 926 } 927 928 #[test] 929 fn setsid_grandchild_cannot_hold_the_drain_until_the_deadline() { 930 // `setsid` takes the sleeper out of the group, so `kill_group` cannot 931 // reach it and it keeps both pipes open. The drain must stop shortly 932 // after the leader exits, not at the 10 s deadline. 933 let dir = std::env::temp_dir().join(format!( 934 "aien-drive-setsid-{}-{}", 935 std::process::id(), 936 std::time::SystemTime::now() 937 .duration_since(std::time::UNIX_EPOCH) 938 .unwrap() 939 .as_nanos() 940 )); 941 std::fs::create_dir_all(&dir).unwrap(); 942 let script = dir.join("escape.sh"); 943 let pidfile = dir.join("pid"); 944 std::fs::write( 945 &script, 946 // The leader waits until the sleeper has left the group and 947 // recorded its pid, so `kill_group` cannot win a race with it. 948 "#!/bin/sh\nsetsid sh -c 'echo $$ > \"$1\"; exec sleep 30' escape \"$1\" &\nwhile [ ! -s \"$1\" ]; do sleep 0.01; done\necho leader-done\nexit 0\n", 949 ) 950 .unwrap(); 951 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); 952 let started = Instant::now(); 953 let result = run_captured( 954 &script, 955 &[pidfile.display().to_string()], 956 &dir, 957 Duration::from_secs(10), 958 1024 * 1024, 959 "escape", 960 ); 961 let elapsed = started.elapsed(); 962 let pid: i32 = std::fs::read_to_string(&pidfile) 963 .unwrap_or_default() 964 .trim() 965 .parse() 966 .unwrap_or(0); 967 if pid > 0 { 968 let _ = unsafe { kill(pid, 9) }; 969 } 970 let _ = std::fs::remove_dir_all(&dir); 971 assert!(pid > 0, "helper did not record the sleeper pid"); 972 assert!( 973 elapsed < Duration::from_secs(3), 974 "escaped grandchild held the drain for {elapsed:?}: {result:?}" 975 ); 976 let (code, stdout, _) = result.unwrap(); 977 assert_eq!(code, 0); 978 assert!(stdout.contains("leader-done"), "{stdout:?}"); 979 } 980 }