| 1 | //! Process-tree containment for a spawned child and everything it starts. |
| 2 | //! |
| 3 | //! Moved out of `hooks/executor.rs` (where it was `HookProcessTree` / |
| 4 | //! `WindowsHookJob`) so the hook runner and the extension host share one |
| 5 | //! implementation. Killing only the immediate child can leave the real work |
| 6 | //! alive (a hook's shell runtime, a host plugin's `child_process`), so: |
| 7 | //! |
| 8 | //! * **Unix:** contained commands start in a new session (`setsid`) when |
| 9 | //! possible, or their own process group (`process_group(0)`); the tree is |
| 10 | //! SIGKILLed across its process group and, for session leaders, all remaining |
| 11 | //! session members (catching job-control background jobs in their own groups). |
| 12 | //! * **Windows:** the child is assigned to a Job Object configured with |
| 13 | //! `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, so closing the job kills every |
| 14 | //! process in it. Hooks are created suspended and resumed only after the |
| 15 | //! assignment. Tokio children are assigned after spawning and can start |
| 16 | //! descendants before assignment. This bounds ordinary process lifetimes; |
| 17 | //! it is not a security sandbox. |
| 18 | //! |
| 19 | //! Dropping the guard kills the tree. That is deliberate: the guard's lifetime |
| 20 | //! is the tree's lifetime, unless [`ProcessTree::release`] explicitly lets the |
| 21 | //! tree outlive it. |
| 22 | |
| 23 | #[cfg(windows)] |
| 24 | use windows::Win32::Foundation::{CloseHandle, HANDLE}; |
| 25 | #[cfg(windows)] |
| 26 | use windows::Win32::System::JobObjects::{ |
| 27 | AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, |
| 28 | JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, |
| 29 | JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject, |
| 30 | }; |
| 31 | #[cfg(windows)] |
| 32 | use windows::core::PCWSTR; |
| 33 | |
| 34 | #[cfg(windows)] |
| 35 | use windows::Win32::System::Diagnostics::ToolHelp::{ |
| 36 | CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, |
| 37 | }; |
| 38 | #[cfg(windows)] |
| 39 | use windows::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME}; |
| 40 | |
| 41 | /// Owns the process tree rooted at one spawned child. |
| 42 | pub struct ProcessTree { |
| 43 | #[cfg(unix)] |
| 44 | pgid: libc::pid_t, |
| 45 | #[cfg(unix)] |
| 46 | is_session_leader: bool, |
| 47 | #[cfg(unix)] |
| 48 | armed: std::sync::atomic::AtomicBool, |
| 49 | #[cfg(windows)] |
| 50 | job: WindowsJob, |
| 51 | } |
| 52 | |
| 53 | // SAFETY (Windows): the job handle is an owned kernel handle; it is only |
| 54 | // used through `&self` calls that the OS serializes, and closed once in Drop. |
| 55 | #[cfg(windows)] |
| 56 | unsafe impl Send for ProcessTree {} |
| 57 | #[cfg(windows)] |
| 58 | unsafe impl Sync for ProcessTree {} |
| 59 | |
| 60 | impl ProcessTree { |
| 61 | /// Contain a `std::process::Child` (spawned with `process_group(0)` on Unix). |
| 62 | pub fn attach(child: &std::process::Child) -> std::io::Result<Self> { |
| 63 | #[cfg(windows)] |
| 64 | { |
| 65 | use std::os::windows::io::AsRawHandle; |
| 66 | Self::attach_parts(child.id(), child.as_raw_handle()) |
| 67 | } |
| 68 | #[cfg(not(windows))] |
| 69 | { |
| 70 | Self::attach_parts(child.id()) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Contain a `tokio::process::Child` (spawned with `process_group(0)` on |
| 75 | /// Unix). Fails if the child has already been reaped. |
| 76 | pub fn attach_tokio(child: &tokio::process::Child) -> std::io::Result<Self> { |
| 77 | let pid = child |
| 78 | .id() |
| 79 | .ok_or_else(|| std::io::Error::other("child already exited"))?; |
| 80 | #[cfg(windows)] |
| 81 | { |
| 82 | let handle = child |
| 83 | .raw_handle() |
| 84 | .ok_or_else(|| std::io::Error::other("child already exited"))?; |
| 85 | Self::attach_parts(pid, handle) |
| 86 | } |
| 87 | #[cfg(not(windows))] |
| 88 | { |
| 89 | Self::attach_parts(pid) |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// Typed owned handle from a suspended Core-selected process. The caller |
| 94 | /// attaches/caps the Job before any process thread is resumed. |
| 95 | #[cfg(windows)] |
| 96 | pub fn attach_windows_handle( |
| 97 | pid: u32, |
| 98 | process: &std::os::windows::io::OwnedHandle, |
| 99 | ) -> std::io::Result<Self> { |
| 100 | use std::os::windows::io::AsRawHandle; |
| 101 | Self::attach_parts(pid, process.as_raw_handle()) |
| 102 | } |
| 103 | |
| 104 | #[cfg(windows)] |
| 105 | fn attach_parts(_pid: u32, handle: std::os::windows::io::RawHandle) -> std::io::Result<Self> { |
| 106 | Ok(Self { |
| 107 | job: WindowsJob::attach(handle)?, |
| 108 | }) |
| 109 | } |
| 110 | |
| 111 | #[cfg(not(windows))] |
| 112 | #[allow(clippy::unnecessary_wraps)] |
| 113 | fn attach_parts(pid: u32) -> std::io::Result<Self> { |
| 114 | #[cfg(unix)] |
| 115 | { |
| 116 | let pgid = pid as libc::pid_t; |
| 117 | // SAFETY: `getsid` is a read-only process query. |
| 118 | let sid = unsafe { libc::getsid(pgid) }; |
| 119 | let is_session_leader = pgid > 0 |
| 120 | && (sid == pgid |
| 121 | || (sid == -1 |
| 122 | && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH))); |
| 123 | contained_exit_groups().push((pgid, is_session_leader)); |
| 124 | Ok(Self { |
| 125 | pgid, |
| 126 | is_session_leader, |
| 127 | armed: std::sync::atomic::AtomicBool::new(true), |
| 128 | }) |
| 129 | } |
| 130 | #[cfg(not(unix))] |
| 131 | { |
| 132 | let _ = pid; |
| 133 | Ok(Self {}) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | /// Kill every process in the tree. A tree that is already gone, or was |
| 138 | /// disarmed after its leader was reaped, is not an error. On failure the |
| 139 | /// caller should fall back to killing the child. |
| 140 | pub fn kill(&self) -> std::io::Result<()> { |
| 141 | #[cfg(unix)] |
| 142 | { |
| 143 | if !self.armed.load(std::sync::atomic::Ordering::SeqCst) { |
| 144 | return Ok(()); |
| 145 | } |
| 146 | kill_unix_tree(self.pgid, self.is_session_leader) |
| 147 | } |
| 148 | #[cfg(windows)] |
| 149 | { |
| 150 | self.job.terminate() |
| 151 | } |
| 152 | #[cfg(not(any(unix, windows)))] |
| 153 | { |
| 154 | Err(std::io::Error::other( |
| 155 | "process-tree containment is not supported on this platform", |
| 156 | )) |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | impl ProcessTree { |
| 162 | /// Windows: cap the committed memory of every process in the job at |
| 163 | /// `bytes` each (`JOB_OBJECT_LIMIT_PROCESS_MEMORY`); an allocation past |
| 164 | /// it fails. Kill-on-close stays set. The extension host's memory cap. |
| 165 | #[cfg(windows)] |
| 166 | pub fn limit_process_memory(&self, bytes: u64) -> std::io::Result<()> { |
| 167 | self.job.limit_process_memory(bytes) |
| 168 | } |
| 169 | |
| 170 | /// Give up containment without killing anything: the tree outlives the |
| 171 | /// guard. For a command that exited on its own and may have deliberately |
| 172 | /// left something running. |
| 173 | pub fn release(self) { |
| 174 | #[cfg(windows)] |
| 175 | { |
| 176 | // Closing the handle kills the job unless the limit is cleared |
| 177 | // first. If clearing fails, the close still kills: the safe side. |
| 178 | let _ = self.job.clear_kill_on_close(); |
| 179 | } |
| 180 | self.disarm(); |
| 181 | } |
| 182 | |
| 183 | /// The leader has been reaped: never signal this group again. Unix stops |
| 184 | /// `kill`, Drop and the signal-exit path from addressing a group id the |
| 185 | /// OS may now reuse. Windows holds a Job handle, which has no such |
| 186 | /// hazard, so the tree stays killable there. |
| 187 | pub fn disarm(&self) { |
| 188 | #[cfg(unix)] |
| 189 | let _ = self.take_armed(); |
| 190 | } |
| 191 | |
| 192 | #[cfg(unix)] |
| 193 | fn take_armed(&self) -> bool { |
| 194 | let was_armed = self.armed.swap(false, std::sync::atomic::Ordering::SeqCst); |
| 195 | if was_armed { |
| 196 | let mut groups = contained_exit_groups(); |
| 197 | if let Some(index) = groups.iter().position(|(pgid, _)| *pgid == self.pgid) { |
| 198 | groups.swap_remove(index); |
| 199 | } |
| 200 | } |
| 201 | was_armed |
| 202 | } |
| 203 | |
| 204 | /// Non-blocking. Unix: when the leader has exited, SIGKILL the group |
| 205 | /// while the unreaped leader still pins its id, disarm, and return |
| 206 | /// `true`; the caller then reaps. A leader someone else already reaped is |
| 207 | /// disarmed without a signal. Elsewhere this does nothing and returns |
| 208 | /// `false`: reap first, then [`ProcessTree::kill`]. |
| 209 | pub fn kill_if_leader_exited(&self) -> bool { |
| 210 | #[cfg(unix)] |
| 211 | { |
| 212 | if !self.armed.load(std::sync::atomic::Ordering::SeqCst) { |
| 213 | return true; |
| 214 | } |
| 215 | match observe_leader_exit(self.pgid, false) { |
| 216 | Ok(false) => false, |
| 217 | Ok(true) => { |
| 218 | let _ = self.kill(); |
| 219 | self.disarm(); |
| 220 | true |
| 221 | } |
| 222 | Err(_) => { |
| 223 | self.disarm(); |
| 224 | true |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | #[cfg(not(unix))] |
| 229 | { |
| 230 | false |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | /// Resolve once `child`, this tree's leader, has exited. Unix observes |
| 235 | /// the exit on the blocking pool without reaping, so the group id stays |
| 236 | /// pinned while the caller decides between [`ProcessTree::kill`] and |
| 237 | /// [`ProcessTree::release`]; the caller then reaps with `child.wait()` |
| 238 | /// and calls [`ProcessTree::disarm`]. Elsewhere this is `child.wait()`. |
| 239 | pub async fn leader_exit(&self, child: &mut tokio::process::Child) { |
| 240 | #[cfg(unix)] |
| 241 | { |
| 242 | if child.id().is_none() { |
| 243 | self.disarm(); |
| 244 | return; |
| 245 | } |
| 246 | let pid = self.pgid; |
| 247 | let observed = |
| 248 | tokio::task::spawn_blocking(move || observe_leader_exit(pid, true)).await; |
| 249 | if matches!(observed, Ok(Err(_))) { |
| 250 | self.disarm(); |
| 251 | } |
| 252 | } |
| 253 | #[cfg(not(unix))] |
| 254 | { |
| 255 | let _ = child.wait().await; |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | /// `child.wait()` for this tree's leader that kills the rest of the tree |
| 260 | /// when the leader exits: before the reap on Unix, then disarmed. |
| 261 | pub async fn wait_then_kill( |
| 262 | &self, |
| 263 | child: &mut tokio::process::Child, |
| 264 | ) -> std::io::Result<std::process::ExitStatus> { |
| 265 | self.leader_exit(child).await; |
| 266 | let _ = self.kill(); |
| 267 | let status = child.wait().await; |
| 268 | self.disarm(); |
| 269 | status |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Bounded wait for the direct child to exit without reaping it. Returns true |
| 274 | /// once it has exited, propagates an observation error, and returns |
| 275 | /// false when the grace elapsed first. |
| 276 | #[cfg(unix)] |
| 277 | pub fn wait_leader_exit_until( |
| 278 | child: &std::process::Child, |
| 279 | deadline: std::time::Instant, |
| 280 | ) -> std::io::Result<bool> { |
| 281 | loop { |
| 282 | if leader_exited_unreaped(child.id())? { |
| 283 | return Ok(true); |
| 284 | } |
| 285 | let remaining = deadline.saturating_duration_since(std::time::Instant::now()); |
| 286 | if remaining.is_zero() { |
| 287 | return Ok(false); |
| 288 | } |
| 289 | std::thread::sleep(remaining.min(std::time::Duration::from_millis(10))); |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | /// Whether child `pid` has exited and still awaits its reap. Non-blocking and |
| 294 | /// non-reaping (`WNOWAIT`): while this is `true` the pid, and the process |
| 295 | /// group it leads, cannot be reused. Errors when `pid` is not an unreaped |
| 296 | /// child of this process. |
| 297 | #[cfg(unix)] |
| 298 | pub fn leader_exited_unreaped(pid: u32) -> std::io::Result<bool> { |
| 299 | observe_leader_exit(pid as libc::pid_t, false) |
| 300 | } |
| 301 | |
| 302 | #[cfg(unix)] |
| 303 | fn observe_leader_exit(pid: libc::pid_t, block: bool) -> std::io::Result<bool> { |
| 304 | let options = libc::WEXITED | libc::WNOWAIT | if block { 0 } else { libc::WNOHANG }; |
| 305 | loop { |
| 306 | // SAFETY: all-zero bytes are a valid `siginfo_t`. |
| 307 | let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; |
| 308 | // SAFETY: `info` is live and writable for the duration of the call. |
| 309 | let result = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, options) }; |
| 310 | if result == 0 { |
| 311 | return Ok(block || info.si_signo == libc::SIGCHLD); |
| 312 | } |
| 313 | let error = std::io::Error::last_os_error(); |
| 314 | if error.kind() != std::io::ErrorKind::Interrupted { |
| 315 | return Err(error); |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | impl Drop for ProcessTree { |
| 321 | fn drop(&mut self) { |
| 322 | #[cfg(unix)] |
| 323 | if self.take_armed() { |
| 324 | let _ = kill_unix_tree(self.pgid, self.is_session_leader); |
| 325 | } |
| 326 | // On Windows, dropping `WindowsJob` closes a Job Object configured |
| 327 | // with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE. |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | /// Start a synchronous child inside the same process group / Job used by hooks. |
| 332 | /// Windows starts suspended and resumes only after Job assignment. The caller |
| 333 | /// still owns environment policy and bounded waits; this is lifetime containment. |
| 334 | pub fn spawn_contained_std( |
| 335 | command: &mut std::process::Command, |
| 336 | ) -> std::io::Result<(std::process::Child, ProcessTree)> { |
| 337 | use wait_timeout::ChildExt; |
| 338 | configure_contained_command(command); |
| 339 | let mut child = command.spawn()?; |
| 340 | let tree = match ProcessTree::attach(&child) { |
| 341 | Ok(tree) => tree, |
| 342 | Err(error) => { |
| 343 | let _ = child.kill(); |
| 344 | let _ = child.wait_timeout(std::time::Duration::from_millis(250)); |
| 345 | return Err(error); |
| 346 | } |
| 347 | }; |
| 348 | #[cfg(windows)] |
| 349 | if let Err(error) = resume_windows_process(child.id()) { |
| 350 | drop(tree); |
| 351 | let _ = child.kill(); |
| 352 | let _ = child.wait_timeout(std::time::Duration::from_millis(250)); |
| 353 | return Err(error); |
| 354 | } |
| 355 | Ok((child, tree)) |
| 356 | } |
| 357 | |
| 358 | #[cfg(unix)] |
| 359 | fn configure_unix_contained_command(command: &mut std::process::Command) { |
| 360 | use std::os::unix::process::CommandExt; |
| 361 | // SAFETY: `setsid`, `setpgid`, `getpgrp`, and `getpid` are async-signal-safe. |
| 362 | unsafe { |
| 363 | command.pre_exec(|| { |
| 364 | if libc::setsid() != -1 { |
| 365 | return Ok(()); |
| 366 | } |
| 367 | let error = std::io::Error::last_os_error(); |
| 368 | if error.raw_os_error() != Some(libc::EPERM) { |
| 369 | return Err(error); |
| 370 | } |
| 371 | if libc::setpgid(0, 0) == 0 || libc::getpgrp() == libc::getpid() { |
| 372 | return Ok(()); |
| 373 | } |
| 374 | Err(std::io::Error::last_os_error()) |
| 375 | }); |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | fn configure_contained_command(command: &mut std::process::Command) { |
| 380 | #[cfg(unix)] |
| 381 | configure_unix_contained_command(command); |
| 382 | #[cfg(windows)] |
| 383 | { |
| 384 | use std::os::windows::process::CommandExt; |
| 385 | use windows::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED}; |
| 386 | command.creation_flags(CREATE_SUSPENDED.0 | CREATE_NO_WINDOW.0); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | pub fn spawn_contained_tokio( |
| 391 | command: &mut tokio::process::Command, |
| 392 | ) -> std::io::Result<(tokio::process::Child, ProcessTree)> { |
| 393 | configure_contained_command(command.as_std_mut()); |
| 394 | let child = command.kill_on_drop(true).spawn()?; |
| 395 | let tree = ProcessTree::attach_tokio(&child).map_err(|error| { |
| 396 | std::io::Error::other(format!("failed to contain child process: {error}")) |
| 397 | })?; |
| 398 | #[cfg(windows)] |
| 399 | { |
| 400 | let pid = child |
| 401 | .id() |
| 402 | .ok_or_else(|| std::io::Error::other("child already exited"))?; |
| 403 | resume_windows_process(pid).map_err(|error| { |
| 404 | std::io::Error::other(format!("failed to start contained process: {error}")) |
| 405 | })?; |
| 406 | } |
| 407 | Ok((child, tree)) |
| 408 | } |
| 409 | |
| 410 | #[cfg(windows)] |
| 411 | fn resume_windows_process(pid: u32) -> std::io::Result<()> { |
| 412 | let snapshot = |
| 413 | // SAFETY: returned handle is owned here; closed before return. |
| 414 | unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0).map_err(windows_io_error)? }; |
| 415 | let result = (|| { |
| 416 | let mut entry = THREADENTRY32 { |
| 417 | dwSize: std::mem::size_of::<THREADENTRY32>() as u32, |
| 418 | ..Default::default() |
| 419 | }; |
| 420 | // SAFETY: `entry` is live with dwSize initialized above. |
| 421 | let mut next = unsafe { Thread32First(snapshot, &mut entry) }; |
| 422 | let mut resumed = 0usize; |
| 423 | while next.is_ok() { |
| 424 | if entry.th32OwnerProcessID == pid { |
| 425 | // SAFETY: returned handle is owned here; closed below. |
| 426 | let thread = unsafe { |
| 427 | OpenThread(THREAD_SUSPEND_RESUME, false, entry.th32ThreadID) |
| 428 | .map_err(windows_io_error)? |
| 429 | }; |
| 430 | // SAFETY: `thread` is a live owned handle. |
| 431 | let resume_result = unsafe { ResumeThread(thread) }; |
| 432 | // SAFETY: `thread` is owned here and not used after. |
| 433 | let close_result = unsafe { CloseHandle(thread).map_err(windows_io_error) }; |
| 434 | if resume_result == u32::MAX { |
| 435 | return Err(std::io::Error::last_os_error()); |
| 436 | } |
| 437 | close_result?; |
| 438 | resumed += 1; |
| 439 | } |
| 440 | // SAFETY: `entry` is live with dwSize initialized above. |
| 441 | next = unsafe { Thread32Next(snapshot, &mut entry) }; |
| 442 | } |
| 443 | if resumed == 0 { |
| 444 | return Err(std::io::Error::other( |
| 445 | "suspended process had no resumable thread", |
| 446 | )); |
| 447 | } |
| 448 | Ok(()) |
| 449 | })(); |
| 450 | // SAFETY: `snapshot` is owned here and not used after. |
| 451 | let close_result = unsafe { CloseHandle(snapshot).map_err(windows_io_error) }; |
| 452 | result?; |
| 453 | close_result |
| 454 | } |
| 455 | |
| 456 | /// `Command::output()` for a child whose whole process tree dies with the |
| 457 | /// returned future. Dropping it — a caller's `timeout` elapsing, or a |
| 458 | /// cancelled tool call — kills the child and everything it started, where a |
| 459 | /// bare `output()` left them running. Stdin is closed: callers run |
| 460 | /// non-interactive work that must never wait on input. |
| 461 | pub async fn contained_output( |
| 462 | cmd: &mut tokio::process::Command, |
| 463 | ) -> std::io::Result<std::process::Output> { |
| 464 | contained_output_until(cmd, std::future::pending()) |
| 465 | .await |
| 466 | .map(|run| run.output) |
| 467 | } |
| 468 | |
| 469 | /// What [`contained_output_until`] collected. |
| 470 | pub struct ContainedOutput { |
| 471 | pub output: std::process::Output, |
| 472 | /// `stop` fired before the command exited: the tree was killed, and |
| 473 | /// `output` holds everything it wrote until then. |
| 474 | pub stopped: bool, |
| 475 | } |
| 476 | |
| 477 | /// [`contained_output`], plus a `stop` future (a deadline, a cancel token). |
| 478 | /// When `stop` fires first the tree is killed and the output written so far is |
| 479 | /// still returned, so a hung command leaves evidence of where it hung. |
| 480 | /// |
| 481 | /// A command that exits on its own is released, not killed: whatever it |
| 482 | /// deliberately left running with its output redirected (`nohup server >log |
| 483 | /// &`) keeps running, as it did with a bare `output()`. Only a dropped future |
| 484 | /// or `stop` kills the tree. Until then the group is also listed for |
| 485 | /// [`kill_contained_trees_for_exit`], because a terminating signal ends |
| 486 | /// Codewhale through `process::exit`, where no destructor runs, and a child in |
| 487 | /// its own process group no longer receives the terminal's Ctrl+C itself. |
| 488 | pub async fn contained_output_until( |
| 489 | cmd: &mut tokio::process::Command, |
| 490 | stop: impl std::future::Future<Output = ()>, |
| 491 | ) -> std::io::Result<ContainedOutput> { |
| 492 | contained_run(cmd, None, stop, ProcessTree::attach_tokio).await |
| 493 | } |
| 494 | |
| 495 | /// [`contained_output`] for a command that reads a request on stdin (a plugin |
| 496 | /// tool's JSON input): `input` is written while the output pipes drain, then |
| 497 | /// stdin is closed. |
| 498 | pub async fn contained_output_with_input( |
| 499 | cmd: &mut tokio::process::Command, |
| 500 | input: Vec<u8>, |
| 501 | ) -> std::io::Result<std::process::Output> { |
| 502 | contained_run( |
| 503 | cmd, |
| 504 | Some(input), |
| 505 | std::future::pending(), |
| 506 | ProcessTree::attach_tokio, |
| 507 | ) |
| 508 | .await |
| 509 | .map(|run| run.output) |
| 510 | } |
| 511 | |
| 512 | async fn contained_run( |
| 513 | cmd: &mut tokio::process::Command, |
| 514 | input: Option<Vec<u8>>, |
| 515 | stop: impl std::future::Future<Output = ()>, |
| 516 | attach: impl FnOnce(&tokio::process::Child) -> std::io::Result<ProcessTree>, |
| 517 | ) -> std::io::Result<ContainedOutput> { |
| 518 | contained_run_with_limits(cmd, input, stop, attach, None).await |
| 519 | } |
| 520 | |
| 521 | /// Strict capture bounds for the admitted script runner. Overflow refuses the result; |
| 522 | /// it never presents a truncated ToolResult as success. Same containment driver. |
| 523 | pub async fn contained_output_with_input_bounded( |
| 524 | cmd: &mut tokio::process::Command, |
| 525 | input: Vec<u8>, |
| 526 | stdout_limit: usize, |
| 527 | stderr_limit: usize, |
| 528 | stop: impl std::future::Future<Output = ()>, |
| 529 | ) -> std::io::Result<ContainedOutput> { |
| 530 | contained_run_with_limits( |
| 531 | cmd, |
| 532 | Some(input), |
| 533 | stop, |
| 534 | ProcessTree::attach_tokio, |
| 535 | Some((stdout_limit, stderr_limit)), |
| 536 | ) |
| 537 | .await |
| 538 | } |
| 539 | async fn contained_run_with_limits( |
| 540 | cmd: &mut tokio::process::Command, |
| 541 | input: Option<Vec<u8>>, |
| 542 | stop: impl std::future::Future<Output = ()>, |
| 543 | attach: impl FnOnce(&tokio::process::Child) -> std::io::Result<ProcessTree>, |
| 544 | limits: Option<(usize, usize)>, |
| 545 | ) -> std::io::Result<ContainedOutput> { |
| 546 | use std::process::Stdio; |
| 547 | cmd.stdin(if input.is_some() { |
| 548 | Stdio::piped() |
| 549 | } else { |
| 550 | Stdio::null() |
| 551 | }) |
| 552 | .stdout(Stdio::piped()) |
| 553 | .stderr(Stdio::piped()) |
| 554 | .kill_on_drop(true); |
| 555 | #[cfg(unix)] |
| 556 | configure_unix_contained_command(cmd.as_std_mut()); |
| 557 | let mut child = cmd.spawn()?; |
| 558 | // Never report a contained run when attachment failed. The child's |
| 559 | // kill-on-drop guard still cleans up the direct child on this error path. |
| 560 | let tree = attach(&child)?; |
| 561 | let mut stdout_pipe = child.stdout.take(); |
| 562 | let mut stderr_pipe = child.stderr.take(); |
| 563 | let stdin_pipe = child.stdin.take(); |
| 564 | let mut stdout = Vec::new(); |
| 565 | let mut stderr = Vec::new(); |
| 566 | let exited = { |
| 567 | // Written alongside the drains: a child that answers before it has |
| 568 | // read all of its input would otherwise deadlock on a full pipe. |
| 569 | let feed = async move { |
| 570 | use tokio::io::AsyncWriteExt; |
| 571 | if let (Some(mut pipe), Some(input)) = (stdin_pipe, input) { |
| 572 | // A child that exits without reading its input closes the |
| 573 | // pipe; that is its answer, not a run failure. |
| 574 | if pipe.write_all(&input).await.is_ok() { |
| 575 | let _ = pipe.shutdown().await; |
| 576 | } |
| 577 | } |
| 578 | }; |
| 579 | let run = async { |
| 580 | let out = drain_pipe_with_limit( |
| 581 | stdout_pipe.as_mut(), |
| 582 | &mut stdout, |
| 583 | limits.map(|limits| limits.0), |
| 584 | ); |
| 585 | let err = drain_pipe_with_limit( |
| 586 | stderr_pipe.as_mut(), |
| 587 | &mut stderr, |
| 588 | limits.map(|limits| limits.1), |
| 589 | ); |
| 590 | let wait = async { |
| 591 | if limits.is_some() { |
| 592 | tree.wait_then_kill(&mut child).await |
| 593 | } else { |
| 594 | child.wait().await |
| 595 | } |
| 596 | }; |
| 597 | if limits.is_some() { |
| 598 | let (_, _, status, ()) = tokio::try_join!(out, err, wait, async { |
| 599 | feed.await; |
| 600 | Ok::<(), std::io::Error>(()) |
| 601 | })?; |
| 602 | Ok(status) |
| 603 | } else { |
| 604 | let (out, err, status, ()) = tokio::join!(out, err, wait, feed); |
| 605 | out?; |
| 606 | err?; |
| 607 | status |
| 608 | } |
| 609 | }; |
| 610 | tokio::select! { |
| 611 | status = run => match status { |
| 612 | Ok(status) => Some(status), |
| 613 | Err(error) => { |
| 614 | let _ = tree.kill(); let _ = child.start_kill(); |
| 615 | let _ = tokio::time::timeout(std::time::Duration::from_secs(2), child.wait()).await; |
| 616 | return Err(error); |
| 617 | } |
| 618 | }, |
| 619 | () = stop => None, |
| 620 | } |
| 621 | }; |
| 622 | let (status, stopped) = match exited { |
| 623 | Some(status) => { |
| 624 | if limits.is_some() { |
| 625 | drop(tree); |
| 626 | } else { |
| 627 | tree.release(); |
| 628 | } |
| 629 | (status, false) |
| 630 | } |
| 631 | None => { |
| 632 | drop(tree); |
| 633 | let _ = child.start_kill(); |
| 634 | let status = if limits.is_some() { |
| 635 | tokio::time::timeout(std::time::Duration::from_secs(2), child.wait()) |
| 636 | .await |
| 637 | .map_err(|_| { |
| 638 | std::io::Error::other("execution child did not reap after cancellation") |
| 639 | })?? |
| 640 | } else { |
| 641 | child.wait().await? |
| 642 | }; |
| 643 | // Collect what is still buffered in the pipes. Bounded: a process |
| 644 | // that escaped the tree may still hold one open. |
| 645 | let _ = tokio::time::timeout(std::time::Duration::from_secs(1), async { |
| 646 | let _ = tokio::join!( |
| 647 | drain_pipe_with_limit( |
| 648 | stdout_pipe.as_mut(), |
| 649 | &mut stdout, |
| 650 | limits.map(|limits| limits.0) |
| 651 | ), |
| 652 | drain_pipe_with_limit( |
| 653 | stderr_pipe.as_mut(), |
| 654 | &mut stderr, |
| 655 | limits.map(|limits| limits.1) |
| 656 | ), |
| 657 | ); |
| 658 | }) |
| 659 | .await; |
| 660 | (status, true) |
| 661 | } |
| 662 | }; |
| 663 | Ok(ContainedOutput { |
| 664 | output: std::process::Output { |
| 665 | status, |
| 666 | stdout, |
| 667 | stderr, |
| 668 | }, |
| 669 | stopped, |
| 670 | }) |
| 671 | } |
| 672 | |
| 673 | /// Read each chunk under the selected capture bound; overflow is an error. |
| 674 | async fn drain_pipe_with_limit<R: tokio::io::AsyncRead + Unpin>( |
| 675 | pipe: Option<&mut R>, |
| 676 | into: &mut Vec<u8>, |
| 677 | limit: Option<usize>, |
| 678 | ) -> std::io::Result<()> { |
| 679 | use tokio::io::AsyncReadExt; |
| 680 | let Some(pipe) = pipe else { |
| 681 | return Ok(()); |
| 682 | }; |
| 683 | let mut chunk = [0_u8; 8 * 1024]; |
| 684 | loop { |
| 685 | let read = pipe.read(&mut chunk).await?; |
| 686 | if read == 0 { |
| 687 | return Ok(()); |
| 688 | } |
| 689 | if limit.is_some_and(|limit| into.len().saturating_add(read) > limit) { |
| 690 | return Err(std::io::Error::other( |
| 691 | "execution output exceeded its capture limit", |
| 692 | )); |
| 693 | } |
| 694 | into.extend_from_slice(&chunk[..read]); |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | /// Process groups of every armed [`ProcessTree`]: listed on attach, unlisted |
| 699 | /// when the tree is dropped, released or disarmed. |
| 700 | #[cfg(unix)] |
| 701 | static CONTAINED_EXIT_GROUPS: std::sync::Mutex<Vec<(libc::pid_t, bool)>> = |
| 702 | std::sync::Mutex::new(Vec::new()); |
| 703 | |
| 704 | #[cfg(unix)] |
| 705 | fn contained_exit_groups() -> std::sync::MutexGuard<'static, Vec<(libc::pid_t, bool)>> { |
| 706 | CONTAINED_EXIT_GROUPS |
| 707 | .lock() |
| 708 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 709 | } |
| 710 | |
| 711 | #[cfg(unix)] |
| 712 | fn kill_unix_tree(pgid: libc::pid_t, is_session_leader: bool) -> std::io::Result<()> { |
| 713 | if pgid <= 0 { |
| 714 | return Ok(()); |
| 715 | } |
| 716 | // SAFETY: kill(2) dereferences no pointers; a negative pid names the process group. |
| 717 | let result = unsafe { libc::kill(-pgid, libc::SIGKILL) }; |
| 718 | if result != 0 { |
| 719 | let error = std::io::Error::last_os_error(); |
| 720 | let raw = error.raw_os_error(); |
| 721 | if raw != Some(libc::ESRCH) && !(is_session_leader && raw == Some(libc::EPERM)) { |
| 722 | return Err(error); |
| 723 | } |
| 724 | } |
| 725 | if is_session_leader { |
| 726 | let mut last = Vec::new(); |
| 727 | for _ in 0..8 { |
| 728 | let members = session_members(pgid); |
| 729 | if members.is_empty() || members == last { |
| 730 | break; |
| 731 | } |
| 732 | for &member in &members { |
| 733 | kill_member_in_session(member, pgid); |
| 734 | } |
| 735 | last = members; |
| 736 | } |
| 737 | } |
| 738 | Ok(()) |
| 739 | } |
| 740 | |
| 741 | #[cfg(unix)] |
| 742 | fn session_members(sid: libc::pid_t) -> Vec<libc::pid_t> { |
| 743 | // SAFETY: `getsid` is a read-only process query. |
| 744 | let mut members: Vec<libc::pid_t> = all_pids() |
| 745 | .into_iter() |
| 746 | .filter(|&pid| pid > 0 && unsafe { libc::getsid(pid) } == sid) |
| 747 | .collect(); |
| 748 | members.sort_unstable(); |
| 749 | members |
| 750 | } |
| 751 | |
| 752 | #[cfg(all(unix, not(target_vendor = "apple")))] |
| 753 | fn all_pids() -> Vec<libc::pid_t> { |
| 754 | let mut pids = Vec::new(); |
| 755 | // SAFETY: `opendir`, `readdir`, and `closedir` operate on a valid NUL-terminated path and live DIR pointer. |
| 756 | unsafe { |
| 757 | let dir = libc::opendir(c"/proc".as_ptr()); |
| 758 | if dir.is_null() { |
| 759 | return pids; |
| 760 | } |
| 761 | loop { |
| 762 | let entry = libc::readdir(dir); |
| 763 | if entry.is_null() { |
| 764 | break; |
| 765 | } |
| 766 | let name = std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()); |
| 767 | if let Ok(text) = name.to_str() |
| 768 | && let Ok(pid) = text.parse::<libc::pid_t>() |
| 769 | { |
| 770 | pids.push(pid); |
| 771 | } |
| 772 | } |
| 773 | libc::closedir(dir); |
| 774 | } |
| 775 | pids |
| 776 | } |
| 777 | |
| 778 | #[cfg(all(unix, target_vendor = "apple"))] |
| 779 | fn all_pids() -> Vec<libc::pid_t> { |
| 780 | // SAFETY: `proc_listallpids` writes at most `bytes` into the owned `pids` buffer. |
| 781 | unsafe { |
| 782 | let count = libc::proc_listallpids(std::ptr::null_mut(), 0); |
| 783 | if count <= 0 { |
| 784 | return Vec::new(); |
| 785 | } |
| 786 | let mut pids = vec![0 as libc::pid_t; count as usize + 64]; |
| 787 | let bytes = (pids.len() * std::mem::size_of::<libc::pid_t>()) as libc::c_int; |
| 788 | let filled = libc::proc_listallpids(pids.as_mut_ptr().cast(), bytes); |
| 789 | pids.truncate(filled.max(0) as usize); |
| 790 | pids |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | #[cfg(target_os = "linux")] |
| 795 | const PIDFD_OPEN: libc::c_long = 434; |
| 796 | #[cfg(target_os = "linux")] |
| 797 | const PIDFD_SEND_SIGNAL: libc::c_long = 424; |
| 798 | |
| 799 | #[cfg(unix)] |
| 800 | fn kill_member_in_session(member: libc::pid_t, sid: libc::pid_t) { |
| 801 | #[cfg(target_os = "linux")] |
| 802 | // SAFETY: `pidfd_open` and `pidfd_send_signal` operate on an owned fd closed before return. |
| 803 | unsafe { |
| 804 | let fd = libc::syscall(PIDFD_OPEN, member, 0) as libc::c_int; |
| 805 | if fd >= 0 { |
| 806 | if libc::getsid(member) == sid { |
| 807 | libc::syscall( |
| 808 | PIDFD_SEND_SIGNAL, |
| 809 | fd, |
| 810 | libc::SIGKILL, |
| 811 | std::ptr::null::<libc::siginfo_t>(), |
| 812 | 0, |
| 813 | ); |
| 814 | } |
| 815 | libc::close(fd); |
| 816 | return; |
| 817 | } |
| 818 | } |
| 819 | // SAFETY: `getsid` and `kill` are plain process queries and signal delivery. |
| 820 | unsafe { |
| 821 | if libc::getsid(member) == sid { |
| 822 | libc::kill(member, libc::SIGKILL); |
| 823 | } |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | /// Kill every armed contained tree. The process-wide signal path calls this |
| 828 | /// immediately before `process::exit`, where Rust destructors cannot run. |
| 829 | #[cfg(unix)] |
| 830 | pub fn kill_contained_trees_for_exit() { |
| 831 | let groups = std::mem::take(&mut *contained_exit_groups()); |
| 832 | for (process_group_id, is_session_leader) in groups { |
| 833 | let _ = kill_unix_tree(process_group_id, is_session_leader); |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | #[cfg(windows)] |
| 838 | struct WindowsJob { |
| 839 | handle: HANDLE, |
| 840 | } |
| 841 | |
| 842 | #[cfg(windows)] |
| 843 | impl WindowsJob { |
| 844 | fn attach(child: std::os::windows::io::RawHandle) -> std::io::Result<Self> { |
| 845 | // SAFETY: returned handle is owned by the new wrapper. |
| 846 | let handle = unsafe { CreateJobObjectW(None, PCWSTR::null()).map_err(windows_io_error)? }; |
| 847 | let job = Self { handle }; |
| 848 | let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); |
| 849 | limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; |
| 850 | |
| 851 | // SAFETY: `limits` is live with matching size; both handles are live. |
| 852 | unsafe { |
| 853 | SetInformationJobObject( |
| 854 | job.handle, |
| 855 | JobObjectExtendedLimitInformation, |
| 856 | &limits as *const _ as *const core::ffi::c_void, |
| 857 | std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, |
| 858 | ) |
| 859 | .map_err(windows_io_error)?; |
| 860 | AssignProcessToJobObject(job.handle, HANDLE(child)).map_err(windows_io_error)?; |
| 861 | } |
| 862 | Ok(job) |
| 863 | } |
| 864 | |
| 865 | fn limit_process_memory(&self, bytes: u64) -> std::io::Result<()> { |
| 866 | let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); |
| 867 | limits.BasicLimitInformation.LimitFlags = |
| 868 | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_PROCESS_MEMORY; |
| 869 | limits.ProcessMemoryLimit = usize::try_from(bytes).unwrap_or(usize::MAX); |
| 870 | // SAFETY: `limits` is live with matching size; the handle is live. |
| 871 | unsafe { |
| 872 | SetInformationJobObject( |
| 873 | self.handle, |
| 874 | JobObjectExtendedLimitInformation, |
| 875 | &limits as *const _ as *const core::ffi::c_void, |
| 876 | std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, |
| 877 | ) |
| 878 | .map_err(windows_io_error) |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | fn clear_kill_on_close(&self) -> std::io::Result<()> { |
| 883 | let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); |
| 884 | // SAFETY: `limits` is live with matching size; the handle is live. |
| 885 | unsafe { |
| 886 | SetInformationJobObject( |
| 887 | self.handle, |
| 888 | JobObjectExtendedLimitInformation, |
| 889 | &limits as *const _ as *const core::ffi::c_void, |
| 890 | std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, |
| 891 | ) |
| 892 | .map_err(windows_io_error) |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | fn terminate(&self) -> std::io::Result<()> { |
| 897 | // SAFETY: `self.handle` is a live owned job handle. |
| 898 | unsafe { TerminateJobObject(self.handle, 1).map_err(windows_io_error) } |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | #[cfg(windows)] |
| 903 | impl Drop for WindowsJob { |
| 904 | fn drop(&mut self) { |
| 905 | // SAFETY: `self.handle` is owned here; Drop runs once. |
| 906 | unsafe { |
| 907 | let _ = CloseHandle(self.handle); |
| 908 | } |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | #[cfg(windows)] |
| 913 | pub(crate) fn windows_io_error(error: windows::core::Error) -> std::io::Error { |
| 914 | std::io::Error::other(error) |
| 915 | } |
| 916 | |
| 917 | /// Test support: wait for `pid` to stop existing. `true` once it is gone. |
| 918 | /// A zombie counts as gone: it was killed and only awaits a reaper, which a |
| 919 | /// container whose PID 1 does not reap orphans may never provide. |
| 920 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 921 | pub fn wait_for_pid_exit(pid: libc::pid_t, within: std::time::Duration) -> bool { |
| 922 | let deadline = std::time::Instant::now() + within; |
| 923 | loop { |
| 924 | // SAFETY: signal 0 only checks that the process exists. |
| 925 | if unsafe { libc::kill(pid, 0) } != 0 || is_zombie(pid) { |
| 926 | return true; |
| 927 | } |
| 928 | if std::time::Instant::now() >= deadline { |
| 929 | // Do not leak the fixture when the assertion is about to fail. |
| 930 | // SAFETY: kill(2) dereferences no pointers. |
| 931 | unsafe { libc::kill(pid, libc::SIGKILL) }; |
| 932 | return false; |
| 933 | } |
| 934 | std::thread::sleep(std::time::Duration::from_millis(50)); |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | /// Linux only (`/proc`); elsewhere launchd/init reaps orphans promptly. |
| 939 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 940 | fn is_zombie(pid: libc::pid_t) -> bool { |
| 941 | std::fs::read_to_string(format!("/proc/{pid}/stat")) |
| 942 | .ok() |
| 943 | .and_then(|stat| { |
| 944 | stat.rsplit_once(')') |
| 945 | .map(|(_, rest)| rest.trim_start().starts_with('Z')) |
| 946 | }) |
| 947 | .unwrap_or(false) |
| 948 | } |
| 949 | |
| 950 | /// Test support: read the pid a fixture wrote to `path`, waiting for it. |
| 951 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 952 | pub fn read_pid_file(path: &std::path::Path, within: std::time::Duration) -> libc::pid_t { |
| 953 | let deadline = std::time::Instant::now() + within; |
| 954 | loop { |
| 955 | if let Some(pid) = parse_pid_file(path) { |
| 956 | return pid; |
| 957 | } |
| 958 | assert!( |
| 959 | std::time::Instant::now() < deadline, |
| 960 | "fixture never wrote {}", |
| 961 | path.display() |
| 962 | ); |
| 963 | std::thread::sleep(std::time::Duration::from_millis(20)); |
| 964 | } |
| 965 | } |
| 966 | |
| 967 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 968 | fn parse_pid_file(path: &std::path::Path) -> Option<libc::pid_t> { |
| 969 | std::fs::read_to_string(path) |
| 970 | .ok() |
| 971 | .and_then(|text| text.trim().parse().ok()) |
| 972 | } |
| 973 | |
| 974 | /// Test support: drive `run` until the fixture has written its pid to `path`, |
| 975 | /// then drop `run`. No wall-clock guess about how long the fixture needs to |
| 976 | /// start; `run` finishing first is a fixture bug. |
| 977 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 978 | pub async fn drop_once_pid_written<F: std::future::Future>( |
| 979 | run: F, |
| 980 | path: &std::path::Path, |
| 981 | ) -> libc::pid_t { |
| 982 | let written = async { |
| 983 | loop { |
| 984 | if let Some(pid) = parse_pid_file(path) { |
| 985 | return pid; |
| 986 | } |
| 987 | tokio::time::sleep(std::time::Duration::from_millis(20)).await; |
| 988 | } |
| 989 | }; |
| 990 | tokio::time::timeout(std::time::Duration::from_secs(60), async { |
| 991 | tokio::select! { |
| 992 | _ = run => panic!("fixture exited before writing {}", path.display()), |
| 993 | pid = written => pid, |
| 994 | } |
| 995 | }) |
| 996 | .await |
| 997 | .unwrap_or_else(|_| panic!("fixture never wrote {}", path.display())) |
| 998 | } |
| 999 | |
| 1000 | #[cfg(all(test, unix))] |
| 1001 | mod tests { |
| 1002 | use super::*; |
| 1003 | use std::time::Duration; |
| 1004 | |
| 1005 | #[tokio::test] |
| 1006 | async fn failed_containment_attachment_is_reported_and_kills_the_child() { |
| 1007 | let pid = std::cell::Cell::new(None); |
| 1008 | let mut cmd = tokio::process::Command::new("/bin/sleep"); |
| 1009 | cmd.arg("300"); |
| 1010 | let result = tokio::time::timeout( |
| 1011 | Duration::from_secs(1), |
| 1012 | contained_run(&mut cmd, None, std::future::pending(), |child| { |
| 1013 | pid.set(child.id()); |
| 1014 | Err(std::io::Error::new( |
| 1015 | std::io::ErrorKind::PermissionDenied, |
| 1016 | "injected containment attachment failure", |
| 1017 | )) |
| 1018 | }), |
| 1019 | ) |
| 1020 | .await; |
| 1021 | let pid = libc::pid_t::try_from(pid.get().expect("child spawned")).expect("pid"); |
| 1022 | // Let Tokio reap while checking cleanup; the helper kills the fixture |
| 1023 | // itself if the child ever outlives this failed run. |
| 1024 | assert!( |
| 1025 | tokio::task::spawn_blocking(move || wait_for_pid_exit(pid, Duration::from_secs(5))) |
| 1026 | .await |
| 1027 | .expect("cleanup probe"), |
| 1028 | "the direct child outlived failed containment attachment" |
| 1029 | ); |
| 1030 | let Err(error) = result |
| 1031 | .expect("attachment failure must return without running the command to completion") |
| 1032 | else { |
| 1033 | panic!("a containment failure must not be accepted as a successful run"); |
| 1034 | }; |
| 1035 | assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied); |
| 1036 | assert_eq!(error.to_string(), "injected containment attachment failure"); |
| 1037 | } |
| 1038 | |
| 1039 | #[tokio::test] |
| 1040 | async fn dropping_contained_output_kills_the_whole_tree() { |
| 1041 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1042 | let pid_file = tmp.path().join("grandchild.pid"); |
| 1043 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1044 | cmd.arg("-c") |
| 1045 | .arg("sleep 300 & echo $! > grandchild.pid; wait") |
| 1046 | .current_dir(tmp.path()); |
| 1047 | let grandchild = drop_once_pid_written(contained_output(&mut cmd), &pid_file).await; |
| 1048 | assert!( |
| 1049 | wait_for_pid_exit(grandchild, Duration::from_secs(5)), |
| 1050 | "a process started by the dropped command is still running" |
| 1051 | ); |
| 1052 | } |
| 1053 | |
| 1054 | #[tokio::test] |
| 1055 | async fn dropping_contained_output_kills_job_control_background_child_in_own_group() { |
| 1056 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1057 | let pid_file = tmp.path().join("job.pid"); |
| 1058 | let mut cmd = tokio::process::Command::new("bash"); |
| 1059 | cmd.arg("-c") |
| 1060 | .arg("set -m; sleep 300 </dev/null >/dev/null 2>&1 & echo $! > job.pid; wait") |
| 1061 | .current_dir(tmp.path()); |
| 1062 | let job = drop_once_pid_written(contained_output(&mut cmd), &pid_file).await; |
| 1063 | assert!( |
| 1064 | wait_for_pid_exit(job, Duration::from_secs(5)), |
| 1065 | "a background job in its own process group outlived its dropped session" |
| 1066 | ); |
| 1067 | } |
| 1068 | |
| 1069 | #[tokio::test] |
| 1070 | async fn fast_exit_session_leader_still_kills_job_control_background_child() { |
| 1071 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1072 | let pid_file = tmp.path().join("job.pid"); |
| 1073 | let mut cmd = tokio::process::Command::new("bash"); |
| 1074 | cmd.arg("-c") |
| 1075 | .arg("set -m; sleep 300 </dev/null >/dev/null 2>&1 & echo $! > job.pid") |
| 1076 | .current_dir(tmp.path()); |
| 1077 | configure_unix_contained_command(cmd.as_std_mut()); |
| 1078 | let mut child = cmd.spawn().expect("spawn"); |
| 1079 | let pid = child.id().expect("pid"); |
| 1080 | let job = read_pid_file(&pid_file, Duration::from_secs(5)); |
| 1081 | let deadline = std::time::Instant::now() + Duration::from_secs(5); |
| 1082 | while !leader_exited_unreaped(pid).expect("observe") { |
| 1083 | assert!(std::time::Instant::now() < deadline, "leader never exited"); |
| 1084 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 1085 | } |
| 1086 | let tree = ProcessTree::attach_tokio(&child).expect("attach"); |
| 1087 | tree.kill().expect("kill"); |
| 1088 | let _ = child.wait().await; |
| 1089 | tree.disarm(); |
| 1090 | assert!( |
| 1091 | wait_for_pid_exit(job, Duration::from_secs(5)), |
| 1092 | "a job-control child outlived a fast-exiting session leader" |
| 1093 | ); |
| 1094 | } |
| 1095 | |
| 1096 | #[tokio::test] |
| 1097 | async fn contained_output_captures_output_and_closes_stdin() { |
| 1098 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1099 | cmd.arg("-c").arg("cat; echo done"); |
| 1100 | let output = tokio::time::timeout(Duration::from_secs(10), contained_output(&mut cmd)) |
| 1101 | .await |
| 1102 | .expect("stdin must be closed, not inherited") |
| 1103 | .expect("run"); |
| 1104 | assert!(output.status.success()); |
| 1105 | assert_eq!(String::from_utf8_lossy(&output.stdout), "done\n"); |
| 1106 | } |
| 1107 | |
| 1108 | /// The input reaches stdin, and stdin is closed after it. |
| 1109 | #[tokio::test] |
| 1110 | async fn contained_output_with_input_feeds_then_closes_stdin() { |
| 1111 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1112 | cmd.arg("-c").arg("cat; echo done"); |
| 1113 | let output = tokio::time::timeout( |
| 1114 | Duration::from_secs(10), |
| 1115 | contained_output_with_input(&mut cmd, b"request\n".to_vec()), |
| 1116 | ) |
| 1117 | .await |
| 1118 | .expect("stdin must be closed after the input") |
| 1119 | .expect("run"); |
| 1120 | assert!(output.status.success()); |
| 1121 | assert_eq!(String::from_utf8_lossy(&output.stdout), "request\ndone\n"); |
| 1122 | } |
| 1123 | |
| 1124 | /// A command that exits on its own is not reaped along with what it |
| 1125 | /// deliberately left running, as with a bare `output()`. |
| 1126 | #[tokio::test] |
| 1127 | async fn contained_output_leaves_a_detached_daemon_of_a_clean_exit_running() { |
| 1128 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1129 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1130 | cmd.arg("-c") |
| 1131 | .arg("sleep 300 >/dev/null 2>&1 & echo $! > daemon.pid") |
| 1132 | .current_dir(tmp.path()); |
| 1133 | let output = contained_output(&mut cmd).await.expect("run"); |
| 1134 | assert!(output.status.success()); |
| 1135 | let daemon = read_pid_file(&tmp.path().join("daemon.pid"), Duration::from_secs(5)); |
| 1136 | // `wait_for_pid_exit` kills the fixture when it times out. |
| 1137 | assert!( |
| 1138 | !wait_for_pid_exit(daemon, Duration::from_millis(500)), |
| 1139 | "the daemon a clean command left behind was killed" |
| 1140 | ); |
| 1141 | } |
| 1142 | |
| 1143 | /// `stop` kills the tree but keeps what the command already wrote. |
| 1144 | #[tokio::test] |
| 1145 | async fn stopped_contained_output_keeps_partial_output_and_kills_the_tree() { |
| 1146 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1147 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1148 | cmd.arg("-c") |
| 1149 | .arg("echo before-stop; sleep 300 & echo $! > grandchild.pid; wait") |
| 1150 | .current_dir(tmp.path()); |
| 1151 | let pid_file = tmp.path().join("grandchild.pid"); |
| 1152 | let stop = async { |
| 1153 | while parse_pid_file(&pid_file).is_none() { |
| 1154 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 1155 | } |
| 1156 | }; |
| 1157 | let run = tokio::time::timeout( |
| 1158 | Duration::from_secs(60), |
| 1159 | contained_output_until(&mut cmd, stop), |
| 1160 | ) |
| 1161 | .await |
| 1162 | .expect("stop must end the run") |
| 1163 | .expect("run"); |
| 1164 | assert!(run.stopped); |
| 1165 | assert_eq!(String::from_utf8_lossy(&run.output.stdout), "before-stop\n"); |
| 1166 | let grandchild = read_pid_file(&pid_file, Duration::from_secs(5)); |
| 1167 | assert!( |
| 1168 | wait_for_pid_exit(grandchild, Duration::from_secs(5)), |
| 1169 | "a process started by the stopped command is still running" |
| 1170 | ); |
| 1171 | } |
| 1172 | |
| 1173 | /// An in-flight run is listed for the signal-exit kill, and unlisted once |
| 1174 | /// the future is gone. |
| 1175 | #[tokio::test] |
| 1176 | async fn in_flight_contained_run_is_listed_for_signal_exit() { |
| 1177 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1178 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1179 | cmd.arg("-c") |
| 1180 | .arg("echo $$ > leader.pid; sleep 300") |
| 1181 | .current_dir(tmp.path()); |
| 1182 | let pid_file = tmp.path().join("leader.pid"); |
| 1183 | let mut run = Box::pin(contained_output(&mut cmd)); |
| 1184 | let leader = drop_once_pid_written( |
| 1185 | async { |
| 1186 | run.as_mut().await.ok(); |
| 1187 | }, |
| 1188 | &pid_file, |
| 1189 | ) |
| 1190 | .await; |
| 1191 | assert!( |
| 1192 | contained_exit_groups() |
| 1193 | .iter() |
| 1194 | .any(|(pgid, _)| *pgid == leader) |
| 1195 | ); |
| 1196 | drop(run); |
| 1197 | assert!( |
| 1198 | !contained_exit_groups() |
| 1199 | .iter() |
| 1200 | .any(|(pgid, _)| *pgid == leader) |
| 1201 | ); |
| 1202 | // Let this current-thread runtime poll Tokio's orphan reaper while the |
| 1203 | // cleanup probe waits; kill(pid, 0) still sees an unreaped macOS child. |
| 1204 | assert!( |
| 1205 | tokio::task::spawn_blocking(move || wait_for_pid_exit(leader, Duration::from_secs(5))) |
| 1206 | .await |
| 1207 | .expect("cleanup probe") |
| 1208 | ); |
| 1209 | } |
| 1210 | |
| 1211 | #[test] |
| 1212 | fn attached_tree_is_listed_until_dropped_or_released() { |
| 1213 | for release in [false, true] { |
| 1214 | let mut cmd = std::process::Command::new("/bin/sleep"); |
| 1215 | cmd.arg("300"); |
| 1216 | let (mut child, tree) = spawn_contained_std(&mut cmd).expect("spawn"); |
| 1217 | let group = libc::pid_t::try_from(child.id()).expect("pid"); |
| 1218 | assert!( |
| 1219 | contained_exit_groups() |
| 1220 | .iter() |
| 1221 | .any(|(pgid, _)| *pgid == group) |
| 1222 | ); |
| 1223 | if release { |
| 1224 | tree.release(); |
| 1225 | } else { |
| 1226 | drop(tree); |
| 1227 | } |
| 1228 | assert!( |
| 1229 | !contained_exit_groups() |
| 1230 | .iter() |
| 1231 | .any(|(pgid, _)| *pgid == group) |
| 1232 | ); |
| 1233 | let _ = child.kill(); |
| 1234 | let _ = child.wait(); |
| 1235 | } |
| 1236 | } |
| 1237 | |
| 1238 | #[tokio::test] |
| 1239 | async fn leader_exit_kills_the_rest_of_the_group_before_the_reap() { |
| 1240 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1241 | let mut cmd = tokio::process::Command::new("/bin/sh"); |
| 1242 | cmd.arg("-c") |
| 1243 | .arg("sleep 300 >/dev/null 2>&1 & echo $! > member.pid") |
| 1244 | .current_dir(tmp.path()) |
| 1245 | .process_group(0); |
| 1246 | let mut child = cmd.spawn().expect("spawn"); |
| 1247 | let group = libc::pid_t::try_from(child.id().expect("pid")).expect("pid"); |
| 1248 | let tree = ProcessTree::attach_tokio(&child).expect("attach"); |
| 1249 | let status = tokio::time::timeout(Duration::from_secs(30), tree.wait_then_kill(&mut child)) |
| 1250 | .await |
| 1251 | .expect("the leader exits on its own") |
| 1252 | .expect("wait"); |
| 1253 | assert!(status.success()); |
| 1254 | let member = read_pid_file(&tmp.path().join("member.pid"), Duration::from_secs(5)); |
| 1255 | assert!( |
| 1256 | wait_for_pid_exit(member, Duration::from_secs(5)), |
| 1257 | "a group member outlived its exited leader" |
| 1258 | ); |
| 1259 | assert!( |
| 1260 | !contained_exit_groups() |
| 1261 | .iter() |
| 1262 | .any(|(pgid, _)| *pgid == group) |
| 1263 | ); |
| 1264 | } |
| 1265 | |
| 1266 | #[test] |
| 1267 | fn reaped_disarmed_tree_sends_no_signal() { |
| 1268 | let mut cmd = std::process::Command::new("/bin/sleep"); |
| 1269 | cmd.arg("300"); |
| 1270 | let (mut bystander, tree) = spawn_contained_std(&mut cmd).expect("spawn"); |
| 1271 | let group = libc::pid_t::try_from(bystander.id()).expect("pid"); |
| 1272 | tree.disarm(); |
| 1273 | assert!( |
| 1274 | !contained_exit_groups() |
| 1275 | .iter() |
| 1276 | .any(|(pgid, _)| *pgid == group) |
| 1277 | ); |
| 1278 | tree.kill().expect("a disarmed kill is a no-op"); |
| 1279 | drop(tree); |
| 1280 | std::thread::sleep(Duration::from_millis(200)); |
| 1281 | let survived = bystander.try_wait().expect("probe").is_none(); |
| 1282 | let _ = bystander.kill(); |
| 1283 | let _ = bystander.wait(); |
| 1284 | assert!(survived, "a disarmed tree signalled its former group id"); |
| 1285 | } |
| 1286 | } |
| 1287 | |
| 1288 | #[cfg(all(test, unix))] |
| 1289 | mod admitted_execution_tests { |
| 1290 | use super::*; |
| 1291 | #[tokio::test] |
| 1292 | async fn bounded_script_driver_refuses_overflow_without_deadlock() { |
| 1293 | let mut command = tokio::process::Command::new("sh"); |
| 1294 | command.args(["-c", "while :; do printf 1234567890; done"]); |
| 1295 | let result = tokio::time::timeout( |
| 1296 | std::time::Duration::from_secs(3), |
| 1297 | contained_output_with_input_bounded( |
| 1298 | &mut command, |
| 1299 | Vec::new(), |
| 1300 | 64, |
| 1301 | 64, |
| 1302 | std::future::pending(), |
| 1303 | ), |
| 1304 | ) |
| 1305 | .await |
| 1306 | .expect("overflow must not wait for execution deadline"); |
| 1307 | assert!(result.is_err()); |
| 1308 | } |
| 1309 | #[tokio::test] |
| 1310 | async fn bounded_script_driver_feeds_and_drains_concurrently() { |
| 1311 | let mut command = tokio::process::Command::new("sh"); |
| 1312 | command.args(["-c", "printf answer; cat >/dev/null"]); |
| 1313 | let result = tokio::time::timeout( |
| 1314 | std::time::Duration::from_secs(3), |
| 1315 | contained_output_with_input_bounded( |
| 1316 | &mut command, |
| 1317 | vec![b'x'; 256 * 1024], |
| 1318 | 64, |
| 1319 | 64, |
| 1320 | std::future::pending(), |
| 1321 | ), |
| 1322 | ) |
| 1323 | .await |
| 1324 | .unwrap() |
| 1325 | .unwrap(); |
| 1326 | assert!(!result.stopped); |
| 1327 | assert!(result.output.status.success()); |
| 1328 | assert_eq!(result.output.stdout, b"answer"); |
| 1329 | } |
| 1330 | } |
| 1331 |