diff --git a/Cargo.lock b/Cargo.lock index 6437033e5..eb82c9e4d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2071,17 +2071,20 @@ name = "portable-pty" version = "0.2.0" dependencies = [ "anyhow", + "async-trait", "bitflags 1.2.1", "filedescriptor", "lazy_static", "libc", "log", + "mio", "serde", "serde_derive", "serial", "shared_library", "shell-words", "ssh2", + "tokio", "uds_windows", "winapi 0.3.8", ] diff --git a/pty/Cargo.toml b/pty/Cargo.toml index 811c56d1c..3571dd957 100644 --- a/pty/Cargo.toml +++ b/pty/Cargo.toml @@ -9,6 +9,7 @@ license = "MIT" documentation = "https://docs.rs/portable-pty" [dependencies] +async-trait = "0.1" anyhow = "1.0" filedescriptor = "0.7" log = "0.4" @@ -24,6 +25,10 @@ default = [] serde_support = ["serde", "serde_derive"] ssh = ["ssh2"] +[target."cfg(unix)".dependencies] +mio = { version = "0.6" } +tokio = { version = "0.2", features = ["io-driver", "io-util"] } + [target."cfg(windows)".dependencies] bitflags = "1.0" lazy_static = "1.3" @@ -38,3 +43,5 @@ winapi = { version = "0.3", features = [ "synchapi", ]} +[dev-dependencies] +tokio = { version = "0.2", features = ["rt-threaded", "macros"] } diff --git a/pty/examples/whoami.rs b/pty/examples/whoami.rs index f98f703b7..a0474c8d4 100644 --- a/pty/examples/whoami.rs +++ b/pty/examples/whoami.rs @@ -4,23 +4,6 @@ //! is not paid to those pipes! use portable_pty::{CommandBuilder, NativePtySystem, PtySize, PtySystem}; -// Read all available data until we reach EOF or encounter an error -// condition. Only returns an error if we didn't receive any data. -fn read_until_eof_or_error(mut r: R) -> std::io::Result> { - let mut result = vec![]; - - match r.read_to_end(&mut result) { - Ok(_len) => Ok(result), - Err(err) => { - if result.is_empty() { - Err(err) - } else { - Ok(result) - } - } - } -} - fn main() { let pty_system = NativePtySystem::default(); @@ -39,7 +22,7 @@ fn main() { // that we've spawned the child. drop(pair.slave); - let reader = pair.master.try_clone_reader().unwrap(); + let mut reader = pair.master.try_clone_reader().unwrap(); println!("child status: {:?}", child.wait().unwrap()); // We hold handles on the pty. Now that the child is complete // there are no processes remaining that will write to it until @@ -50,8 +33,8 @@ fn main() { drop(pair.master); // Consume the output from the child - let buf = read_until_eof_or_error(reader).unwrap(); - let s = String::from_utf8(buf).unwrap(); + let mut s = String::new(); + reader.read_to_string(&mut s).unwrap(); // We print with escapes escaped because the windows conpty // implementation synthesizes title change escape sequences diff --git a/pty/examples/whoami_async.rs b/pty/examples/whoami_async.rs new file mode 100644 index 000000000..37a92b066 --- /dev/null +++ b/pty/examples/whoami_async.rs @@ -0,0 +1,49 @@ +use portable_pty::awaitable::native_pty_system; +use portable_pty::{CommandBuilder, PtySize}; +use tokio::prelude::*; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let pty_system = native_pty_system(); + + let pair = pty_system + .openpty(PtySize { + rows: 24, + cols: 80, + pixel_width: 0, + pixel_height: 0, + }) + .await?; + + let cmd = CommandBuilder::new("whoami"); + let child = pair.slave.spawn_command(cmd).await?; + // Release any handles owned by the slave: we don't need it now + // that we've spawned the child, and if we don't drop it, we'll + // block a one of the awaits we perform below. + drop(pair.slave); + + let reader = pair.master.try_clone_reader()?; + println!("child status: {:?}", child.await?); + + // We hold handles on the pty. Now that the child is complete + // there are no processes remaining that will write to it until + // we spawn more. We're not going to do that in this example, + // so we should close it down. If we didn't drop it explicitly + // here, then the attempt to read its output would block forever + // waiting for a future child that will never be spawned. + drop(pair.master); + + let mut lines = tokio::io::BufReader::new(reader).lines(); + while let Some(line) = lines.next_line().await? { + // We print with escapes escaped because the windows conpty + // implementation synthesizes title change escape sequences + // in the output stream and it can be confusing to see those + // printed out raw in another terminal. + print!("output: "); + for c in line.escape_debug() { + print!("{}", c); + } + println!(); + } + Ok(()) +} diff --git a/pty/src/awaitable.rs b/pty/src/awaitable.rs new file mode 100644 index 000000000..fbfbce508 --- /dev/null +++ b/pty/src/awaitable.rs @@ -0,0 +1,56 @@ +use super::*; +use async_trait::async_trait; +use std::pin::Pin; + +/// Represents the master/control end of the pty +#[async_trait(?Send)] +pub trait MasterPty: tokio::io::AsyncWrite { + /// Inform the kernel and thus the child process that the window resized. + /// It will update the winsize information maintained by the kernel, + /// and generate a signal for the child to notice and update its state. + async fn resize(&self, size: PtySize) -> anyhow::Result<()>; + /// Retrieves the size of the pty as known by the kernel + async fn get_size(&self) -> anyhow::Result; + /// Obtain a readable handle; output from the slave(s) is readable + /// via this stream. + fn try_clone_reader(&self) -> anyhow::Result>>; +} + +/// Represents a child process spawned into the pty. +/// This handle can be used to wait for or terminate that child process. +/// awaiting the Child yields the ExitStatus when the child completes. +pub trait Child: + std::fmt::Debug + std::future::Future> +{ + /// Terminate the child process + fn kill(&mut self) -> IoResult<()>; +} + +/// Represents the slave side of a pty. +/// Can be used to spawn processes into the pty. +#[async_trait(?Send)] +pub trait SlavePty { + /// Spawns the command specified by the provided CommandBuilder + async fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result>>; +} + +pub struct PtyPair { + // slave is listed first so that it is dropped first. + // The drop order is stable and specified by rust rfc 1857 + pub slave: Pin>, + pub master: Pin>, +} + +/// The `PtySystem` trait allows an application to work with multiple +/// possible Pty implementations at runtime. +#[async_trait(?Send)] +pub trait PtySystem { + /// Create a new Pty instance with the window size set to the specified + /// dimensions. Returns a (master, slave) Pty pair. The master side + /// is used to drive the slave side. + async fn openpty(&self, size: PtySize) -> anyhow::Result; +} + +pub fn native_pty_system() -> Box { + Box::new(NativePtySystem::default()) +} diff --git a/pty/src/lib.rs b/pty/src/lib.rs index 5d7fe2aed..fbd7a8492 100644 --- a/pty/src/lib.rs +++ b/pty/src/lib.rs @@ -59,6 +59,7 @@ pub mod win; #[cfg(feature = "ssh")] pub mod ssh; +pub mod awaitable; pub mod serial; /// Represents the size of the visible display area in the pty @@ -126,7 +127,7 @@ pub trait SlavePty { /// Represents the exit status of a child process. /// This is rather anemic in the current version of this crate, /// holding only an indicator of success or failure. -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct ExitStatus { successful: bool, } diff --git a/pty/src/unix.rs b/pty/src/unix.rs index 857ccd1c9..c5e47081d 100644 --- a/pty/src/unix.rs +++ b/pty/src/unix.rs @@ -1,61 +1,72 @@ //! Working with pseudo-terminals -use crate::{Child, CommandBuilder, MasterPty, PtyPair, PtySize, PtySystem, SlavePty}; -use anyhow::{bail, Error}; +use crate::{Child, CommandBuilder, ExitStatus, MasterPty, PtyPair, PtySize, PtySystem, SlavePty}; +use anyhow::{bail, Context as _, Error}; +use async_trait::async_trait; use filedescriptor::FileDescriptor; use libc::{self, winsize}; +use mio::unix::EventedFd; +use mio::{self, Evented, PollOpt, Ready, Token}; use std::io; +use std::io::{Read, Write}; use std::mem; -use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::process::CommandExt; -use std::process::Stdio; +use std::pin::Pin; use std::ptr; +use std::task::{Context, Poll}; +use tokio::io::PollEvented; #[derive(Default)] pub struct UnixPtySystem {} +fn openpty(size: PtySize) -> anyhow::Result<(UnixMasterPty, UnixSlavePty)> { + let mut master: RawFd = -1; + let mut slave: RawFd = -1; + + let mut size = winsize { + ws_row: size.rows, + ws_col: size.cols, + ws_xpixel: size.pixel_width, + ws_ypixel: size.pixel_height, + }; + + let result = unsafe { + // BSDish systems may require mut pointers to some args + #[cfg_attr(feature = "cargo-clippy", allow(clippy::unnecessary_mut_passed))] + libc::openpty( + &mut master, + &mut slave, + ptr::null_mut(), + ptr::null_mut(), + &mut size, + ) + }; + + if result != 0 { + bail!("failed to openpty: {:?}", io::Error::last_os_error()); + } + + let master = UnixMasterPty { + fd: PtyFd(unsafe { FileDescriptor::from_raw_fd(master) }), + }; + let slave = UnixSlavePty { + fd: PtyFd(unsafe { FileDescriptor::from_raw_fd(slave) }), + }; + + // Ensure that these descriptors will get closed when we execute + // the child process. This is done after constructing the Pty + // instances so that we ensure that the Ptys get drop()'d if + // the cloexec() functions fail (unlikely!). + cloexec(master.fd.as_raw_fd())?; + cloexec(slave.fd.as_raw_fd())?; + + Ok((master, slave)) +} + impl PtySystem for UnixPtySystem { fn openpty(&self, size: PtySize) -> anyhow::Result { - let mut master: RawFd = -1; - let mut slave: RawFd = -1; - - let mut size = winsize { - ws_row: size.rows, - ws_col: size.cols, - ws_xpixel: size.pixel_width, - ws_ypixel: size.pixel_height, - }; - - let result = unsafe { - // BSDish systems may require mut pointers to some args - #[cfg_attr(feature = "cargo-clippy", allow(clippy::unnecessary_mut_passed))] - libc::openpty( - &mut master, - &mut slave, - ptr::null_mut(), - ptr::null_mut(), - &mut size, - ) - }; - - if result != 0 { - bail!("failed to openpty: {:?}", io::Error::last_os_error()); - } - - let master = UnixMasterPty { - fd: unsafe { FileDescriptor::from_raw_fd(master) }, - }; - let slave = UnixSlavePty { - fd: unsafe { FileDescriptor::from_raw_fd(slave) }, - }; - - // Ensure that these descriptors will get closed when we execute - // the child process. This is done after constructing the Pty - // instances so that we ensure that the Ptys get drop()'d if - // the cloexec() functions fail (unlikely!). - cloexec(master.fd.as_raw_fd())?; - cloexec(slave.fd.as_raw_fd())?; - + let (master, slave) = openpty(size)?; Ok(PtyPair { master: Box::new(master), slave: Box::new(slave), @@ -63,39 +74,91 @@ impl PtySystem for UnixPtySystem { } } -/// Represents the master end of a pty. -/// The file descriptor will be closed when the Pty is dropped. -pub struct UnixMasterPty { - fd: FileDescriptor, -} +#[async_trait(?Send)] +impl crate::awaitable::PtySystem for UnixPtySystem { + async fn openpty(&self, size: PtySize) -> anyhow::Result { + let (mut master, mut slave) = openpty(size)?; -/// Represents the slave end of a pty. -/// The file descriptor will be closed when the Pty is dropped. -pub struct UnixSlavePty { - fd: FileDescriptor, -} + master.fd.set_non_blocking(true)?; + slave.fd.set_non_blocking(true)?; -/// Helper function to set the close-on-exec flag for a raw descriptor -fn cloexec(fd: RawFd) -> Result<(), Error> { - let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; - if flags == -1 { - bail!( - "fcntl to read flags failed: {:?}", - io::Error::last_os_error() - ); + Ok(crate::awaitable::PtyPair { + master: Box::pin(AwaitableMasterPty { + io: PollEvented::new(master.fd)?, + }), + slave: Box::pin(AwaitableSlavePty { + io: PollEvented::new(slave.fd)?, + }), + }) } - let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; - if result == -1 { - bail!( - "fcntl to set CLOEXEC failed: {:?}", - io::Error::last_os_error() - ); - } - Ok(()) } -impl SlavePty for UnixSlavePty { - fn spawn_command(&self, builder: CommandBuilder) -> Result, Error> { +struct PtyFd(pub FileDescriptor); +impl std::ops::Deref for PtyFd { + type Target = FileDescriptor; + fn deref(&self) -> &FileDescriptor { + &self.0 + } +} +impl std::ops::DerefMut for PtyFd { + fn deref_mut(&mut self) -> &mut FileDescriptor { + &mut self.0 + } +} + +impl Read for PtyFd { + fn read(&mut self, buf: &mut [u8]) -> Result { + match self.0.read(buf) { + Err(ref e) + if e.kind() == io::ErrorKind::Other && e.raw_os_error() == Some(libc::EIO) => + { + // EIO indicates that the slave pty has been closed. + // Treat this as EOF so that std::io::Read::read_to_string + // and similar functions gracefully terminate when they + // encounter this condition + Ok(0) + } + x => x, + } + } +} + +impl PtyFd { + fn resize(&self, size: PtySize) -> Result<(), Error> { + let ws_size = winsize { + ws_row: size.rows, + ws_col: size.cols, + ws_xpixel: size.pixel_width, + ws_ypixel: size.pixel_height, + }; + + if unsafe { libc::ioctl(self.0.as_raw_fd(), libc::TIOCSWINSZ, &ws_size as *const _) } != 0 { + bail!( + "failed to ioctl(TIOCSWINSZ): {:?}", + io::Error::last_os_error() + ); + } + + Ok(()) + } + + fn get_size(&self) -> Result { + let mut size: winsize = unsafe { mem::zeroed() }; + if unsafe { libc::ioctl(self.0.as_raw_fd(), libc::TIOCGWINSZ, &mut size as *mut _) } != 0 { + bail!( + "failed to ioctl(TIOCGWINSZ): {:?}", + io::Error::last_os_error() + ); + } + Ok(PtySize { + rows: size.ws_row, + cols: size.ws_col, + pixel_width: size.ws_xpixel, + pixel_height: size.ws_ypixel, + }) + } + + fn spawn_command(&self, builder: CommandBuilder) -> anyhow::Result { let mut cmd = builder.as_command()?; unsafe { @@ -151,61 +214,89 @@ impl SlavePty for UnixSlavePty { child.stdout.take(); child.stderr.take(); - Ok(Box::new(child)) + Ok(child) } } -impl UnixSlavePty { - /// Helper for setting up a Command instance - fn as_stdio(&self) -> Result { - let dup = self.fd.try_clone()?; - Ok(unsafe { Stdio::from_raw_fd(dup.into_raw_fd()) }) +impl Evented for PtyFd { + fn register( + &self, + poll: &mio::Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> std::io::Result<()> { + EventedFd(&self.0.as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &mio::Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> std::io::Result<()> { + EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &mio::Poll) -> std::io::Result<()> { + EventedFd(&self.0.as_raw_fd()).deregister(poll) + } +} + +/// Represents the master end of a pty. +/// The file descriptor will be closed when the Pty is dropped. +struct UnixMasterPty { + fd: PtyFd, +} + +/// Represents the slave end of a pty. +/// The file descriptor will be closed when the Pty is dropped. +struct UnixSlavePty { + fd: PtyFd, +} + +/// Helper function to set the close-on-exec flag for a raw descriptor +fn cloexec(fd: RawFd) -> Result<(), Error> { + let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; + if flags == -1 { + bail!( + "fcntl to read flags failed: {:?}", + io::Error::last_os_error() + ); + } + let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; + if result == -1 { + bail!( + "fcntl to set CLOEXEC failed: {:?}", + io::Error::last_os_error() + ); + } + Ok(()) +} + +impl SlavePty for UnixSlavePty { + fn spawn_command(&self, builder: CommandBuilder) -> Result, Error> { + Ok(Box::new(self.fd.spawn_command(builder)?)) } } impl MasterPty for UnixMasterPty { fn resize(&self, size: PtySize) -> Result<(), Error> { - let ws_size = winsize { - ws_row: size.rows, - ws_col: size.cols, - ws_xpixel: size.pixel_width, - ws_ypixel: size.pixel_height, - }; - - if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::TIOCSWINSZ, &ws_size as *const _) } != 0 - { - bail!( - "failed to ioctl(TIOCSWINSZ): {:?}", - io::Error::last_os_error() - ); - } - - Ok(()) + self.fd.resize(size) } fn get_size(&self) -> Result { - let mut size: winsize = unsafe { mem::zeroed() }; - if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::TIOCGWINSZ, &mut size as *mut _) } != 0 { - bail!( - "failed to ioctl(TIOCGWINSZ): {:?}", - io::Error::last_os_error() - ); - } - Ok(PtySize { - rows: size.ws_row, - cols: size.ws_col, - pixel_width: size.ws_xpixel, - pixel_height: size.ws_ypixel, - }) + self.fd.get_size() } - fn try_clone_reader(&self) -> Result, Error> { - let fd = self.fd.try_clone()?; + fn try_clone_reader(&self) -> Result, Error> { + let fd = PtyFd(self.fd.try_clone()?); Ok(Box::new(fd)) } } -impl io::Write for UnixMasterPty { +impl Write for UnixMasterPty { fn write(&mut self, buf: &[u8]) -> Result { self.fd.write(buf) } @@ -213,3 +304,178 @@ impl io::Write for UnixMasterPty { self.fd.flush() } } + +struct AwaitableSlavePty { + io: PollEvented, +} + +struct AwaitableMasterPty { + io: PollEvented, +} + +#[derive(Debug)] +struct AwaitableChild { + pid: libc::pid_t, + waiting: Option>>, +} + +impl crate::awaitable::Child for AwaitableChild { + fn kill(&mut self) -> std::io::Result<()> { + let res = unsafe { libc::kill(self.pid, libc::SIGKILL) }; + if res != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } +} + +impl std::future::Future for AwaitableChild { + type Output = anyhow::Result; + fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll> { + if self.waiting.is_none() { + let (tx, rx) = std::sync::mpsc::channel(); + let pid = self.pid; + let waker = cx.waker().clone(); + std::thread::spawn(move || loop { + let mut status = 0; + let reaped = unsafe { libc::waitpid(pid, &mut status, 0) }; + let err = std::io::Error::last_os_error(); + if reaped == pid { + let exit_code = if unsafe { libc::WIFEXITED(status) } { + unsafe { libc::WEXITSTATUS(status) as u32 } + } else { + 1 + }; + tx.send(Ok(ExitStatus::with_exit_code(exit_code))).ok(); + waker.wake(); + return; + } + + if err.kind() == std::io::ErrorKind::Interrupted { + continue; + } + + tx.send(Err(err).context("waitpid result")).ok(); + waker.wake(); + return; + }); + self.waiting = Some(rx); + } + + match self.waiting.as_mut().unwrap().try_recv() { + Ok(status) => Poll::Ready(status), + Err(std::sync::mpsc::TryRecvError::Empty) => Poll::Pending, + Err(err) => Poll::Ready(Err(err).context("receiving process wait status")), + } + } +} + +#[async_trait(?Send)] +impl crate::awaitable::SlavePty for AwaitableSlavePty { + async fn spawn_command( + &self, + builder: CommandBuilder, + ) -> anyhow::Result>> { + let child = self.io.get_ref().spawn_command(builder)?; + let pid = child.id() as libc::pid_t; + Ok(Box::pin(AwaitableChild { pid, waiting: None })) + } +} + +#[async_trait(?Send)] +impl crate::awaitable::MasterPty for AwaitableMasterPty { + async fn resize(&self, size: PtySize) -> Result<(), Error> { + self.io.get_ref().resize(size) + } + + async fn get_size(&self) -> Result { + self.io.get_ref().get_size() + } + + fn try_clone_reader(&self) -> anyhow::Result>> { + let mut fd = self.io.get_ref().try_clone()?; + fd.set_non_blocking(true)?; + Ok(Box::pin(AwaitableMasterPty { + io: PollEvented::new(PtyFd(fd))?, + })) + } +} + +impl AwaitableMasterPty { + fn poll_write_impl( + &mut self, + cx: &mut Context, + buf: &[u8], + ) -> Poll> { + if Poll::Pending == self.io.poll_write_ready(cx)? { + return Poll::Pending; + } + + match self.io.get_mut().0.write(buf) { + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { + self.io.clear_write_ready(cx)?; + Poll::Pending + } + x => Poll::Ready(x), + } + } +} + +impl tokio::io::AsyncWrite for AwaitableMasterPty { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context, + buf: &[u8], + ) -> Poll> { + self.poll_write_impl(cx, buf) + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown( + self: Pin<&mut Self>, + _cx: &mut Context, + ) -> std::task::Poll> { + Poll::Ready(Ok(())) + } +} + +impl tokio::io::AsyncRead for AwaitableMasterPty { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { + poll_read_impl(&mut self.io, cx, buf) + } +} + +fn poll_read_impl( + io: &mut PollEvented, + cx: &mut Context<'_>, + buf: &mut [u8], +) -> Poll> { + if Poll::Pending == io.poll_read_ready(cx, Ready::readable())? { + return Poll::Pending; + } + + match io.get_mut().read(buf) { + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { + io.clear_read_ready(cx, Ready::readable())?; + Poll::Pending + } + x => Poll::Ready(x), + } +} + +impl tokio::io::AsyncRead for AwaitableSlavePty { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { + poll_read_impl(&mut self.io, cx, buf) + } +}