1#[cfg(windows)]
11mod secret_windows;
12#[cfg(windows)]
13#[doc(hidden)]
14pub use secret_windows::read_secret_stdout;
15
16pub struct CapturedOutput {
17 pub output: std::process::Output,
18 pub timed_out: bool,
19 #[doc(hidden)]
21 pub cancelled: bool,
22}
23
24pub fn run_with_output_limits(
28 command: &mut std::process::Command,
29 timeout: Option<std::time::Duration>,
30 stdout_limit: usize,
31 stderr_limit: usize,
32) -> Result<CapturedOutput, String> {
33 wait_for_capture_with_limits(
34 spawn_capture(command)?,
35 timeout,
36 Some((stdout_limit as u64, stderr_limit as u64)),
37 &mut || false,
38 )
39}
40
41#[doc(hidden)]
44pub fn run_with_output_limits_cancellable(
45 command: &mut std::process::Command,
46 timeout: std::time::Duration,
47 stdout_limit: usize,
48 stderr_limit: usize,
49 mut cancellation_requested: impl FnMut() -> bool,
50) -> Result<CapturedOutput, String> {
51 wait_for_capture_with_limits(
52 spawn_capture(command)?,
53 Some(timeout),
54 Some((stdout_limit as u64, stderr_limit as u64)),
55 &mut cancellation_requested,
56 )
57}
58
59pub(crate) struct CapturedChild {
60 child: std::process::Child,
61 stdout: std::fs::File,
62 stderr: std::fs::File,
63 bin: String,
64 cleanup: ProcessCleanup,
65 #[cfg(unix)]
68 guard: Option<crate::shell::containment::CallGuard>,
69}
70
71impl CapturedChild {
72 pub(crate) fn program(&self) -> &str {
73 &self.bin
74 }
75}
76
77#[derive(Default)]
78struct ProcessCleanup {
79 #[cfg(windows)]
80 job: Option<ProcessJob>,
81}
82
83#[cfg(windows)]
84struct ProcessJob(windows_sys::Win32::Foundation::HANDLE);
85
86#[cfg(windows)]
87impl Drop for ProcessJob {
88 fn drop(&mut self) {
89 unsafe {
91 windows_sys::Win32::Foundation::CloseHandle(self.0);
92 }
93 }
94}
95
96pub(crate) fn spawn_capture(command: &mut std::process::Command) -> Result<CapturedChild, String> {
97 use std::process::Stdio;
98
99 let program = command.get_program().to_string_lossy().into_owned();
100 let bin = program.as_str();
101 let stdout = tempfile::tempfile()
102 .map_err(|error| format!("failed to create command '{bin}' stdout capture: {error}"))?;
103 let stderr = tempfile::tempfile()
104 .map_err(|error| format!("failed to create command '{bin}' stderr capture: {error}"))?;
105 command
106 .stdout(Stdio::from(stdout.try_clone().map_err(|error| {
107 format!("failed to clone command '{bin}' stdout capture: {error}")
108 })?))
109 .stderr(Stdio::from(stderr.try_clone().map_err(|error| {
110 format!("failed to clone command '{bin}' stderr capture: {error}")
111 })?));
112 #[cfg(unix)]
113 {
114 use std::os::unix::process::CommandExt;
115 command.process_group(0);
116 }
117 #[cfg(windows)]
118 {
119 use std::os::windows::process::CommandExt;
120 command.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
121 }
122 let spawn_error = |e: std::io::Error| {
123 if e.kind() == std::io::ErrorKind::NotFound {
124 format!("command '{bin}' not found in PATH")
125 } else {
126 format!("failed to run '{bin}': {e}")
127 }
128 };
129 #[cfg(unix)]
135 let (mut child, guard) = {
136 use crate::shell::containment::Refusal;
137 match crate::shell::containment::start_guarded_child(command) {
138 Ok(started) => started,
139 Err(Refusal::NotStarted(error)) => return Err(spawn_error(error)),
140 Err(Refusal::NotLeader) => {
141 return Err(format!(
142 "command '{bin}' could not be contained: the process does not lead a group of its own"
143 ));
144 }
145 Err(Refusal::NoGuard(reason)) => {
146 return Err(format!("command '{bin}' could not be contained: {reason}"));
147 }
148 }
149 };
150 #[cfg(not(unix))]
151 let mut child = command.spawn().map_err(spawn_error)?;
152
153 let cleanup = match process_cleanup(&child, bin) {
155 Ok(cleanup) => cleanup,
156 Err(error) => {
157 let _ = child.kill();
158 let _ = child.wait();
159 return Err(error);
160 }
161 };
162
163 Ok(CapturedChild {
164 child,
165 stdout,
166 stderr,
167 bin: bin.to_owned(),
168 cleanup,
169 #[cfg(unix)]
170 guard,
171 })
172}
173
174#[cfg(unix)]
178fn child_exited(child: &mut std::process::Child) -> std::io::Result<bool> {
179 crate::shell::exec::exited_unreaped(child)
180}
181
182#[cfg(not(unix))]
183fn child_exited(child: &mut std::process::Child) -> std::io::Result<bool> {
184 child.try_wait().map(|status| status.is_some())
185}
186
187#[cfg(windows)]
188fn process_cleanup(child: &std::process::Child, bin: &str) -> Result<ProcessCleanup, String> {
189 use std::os::windows::io::AsRawHandle;
190 use windows_sys::Win32::System::JobObjects::{
191 AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
192 JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
193 SetInformationJobObject,
194 };
195
196 let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
198 if handle.is_null() {
199 return Err(format!(
200 "failed to create child job for '{bin}': {}",
201 std::io::Error::last_os_error()
202 ));
203 }
204 let job = ProcessJob(handle);
205 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
206 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
207 let configured = unsafe {
209 SetInformationJobObject(
210 job.0,
211 JobObjectExtendedLimitInformation,
212 std::ptr::from_ref(&limits).cast(),
213 std::mem::size_of_val(&limits) as u32,
214 )
215 };
216 if configured == 0 {
217 return Err(format!(
218 "failed to configure child job for '{bin}': {}",
219 std::io::Error::last_os_error()
220 ));
221 }
222 let assigned = unsafe { AssignProcessToJobObject(job.0, child.as_raw_handle().cast()) };
224 if assigned == 0 {
225 return Err(format!(
226 "failed to assign command '{bin}' to its job: {}",
227 std::io::Error::last_os_error()
228 ));
229 }
230 resume_process_threads(child.id(), bin)?;
231 Ok(ProcessCleanup { job: Some(job) })
232}
233
234#[cfg(windows)]
235fn resume_process_threads(process_id: u32, bin: &str) -> Result<(), String> {
236 use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
237 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
238 CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
239 };
240 use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
241
242 let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
244 if snapshot == INVALID_HANDLE_VALUE {
245 return Err(format!(
246 "failed to inspect suspended command '{bin}' threads: {}",
247 std::io::Error::last_os_error()
248 ));
249 }
250 let mut entry = THREADENTRY32 {
251 dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
252 ..THREADENTRY32::default()
253 };
254 let mut has_entry = unsafe { Thread32First(snapshot, &raw mut entry) } != 0;
256 let mut resumed = false;
257 let result = loop {
258 if !has_entry {
259 break if resumed {
260 Ok(())
261 } else {
262 Err(format!(
263 "suspended command '{bin}' exposed no resumable thread"
264 ))
265 };
266 }
267 if entry.th32OwnerProcessID == process_id {
268 let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
270 if thread.is_null() {
271 break Err(format!(
272 "failed to open suspended command '{bin}' thread: {}",
273 std::io::Error::last_os_error()
274 ));
275 }
276 let resume_result = unsafe { ResumeThread(thread) };
278 unsafe { CloseHandle(thread) };
280 if resume_result == u32::MAX {
281 break Err(format!(
282 "failed to resume command '{bin}' thread: {}",
283 std::io::Error::last_os_error()
284 ));
285 }
286 resumed = true;
287 }
288 has_entry = unsafe { Thread32Next(snapshot, &raw mut entry) } != 0;
290 };
291 unsafe { CloseHandle(snapshot) };
293 result
294}
295
296#[cfg(not(windows))]
297fn process_cleanup(_: &std::process::Child, _: &str) -> Result<ProcessCleanup, String> {
298 Ok(ProcessCleanup::default())
299}
300
301pub(crate) fn wait_for_capture(
302 child: CapturedChild,
303 timeout: std::time::Duration,
304) -> Result<CapturedOutput, String> {
305 wait_for_capture_with_limits(child, Some(timeout), None, &mut || false)
306}
307
308fn wait_for_capture_with_limits(
309 CapturedChild {
310 mut child,
311 mut stdout,
312 mut stderr,
313 bin,
314 mut cleanup,
315 #[cfg(unix)]
316 guard,
317 }: CapturedChild,
318 timeout: Option<std::time::Duration>,
319 limits: Option<(u64, u64)>,
320 cancellation_requested: &mut dyn FnMut() -> bool,
321) -> Result<CapturedOutput, String> {
322 const CLEANUP_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
323
324 let started = std::time::Instant::now();
325 let (status, timed_out, cancelled, cleanup_error) = loop {
326 let state = child_exited(&mut child)
329 .map_err(|error| format!("failed to wait for '{bin}': {error}"))
330 .and_then(|state| {
331 if let Some((stdout_limit, stderr_limit)) = limits {
332 capture_length(&stdout, &bin, "stdout", Some(stdout_limit))?;
333 capture_length(&stderr, &bin, "stderr", Some(stderr_limit))?;
334 }
335 Ok(state)
336 });
337 match state {
338 Err(wait_error) => {
339 let cleanup_error = terminate_process_tree(&mut child, &bin, &mut cleanup)
340 .err()
341 .map(|error| format!("cleanup failed: {error}"));
342 let reap_error = reap_child(&mut child, &bin, CLEANUP_GRACE)
343 .err()
344 .map(|error| format!("reap failed: {error}"));
345 let details = [cleanup_error, reap_error]
346 .into_iter()
347 .flatten()
348 .collect::<Vec<_>>()
349 .join("; ");
350 return Err(if details.is_empty() {
351 wait_error
352 } else {
353 format!("{wait_error}; {details}")
354 });
355 }
356 Ok(true) => {
357 let cleanup_error = stop_remaining_process_group(&child, &bin, &mut cleanup).err();
359 break (
360 reap_child(&mut child, &bin, CLEANUP_GRACE)?,
361 false,
362 false,
363 cleanup_error,
364 );
365 }
366 Ok(false) if cancellation_requested() => {
367 let cleanup_error = terminate_process_tree(&mut child, &bin, &mut cleanup).err();
368 break (
369 reap_child(&mut child, &bin, CLEANUP_GRACE)?,
370 false,
371 true,
372 cleanup_error,
373 );
374 }
375 Ok(false) if timeout.is_some_and(|timeout| started.elapsed() >= timeout) => {
376 let cleanup_error = terminate_process_tree(&mut child, &bin, &mut cleanup).err();
377 break (
378 reap_child(&mut child, &bin, CLEANUP_GRACE)?,
379 true,
380 false,
381 cleanup_error,
382 );
383 }
384 Ok(false) => std::thread::sleep(std::time::Duration::from_millis(10)),
385 }
386 };
387 #[cfg(unix)]
390 if let Some(guard) = guard {
391 let ended = guard.finish();
392 if ended != crate::shell::containment::GuardOutcome::Ended {
393 tracing::warn!("command '{bin}': the end of its process group is {ended:?}");
394 }
395 }
396 let stdout = read_capture(&mut stdout, &bin, "stdout", limits.map(|limits| limits.0))?;
397 let stderr = read_capture(&mut stderr, &bin, "stderr", limits.map(|limits| limits.1))?;
398
399 if let Some(error) = cleanup_error {
400 return Err(error);
401 }
402
403 Ok(CapturedOutput {
404 output: std::process::Output {
405 status,
406 stdout,
407 stderr,
408 },
409 timed_out,
410 cancelled,
411 })
412}
413
414fn read_capture(
415 capture: &mut std::fs::File,
416 bin: &str,
417 stream: &str,
418 limit: Option<u64>,
419) -> Result<Vec<u8>, String> {
420 use std::io::{Read, Seek};
421
422 capture
423 .rewind()
424 .map_err(|error| format!("failed to rewind command '{bin}' {stream}: {error}"))?;
425 let length = capture_length(capture, bin, stream, limit)?;
427 let mut bytes = Vec::new();
428 capture
429 .take(length)
430 .read_to_end(&mut bytes)
431 .map_err(|error| format!("failed to read command '{bin}' {stream}: {error}"))?;
432 Ok(bytes)
433}
434
435fn capture_length(
436 capture: &std::fs::File,
437 bin: &str,
438 stream: &str,
439 limit: Option<u64>,
440) -> Result<u64, String> {
441 let length = capture
442 .metadata()
443 .map_err(|error| format!("failed to inspect command '{bin}' {stream}: {error}"))?
444 .len();
445 if let Some(limit) = limit
446 && length > limit
447 {
448 return Err(format!(
449 "command '{bin}' {stream} output exceeded the capture bound ({limit} bytes)"
450 ));
451 }
452 Ok(length)
453}
454
455fn reap_child(
456 child: &mut std::process::Child,
457 bin: &str,
458 timeout: std::time::Duration,
459) -> Result<std::process::ExitStatus, String> {
460 let deadline = std::time::Instant::now() + timeout;
461 loop {
462 match child
463 .try_wait()
464 .map_err(|error| format!("failed to reap command '{bin}': {error}"))?
465 {
466 Some(status) => return Ok(status),
467 None if std::time::Instant::now() >= deadline => {
468 return Err(format!("command '{bin}' did not exit after termination"));
469 }
470 None => std::thread::sleep(std::time::Duration::from_millis(10)),
471 }
472 }
473}
474
475#[cfg(all(any(test, feature = "test-support"), unix))]
479thread_local! {
480 static GROUP_SIGNAL_LOG: std::cell::RefCell<Vec<bool>> =
481 const { std::cell::RefCell::new(Vec::new()) };
482}
483
484#[cfg(all(any(test, feature = "test-support"), unix))]
485pub(crate) fn take_group_signal_log() -> Vec<bool> {
486 GROUP_SIGNAL_LOG.with(|log| std::mem::take(&mut *log.borrow_mut()))
487}
488
489#[cfg(all(any(test, feature = "test-support"), unix))]
490fn leader_unreaped(pid: libc::pid_t) -> bool {
491 unsafe {
494 let mut info: libc::siginfo_t = std::mem::zeroed();
495 libc::waitid(
496 libc::P_PID,
497 pid as libc::id_t,
498 &raw mut info,
499 libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
500 ) == 0
501 }
502}
503
504#[cfg(unix)]
505fn stop_remaining_process_group(
506 child: &std::process::Child,
507 bin: &str,
508 _: &mut ProcessCleanup,
509) -> Result<(), String> {
510 let pgid = crate::ipc::process::group_target(child.id())
511 .map_err(|refusal| format!("failed to stop child process group '{bin}': {refusal}"))?;
512 #[cfg(any(test, feature = "test-support"))]
517 GROUP_SIGNAL_LOG.with(|log| log.borrow_mut().push(leader_unreaped(pgid)));
518 if unsafe { libc::killpg(pgid, libc::SIGKILL) } == 0 {
521 return Ok(());
522 }
523 let error = std::io::Error::last_os_error();
524 if error.raw_os_error() == Some(libc::ESRCH)
525 || (error.raw_os_error() == Some(libc::EPERM)
529 && crate::shell::containment::live_members(pgid) == Some(0))
530 {
531 Ok(())
532 } else {
533 Err(format!(
534 "failed to stop child process group '{bin}': {error}"
535 ))
536 }
537}
538
539#[cfg(windows)]
540fn stop_remaining_process_group(
541 _: &std::process::Child,
542 _: &str,
543 cleanup: &mut ProcessCleanup,
544) -> Result<(), String> {
545 drop(cleanup.job.take());
546 Ok(())
547}
548
549fn terminate_process_tree(
550 child: &mut std::process::Child,
551 bin: &str,
552 cleanup: &mut ProcessCleanup,
553) -> Result<(), String> {
554 #[cfg(unix)]
555 {
556 match stop_remaining_process_group(child, bin, cleanup) {
557 Ok(()) => return Ok(()),
558 Err(group_error) => {
559 child.kill().map_err(|error| {
560 format!("{group_error}; failed to stop direct formatter child '{bin}': {error}")
561 })?;
562 return Err(group_error);
563 }
564 }
565 }
566 #[cfg(windows)]
567 {
568 stop_remaining_process_group(child, bin, cleanup)?;
569 return Ok(());
570 }
571
572 #[allow(unreachable_code)]
573 child
574 .kill()
575 .map_err(|e| format!("failed to stop timed-out command '{bin}': {e}"))
576}
577
578#[cfg(test)]
579mod bounded_capture_tests {
580 use std::io::Write;
581
582 #[test]
583 fn capture_checks_length_before_reading_and_keeps_exact_boundary() {
584 let mut file = tempfile::tempfile().expect("capture file");
585 file.write_all(b"four").expect("capture bytes");
586 let error = super::read_capture(&mut file, "test", "stdout", Some(3))
587 .expect_err("oversized capture must be rejected");
588 assert!(error.contains("output exceeded"));
589 assert_eq!(
590 super::read_capture(&mut file, "test", "stdout", Some(4)).unwrap(),
591 b"four"
592 );
593 assert_eq!(
594 super::read_capture(&mut file, "test", "stdout", None).unwrap(),
595 b"four"
596 );
597 }
598
599 #[test]
600 fn capture_read_errors_are_not_silently_accepted_as_eof() {
601 let directory = tempfile::tempdir().expect("temporary directory");
602 let mut file =
603 std::fs::File::create(directory.path().join("write-only")).expect("write-only capture");
604 file.write_all(b"four").expect("capture bytes");
605 for limit in [None, Some(4)] {
606 let error = super::read_capture(&mut file, "test", "stderr", limit)
607 .expect_err("write-only file cannot supply readable output");
608 assert!(error.contains("failed to read"), "{error}");
609 }
610 }
611}