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;
15use std::sync::atomic::AtomicBool;
16
17use anyhow::{Context, Result};
18use bytes::{Bytes, BytesMut};
19use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
20use tokio::process::Command;
21use tokio::sync::{broadcast, mpsc, oneshot};
22use tokio::task::JoinHandle;
23
24use crate::process::{ChildTerminator, ProcessHandle, SpawnedProcess};
25use crate::process_group;
26
27struct PipeChildTerminator {
29 #[cfg(windows)]
30 pid: u32,
31 #[cfg(unix)]
32 process_group_id: u32,
33}
34
35impl ChildTerminator for PipeChildTerminator {
36 fn kill(&mut self) -> io::Result<()> {
37 #[cfg(unix)]
38 {
39 process_group::kill_process_group(self.process_group_id)
40 }
41
42 #[cfg(windows)]
43 {
44 process_group::kill_process(self.pid)
45 }
46
47 #[cfg(not(any(unix, windows)))]
48 {
49 Ok(())
50 }
51 }
52}
53
54const RELIABLE_OUTPUT_CHANNEL_CAPACITY: usize = 128;
55
56async fn read_output_stream<R>(
61 mut reader: R,
62 output_tx: broadcast::Sender<Bytes>,
63 mut reliable_output_tx: Option<mpsc::Sender<Bytes>>,
64) where
65 R: AsyncRead + Unpin,
66{
67 let mut buf = BytesMut::with_capacity(65_536);
70 loop {
71 buf.clear();
72 match reader.read_buf(&mut buf).await {
73 Ok(0) => break,
74 Ok(n) => {
75 let chunk = buf.split_to(n).freeze();
76 let _ = output_tx.send(chunk.clone());
77 if let Some(sender) = reliable_output_tx.as_ref().cloned()
78 && sender.send(chunk).await.is_err()
79 {
80 reliable_output_tx = None;
84 }
85 }
86 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
87 Err(_) => break,
88 }
89 }
90}
91
92#[derive(Clone, Copy)]
94pub enum PipeStdinMode {
95 Piped,
97 Null,
99}
100
101#[derive(Clone)]
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_status = Arc::new(AtomicBool::new(false));
317 let wait_exit_status = Arc::clone(&exit_status);
318 let exit_code = Arc::new(StdMutex::new(None));
319 let wait_exit_code = Arc::clone(&exit_code);
320
321 let wait_handle: JoinHandle<()> = tokio::spawn(async move {
322 let code = match child.wait().await {
323 Ok(status) => status.code().unwrap_or(-1),
324 Err(_) => -1,
325 };
326 wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
327 if let Ok(mut guard) = wait_exit_code.lock() {
328 *guard = Some(code);
329 }
330 let _ = exit_tx.send(code);
331 });
332
333 let (handle, output_rx) = ProcessHandle::new(
334 writer_tx,
335 output_tx,
336 initial_output_rx,
337 Box::new(PipeChildTerminator {
338 #[cfg(windows)]
339 pid,
340 #[cfg(unix)]
341 process_group_id,
342 }),
343 reader_handle,
344 reader_abort_handles,
345 writer_handle,
346 wait_handle,
347 exit_status,
348 exit_code,
349 None,
350 );
351
352 Ok(SpawnedProcess {
353 session: handle,
354 process_id: pid,
355 output_rx,
356 reliable_output_rx,
357 reliable_output_enabled,
358 exit_rx,
359 })
360}
361
362pub async fn spawn_process(
376 program: &str,
377 args: &[String],
378 cwd: &Path,
379 env: &HashMap<String, String>,
380 arg0: &Option<String>,
381) -> Result<SpawnedProcess> {
382 let opts = PipeSpawnOptions {
383 program: program.to_string(),
384 args: args.to_vec(),
385 cwd: cwd.to_path_buf(),
386 env: Some(env.clone()),
387 arg0: arg0.clone(),
388 stdin_mode: PipeStdinMode::Piped,
389 lossless_output: false,
390 };
391 spawn_process_internal(opts).await
392}
393
394pub async fn spawn_process_no_stdin(
398 program: &str,
399 args: &[String],
400 cwd: &Path,
401 env: &HashMap<String, String>,
402 arg0: &Option<String>,
403) -> Result<SpawnedProcess> {
404 let opts = PipeSpawnOptions {
405 program: program.to_string(),
406 args: args.to_vec(),
407 cwd: cwd.to_path_buf(),
408 env: Some(env.clone()),
409 arg0: arg0.clone(),
410 stdin_mode: PipeStdinMode::Null,
411 lossless_output: false,
412 };
413 spawn_process_internal(opts).await
414}
415
416pub async fn spawn_process_with_options(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
418 spawn_process_internal(opts).await
419}
420
421#[cfg(test)]
422mod tests {
423 use super::*;
424 use assert_fs::TempDir;
425
426 fn find_echo_command() -> Option<(String, Vec<String>)> {
427 #[cfg(windows)]
428 {
429 Some(("cmd.exe".to_string(), vec!["/C".to_string(), "echo".to_string()]))
430 }
431 #[cfg(not(windows))]
432 {
433 Some(("echo".to_string(), vec![]))
434 }
435 }
436
437 #[tokio::test]
438 async fn test_spawn_process_echo() -> Result<()> {
439 let Some((program, mut base_args)) = find_echo_command() else {
440 return Ok(());
441 };
442
443 base_args.push("hello".to_string());
444
445 let env: HashMap<String, String> = std::env::vars().collect();
446 let spawned = spawn_process(&program, &base_args, Path::new("."), &env, &None).await?;
447
448 let exit_code = spawned.exit_rx.await.unwrap_or(-1);
449 assert_eq!(exit_code, 0);
450
451 Ok(())
452 }
453
454 #[tokio::test]
455 async fn test_spawn_options_builder() {
456 let opts = PipeSpawnOptions::new("echo", ".")
457 .args(["hello", "world"])
458 .stdin_mode(PipeStdinMode::Null);
459
460 assert_eq!(opts.program, "echo");
461 assert_eq!(opts.args, vec!["hello", "world"]);
462 assert!(matches!(opts.stdin_mode, PipeStdinMode::Null));
463 }
464
465 #[cfg(unix)]
466 #[tokio::test]
467 async fn test_spawn_process_detaches_from_tty() {
468 let dir = TempDir::new().expect("tempdir");
469 let env: HashMap<String, String> = HashMap::new();
470
471 let spawned = spawn_process("sh", &["-c".into(), "echo ok".into()], dir.path(), &env, &None)
472 .await
473 .expect("spawn");
474
475 let exit_code = spawned.exit_rx.await.unwrap_or(-1);
476 assert_eq!(exit_code, 0);
477 }
478}