use std::collections::HashMap; #[cfg(unix)] use std::fs::File; use std::io::ErrorKind; #[cfg(unix)] use std::os::fd::AsRawFd; #[cfg(unix)] use std::os::fd::FromRawFd; #[cfg(unix)] use std::os::fd::RawFd; #[cfg(all(unix, not(target_os = "linux")))] use std::os::unix::process::CommandExt; use std::path::Path; #[cfg(all(unix, not(target_os = "linux")))] use std::process::Command as StdCommand; #[cfg(all(unix, not(target_os = "linux")))] use std::process::Stdio; use std::sync::Arc; use std::sync::Mutex as StdMutex; use std::sync::atomic::AtomicBool; #[cfg(not(unix))] use std::time::Duration; use anyhow::Result; use portable_pty::CommandBuilder; #[cfg(not(windows))] use portable_pty::native_pty_system; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::task::JoinHandle; #[cfg(target_os = "linux")] pub(crate) use crate::linux_fds::close_inherited_fds_except; use crate::process::ChildTerminator; use crate::process::ProcessHandle; use crate::process::ProcessSignal; use crate::process::PtyHandles; use crate::process::PtyMasterHandle; use crate::process::SpawnedProcess; use crate::process::TerminalSize; #[cfg(unix)] use crate::process::exit_code_from_status; /// Extra descriptors accompanying a process launch. #[derive(Clone, Copy)] pub enum ChildFds<'a> { /// Existing escalation sockets, with the legacy PTY I/O and status behavior. Inherited(&'a [i32]), /// Launch attachments, including CLOEXEC files, with ordinary PTY behavior. Attached(&'a [i32]), } impl<'a> ChildFds<'a> { pub fn as_slice(self) -> &'a [i32] { match self { Self::Inherited(fds) | Self::Attached(fds) => fds, } } } /// Returns true when ConPTY support is available (Windows only). #[cfg(windows)] pub fn conpty_supported() -> bool { crate::win::conpty_supported() } /// Returns true when ConPTY support is available (non-Windows always true). #[cfg(not(windows))] pub fn conpty_supported() -> bool { true } struct PtyChildTerminator { killer: Box, #[cfg(unix)] process_group_id: Option, } impl ChildTerminator for PtyChildTerminator { fn signal(&mut self, signal: ProcessSignal) -> std::io::Result<()> { match signal { ProcessSignal::Interrupt => { #[cfg(unix)] if let Some(process_group_id) = self.process_group_id { return crate::process_group::interrupt_process_group(process_group_id); } Err(crate::process::unsupported_signal(signal)) } } } fn kill(&mut self) -> std::io::Result<()> { #[cfg(unix)] if let Some(process_group_id) = self.process_group_id { // Match the pipe backend's hard-kill behavior so descendant // processes from interactive shells/REPLs do not survive shutdown. // Also try the direct child killer in case the cached PGID is stale. let process_group_kill_result = crate::process_group::kill_process_group(process_group_id); let child_kill_result = self.killer.kill(); return match child_kill_result { Ok(()) => Ok(()), Err(err) if err.kind() == ErrorKind::NotFound => process_group_kill_result, Err(err) => process_group_kill_result.or(Err(err)), }; } self.killer.kill() } } #[cfg(unix)] struct RawPidTerminator { process_group_id: u32, } #[cfg(unix)] impl ChildTerminator for RawPidTerminator { fn signal(&mut self, signal: ProcessSignal) -> std::io::Result<()> { match signal { ProcessSignal::Interrupt => { crate::process_group::interrupt_process_group(self.process_group_id) } } } fn kill(&mut self) -> std::io::Result<()> { crate::process_group::kill_process_group(self.process_group_id) } } fn platform_native_pty_system() -> Box { #[cfg(windows)] { Box::new(crate::win::ConPtySystem::default()) } #[cfg(not(windows))] { native_pty_system() } } /// Spawn a process attached to a PTY, preserving selected inherited file /// descriptors across exec on Unix. pub async fn spawn_process( program: &str, args: &[String], cwd: &Path, env: &HashMap, arg0: &Option, size: TerminalSize, inherited_fds: ChildFds<'_>, ) -> Result { if program.is_empty() { anyhow::bail!("missing program for PTY spawn"); } #[cfg(not(unix))] let _ = inherited_fds; #[cfg(target_os = "linux")] if crate::spawn_helper::is_available() && inherited_fds.as_slice().is_empty() && Path::new(program).is_absolute() && arg0.is_none() && cwd.is_dir() { // Keep portable-pty's PATH, argv0, and missing-cwd behavior for requests // whose launch settings require its command builder. return spawn_process_preserving_fds(program, args, cwd, env, arg0, size, inherited_fds) .await; } #[cfg(unix)] if !inherited_fds.as_slice().is_empty() { return spawn_process_preserving_fds(program, args, cwd, env, arg0, size, inherited_fds) .await; } spawn_process_portable(program, args, cwd, env, arg0, size).await } async fn spawn_process_portable( program: &str, args: &[String], cwd: &Path, env: &HashMap, arg0: &Option, size: TerminalSize, ) -> Result { let pty_system = platform_native_pty_system(); let pair = pty_system.openpty(size.into())?; #[cfg(unix)] let io = crate::unix_io::PtyIo::new( pair.master .as_raw_fd() .ok_or_else(|| anyhow::anyhow!("PTY master has no file descriptor"))?, )?; let mut command_builder = CommandBuilder::new(arg0.as_ref().unwrap_or(&program.to_string())); command_builder.cwd(cwd); command_builder.env_clear(); for arg in args { command_builder.arg(arg); } for (key, value) in env { command_builder.env(key, value); } let mut child = pair.slave.spawn_command(command_builder)?; #[cfg(unix)] // portable-pty establishes the spawned PTY child as a new session leader on // Unix, so PID == PGID and we can reuse the pipe backend's process-group // hard-kill semantics for descendants. let process_group_id = child.process_id(); let killer = child.clone_killer(); let (writer_tx, writer_rx) = mpsc::channel::>(128); let (stdout_tx, stdout_rx) = mpsc::channel::>(128); let (_stderr_tx, stderr_rx) = mpsc::channel::>(1); #[cfg(unix)] let (reader_handle, writer_handle) = io.spawn( stdout_tx, writer_rx, crate::unix_io::StdinCloseBehavior::SendEof, ); #[cfg(not(unix))] let (reader_handle, writer_handle) = { let mut reader = pair.master.try_clone_reader()?; let reader_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || { let mut buf = [0u8; 8_192]; loop { match reader.read(&mut buf) { Ok(0) => break, Ok(n) => { let _ = stdout_tx.blocking_send(buf[..n].to_vec()); } Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(ref e) if e.kind() == ErrorKind::WouldBlock => { std::thread::sleep(Duration::from_millis(5)); continue; } Err(_) => break, } } }); let mut writer_rx = writer_rx; let writer = pair.master.take_writer()?; let writer = Arc::new(tokio::sync::Mutex::new(writer)); let writer_handle: JoinHandle<()> = tokio::spawn({ let writer = Arc::clone(&writer); async move { #[cfg(windows)] let mut windows_input = crate::WindowsTtyInputNormalizer::default(); while let Some(bytes) = writer_rx.recv().await { #[cfg(windows)] let bytes = windows_input.normalize(&bytes); let mut guard = writer.lock().await; use std::io::Write; let _ = guard.write_all(&bytes); let _ = guard.flush(); } } }); (reader_handle, writer_handle) }; let (exit_tx, exit_rx) = oneshot::channel::(); let exit_status = Arc::new(AtomicBool::new(false)); let wait_exit_status = Arc::clone(&exit_status); let exit_code = Arc::new(StdMutex::new(None)); let wait_exit_code = Arc::clone(&exit_code); let wait_handle: JoinHandle<()> = tokio::task::spawn_blocking(move || { let code = match child.wait() { Ok(status) => status.exit_code() as i32, Err(_) => -1, }; wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst); if let Ok(mut guard) = wait_exit_code.lock() { *guard = Some(code); } let _ = exit_tx.send(code); }); let handles = PtyHandles { _slave: if cfg!(windows) { Some(pair.slave) } else { None }, _master: PtyMasterHandle::Resizable(pair.master), }; let handle = ProcessHandle::new( writer_tx, Box::new(PtyChildTerminator { killer, #[cfg(unix)] process_group_id, }), Some(reader_handle), /*stderr_reader*/ None, writer_handle, wait_handle, exit_status, exit_code, Some(handles), /*resizer*/ None, ); Ok(SpawnedProcess { session: handle, stdout_rx, stderr_rx, exit_rx, }) } #[cfg(unix)] async fn spawn_process_preserving_fds( program: &str, args: &[String], cwd: &Path, env: &HashMap, arg0: &Option, size: TerminalSize, descriptors: ChildFds<'_>, ) -> Result { let (master, slave) = open_unix_pty(size)?; let io = crate::unix_io::PtyIo::new(master.as_raw_fd())?; let uses_portable_status = match descriptors { ChildFds::Inherited(fds) => fds.is_empty(), ChildFds::Attached(_) => true, }; let inherited_fds = descriptors.as_slice(); let stdin_close_behavior = if uses_portable_status { crate::unix_io::StdinCloseBehavior::SendEof } else { crate::unix_io::StdinCloseBehavior::NoEof }; let default_shell = (uses_portable_status && !env.contains_key("SHELL")).then(|| { let mut builder = CommandBuilder::new(program); builder.env_clear(); builder.get_shell() }); #[cfg(target_os = "linux")] let mut child = { let mut command = crate::Command::new(program); if let Some(shell) = &default_shell { // portable-pty supplies the login shell when SHELL is absent. command.env("SHELL", shell); } command .args(args) .current_dir(cwd) .envs(env) .drop_policy(crate::child_command::ChildDropPolicy::ReapOnly) .descriptor_policy(crate::DescriptorPolicy::Explicit) .inherit_fds(inherited_fds) .stdin(crate::ChildStdin::File(slave.try_clone()?.into())); if let Some(arg0) = arg0 { command.arg0(arg0); } command.stdout_file = Some(slave.try_clone()?.into()); command.stderr_file = Some(slave.try_clone()?.into()); match crate::spawn_helper::spawn(&command, crate::spawn_helper::Setup::Pty).await? { Some(child) => child, None if inherited_fds.is_empty() => { // Free the first PTY before allocating its portable replacement. drop(command); drop(io); drop(slave); drop(master); return spawn_process_portable(program, args, cwd, env, arg0, size).await; } None => { // Explicit descriptors select the shared fallback on Linux. Keep // terminal setup there when this executable cannot run the helper. unsafe { command.inner.pre_exec(configure_child_terminal); } command.spawn()? } } }; #[cfg(not(target_os = "linux"))] let mut child = { let mut command = StdCommand::new(program); if let Some(arg0) = arg0 { command.arg0(arg0); } command.current_dir(cwd).env_clear().args(args).envs(env); if let Some(shell) = &default_shell { command.env("SHELL", shell); } let inherited_fds = inherited_fds.to_vec(); // The child sees the same terminal on stdin, stdout, and stderr. unsafe { command .stdin(Stdio::from(slave.try_clone()?)) .stdout(Stdio::from(slave.try_clone()?)) .stderr(Stdio::from(slave.try_clone()?)) .pre_exec(move || { configure_child_terminal()?; close_inherited_fds_except(&inherited_fds); make_fds_inheritable(&inherited_fds)?; Ok(()) }); } command.spawn()? }; drop(slave); #[cfg(target_os = "linux")] let process_group_id = child .id() .ok_or_else(|| std::io::Error::other("missing child pid"))?; #[cfg(not(target_os = "linux"))] let process_group_id = child.id(); let (writer_tx, writer_rx) = mpsc::channel::>(128); let (stdout_tx, stdout_rx) = mpsc::channel::>(128); let (_stderr_tx, stderr_rx) = mpsc::channel::>(1); let (reader_handle, writer_handle) = io.spawn(stdout_tx, writer_rx, stdin_close_behavior); let (exit_tx, exit_rx) = oneshot::channel::(); let exit_status = Arc::new(AtomicBool::new(false)); let wait_exit_status = Arc::clone(&exit_status); let exit_code = Arc::new(StdMutex::new(None)); let wait_exit_code = Arc::clone(&exit_code); let on_exit = move |status: std::io::Result| { let code = match status { Ok(status) if uses_portable_status => { portable_pty::ExitStatus::from(status).exit_code() as i32 } Ok(status) => exit_code_from_status(status), Err(_) => -1, }; wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst); if let Ok(mut guard) = wait_exit_code.lock() { *guard = Some(code); } let _ = exit_tx.send(code); }; #[cfg(target_os = "linux")] let wait_handle = tokio::spawn(async move { on_exit(child.wait().await) }); #[cfg(not(target_os = "linux"))] let wait_handle = tokio::task::spawn_blocking(move || on_exit(child.wait())); let handles = PtyHandles { _slave: None, _master: PtyMasterHandle::Opaque { raw_fd: master.as_raw_fd(), _handle: Box::new(master), }, }; let handle = ProcessHandle::new( writer_tx, Box::new(RawPidTerminator { process_group_id }), Some(reader_handle), /*stderr_reader*/ None, writer_handle, wait_handle, exit_status, exit_code, Some(handles), /*resizer*/ None, ); Ok(SpawnedProcess { session: handle, stdout_rx, stderr_rx, exit_rx, }) } #[cfg(unix)] fn open_unix_pty(size: TerminalSize) -> Result<(File, File)> { let mut master: RawFd = -1; let mut slave: RawFd = -1; let mut size = libc::winsize { ws_row: size.rows, ws_col: size.cols, ws_xpixel: 0, ws_ypixel: 0, }; let winp = std::ptr::addr_of_mut!(size); let result = unsafe { libc::openpty( &mut master, &mut slave, std::ptr::null_mut(), std::ptr::null_mut(), winp, ) }; if result != 0 { anyhow::bail!("failed to openpty: {:?}", std::io::Error::last_os_error()); } set_cloexec(master)?; set_cloexec(slave)?; Ok(unsafe { (File::from_raw_fd(master), File::from_raw_fd(slave)) }) } #[cfg(unix)] fn set_cloexec(fd: RawFd) -> std::io::Result<()> { let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; if flags == -1 { return Err(std::io::Error::last_os_error()); } let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; if result == -1 { return Err(std::io::Error::last_os_error()); } Ok(()) } /// Called only in the child: never make attachments inheritable in the parent. #[cfg(unix)] pub(crate) fn make_fds_inheritable(fds: &[RawFd]) -> std::io::Result<()> { for &fd in fds { // SAFETY: fcntl only changes the current process's descriptor flags. let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; if flags == -1 || unsafe { libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) } == -1 { return Err(std::io::Error::last_os_error()); } } Ok(()) } // macOS needs a fork-safe sweep because recvmsg cannot set close-on-exec. // Cleanup is best-effort; enumeration and close failures do not prevent launch. #[cfg(target_os = "macos")] pub fn close_inherited_fds_except(preserved_fds: &[RawFd]) { let mut descriptors = [libc::proc_fdinfo { proc_fd: 0, proc_fdtype: 0, }; 1024]; // SAFETY: proc_pidinfo writes descriptor records into the stack buffer. let bytes = unsafe { libc::proc_pidinfo( libc::getpid(), libc::PROC_PIDLISTFDS, /*arg*/ 0, descriptors.as_mut_ptr().cast(), std::mem::size_of_val(&descriptors) as libc::c_int, ) }; let close_inheritable = |fd| { if fd <= libc::STDERR_FILENO || preserved_fds.contains(&fd) { return; } // std::process keeps a CLOEXEC pipe open until exec to report spawn errors. // SAFETY: fcntl and close only operate on a descriptor owned by this process. unsafe { let flags = libc::fcntl(fd, libc::F_GETFD); if flags >= 0 && flags & libc::FD_CLOEXEC == 0 { libc::close(fd); } } }; if bytes > 0 && (bytes as usize) < std::mem::size_of_val(&descriptors) { let count = bytes as usize / std::mem::size_of::(); for descriptor in descriptors.iter().take(count) { close_inheritable(descriptor.proc_fd); } return; } // SAFETY: proc_pidinfo accepts a null buffer when its size is zero. let descriptor_table_bytes = unsafe { libc::proc_pidinfo( libc::getpid(), libc::PROC_PIDLISTFDS, /*arg*/ 0, std::ptr::null_mut(), /*buffersize*/ 0, ) }; if descriptor_table_bytes > 0 { let upper_bound = descriptor_table_bytes as usize / std::mem::size_of::(); for fd in libc::STDERR_FILENO + 1..upper_bound as RawFd { close_inheritable(fd); } return; } let mut limit = libc::rlimit { rlim_cur: 0, rlim_max: 0, }; // SAFETY: getrlimit writes into the stack-owned resource-limit structure. if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } == 0 { let upper_bound = limit.rlim_cur.min(RawFd::MAX as _) as RawFd; for fd in libc::STDERR_FILENO + 1..upper_bound { close_inheritable(fd); } } } // Other Unix platforms use best-effort /dev/fd cleanup. // Directory enumeration allocates, so this path is not guaranteed fork-safe. #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))] pub(crate) fn close_inherited_fds_except(preserved_fds: &[RawFd]) { if let Ok(dir) = std::fs::read_dir("/dev/fd") { let mut fds = Vec::new(); for entry in dir { let num = entry .ok() .map(|entry| entry.file_name()) .and_then(|name| name.into_string().ok()) .and_then(|name| name.parse::().ok()); if let Some(num) = num { if num <= 2 || preserved_fds.contains(&num) { continue; } // Keep CLOEXEC descriptors open so std::process can still use // its internal exec-error pipe to report spawn failures. let flags = unsafe { libc::fcntl(num, libc::F_GETFD) }; if flags == -1 || flags & libc::FD_CLOEXEC != 0 { continue; } fds.push(num); } } for fd in fds { unsafe { libc::close(fd); } } } } /// Establish the controlling terminal and signal state before a PTY target exec. /// This also runs in the legacy pre-exec callback, so it must stay async-signal-safe. #[cfg(unix)] pub(crate) fn configure_child_terminal() -> std::io::Result<()> { // SAFETY: These operations only change the calling child's signal/session state. unsafe { for signo in &[ libc::SIGCHLD, libc::SIGHUP, libc::SIGINT, libc::SIGQUIT, libc::SIGTERM, libc::SIGALRM, ] { libc::signal(*signo, libc::SIG_DFL); } let empty_set: libc::sigset_t = std::mem::zeroed(); libc::sigprocmask(libc::SIG_SETMASK, &empty_set, std::ptr::null_mut()); if libc::setsid() == -1 { return Err(std::io::Error::last_os_error()); } // stdin now refers to the PTY slave, so make that fd the // controlling terminal for the child's new session. stdout and // stderr point at clones of the same slave device. #[allow(clippy::cast_lossless)] if libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 { return Err(std::io::Error::last_os_error()); } } Ok(()) } #[cfg(all(test, target_os = "linux"))] #[path = "pty_linux_tests.rs"] mod linux_tests;