From 48306f3719cef55044ef09a24f3ca25877b3b379 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Tue, 24 Nov 2026 14:22:19 +0100 Subject: [PATCH] exec: move line capture out of context The line sink, stream and pump are not context concerns: the host runner and every sandbox backend feed the same cleaned lines to the terminal. Move them and the fd sanitizer to exec, and have LocalDriver delegate to the shared host runner. Add a run_captured test against sh to pin the two-stream contract before the sandbox backends move. --- src/build/mod.rs | 4 +- src/context/api.rs | 19 +-- src/context/capture.rs | 125 ----------------- src/context/local.rs | 113 +--------------- src/context/mod.rs | 4 +- src/context/schroot.rs | 3 +- src/context/ssh.rs | 4 +- src/context/unshare.rs | 5 +- src/deb/local.rs | 3 +- src/deb/mod.rs | 4 +- src/deb/session.rs | 2 +- src/exec.rs | 295 +++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 3 + src/logfmt.rs | 2 +- src/report.rs | 2 +- src/test/mod.rs | 2 +- src/test_support.rs | 5 +- src/ui/deb.rs | 2 +- 18 files changed, 326 insertions(+), 271 deletions(-) delete mode 100644 src/context/capture.rs create mode 100644 src/exec.rs diff --git a/src/build/mod.rs b/src/build/mod.rs index cc631f6..4185ed4 100644 --- a/src/build/mod.rs +++ b/src/build/mod.rs @@ -18,11 +18,11 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Arc; -use crate::context::capture::pump; -use crate::context::{LineSink, Stream}; use crate::debian::{ ChecksumEntry, ControlInfo, FileChecksums, FilesEntry, FilesList, parse_paragraphs, }; +use crate::exec::pump; +use crate::exec::{LineSink, Stream}; use crate::logfmt::{DpkgSourceClassifier, GenericClassifier}; use crate::report::{BuildTarget, BuildView, Prompter}; diff --git a/src/context/api.rs b/src/context/api.rs index fd21ec4..138ce11 100644 --- a/src/context/api.rs +++ b/src/context/api.rs @@ -5,24 +5,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::Mutex; -/// Stream from which a captured output line originates -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Stream { - /// Standard output of the subprocess - Stdout, - /// Standard error of the subprocess - Stderr, -} - -/// Receiver for lines captured from a subprocess -/// -/// Implementations receive every decoded line (ANSI escapes stripped, -/// carriage-return progress fragments collapsed) as soon as it is produced, -/// allowing live UIs to display and rewrite subprocess output while it runs. -pub trait LineSink: Send + Sync { - /// Called for each captured line - fn line(&self, stream: Stream, line: &str); -} +use crate::exec::LineSink; use super::local::LocalDriver; use super::schroot::SchrootDriver; diff --git a/src/context/capture.rs b/src/context/capture.rs deleted file mode 100644 index 7aa30fb..0000000 --- a/src/context/capture.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! Shared helpers for capturing subprocess output line by line -//! -//! Used by the context drivers implementing -//! [`ContextDriver::run_captured`](super::api::ContextDriver::run_captured): -//! raw bytes are read incrementally, split into lines, cleaned up (ANSI escape -//! stripping, carriage-return progress collapsing) and forwarded to a -//! [`LineSink`](super::api::LineSink). - -use std::io::Read; -use std::sync::OnceLock; - -use super::api::{LineSink, Stream}; -use regex::Regex; - -/// Precompiled regex matching ANSI escape sequences (CSI and simple escapes) -fn ansi_regex() -> &'static Regex { - static RE: OnceLock = OnceLock::new(); - RE.get_or_init(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])").unwrap()) -} - -/// Strip ANSI escape sequences from a line -pub(crate) fn strip_ansi(line: &str) -> String { - ansi_regex().replace_all(line, "").to_string() -} - -/// Read `reader` to EOF, forwarding each decoded line to `sink` -/// -/// Lines are split on `\n`; when a line contains carriage returns (e.g. apt's -/// `0% [Working]` progress fragments), only the last `\r`-segment is kept so -/// progress updates replace each other instead of accumulating. Empty lines -/// are dropped. -pub(crate) fn pump(mut reader: R, stream: Stream, sink: &dyn LineSink) { - let mut buf: Vec = Vec::with_capacity(8192); - let mut chunk = [0u8; 4096]; - - loop { - match reader.read(&mut chunk) { - Ok(0) => break, - Ok(n) => buf.extend_from_slice(&chunk[..n]), - Err(_) => break, - } - - while let Some(pos) = buf.iter().position(|&b| b == b'\n') { - let line: Vec = buf.drain(..=pos).collect(); - emit(&line[..line.len() - 1], stream, sink); - } - } - - // Flush a trailing line without newline, if any - if !buf.is_empty() { - emit(&buf, stream, sink); - } -} - -/// Clean up and forward one raw line to the sink -fn emit(raw: &[u8], stream: Stream, sink: &dyn LineSink) { - let mut line = String::from_utf8_lossy(raw).to_string(); - - // Strip a trailing carriage return left over from CRLF line endings - if line.ends_with('\r') { - line.pop(); - } - - // Carriage-return progress: keep only the last segment of the line - if let Some(idx) = line.rfind('\r') { - line = line[idx + 1..].to_string(); - } - - let line = strip_ansi(&line); - let trimmed = line.trim_end(); - if trimmed.trim().is_empty() { - return; - } - - sink.line(stream, trimmed); -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Mutex; - - #[derive(Default)] - struct CollectingSink(Mutex>); - - impl LineSink for CollectingSink { - fn line(&self, stream: Stream, line: &str) { - self.0.lock().unwrap().push((stream, line.to_string())); - } - } - - #[test] - fn test_pump_splits_lines_and_merges_cr_fragments() { - let sink = CollectingSink::default(); - let data = - b"Get:1 http://x InRelease [1 kB]\r0% [Working]\r\nHit:2 http://y Release\npartial"; - pump(&data[..], Stream::Stdout, &sink); - - let lines = sink.0.lock().unwrap().clone(); - assert_eq!( - lines, - vec![ - (Stream::Stdout, "0% [Working]".to_string()), - (Stream::Stdout, "Hit:2 http://y Release".to_string()), - (Stream::Stdout, "partial".to_string()), - ] - ); - } - - #[test] - fn test_pump_strips_ansi_and_skips_empty_lines() { - let sink = CollectingSink::default(); - let data = b"\x1b[1mSetting up foo\x1b[0m\n\n \nE: boom\n"; - pump(&data[..], Stream::Stderr, &sink); - - let lines = sink.0.lock().unwrap().clone(); - assert_eq!( - lines, - vec![ - (Stream::Stderr, "Setting up foo".to_string()), - (Stream::Stderr, "E: boom".to_string()), - ] - ); - } -} diff --git a/src/context/local.rs b/src/context/local.rs index a9f1661..4dae696 100644 --- a/src/context/local.rs +++ b/src/context/local.rs @@ -1,41 +1,15 @@ /// Local context: execute commands locally /// Context driver: Does nothing -use super::api::{ContextDriver, LineSink, Stream}; -use super::capture::pump; +use super::api::ContextDriver; +use crate::exec::{self, LineSink}; use std::io; use std::os::unix::fs::symlink; -use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; use std::sync::Arc; use std::time::SystemTime; pub struct LocalDriver; -/// Close every file descriptor above stdio in the spawned child -/// -/// pkh's process legitimately carries descriptors that stay open for its -/// lifetime (the async runtime, gpgme sockets, the log tee), and std passes -/// any inheritable one to children. Tools with fd-number assumptions then -/// see their low-numbered allocations land on two-digit fds: mmdebstrap's -/// apt hook is `cat >&N`, which /bin/sh (dash) rejects for N >= 10 with -/// "Bad fd number" — the fresh-chroot bootstrap died exactly there. A -/// clean child table keeps those numbers single-digit. -fn sanitize_fds(cmd: &mut Command) { - unsafe { - cmd.pre_exec(|| { - // One syscall when the kernel has close_range; the loop - // covers the rest (and is what the syscall does anyway). - if libc::syscall(libc::SYS_close_range, 3, libc::c_uint::MAX, 0u32) != 0 { - for fd in 3..1024 { - libc::close(fd); - } - } - Ok(()) - }); - } -} - impl ContextDriver for LocalDriver { fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result { let dest_root_path = Path::new(dest_root); @@ -97,13 +71,7 @@ impl ContextDriver for LocalDriver { env: &[(String, String)], cwd: Option<&str>, ) -> io::Result { - let mut cmd = Command::new(program); - cmd.args(args).envs(env.iter().map(|(k, v)| (k, v))); - if let Some(dir) = cwd { - cmd.current_dir(dir); - } - sanitize_fds(&mut cmd); - cmd.status() + exec::run(program, args, env, cwd) } fn run_captured( @@ -114,42 +82,7 @@ impl ContextDriver for LocalDriver { cwd: Option<&str>, sink: Arc, ) -> io::Result { - let mut cmd = Command::new(program); - cmd.args(args).envs(env.iter().map(|(k, v)| (k, v))); - // Best-effort: ask children not to emit ANSI colors; captured lines are - // stripped anyway. - cmd.env("NO_COLOR", "1"); - if let Some(dir) = cwd { - cmd.current_dir(dir); - } - cmd.stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .stdin(Stdio::null()); - sanitize_fds(&mut cmd); - - let mut child = cmd.spawn()?; - let stdout = child.stdout.take(); - let stderr = child.stderr.take(); - - // One reader thread per stream; lines are forwarded to the sink as - // they arrive so the UI stays live. - let out_sink = sink.clone(); - let t_out = - stdout.map(|r| std::thread::spawn(move || pump(r, Stream::Stdout, out_sink.as_ref()))); - let err_sink = sink.clone(); - let t_err = - stderr.map(|r| std::thread::spawn(move || pump(r, Stream::Stderr, err_sink.as_ref()))); - - let status = child.wait(); - - if let Some(t) = t_out { - let _ = t.join(); - } - if let Some(t) = t_err { - let _ = t.join(); - } - - status + exec::run_captured(program, args, env, cwd, sink) } fn run_output( @@ -159,13 +92,7 @@ impl ContextDriver for LocalDriver { env: &[(String, String)], cwd: Option<&str>, ) -> io::Result { - let mut cmd = Command::new(program); - cmd.args(args).envs(env.iter().map(|(k, v)| (k, v))); - if let Some(dir) = cwd { - cmd.current_dir(dir); - } - sanitize_fds(&mut cmd); - cmd.output() + exec::run_output(program, args, env, cwd) } fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> { @@ -255,34 +182,4 @@ mod tests { std::fs::remove_dir(name).unwrap(); } } - - /// Inherited descriptors must not leak into spawned children: the - /// tools' low-numbered fd assumptions break on a shifted table - /// (mmdebstrap's dash-executed `cat >&N` apt hook). - #[test] - fn spawned_children_get_a_clean_fd_table() { - // Raw open(): std marks its own descriptors close-on-exec, which - // would make the test pass vacuously. - let mut strays = Vec::new(); - for _ in 0..8 { - let path = std::ffi::CString::new("/dev/null").unwrap(); - let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR) }; - assert!(fd >= 0); - strays.push(fd); - } - let mut cmd = Command::new("sh"); - cmd.arg("-c").arg("ls /proc/self/fd"); - sanitize_fds(&mut cmd); - let out = cmd.output().unwrap(); - for fd in strays { - unsafe { libc::close(fd) }; - } - - // stdio (3) + the directory ls itself opened (1) - let table = String::from_utf8_lossy(&out.stdout); - assert!( - table.lines().count() <= 5, - "child fd table should be clean, got:\n{table}" - ); - } } diff --git a/src/context/mod.rs b/src/context/mod.rs index e08dcf1..59bbaf1 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,5 +1,4 @@ mod api; -pub(crate) mod capture; mod local; mod manager; mod schroot; @@ -7,7 +6,8 @@ pub(crate) mod shell; mod ssh; mod unshare; -pub use api::{Context, ContextCommand, ContextConfig, LineSink, OverlayStaging, Stream}; +pub use crate::exec::{LineSink, Stream}; +pub use api::{Context, ContextCommand, ContextConfig, OverlayStaging}; pub(crate) use api::{MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV}; // The driver trait is implementation detail of the context API; it is only // needed crate-internally (test-run capture wrapper), so keep it out of the diff --git a/src/context/schroot.rs b/src/context/schroot.rs index aa264ee..d7a7ae5 100644 --- a/src/context/schroot.rs +++ b/src/context/schroot.rs @@ -1,7 +1,8 @@ /// Schroot context: execute commands in a schroot session /// Not tested, will need more work! -use super::api::{Context, ContextConfig, ContextDriver, LineSink}; +use super::api::{Context, ContextConfig, ContextDriver}; use super::shell::shell_quote; +use crate::exec::LineSink; use std::io; use std::path::{Path, PathBuf}; use std::sync::Arc; diff --git a/src/context/ssh.rs b/src/context/ssh.rs index 8f9c173..b983b5f 100644 --- a/src/context/ssh.rs +++ b/src/context/ssh.rs @@ -1,8 +1,8 @@ /// SSH context: execute commands over an SSH connection /// Context driver: Copies over SFTP with ssh2, executes commands over ssh2 channels -use super::api::{ContextDriver, LineSink, Stream}; -use super::capture::pump; +use super::api::ContextDriver; use super::shell::shell_quote; +use crate::exec::{LineSink, Stream, pump}; use log::debug; use ssh2; use std::fs; diff --git a/src/context/unshare.rs b/src/context/unshare.rs index 93d5cb0..c08f3fc 100644 --- a/src/context/unshare.rs +++ b/src/context/unshare.rs @@ -1,7 +1,6 @@ -use super::api::{ - Context, ContextCommand, ContextDriver, LineSink, MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV, -}; +use super::api::{Context, ContextCommand, ContextDriver, MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV}; use super::shell::shell_quote; +use crate::exec::LineSink; use log::debug; use std::fs; use std::io; diff --git a/src/deb/local.rs b/src/deb/local.rs index 571ca00..700fe69 100644 --- a/src/deb/local.rs +++ b/src/deb/local.rs @@ -1,7 +1,8 @@ /// Local binary package building /// Directly calling 'debian/rules' in current context -use crate::context::{Context, ContextCommand, LineSink}; +use crate::context::{Context, ContextCommand}; use crate::deb::{BuildProfiler, Phase, enter_phase, find_dsc_file}; +use crate::exec::LineSink; use crate::logfmt::QuiltClassifier; use crate::report::BuildView; use log::warn; diff --git a/src/deb/mod.rs b/src/deb/mod.rs index 97b1d84..a68fd64 100644 --- a/src/deb/mod.rs +++ b/src/deb/mod.rs @@ -302,7 +302,7 @@ impl BuildView for RecordLogView<'_> { self.inner.byte_progress(label, pos, total); } - fn sink(&self) -> Option> { + fn sink(&self) -> Option> { Some(self.log.clone()) } @@ -2119,8 +2119,8 @@ mod tests { /// build.log and on the writers (the terminal, in production). #[test] fn record_log_view_shows_raw_output_when_the_view_has_no_sink() { - use crate::context::{LineSink, Stream}; use crate::deb::session::record_fixtures::SharedWriter; + use crate::exec::{LineSink, Stream}; let (root, _tarball) = sessions_fixture(); let identity = test_identity(); diff --git a/src/deb/session.rs b/src/deb/session.rs index b0c80ee..5feaf4e 100644 --- a/src/deb/session.rs +++ b/src/deb/session.rs @@ -54,7 +54,7 @@ use std::time::Duration; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use crate::context::{LineSink, Stream}; +use crate::exec::{LineSink, Stream}; /// Manifest schema version: a record recorded by another schema is /// ignored (and eventually pruned) rather than forked. diff --git a/src/exec.rs b/src/exec.rs new file mode 100644 index 0000000..bae65dd --- /dev/null +++ b/src/exec.rs @@ -0,0 +1,295 @@ +//! Subprocess execution and line capture. +//! +//! The host runner and every sandbox backend feed captured output through +//! [`pump`], so the terminal sees the same cleaned lines whatever runs the +//! command. + +use std::io::{self, Read}; +use std::os::unix::process::CommandExt; +use std::process::{Command, ExitStatus, Output, Stdio}; +use std::sync::{Arc, OnceLock}; + +use regex::Regex; + +/// Stream from which a captured output line originates +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Stream { + /// Standard output of the subprocess + Stdout, + /// Standard error of the subprocess + Stderr, +} + +/// Receiver for lines captured from a subprocess +/// +/// Implementations receive every decoded line (ANSI escapes stripped, +/// carriage-return progress fragments collapsed) as soon as it is produced, +/// allowing live UIs to display and rewrite subprocess output while it runs. +pub trait LineSink: Send + Sync { + /// Called for each captured line + fn line(&self, stream: Stream, line: &str); +} + +/// Precompiled regex matching ANSI escape sequences (CSI and simple escapes) +fn ansi_regex() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])").unwrap()) +} + +/// Strip ANSI escape sequences from a line +pub(crate) fn strip_ansi(line: &str) -> String { + ansi_regex().replace_all(line, "").to_string() +} + +/// Read `reader` to EOF, forwarding each decoded line to `sink` +/// +/// Lines are split on `\n`; when a line contains carriage returns (e.g. apt's +/// `0% [Working]` progress fragments), only the last `\r`-segment is kept so +/// progress updates replace each other instead of accumulating. Empty lines +/// are dropped. +pub(crate) fn pump(mut reader: R, stream: Stream, sink: &dyn LineSink) { + let mut buf: Vec = Vec::with_capacity(8192); + let mut chunk = [0u8; 4096]; + + loop { + match reader.read(&mut chunk) { + Ok(0) => break, + Ok(n) => buf.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + + while let Some(pos) = buf.iter().position(|&b| b == b'\n') { + let line: Vec = buf.drain(..=pos).collect(); + emit(&line[..line.len() - 1], stream, sink); + } + } + + // Flush a trailing line without newline, if any + if !buf.is_empty() { + emit(&buf, stream, sink); + } +} + +/// Clean up and forward one raw line to the sink +fn emit(raw: &[u8], stream: Stream, sink: &dyn LineSink) { + let mut line = String::from_utf8_lossy(raw).to_string(); + + // Strip a trailing carriage return left over from CRLF line endings + if line.ends_with('\r') { + line.pop(); + } + + // Carriage-return progress: keep only the last segment of the line + if let Some(idx) = line.rfind('\r') { + line = line[idx + 1..].to_string(); + } + + let line = strip_ansi(&line); + let trimmed = line.trim_end(); + if trimmed.trim().is_empty() { + return; + } + + sink.line(stream, trimmed); +} + +/// Close every file descriptor above stdio in the spawned child +/// +/// pkh's process legitimately carries descriptors that stay open for its +/// lifetime (the async runtime, gpgme sockets, the log tee), and std passes +/// any inheritable one to children. Tools with fd-number assumptions then +/// see their low-numbered allocations land on two-digit fds: mmdebstrap's +/// apt hook is `cat >&N`, which /bin/sh (dash) rejects for N >= 10 with +/// "Bad fd number" — the fresh-chroot bootstrap died exactly there. A +/// clean child table keeps those numbers single-digit. +pub(crate) fn sanitize_fds(cmd: &mut Command) { + unsafe { + cmd.pre_exec(|| { + // One syscall when the kernel has close_range; the loop + // covers the rest (and is what the syscall does anyway). + if libc::syscall(libc::SYS_close_range, 3, libc::c_uint::MAX, 0u32) != 0 { + for fd in 3..1024 { + libc::close(fd); + } + } + Ok(()) + }); + } +} + +/// Run a host command with inherited standard streams +pub(crate) fn run( + program: &str, + args: &[String], + env: &[(String, String)], + cwd: Option<&str>, +) -> io::Result { + let mut cmd = Command::new(program); + cmd.args(args).envs(env.iter().map(|(k, v)| (k, v))); + if let Some(dir) = cwd { + cmd.current_dir(dir); + } + sanitize_fds(&mut cmd); + cmd.status() +} + +/// Run a host command, forwarding its output line by line to `sink` +pub(crate) fn run_captured( + program: &str, + args: &[String], + env: &[(String, String)], + cwd: Option<&str>, + sink: Arc, +) -> io::Result { + let mut cmd = Command::new(program); + cmd.args(args).envs(env.iter().map(|(k, v)| (k, v))); + // Best-effort: ask children not to emit ANSI colors; captured lines are + // stripped anyway. + cmd.env("NO_COLOR", "1"); + if let Some(dir) = cwd { + cmd.current_dir(dir); + } + cmd.stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .stdin(Stdio::null()); + sanitize_fds(&mut cmd); + + let mut child = cmd.spawn()?; + let stdout = child.stdout.take(); + let stderr = child.stderr.take(); + + // One reader thread per stream; lines are forwarded to the sink as + // they arrive so the UI stays live. + let out_sink = sink.clone(); + let t_out = + stdout.map(|r| std::thread::spawn(move || pump(r, Stream::Stdout, out_sink.as_ref()))); + let err_sink = sink.clone(); + let t_err = + stderr.map(|r| std::thread::spawn(move || pump(r, Stream::Stderr, err_sink.as_ref()))); + + let status = child.wait(); + + if let Some(t) = t_out { + let _ = t.join(); + } + if let Some(t) = t_err { + let _ = t.join(); + } + + status +} + +/// Run a host command and capture its complete output +pub(crate) fn run_output( + program: &str, + args: &[String], + env: &[(String, String)], + cwd: Option<&str>, +) -> io::Result { + let mut cmd = Command::new(program); + cmd.args(args).envs(env.iter().map(|(k, v)| (k, v))); + if let Some(dir) = cwd { + cmd.current_dir(dir); + } + sanitize_fds(&mut cmd); + cmd.output() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + #[derive(Default)] + struct CollectingSink(Mutex>); + + impl LineSink for CollectingSink { + fn line(&self, stream: Stream, line: &str) { + self.0.lock().unwrap().push((stream, line.to_string())); + } + } + + #[test] + fn test_pump_splits_lines_and_merges_cr_fragments() { + let sink = CollectingSink::default(); + let data = + b"Get:1 http://x InRelease [1 kB]\r0% [Working]\r\nHit:2 http://y Release\npartial"; + pump(&data[..], Stream::Stdout, &sink); + + let lines = sink.0.lock().unwrap().clone(); + assert_eq!( + lines, + vec![ + (Stream::Stdout, "0% [Working]".to_string()), + (Stream::Stdout, "Hit:2 http://y Release".to_string()), + (Stream::Stdout, "partial".to_string()), + ] + ); + } + + #[test] + fn test_pump_strips_ansi_and_skips_empty_lines() { + let sink = CollectingSink::default(); + let data = b"\x1b[1mSetting up foo\x1b[0m\n\n \nE: boom\n"; + pump(&data[..], Stream::Stderr, &sink); + + let lines = sink.0.lock().unwrap().clone(); + assert_eq!( + lines, + vec![ + (Stream::Stderr, "Setting up foo".to_string()), + (Stream::Stderr, "E: boom".to_string()), + ] + ); + } + + /// The host runner forwards both streams through the same cleaned line + /// contract the sandbox backends use. + #[test] + fn test_run_captured_forwards_stdout_and_stderr() { + let sink = Arc::new(CollectingSink::default()); + let args = vec!["-c".to_string(), "echo out; echo err >&2".to_string()]; + let status = run_captured("sh", &args, &[], None, sink.clone()).unwrap(); + assert!(status.success()); + + let mut lines = sink.0.lock().unwrap().clone(); + lines.sort_by(|a, b| a.1.cmp(&b.1)); + assert_eq!( + lines, + vec![ + (Stream::Stderr, "err".to_string()), + (Stream::Stdout, "out".to_string()), + ] + ); + } + + /// Inherited descriptors must not leak into spawned children: the + /// tools' low-numbered fd assumptions break on a shifted table + /// (mmdebstrap's dash-executed `cat >&N` apt hook). + #[test] + fn spawned_children_get_a_clean_fd_table() { + // Raw open(): std marks its own descriptors close-on-exec, which + // would make the test pass vacuously. + let mut strays = Vec::new(); + for _ in 0..8 { + let path = std::ffi::CString::new("/dev/null").unwrap(); + let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR) }; + assert!(fd >= 0); + strays.push(fd); + } + let mut cmd = Command::new("sh"); + cmd.arg("-c").arg("ls /proc/self/fd"); + sanitize_fds(&mut cmd); + let out = cmd.output().unwrap(); + for fd in strays { + unsafe { libc::close(fd) }; + } + + // stdio (3) + the directory ls itself opened (1) + let table = String::from_utf8_lossy(&out.stdout); + assert!( + table.lines().count() <= 5, + "child fd table should be clean, got:\n{table}" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index c7774d4..a40646b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,6 +22,9 @@ pub mod deb; pub mod debian; /// Obtain general information about distribution, series, etc pub mod distro_info; +/// Subprocess output capture: stream identification, line sinks, the line +/// pump and host process helpers +pub mod exec; /// Passive interrupt state: the interrupted flag, the cleanup hook registry /// and the live view's reporter slot (the CLI owns the signal handling) pub mod interrupt; diff --git a/src/logfmt.rs b/src/logfmt.rs index e1a0bd6..914ae45 100644 --- a/src/logfmt.rs +++ b/src/logfmt.rs @@ -7,7 +7,7 @@ use std::sync::{LazyLock, OnceLock}; -use crate::context::Stream; +use crate::exec::Stream; use regex::Regex; /// Maximum length of a rewritten line displayed in the rolling pane diff --git a/src/report.rs b/src/report.rs index 2c362c0..152e8b5 100644 --- a/src/report.rs +++ b/src/report.rs @@ -21,7 +21,7 @@ use std::error::Error; use std::path::{Path, PathBuf}; use std::sync::Arc; -use crate::context::LineSink; +use crate::exec::LineSink; use crate::logfmt::Classifier; /// Answer validator of [`Prompter::text`]: accepts the answer, or explains diff --git a/src/test/mod.rs b/src/test/mod.rs index 51dcda7..dd1920e 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -27,9 +27,9 @@ use std::fs; use std::path::{Path, PathBuf}; use std::sync::Arc; -use crate::context::{LineSink, Stream}; use crate::debian::control::{ControlInfo, parse_paragraphs}; use crate::debian::tests_control::TestsControl; +use crate::exec::{LineSink, Stream}; use crate::logfmt::GenericClassifier; use crate::report::{BuildTarget, BuildView, TargetKind}; use crate::test::bed::Bed; diff --git a/src/test_support.rs b/src/test_support.rs index 885fe5e..392aeaa 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -40,7 +40,7 @@ mod imp { false } - pub(crate) fn subprocess_sink() -> Option> { + pub(crate) fn subprocess_sink() -> Option> { None } @@ -78,7 +78,8 @@ mod imp { use std::process::{Command, ExitStatus}; use std::sync::{Arc, Mutex, OnceLock}; - use crate::context::{ContextDriver, LineSink, Stream}; + use crate::context::ContextDriver; + use crate::exec::{LineSink, Stream}; /// Directory receiving one log file per test fn log_dir() -> PathBuf { diff --git a/src/ui/deb.rs b/src/ui/deb.rs index 5bcfdd2..36a4f40 100644 --- a/src/ui/deb.rs +++ b/src/ui/deb.rs @@ -21,7 +21,7 @@ use directories::ProjectDirs; use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; -use crate::context::{LineSink, Stream}; +use crate::exec::{LineSink, Stream}; use crate::logfmt::{Action, Classifier, GenericClassifier}; use crate::report::BuildTarget;