1use hashbrown::HashMap;
10use std::io::{self, ErrorKind};
11use std::path::Path;
12use std::process::Stdio;
13use std::sync::Arc;
14use std::sync::Mutex as StdMutex;
15
16use anyhow::{Context, Result};
17use bytes::{Bytes, BytesMut};
18use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
19use tokio::process::Command;
20use tokio::sync::{broadcast, mpsc, oneshot};
21use tokio::task::JoinHandle;
22
23use crate::process::{ChildTerminator, ProcessExitState, ProcessHandle, SpawnedProcess};
24use crate::process_group;
25
26struct PipeChildTerminator {
28 #[cfg(windows)]
29 pid: u32,
30 #[cfg(unix)]
31 process_group_id: u32,
32}
33
34impl ChildTerminator for PipeChildTerminator {
35 fn kill(&mut self) -> io::Result<()> {
36 #[cfg(unix)]
37 {
38 process_group::kill_process_group(self.process_group_id)
39 }
40
41 #[cfg(windows)]
42 {
43 process_group::kill_process(self.pid)
44 }
45
46 #[cfg(not(any(unix, windows)))]
47 {
48 Ok(())
49 }
50 }
51}
52
53const RELIABLE_OUTPUT_CHANNEL_CAPACITY: usize = 128;
54
55async fn read_output_stream<R>(
60 mut reader: R,
61 output_tx: broadcast::Sender<Bytes>,
62 mut reliable_output_tx: Option<mpsc::Sender<Bytes>>,
63) where
64 R: AsyncRead + Unpin,
65{
66 let mut buf = BytesMut::with_capacity(65_536);
69 loop {
70 buf.clear();
71 match reader.read_buf(&mut buf).await {
72 Ok(0) => break,
73 Ok(n) => {
74 let chunk = buf.split_to(n).freeze();
75 let _ = output_tx.send(chunk.clone());
76 if let Some(sender) = reliable_output_tx.as_ref().cloned()
77 && sender.send(chunk).await.is_err()
78 {
79 reliable_output_tx = None;
83 }
84 }
85 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
86 Err(_) => break,
87 }
88 }
89}
90
91#[derive(Clone, Copy)]
93pub enum PipeStdinMode {
94 Piped,
96 Null,
98}
99
100#[derive(Clone)]
102#[must_use = "spawn options must be passed to a spawn function"]
103pub struct PipeSpawnOptions {
104 program: String,
106 args: Vec<String>,
108 cwd: std::path::PathBuf,
110 env: Option<HashMap<String, String>>,
112 arg0: Option<String>,
114 stdin_mode: PipeStdinMode,
116 lossless_output: bool,
120}
121
122impl PipeSpawnOptions {
123 pub fn new(program: impl Into<String>, cwd: impl Into<std::path::PathBuf>) -> Self {
125 Self {
126 program: program.into(),
127 args: Vec::new(),
128 cwd: cwd.into(),
129 env: None,
130 arg0: None,
131 stdin_mode: PipeStdinMode::Piped,
132 lossless_output: false,
133 }
134 }
135
136 pub fn args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
138 self.args = args.into_iter().map(Into::into).collect();
139 self
140 }
141
142 pub fn env(mut self, env: HashMap<String, String>) -> Self {
144 self.env = Some(env);
145 self
146 }
147
148 pub fn arg0(mut self, arg0: impl Into<String>) -> Self {
150 self.arg0 = Some(arg0.into());
151 self
152 }
153
154 pub fn stdin_mode(mut self, mode: PipeStdinMode) -> Self {
156 self.stdin_mode = mode;
157 self
158 }
159
160 pub fn lossless_output(mut self, enabled: bool) -> Self {
162 self.lossless_output = enabled;
163 self
164 }
165}
166
167async fn spawn_process_internal(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
169 if opts.program.is_empty() {
170 anyhow::bail!("missing program for pipe spawn");
171 }
172
173 #[cfg(unix)]
174 let owned = crate::process_owner::OwnedCommand::from_environment(
175 opts.program.as_ref(),
176 opts.args.iter(),
177 opts.arg0.as_deref().map(std::ffi::OsStr::new),
178 )?;
179
180 #[cfg(unix)]
181 let mut command = match &owned {
182 Some(owned) => {
183 let mut command = Command::new(&owned.executable);
184 command.args(&owned.arguments);
185 command
186 }
187 None => Command::new(&opts.program),
188 };
189 #[cfg(not(unix))]
190 let mut command = Command::new(&opts.program);
191
192 #[cfg(unix)]
193 if owned.is_none()
194 && let Some(ref arg0) = opts.arg0
195 {
196 command.arg0(arg0);
197 }
198
199 #[cfg(unix)]
200 #[expect(
201 unsafe_code,
202 reason = "detach_from_tty only calls setsid/setpgid via safe nix wrappers to detach the child from the controlling terminal; it is a pure process-group operation with no undefined behavior"
203 )]
204 unsafe {
210 command.pre_exec(process_group::detach_from_tty);
211 }
212
213 #[cfg(not(unix))]
214 let _ = &opts.arg0;
215
216 command.current_dir(&opts.cwd);
217
218 if let Some(ref env) = opts.env {
220 command.env_clear();
221 for (key, value) in env {
222 command.env(key, value);
223 }
224 }
225
226 #[cfg(unix)]
227 if let Some(owned) = &owned {
228 command.env(crate::process_owner::OWNER_SOCKET_ENV, &owned.owner_socket);
231 } else {
232 command.args(&opts.args);
233 }
234 #[cfg(not(unix))]
235 command.args(&opts.args);
236
237 match opts.stdin_mode {
238 PipeStdinMode::Piped => {
239 command.stdin(Stdio::piped());
240 }
241 PipeStdinMode::Null => {
242 command.stdin(Stdio::null());
243 }
244 }
245 command.stdout(Stdio::piped());
246 command.stderr(Stdio::piped());
247
248 let mut child = command.spawn().context("failed to spawn pipe process")?;
249 let pid = child.id().ok_or_else(|| io::Error::other("missing child pid"))?;
250
251 #[cfg(unix)]
252 let process_group_id = pid;
253
254 let stdin = child.stdin.take();
255 let stdout = child.stdout.take();
256 let stderr = child.stderr.take();
257
258 let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
259 let (output_tx, _) = broadcast::channel::<Bytes>(256);
260 let initial_output_rx = output_tx.subscribe();
261 let (reliable_output_tx, reliable_output_rx) = mpsc::channel::<Bytes>(RELIABLE_OUTPUT_CHANNEL_CAPACITY);
262 let reliable_output_enabled = opts.lossless_output;
263
264 let writer_handle = if let Some(stdin) = stdin {
266 let writer = Arc::new(tokio::sync::Mutex::new(stdin));
267 tokio::spawn(async move {
268 while let Some(bytes) = writer_rx.recv().await {
269 let mut guard = writer.lock().await;
270 let _ = guard.write_all(&bytes).await;
271 let _ = guard.flush().await;
272 }
273 })
274 } else {
275 drop(writer_rx);
276 tokio::spawn(async {})
277 };
278
279 let stdout_handle = stdout.map(|stdout| {
281 let output_tx = output_tx.clone();
282 let reliable_output_tx = opts.lossless_output.then(|| reliable_output_tx.clone());
283 tokio::spawn(async move {
284 read_output_stream(BufReader::new(stdout), output_tx, reliable_output_tx).await;
285 })
286 });
287
288 let stderr_handle = stderr.map(|stderr| {
289 let output_tx = output_tx.clone();
290 let reliable_output_tx = opts.lossless_output.then(|| reliable_output_tx.clone());
291 tokio::spawn(async move {
292 read_output_stream(BufReader::new(stderr), output_tx, reliable_output_tx).await;
293 })
294 });
295 drop(reliable_output_tx);
296
297 let mut reader_abort_handles = Vec::new();
298 if let Some(ref handle) = stdout_handle {
299 reader_abort_handles.push(handle.abort_handle());
300 }
301 if let Some(ref handle) = stderr_handle {
302 reader_abort_handles.push(handle.abort_handle());
303 }
304
305 let reader_handle = tokio::spawn(async move {
306 if let Some(handle) = stdout_handle {
307 let _ = handle.await;
308 }
309 if let Some(handle) = stderr_handle {
310 let _ = handle.await;
311 }
312 });
313
314 let (exit_tx, exit_rx) = oneshot::channel::<i32>();
316 let exit_state = Arc::new(StdMutex::new(ProcessExitState::default()));
319 let wait_exit_state = Arc::clone(&exit_state);
320
321 let wait_handle: JoinHandle<()> = tokio::spawn(async move {
322 let (code, observed) = match child.wait().await {
323 Ok(status) => (status.code().unwrap_or(-1), true),
324 Err(_) => (-1, false),
325 };
326 ProcessExitState::publish(&wait_exit_state, observed, code);
327 let _ = exit_tx.send(code);
328 });
329
330 let (handle, output_rx) = ProcessHandle::new(
331 writer_tx,
332 output_tx,
333 initial_output_rx,
334 Box::new(PipeChildTerminator {
335 #[cfg(windows)]
336 pid,
337 #[cfg(unix)]
338 process_group_id,
339 }),
340 reader_handle,
341 reader_abort_handles,
342 writer_handle,
343 wait_handle,
344 exit_state,
345 None,
346 );
347
348 Ok(SpawnedProcess {
349 session: handle,
350 process_id: pid,
351 output_rx,
352 reliable_output_rx,
353 reliable_output_enabled,
354 exit_rx,
355 })
356}
357
358pub async fn spawn_process(
378 program: &str,
379 args: &[String],
380 cwd: &Path,
381 env: &HashMap<String, String>,
382 arg0: Option<&str>,
383) -> Result<SpawnedProcess> {
384 let opts = PipeSpawnOptions {
385 program: program.to_string(),
386 args: args.to_vec(),
387 cwd: cwd.to_path_buf(),
388 env: Some(env.clone()),
389 arg0: arg0.map(str::to_owned),
390 stdin_mode: PipeStdinMode::Piped,
391 lossless_output: false,
392 };
393 spawn_process_internal(opts).await
394}
395
396pub async fn spawn_process_no_stdin(
404 program: &str,
405 args: &[String],
406 cwd: &Path,
407 env: &HashMap<String, String>,
408 arg0: Option<&str>,
409) -> Result<SpawnedProcess> {
410 let opts = PipeSpawnOptions {
411 program: program.to_string(),
412 args: args.to_vec(),
413 cwd: cwd.to_path_buf(),
414 env: Some(env.clone()),
415 arg0: arg0.map(str::to_owned),
416 stdin_mode: PipeStdinMode::Null,
417 lossless_output: false,
418 };
419 spawn_process_internal(opts).await
420}
421
422pub async fn spawn_process_with_options(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
424 spawn_process_internal(opts).await
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430 use assert_fs::TempDir;
431
432 fn find_echo_command() -> Option<(String, Vec<String>)> {
433 #[cfg(windows)]
434 {
435 Some(("cmd.exe".to_string(), vec!["/C".to_string(), "echo".to_string()]))
436 }
437 #[cfg(not(windows))]
438 {
439 Some(("echo".to_string(), vec![]))
440 }
441 }
442
443 #[tokio::test]
444 async fn test_spawn_process_echo() -> Result<()> {
445 let Some((program, mut base_args)) = find_echo_command() else {
446 return Ok(());
447 };
448
449 base_args.push("hello".to_string());
450
451 let env: HashMap<String, String> = std::env::vars().collect();
452 let spawned = spawn_process(&program, &base_args, Path::new("."), &env, None).await?;
453
454 let exit_code = spawned.exit_rx.await.unwrap_or(-1);
455 assert_eq!(exit_code, 0);
456 assert!(spawned.session.has_observed_exit(), "successful wait records the direct-child exit");
457
458 Ok(())
459 }
460
461 #[tokio::test]
466 async fn exit_code_is_present_as_soon_as_has_exited_flips() -> Result<()> {
467 let Some((program, mut base_args)) = find_echo_command() else {
468 return Ok(());
469 };
470 base_args.push("hello".to_string());
471
472 let env: HashMap<String, String> = std::env::vars().collect();
473 let spawned = spawn_process(&program, &base_args, Path::new("."), &env, None).await?;
474
475 while !spawned.session.has_exited() {
476 tokio::time::sleep(std::time::Duration::from_millis(1)).await;
477 }
478 assert_eq!(spawned.session.exit_code(), Some(0));
479 assert_eq!(spawned.exit_rx.await.unwrap_or(-1), 0);
480 Ok(())
481 }
482
483 #[tokio::test]
484 async fn test_spawn_options_builder() {
485 let opts = PipeSpawnOptions::new("echo", ".")
486 .args(["hello", "world"])
487 .stdin_mode(PipeStdinMode::Null);
488
489 assert_eq!(opts.program, "echo");
490 assert_eq!(opts.args, vec!["hello", "world"]);
491 assert!(matches!(opts.stdin_mode, PipeStdinMode::Null));
492 }
493
494 #[cfg(unix)]
495 #[tokio::test]
496 async fn test_spawn_process_detaches_from_tty() {
497 let dir = TempDir::new().expect("tempdir");
498 let env: HashMap<String, String> = HashMap::new();
499
500 let spawned = spawn_process("sh", &["-c".into(), "echo ok".into()], dir.path(), &env, None)
501 .await
502 .expect("spawn");
503
504 let exit_code = spawned.exit_rx.await.unwrap_or(-1);
505 assert_eq!(exit_code, 0);
506 }
507}