Skip to main content

portable_pty/
unix.rs

1//! Working with pseudo-terminals
2
3use crate::{
4    Child, CommandBuilder, ContainedPtyChild, ContainedPtyGuard, ContainedPtySpawnError,
5    ContainedPtySpawnErrorStage, FailedChildRecovery, MasterPty, PtyPair, PtySize, PtySystem,
6    SlavePty,
7};
8use anyhow::{bail, Error};
9use filedescriptor::FileDescriptor;
10use libc::{self, winsize};
11use std::cell::RefCell;
12use std::ffi::OsStr;
13use std::io::{Read, Write};
14use std::os::fd::AsFd;
15use std::os::unix::ffi::OsStrExt;
16use std::os::unix::io::{AsRawFd, FromRawFd};
17use std::os::unix::process::CommandExt;
18use std::path::PathBuf;
19use std::{io, mem, ptr};
20
21pub use std::os::unix::io::RawFd;
22
23#[derive(Default)]
24pub struct UnixPtySystem {}
25
26fn openpty(size: PtySize) -> anyhow::Result<(UnixMasterPty, UnixSlavePty)> {
27    let mut master: RawFd = -1;
28    let mut slave: RawFd = -1;
29
30    let mut size = winsize {
31        ws_row: size.rows,
32        ws_col: size.cols,
33        ws_xpixel: size.pixel_width,
34        ws_ypixel: size.pixel_height,
35    };
36
37    let result = unsafe {
38        // BSDish systems may require mut pointers to some args
39        #[allow(clippy::unnecessary_mut_passed)]
40        libc::openpty(
41            &mut master,
42            &mut slave,
43            ptr::null_mut(),
44            ptr::null_mut(),
45            &mut size,
46        )
47    };
48
49    if result != 0 {
50        bail!("failed to openpty: {:?}", io::Error::last_os_error());
51    }
52
53    let tty_name = tty_name(slave);
54
55    let master = UnixMasterPty {
56        fd: PtyFd(unsafe { FileDescriptor::from_raw_fd(master) }),
57        took_writer: RefCell::new(false),
58        tty_name,
59    };
60    let slave = UnixSlavePty {
61        fd: PtyFd(unsafe { FileDescriptor::from_raw_fd(slave) }),
62    };
63
64    // Ensure that these descriptors will get closed when we execute
65    // the child process.  This is done after constructing the Pty
66    // instances so that we ensure that the Ptys get drop()'d if
67    // the cloexec() functions fail (unlikely!).
68    cloexec(master.fd.as_raw_fd())?;
69    cloexec(slave.fd.as_raw_fd())?;
70
71    Ok((master, slave))
72}
73
74impl PtySystem for UnixPtySystem {
75    fn openpty(&self, size: PtySize) -> anyhow::Result<PtyPair> {
76        let (master, slave) = openpty(size)?;
77        Ok(PtyPair {
78            master: Box::new(master),
79            slave: Box::new(slave),
80        })
81    }
82}
83
84struct PtyFd(pub FileDescriptor);
85impl std::ops::Deref for PtyFd {
86    type Target = FileDescriptor;
87    fn deref(&self) -> &FileDescriptor {
88        &self.0
89    }
90}
91impl std::ops::DerefMut for PtyFd {
92    fn deref_mut(&mut self) -> &mut FileDescriptor {
93        &mut self.0
94    }
95}
96
97impl Read for PtyFd {
98    fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
99        match self.0.read(buf) {
100            Err(ref e) if e.raw_os_error() == Some(libc::EIO) => {
101                // EIO indicates that the slave pty has been closed.
102                // Treat this as EOF so that std::io::Read::read_to_string
103                // and similar functions gracefully terminate when they
104                // encounter this condition
105                Ok(0)
106            }
107            x => x,
108        }
109    }
110}
111
112fn tty_name(fd: RawFd) -> Option<PathBuf> {
113    let mut buf = vec![0 as std::ffi::c_char; 128];
114
115    loop {
116        let res = unsafe { libc::ttyname_r(fd, buf.as_mut_ptr(), buf.len()) };
117
118        if res == libc::ERANGE {
119            if buf.len() > 64 * 1024 {
120                // on macOS, if the buf is "too big", ttyname_r can
121                // return ERANGE, even though that is supposed to
122                // indicate buf is "too small".
123                return None;
124            }
125            buf.resize(buf.len() * 2, 0 as std::ffi::c_char);
126            continue;
127        }
128
129        return if res == 0 {
130            let cstr = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) };
131            let osstr = OsStr::from_bytes(cstr.to_bytes());
132            Some(PathBuf::from(osstr))
133        } else {
134            None
135        };
136    }
137}
138
139/// On Big Sur, Cocoa leaks various file descriptors to child processes,
140/// so we need to make a pass through the open descriptors beyond just the
141/// stdio descriptors and close them all out.
142/// This is approximately equivalent to the darwin `posix_spawnattr_setflags`
143/// option POSIX_SPAWN_CLOEXEC_DEFAULT which is used as a bit of a cheat
144/// on macOS.
145/// On Linux, gnome/mutter leak shell extension fds to wezterm too, so we
146/// also need to make an effort to clean up the mess.
147///
148/// This function enumerates the open filedescriptors in the current process
149/// and then will forcibly call close(2) on each open fd that is numbered
150/// 3 or higher, effectively closing all descriptors except for the stdio
151/// streams.
152///
153/// The implementation of this function relies on `/dev/fd` being available
154/// to provide the list of open fds.  Any errors in enumerating or closing
155/// the fds are silently ignored.
156pub fn close_random_fds() {
157    // FreeBSD, macOS and presumably other BSDish systems have /dev/fd as
158    // a directory listing the current fd numbers for the process.
159    //
160    // On Linux, /dev/fd is a symlink to /proc/self/fd
161    if let Ok(dir) = std::fs::read_dir("/dev/fd") {
162        let mut fds = vec![];
163        for entry in dir {
164            if let Some(num) = entry
165                .ok()
166                .map(|e| e.file_name())
167                .and_then(|s| s.into_string().ok())
168                .and_then(|n| n.parse::<libc::c_int>().ok())
169            {
170                if num > 2 {
171                    fds.push(num);
172                }
173            }
174        }
175        for fd in fds {
176            unsafe {
177                libc::close(fd);
178            }
179        }
180    }
181}
182
183impl PtyFd {
184    fn resize(&self, size: PtySize) -> Result<(), Error> {
185        let ws_size = winsize {
186            ws_row: size.rows,
187            ws_col: size.cols,
188            ws_xpixel: size.pixel_width,
189            ws_ypixel: size.pixel_height,
190        };
191
192        if unsafe {
193            libc::ioctl(
194                self.0.as_raw_fd(),
195                libc::TIOCSWINSZ as _,
196                &ws_size as *const _,
197            )
198        } != 0
199        {
200            bail!(
201                "failed to ioctl(TIOCSWINSZ): {:?}",
202                io::Error::last_os_error()
203            );
204        }
205
206        Ok(())
207    }
208
209    fn get_size(&self) -> Result<PtySize, Error> {
210        let mut size: winsize = unsafe { mem::zeroed() };
211        if unsafe {
212            libc::ioctl(
213                self.0.as_raw_fd(),
214                libc::TIOCGWINSZ as _,
215                &mut size as *mut _,
216            )
217        } != 0
218        {
219            bail!(
220                "failed to ioctl(TIOCGWINSZ): {:?}",
221                io::Error::last_os_error()
222            );
223        }
224        Ok(PtySize {
225            rows: size.ws_row,
226            cols: size.ws_col,
227            pixel_width: size.ws_xpixel,
228            pixel_height: size.ws_ypixel,
229        })
230    }
231
232    fn spawn_command(&self, builder: CommandBuilder) -> anyhow::Result<std::process::Child> {
233        let configured_umask = builder.umask;
234
235        let mut cmd = builder.as_command()?;
236        let controlling_tty = builder.get_controlling_tty();
237
238        unsafe {
239            cmd.stdin(self.as_stdio()?)
240                .stdout(self.as_stdio()?)
241                .stderr(self.as_stdio()?)
242                .pre_exec(move || {
243                    // Clean up a few things before we exec the program
244                    // Clear out any potentially problematic signal
245                    // dispositions that we might have inherited
246                    for signo in &[
247                        libc::SIGCHLD,
248                        libc::SIGHUP,
249                        libc::SIGINT,
250                        libc::SIGQUIT,
251                        libc::SIGTERM,
252                        libc::SIGALRM,
253                    ] {
254                        libc::signal(*signo, libc::SIG_DFL);
255                    }
256
257                    let empty_set: libc::sigset_t = std::mem::zeroed();
258                    libc::sigprocmask(libc::SIG_SETMASK, &empty_set, std::ptr::null_mut());
259
260                    // Establish ourselves as a session leader.
261                    if libc::setsid() == -1 {
262                        return Err(io::Error::last_os_error());
263                    }
264
265                    // Clippy wants us to explicitly cast TIOCSCTTY using
266                    // type::from(), but the size and potentially signedness
267                    // are system dependent, which is why we're using `as _`.
268                    // Suppress this lint for this section of code.
269                    #[allow(clippy::cast_lossless)]
270                    if controlling_tty {
271                        // Set the pty as the controlling terminal.
272                        // Failure to do this means that delivery of
273                        // SIGWINCH won't happen when we resize the
274                        // terminal, among other undesirable effects.
275                        if libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
276                            return Err(io::Error::last_os_error());
277                        }
278                    }
279
280                    close_random_fds();
281
282                    if let Some(mask) = configured_umask {
283                        libc::umask(mask);
284                    }
285
286                    Ok(())
287                })
288        };
289
290        let mut child = cmd.spawn()?;
291
292        // Ensure that we close out the slave fds that Child retains;
293        // they are not what we need (we need the master side to reference
294        // them) and won't work in the usual way anyway.
295        // In practice these are None, but it seems best to be move them
296        // out in case the behavior of Command changes in the future.
297        child.stdin.take();
298        child.stdout.take();
299        child.stderr.take();
300
301        Ok(child)
302    }
303
304    fn spawn_contained_command(
305        &self,
306        builder: CommandBuilder,
307    ) -> Result<ContainedPtyGuard, ContainedPtySpawnError> {
308        self.spawn_contained_command_with_fault(builder, ContainedSpawnFault::None)
309    }
310
311    fn spawn_contained_command_with_fault(
312        &self,
313        builder: CommandBuilder,
314        _fault: ContainedSpawnFault,
315    ) -> Result<ContainedPtyGuard, ContainedPtySpawnError> {
316        let configured_umask = builder.umask;
317        let mut cmd = builder
318            .as_command()
319            .map_err(ContainedPtySpawnError::before_spawn)?;
320        let controlling_tty = builder.get_controlling_tty();
321        let (hook, pending_receipt) = sysprims_session::prepare_session_acquisition()
322            .map_err(|error| ContainedPtySpawnError::before_spawn(error.into()))?;
323
324        unsafe {
325            cmd.stdin(
326                self.as_stdio()
327                    .map_err(|error| ContainedPtySpawnError::before_spawn(error.into()))?,
328            )
329            .stdout(
330                self.as_stdio()
331                    .map_err(|error| ContainedPtySpawnError::before_spawn(error.into()))?,
332            )
333            .stderr(
334                self.as_stdio()
335                    .map_err(|error| ContainedPtySpawnError::before_spawn(error.into()))?,
336            )
337            .pre_exec(move || {
338                // Match the legacy PTY spawn's signal reset without
339                // allocating or consulting lock-backed state.
340                for signo in &[
341                    libc::SIGCHLD,
342                    libc::SIGHUP,
343                    libc::SIGINT,
344                    libc::SIGQUIT,
345                    libc::SIGTERM,
346                    libc::SIGALRM,
347                ] {
348                    libc::signal(*signo, libc::SIG_DFL);
349                }
350
351                let empty_set: libc::sigset_t = std::mem::zeroed();
352                libc::sigprocmask(libc::SIG_SETMASK, &empty_set, std::ptr::null_mut());
353
354                // This hook replaces the legacy setsid() slot. It is the
355                // only session or process-group acquirer for this spawn.
356                hook.acquire()?;
357
358                #[allow(clippy::cast_lossless)]
359                if controlling_tty && libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
360                    return Err(io::Error::last_os_error());
361                }
362
363                // The PTY and sysprims companion descriptors are prepared
364                // with CLOEXEC. Avoid portable-pty's allocation-backed
365                // /dev/fd traversal in this post-fork path.
366                if let Some(mask) = configured_umask {
367                    libc::umask(mask);
368                }
369
370                Ok(())
371            });
372        }
373
374        // Establish the parent-side exact-child recovery owner before spawn.
375        // If the spawn succeeds, the idle owner exits when this controller is
376        // dropped. If post-spawn validation fails, it receives the only Child.
377        let recovery = FailedChildRecovery::prepare()
378            .map_err(|error| ContainedPtySpawnError::before_spawn(error.into()))?;
379        let mut child = cmd
380            .spawn()
381            .map_err(|error| ContainedPtySpawnError::before_spawn(error.into()))?;
382        child.stdin.take();
383        child.stdout.take();
384        child.stderr.take();
385
386        let child = ContainedPtyChild::new(child);
387        #[cfg(test)]
388        if _fault == ContainedSpawnFault::Receipt {
389            drop(pending_receipt);
390            return Err(ContainedPtySpawnError::after_spawn_pending_for_test(
391                ContainedPtySpawnErrorStage::Receipt,
392                anyhow::anyhow!("injected receipt failure"),
393                child,
394                recovery,
395            ));
396        }
397        let receipt = match pending_receipt.into_receipt(child.child.id()) {
398            Ok(receipt) => receipt,
399            Err(error) => {
400                return Err(ContainedPtySpawnError::after_spawn(
401                    ContainedPtySpawnErrorStage::Receipt,
402                    error.into(),
403                    child,
404                    recovery,
405                ));
406            }
407        };
408
409        #[cfg(test)]
410        if _fault == ContainedSpawnFault::Adoption {
411            let _receipt = receipt;
412            return Err(ContainedPtySpawnError::after_spawn_pending_for_test(
413                ContainedPtySpawnErrorStage::Adoption,
414                anyhow::anyhow!("injected adoption failure"),
415                child,
416                recovery,
417            ));
418        }
419
420        // SAFETY: `receipt` was sealed by this exact spawn's one-shot hook,
421        // and `child` is its exclusive, unreaped std::process::Child owner.
422        match unsafe { sysprims_timeout::contain_acquired_session(child, receipt) } {
423            Ok(guard) => Ok(guard),
424            Err(adoption) => Err(ContainedPtySpawnError::after_spawn(
425                ContainedPtySpawnErrorStage::Adoption,
426                adoption.error.into(),
427                adoption.child,
428                recovery,
429            )),
430        }
431    }
432}
433
434#[derive(Clone, Copy, PartialEq, Eq)]
435enum ContainedSpawnFault {
436    None,
437    #[cfg(test)]
438    Receipt,
439    #[cfg(test)]
440    Adoption,
441}
442
443/// Represents the master end of a pty.
444/// The file descriptor will be closed when the Pty is dropped.
445struct UnixMasterPty {
446    fd: PtyFd,
447    took_writer: RefCell<bool>,
448    tty_name: Option<PathBuf>,
449}
450
451/// Represents the slave end of a pty.
452/// The file descriptor will be closed when the Pty is dropped.
453struct UnixSlavePty {
454    fd: PtyFd,
455}
456
457/// Helper function to set the close-on-exec flag for a raw descriptor
458fn cloexec(fd: RawFd) -> Result<(), Error> {
459    let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
460    if flags == -1 {
461        bail!(
462            "fcntl to read flags failed: {:?}",
463            io::Error::last_os_error()
464        );
465    }
466    let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
467    if result == -1 {
468        bail!(
469            "fcntl to set CLOEXEC failed: {:?}",
470            io::Error::last_os_error()
471        );
472    }
473    Ok(())
474}
475
476impl SlavePty for UnixSlavePty {
477    fn spawn_command(
478        &self,
479        builder: CommandBuilder,
480    ) -> Result<Box<dyn Child + Send + Sync>, Error> {
481        Ok(Box::new(self.fd.spawn_command(builder)?))
482    }
483
484    fn spawn_contained_command(
485        &self,
486        builder: CommandBuilder,
487    ) -> Result<ContainedPtyGuard, ContainedPtySpawnError> {
488        self.fd.spawn_contained_command(builder)
489    }
490}
491
492impl MasterPty for UnixMasterPty {
493    fn resize(&self, size: PtySize) -> Result<(), Error> {
494        self.fd.resize(size)
495    }
496
497    fn get_size(&self) -> Result<PtySize, Error> {
498        self.fd.get_size()
499    }
500
501    fn try_clone_reader(&self) -> Result<Box<dyn Read + Send>, Error> {
502        let fd = PtyFd(self.fd.try_clone()?);
503        Ok(Box::new(fd))
504    }
505
506    fn take_writer(&self) -> Result<Box<dyn Write + Send>, Error> {
507        if *self.took_writer.borrow() {
508            anyhow::bail!("cannot take writer more than once");
509        }
510        *self.took_writer.borrow_mut() = true;
511        let fd = PtyFd(self.fd.try_clone()?);
512        Ok(Box::new(UnixMasterWriter { fd }))
513    }
514
515    fn as_raw_fd(&self) -> Option<RawFd> {
516        Some(self.fd.0.as_raw_fd())
517    }
518
519    fn tty_name(&self) -> Option<PathBuf> {
520        self.tty_name.clone()
521    }
522
523    fn process_group_leader(&self) -> Option<libc::pid_t> {
524        match unsafe { libc::tcgetpgrp(self.fd.0.as_raw_fd()) } {
525            pid if pid > 0 => Some(pid),
526            _ => None,
527        }
528    }
529
530    fn get_termios(&self) -> Option<nix::sys::termios::Termios> {
531        nix::sys::termios::tcgetattr(self.fd.0.as_fd()).ok()
532    }
533}
534
535/// Represents the master end of a pty.
536/// EOT will be sent, and then the file descriptor will be closed when
537/// the Pty is dropped.
538struct UnixMasterWriter {
539    fd: PtyFd,
540}
541
542impl Drop for UnixMasterWriter {
543    fn drop(&mut self) {
544        let mut t: libc::termios = unsafe { std::mem::MaybeUninit::zeroed().assume_init() };
545        if unsafe { libc::tcgetattr(self.fd.0.as_raw_fd(), &mut t) } == 0 {
546            // EOF is only interpreted after a newline, so if it is set,
547            // we send a newline followed by EOF.
548            let eot = t.c_cc[libc::VEOF];
549            if eot != 0 {
550                let _ = self.fd.0.write_all(&[b'\n', eot]);
551            }
552        }
553    }
554}
555
556impl Write for UnixMasterWriter {
557    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
558        self.fd.write(buf)
559    }
560    fn flush(&mut self) -> Result<(), io::Error> {
561        self.fd.flush()
562    }
563}
564
565#[cfg(test)]
566mod contained_spawn_failure_tests {
567    use super::*;
568    use crate::FailedChildRecoveryFault;
569
570    fn injected_failure(
571        fault: ContainedSpawnFault,
572        stage: ContainedPtySpawnErrorStage,
573    ) -> (ContainedPtySpawnError, UnixMasterPty) {
574        let (master, slave) = openpty(PtySize::default()).unwrap();
575        let mut command = CommandBuilder::new("/usr/bin/perl");
576        command.args(["-e", "sleep 60"]);
577
578        let error = match slave.fd.spawn_contained_command_with_fault(command, fault) {
579            Ok(_) => panic!("injected failure returned a guard"),
580            Err(error) => error,
581        };
582
583        assert_eq!(error.stage(), stage);
584        assert!(
585            error.recovery_pending(),
586            "injected live child was not retained by the error state"
587        );
588        (error, master)
589    }
590
591    fn wait_for_recovery_owner(pending: &std::sync::atomic::AtomicBool) {
592        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
593        while pending.load(std::sync::atomic::Ordering::Acquire) {
594            assert!(
595                std::time::Instant::now() < deadline,
596                "detached exact-child recovery owner did not reap"
597            );
598            std::thread::sleep(std::time::Duration::from_millis(10));
599        }
600    }
601
602    #[test]
603    fn receipt_failure_retains_child_across_kill_error() {
604        let (mut error, _master) = injected_failure(
605            ContainedSpawnFault::Receipt,
606            ContainedPtySpawnErrorStage::Receipt,
607        );
608        let injected = error.recovery.as_ref().unwrap().attempt_with_fault(
609            std::time::Duration::from_millis(10),
610            FailedChildRecoveryFault::KillError,
611        );
612        assert!(injected.is_err());
613        assert!(error.recovery_pending());
614        assert!(
615            error.recover(std::time::Duration::from_secs(2)).unwrap(),
616            "exact-child recovery did not reach reap"
617        );
618        assert!(!error.recovery_pending());
619    }
620
621    #[test]
622    fn adoption_failure_deadline_transfers_to_bounded_drop_owner() {
623        let (error, _master) = injected_failure(
624            ContainedSpawnFault::Adoption,
625            ContainedPtySpawnErrorStage::Adoption,
626        );
627        let completed = error
628            .recovery
629            .as_ref()
630            .unwrap()
631            .attempt_with_fault(
632                std::time::Duration::from_millis(10),
633                FailedChildRecoveryFault::Deadline,
634            )
635            .unwrap();
636        assert!(!completed);
637        assert!(error.recovery_pending());
638
639        let pending = std::sync::Arc::clone(&error.recovery.as_ref().unwrap().pending);
640        let started = std::time::Instant::now();
641        drop(error);
642        assert!(
643            started.elapsed() < std::time::Duration::from_millis(100),
644            "pending-error destructor blocked"
645        );
646        wait_for_recovery_owner(&pending);
647    }
648}