Skip to content

Visual Studio Code, rebuilt in Rust

Rust
12.3 KB
Raw Blame
//! node-pty's unix `spawn` (pty.cc `PtyFork`): the shell runs in a new session whose controlling terminal is a fresh
//! PTY; its output is read on a thread and its exit is waited for on another.

#[cfg(unix)]
use std::collections::HashMap;
#[cfg(target_os = "macos")]
use std::ffi::CStr;
#[cfg(unix)]
use std::fs::File;
#[cfg(unix)]
use std::io::{self, Read, Write};
#[cfg(unix)]
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
#[cfg(unix)]
use std::os::unix::process::CommandExt;
#[cfg(unix)]
use std::path::Path;
#[cfg(unix)]
use std::process::{Command, Stdio};

#[cfg(unix)]
use futures::channel::mpsc::UnboundedSender;

#[cfg(windows)]
mod conpty;
#[cfg(windows)]
pub use conpty::Pty;

pub enum PtyEvent {
    Data(Vec<u8>),
    /// The process exited, with its exit code; `None` when a signal ended it.
    Exit(Option<i32>),
}

#[cfg(unix)]
pub struct Pty {
    master: File,
    pub pid: i32,
}

#[cfg(unix)]
impl Pty {
    pub fn spawn(executable: &Path, args: &[String], cwd: &Path, env: &HashMap<String, String>, cols: u16, rows: u16, events: UnboundedSender<PtyEvent>) -> io::Result<Pty> {
        let (master, slave) = open_pty(cols, rows)?;
        let master_fd = master.as_raw_fd();
        let mut command = Command::new(executable);
        // node-pty unixTerminal.ts sets PWD, so the shell shows the path as given, not the resolved /private/var one.
        command.args(args).env_clear().envs(env).env("PWD", cwd).current_dir(cwd);
        command.stdin(Stdio::from(slave.try_clone()?)).stdout(Stdio::from(slave.try_clone()?)).stderr(Stdio::from(slave));
        // SAFETY: the closure runs between fork and exec and only makes async-signal-safe calls (setsid, ioctl, close, signal).
        unsafe {
            command.pre_exec(move || {
                if libc::setsid() == -1 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
                    return Err(io::Error::last_os_error());
                }
                libc::close(master_fd);
                // pty.cc resets the signals the parent may have changed.
                for signal in [libc::SIGCHLD, libc::SIGHUP, libc::SIGINT, libc::SIGQUIT, libc::SIGTERM, libc::SIGALRM, libc::SIGPIPE] {
                    libc::signal(signal, libc::SIG_DFL);
                }
                Ok(())
            });
        }
        let child = command.spawn()?;
        let pid = child.id() as i32;
        let master = File::from(master);
        let mut reader = master.try_clone()?;
        let data_events = events.clone();
        let (read_done, read_finished) = std::sync::mpsc::channel::<()>();
        std::thread::Builder::new().name("pty-read".into()).spawn(move || {
            let _read_done = read_done;
            let mut buffer = vec![0; 64 * 1024];
            loop {
                match reader.read(&mut buffer) {
                    Ok(0) | Err(_) => break,
                    Ok(read) => {
                        if data_events.unbounded_send(PtyEvent::Data(buffer[..read].to_vec())).is_err() {
                            break;
                        }
                    }
                }
            }
        })?;
        std::thread::Builder::new().name("pty-wait".into()).spawn(move || {
            let mut child = child;
            let code = child.wait().ok().and_then(|status| status.code());
            // unixTerminal.ts emits exit once the pty socket closes, or after DESTROY_SOCKET_TIMEOUT_MS (200 ms).
            let _ = read_finished.recv_timeout(std::time::Duration::from_millis(200));
            let _ = events.unbounded_send(PtyEvent::Exit(code));
        })?;
        Ok(Pty { master, pid })
    }

    pub fn write(&mut self, data: &[u8]) {
        // A write after the shell exited fails with EIO; node-pty drops it the same way.
        let _ = self.master.write_all(data);
    }

    pub fn resize(&self, cols: u16, rows: u16) {
        let size = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
        // SAFETY: the master fd is open while `self` lives; `size` is read during the call.
        unsafe { libc::ioctl(self.master.as_raw_fd(), libc::TIOCSWINSZ, &size) };
    }

    /// node-pty `kill(signal)`, SIGHUP by default.
    pub fn kill(&self, signal: i32) {
        // SAFETY: kill takes a pid and a signal number; no pointers pass.
        unsafe { libc::kill(self.pid, signal) };
    }

    /// childProcessMonitor.ts `hasChildProcesses` (`ignoreProcessNames` is empty): the shell has a child process,
    /// in the foreground or a background job.
    #[cfg(target_os = "macos")]
    pub fn has_child_processes(&self) -> bool {
        let mut children = [0 as libc::pid_t; 16];
        let size = std::mem::size_of_val(&children) as i32;
        // SAFETY: `children` is writable for `size` bytes.
        unsafe { libc::proc_listchildpids(self.pid, children.as_mut_ptr().cast(), size) > 0 }
    }

    /// childProcessMonitor.ts `hasChildProcesses`: the shell has a child process, in the foreground or a background job.
    #[cfg(target_os = "linux")]
    pub fn has_child_processes(&self) -> bool {
        std::fs::read_to_string(format!("/proc/{0}/task/{0}/children", self.pid)).is_ok_and(|children| !children.trim().is_empty())
    }

    /// node-pty `process` (pty.cc `pty_getproc` on Linux): the first argument of the foreground process group leader.
    #[cfg(target_os = "linux")]
    pub fn foreground_process(&self) -> Option<String> {
        // SAFETY: the master fd is open while `self` lives.
        let group = unsafe { libc::tcgetpgrp(self.master.as_raw_fd()) };
        if group <= 0 {
            return None;
        }
        let cmdline = std::fs::read(format!("/proc/{group}/cmdline")).ok()?;
        let name = cmdline.split(|byte| *byte == 0).next()?;
        Some(String::from_utf8_lossy(name).into_owned())
    }

    /// node-pty `process` (pty.cc `pty_getproc`): the name of the terminal's foreground process group leader.
    #[cfg(target_os = "macos")]
    pub fn foreground_process(&self) -> Option<String> {
        // SAFETY: the master fd is open while `self` lives.
        let group = unsafe { libc::tcgetpgrp(self.master.as_raw_fd()) };
        if group <= 0 {
            return None;
        }
        // SAFETY: proc_bsdinfo is integers and byte arrays, valid when zeroed.
        let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
        let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
        // SAFETY: `info` is writable for `size` bytes.
        let read = unsafe { libc::proc_pidinfo(group, libc::PROC_PIDTBSDINFO, 0, (&mut info as *mut libc::proc_bsdinfo).cast(), size) };
        if read != size {
            return None;
        }
        // SAFETY: the kernel NUL-terminates `pbi_comm` (proc_pidbsdinfo), and `read == size` says it filled `info`.
        let name = unsafe { CStr::from_ptr(info.pbi_comm.as_ptr()) };
        Some(name.to_string_lossy().into_owned())
    }

    /// The current directory of the shell (terminalProcess.ts `getCwd`, which reads `/proc/<pid>/cwd` on Linux).
    #[cfg(target_os = "linux")]
    pub fn cwd(&self) -> Option<String> {
        std::fs::read_link(format!("/proc/{}/cwd", self.pid)).ok().map(|path| path.to_string_lossy().into_owned())
    }

    /// The current directory of the shell (terminalProcess.ts `getCwd`, which asks `lsof` on macOS).
    #[cfg(target_os = "macos")]
    pub fn cwd(&self) -> Option<String> {
        // SAFETY: proc_vnodepathinfo is integers and byte arrays, valid when zeroed.
        let mut info: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() };
        let size = std::mem::size_of::<libc::proc_vnodepathinfo>() as i32;
        // SAFETY: `info` is writable for `size` bytes.
        let read = unsafe { libc::proc_pidinfo(self.pid, libc::PROC_PIDVNODEPATHINFO, 0, (&mut info as *mut libc::proc_vnodepathinfo).cast(), size) };
        if read != size {
            return None;
        }
        // SAFETY: `vip_path` is MAXPATHLEN bytes, zeroed above, which the kernel filled with a NUL-terminated path.
        let path = unsafe { CStr::from_ptr(info.pvi_cdir.vip_path.as_ptr().cast()) };
        Some(path.to_string_lossy().into_owned())
    }
}

#[cfg(unix)]
impl Drop for Pty {
    fn drop(&mut self) {
        self.kill(libc::SIGHUP);
    }
}

#[cfg(unix)]
fn open_pty(cols: u16, rows: u16) -> io::Result<(OwnedFd, OwnedFd)> {
    let (mut master, mut slave) = (0, 0);
    let mut size = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
    // SAFETY: the fd and size pointers are locals; the name and termios arguments may be null.
    if unsafe { libc::openpty(&mut master, &mut slave, std::ptr::null_mut(), std::ptr::null_mut(), &mut size) } == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: openpty succeeded, so both are open fds that nothing else owns.
    let (master, slave) = unsafe { (OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave)) };
    // pty.cc sets IUTF8 so the line discipline erases whole UTF-8 characters.
    // SAFETY: termios is integers and a byte array, valid when zeroed.
    let mut termios: libc::termios = unsafe { std::mem::zeroed() };
    // SAFETY: the master fd is open; `termios` is a local the call fills.
    if unsafe { libc::tcgetattr(master.as_raw_fd(), &mut termios) } == 0 {
        termios.c_iflag |= libc::IUTF8;
        // SAFETY: the master fd is open; tcgetattr filled `termios`.
        unsafe { libc::tcsetattr(master.as_raw_fd(), libc::TCSANOW, &termios) };
    }
    for fd in [master.as_raw_fd(), slave.as_raw_fd()] {
        // SAFETY: both fds are open; F_SETFD takes an integer.
        unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
    }
    Ok((master, slave))
}

/// node-pty windowsPtyAgent.ts `argsToCommandLine`: the file and its arguments quoted as the MSVC runtime parses
/// a command line.
#[cfg(any(windows, test))]
fn args_to_command_line(file: &str, args: &[String]) -> String {
    let mut result = String::new();
    for (index, arg) in std::iter::once(file).chain(args.iter().map(String::as_str)).enumerate() {
        if index > 0 {
            result.push(' ');
        }
        let (starts, ends) = (arg.starts_with('"'), arg.ends_with('"'));
        let lopsided = starts != ends;
        let unquoted = !starts && !ends;
        let quote = arg.is_empty() || (arg.contains(' ') || arg.contains('\t')) && arg.chars().count() > 1 && (lopsided || unquoted);
        if quote {
            result.push('"');
        }
        let mut backslashes = 0;
        for char in arg.chars() {
            match char {
                '\\' => backslashes += 1,
                '"' => {
                    result.push_str(&"\\".repeat(backslashes * 2 + 1));
                    result.push('"');
                    backslashes = 0;
                }
                char => {
                    result.push_str(&"\\".repeat(backslashes));
                    backslashes = 0;
                    result.push(char);
                }
            }
        }
        if quote {
            result.push_str(&"\\".repeat(backslashes * 2));
            result.push('"');
        } else {
            result.push_str(&"\\".repeat(backslashes));
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::args_to_command_line;

    fn line(file: &str, args: &[&str]) -> String {
        args_to_command_line(file, &args.iter().map(|arg| arg.to_string()).collect::<Vec<_>>())
    }

    /// Each expected line is what node-pty 1.x lib/windowsPtyAgent.js `argsToCommandLine` returns for the same input.
    #[test]
    fn args_to_command_line_quotes_as_node_pty() {
        assert_eq!(line("file", &[]), "file");
        assert_eq!(line("file", &["foo"]), "file foo");
        assert_eq!(line("file", &["foo", "bar"]), "file foo bar");
        assert_eq!(line("file", &[""]), r#"file """#);
        assert_eq!(line("file", &["foo bar"]), r#"file "foo bar""#);
        assert_eq!(line("file", &["foo\tbar"]), "file \"foo\tbar\"");
        assert_eq!(line("file", &[r#""foo bar""#]), r#"file \"foo bar\""#);
        assert_eq!(line("file", &[r#"foo"bar"#]), r#"file foo\"bar"#);
        assert_eq!(line("file", &[r#""foo bar"#]), r#"file "\"foo bar""#);
        assert_eq!(line("file", &[r#"foo\bar"#]), r#"file foo\bar"#);
        assert_eq!(line("file", &[r#"foo\ bar\"#]), r#"file "foo\ bar\\""#);
        assert_eq!(line("file", &[r#"foo\"bar"#]), r#"file foo\\\"bar"#);
        assert_eq!(line("C:\\Program Files\\pwsh.exe", &["-NoLogo"]), r#""C:\Program Files\pwsh.exe" -NoLogo"#);
    }
}