From b0d1a56eaac7a40732386eecf497bc155e378834 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Mon, 22 Apr 2019 21:20:33 -0700 Subject: [PATCH 01/34] move filedescriptor to its own crate --- filedescriptor/Cargo.toml | 11 ++++ filedescriptor/src/lib.rs | 115 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 filedescriptor/Cargo.toml create mode 100644 filedescriptor/src/lib.rs diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml new file mode 100644 index 000000000..9cb89bd59 --- /dev/null +++ b/filedescriptor/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "filedescriptor" +version = "0.1.0" +authors = ["Wez Furlong"] +edition = "2018" + +[dependencies] +failure = "0.1" +failure_derive = "0.1" +libc = "0.2" + diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs new file mode 100644 index 000000000..de88a1aa4 --- /dev/null +++ b/filedescriptor/src/lib.rs @@ -0,0 +1,115 @@ +use failure::{bail, Fallible}; +use std::os::unix::prelude::*; + +pub struct FileDescriptor { + fd: RawFd, +} + +impl std::io::Read for FileDescriptor { + fn read(&mut self, buf: &mut [u8]) -> Result { + let size = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut _, buf.len()) }; + if size == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(size as usize) + } + } +} + +impl std::io::Write for FileDescriptor { + fn write(&mut self, buf: &[u8]) -> Result { + let size = unsafe { libc::write(self.fd, buf.as_ptr() as *const _, buf.len()) }; + if size == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(size as usize) + } + } + fn flush(&mut self) -> Result<(), std::io::Error> { + Ok(()) + } +} + +impl Drop for FileDescriptor { + fn drop(&mut self) { + unsafe { + libc::close(self.fd); + } + } +} + +impl AsRawFd for FileDescriptor { + fn as_raw_fd(&self) -> RawFd { + self.fd + } +} + +fn dup(fd: RawFd) -> Fallible { + let duped = unsafe { libc::dup(fd) }; + if duped == -1 { + bail!( + "dup of fd {} failed: {:?}", + fd, + std::io::Error::last_os_error() + ) + } else { + let mut owned = FileDescriptor { fd: duped }; + owned.cloexec()?; + Ok(owned) + } +} + +pub struct Pipes { + pub read: FileDescriptor, + pub write: FileDescriptor, +} + +impl FileDescriptor { + pub fn dup(f: F) -> Fallible { + dup(f.as_raw_fd()) + } + + pub fn pipe() -> Fallible { + let mut fds = [-1i32; 2]; + let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; + if res == -1 { + bail!( + "failed to create a pipe: {:?}", + std::io::Error::last_os_error() + ) + } else { + let mut read = FileDescriptor { fd: fds[0] }; + let mut write = FileDescriptor { fd: fds[1] }; + read.cloexec()?; + write.cloexec()?; + Ok(Pipes { read, write }) + } + } + + /// Helper function to set the close-on-exec flag for a raw descriptor + fn cloexec(&mut self) -> Fallible<()> { + let flags = unsafe { libc::fcntl(self.fd, libc::F_GETFD) }; + if flags == -1 { + bail!( + "fcntl to read flags failed: {:?}", + std::io::Error::last_os_error() + ); + } + let result = unsafe { libc::fcntl(self.fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; + if result == -1 { + bail!( + "fcntl to set CLOEXEC failed: {:?}", + std::io::Error::last_os_error() + ); + } + Ok(()) + } + + pub fn as_stdio(&self) -> Fallible { + let duped = dup(self.fd)?; + let fd = duped.fd; + let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; + std::mem::forget(duped); // don't drop; stdio now owns it + Ok(stdio) + } +} From d5cddca18fff05495f9a476509c6670cff1fe215 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Mon, 22 Apr 2019 22:20:20 -0700 Subject: [PATCH 02/34] plumbing for tracking fds in the shell environment --- filedescriptor/src/lib.rs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index de88a1aa4..3015d531f 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -1,6 +1,18 @@ use failure::{bail, Fallible}; use std::os::unix::prelude::*; +#[cfg(unix)] +pub trait AsRawFileDescriptor: AsRawFd {} + +#[cfg(unix)] +impl AsRawFileDescriptor for T {} + +#[cfg(windows)] +pub trait AsRawFileDescriptor: AsRawHandle {} + +#[cfg(windows)] +impl AsRawFileDescriptor for T {} + pub struct FileDescriptor { fd: RawFd, } @@ -44,7 +56,7 @@ impl AsRawFd for FileDescriptor { } } -fn dup(fd: RawFd) -> Fallible { +fn dup_fd(fd: RawFd) -> Fallible { let duped = unsafe { libc::dup(fd) }; if duped == -1 { bail!( @@ -64,9 +76,14 @@ pub struct Pipes { pub write: FileDescriptor, } +pub fn dup(f: F) -> Fallible { + #[cfg(unix)] + dup_fd(f.as_raw_fd()) +} + impl FileDescriptor { - pub fn dup(f: F) -> Fallible { - dup(f.as_raw_fd()) + pub fn dup(f: F) -> Fallible { + dup(f) } pub fn pipe() -> Fallible { @@ -106,7 +123,7 @@ impl FileDescriptor { } pub fn as_stdio(&self) -> Fallible { - let duped = dup(self.fd)?; + let duped = dup_fd(self.fd)?; let fd = duped.fd; let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; std::mem::forget(duped); // don't drop; stdio now owns it From 8a38ab6cb10ab7890625479c2a8925f540e6060e Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 26 Apr 2019 21:48:53 -0700 Subject: [PATCH 03/34] implement pipelines --- filedescriptor/src/lib.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 3015d531f..813fd9bd1 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -13,6 +13,7 @@ pub trait AsRawFileDescriptor: AsRawHandle {} #[cfg(windows)] impl AsRawFileDescriptor for T {} +#[derive(Debug)] pub struct FileDescriptor { fd: RawFd, } @@ -56,6 +57,12 @@ impl AsRawFd for FileDescriptor { } } +impl AsRawFd for &FileDescriptor { + fn as_raw_fd(&self) -> RawFd { + self.fd + } +} + fn dup_fd(fd: RawFd) -> Fallible { let duped = unsafe { libc::dup(fd) }; if duped == -1 { @@ -86,6 +93,10 @@ impl FileDescriptor { dup(f) } + pub fn clone(&self) -> Fallible { + dup(self) + } + pub fn pipe() -> Fallible { let mut fds = [-1i32; 2]; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; From 9271c130c5c8102cdd1e52044bc036b095fe0259 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 18 May 2019 10:30:28 -0700 Subject: [PATCH 04/34] make filedescriptor crate compile on windows --- filedescriptor/Cargo.toml | 7 ++ filedescriptor/src/lib.rs | 137 +--------------------------------- filedescriptor/src/unix.rs | 130 ++++++++++++++++++++++++++++++++ filedescriptor/src/windows.rs | 134 +++++++++++++++++++++++++++++++++ 4 files changed, 275 insertions(+), 133 deletions(-) create mode 100644 filedescriptor/src/unix.rs create mode 100644 filedescriptor/src/windows.rs diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 9cb89bd59..130a4ad59 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -9,3 +9,10 @@ failure = "0.1" failure_derive = "0.1" libc = "0.2" +[target."cfg(windows)".dependencies] +winapi = { version = "0.3", features = [ + "winuser", + "handleapi", + "fileapi", + "namedpipeapi", +]} diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 813fd9bd1..d7b9bf881 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -1,143 +1,14 @@ -use failure::{bail, Fallible}; -use std::os::unix::prelude::*; - #[cfg(unix)] -pub trait AsRawFileDescriptor: AsRawFd {} - +mod unix; #[cfg(unix)] -impl AsRawFileDescriptor for T {} +pub use crate::unix::*; #[cfg(windows)] -pub trait AsRawFileDescriptor: AsRawHandle {} - +mod windows; #[cfg(windows)] -impl AsRawFileDescriptor for T {} - -#[derive(Debug)] -pub struct FileDescriptor { - fd: RawFd, -} - -impl std::io::Read for FileDescriptor { - fn read(&mut self, buf: &mut [u8]) -> Result { - let size = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut _, buf.len()) }; - if size == -1 { - Err(std::io::Error::last_os_error()) - } else { - Ok(size as usize) - } - } -} - -impl std::io::Write for FileDescriptor { - fn write(&mut self, buf: &[u8]) -> Result { - let size = unsafe { libc::write(self.fd, buf.as_ptr() as *const _, buf.len()) }; - if size == -1 { - Err(std::io::Error::last_os_error()) - } else { - Ok(size as usize) - } - } - fn flush(&mut self) -> Result<(), std::io::Error> { - Ok(()) - } -} - -impl Drop for FileDescriptor { - fn drop(&mut self) { - unsafe { - libc::close(self.fd); - } - } -} - -impl AsRawFd for FileDescriptor { - fn as_raw_fd(&self) -> RawFd { - self.fd - } -} - -impl AsRawFd for &FileDescriptor { - fn as_raw_fd(&self) -> RawFd { - self.fd - } -} - -fn dup_fd(fd: RawFd) -> Fallible { - let duped = unsafe { libc::dup(fd) }; - if duped == -1 { - bail!( - "dup of fd {} failed: {:?}", - fd, - std::io::Error::last_os_error() - ) - } else { - let mut owned = FileDescriptor { fd: duped }; - owned.cloexec()?; - Ok(owned) - } -} +pub use crate::windows::*; pub struct Pipes { pub read: FileDescriptor, pub write: FileDescriptor, } - -pub fn dup(f: F) -> Fallible { - #[cfg(unix)] - dup_fd(f.as_raw_fd()) -} - -impl FileDescriptor { - pub fn dup(f: F) -> Fallible { - dup(f) - } - - pub fn clone(&self) -> Fallible { - dup(self) - } - - pub fn pipe() -> Fallible { - let mut fds = [-1i32; 2]; - let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; - if res == -1 { - bail!( - "failed to create a pipe: {:?}", - std::io::Error::last_os_error() - ) - } else { - let mut read = FileDescriptor { fd: fds[0] }; - let mut write = FileDescriptor { fd: fds[1] }; - read.cloexec()?; - write.cloexec()?; - Ok(Pipes { read, write }) - } - } - - /// Helper function to set the close-on-exec flag for a raw descriptor - fn cloexec(&mut self) -> Fallible<()> { - let flags = unsafe { libc::fcntl(self.fd, libc::F_GETFD) }; - if flags == -1 { - bail!( - "fcntl to read flags failed: {:?}", - std::io::Error::last_os_error() - ); - } - let result = unsafe { libc::fcntl(self.fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; - if result == -1 { - bail!( - "fcntl to set CLOEXEC failed: {:?}", - std::io::Error::last_os_error() - ); - } - Ok(()) - } - - pub fn as_stdio(&self) -> Fallible { - let duped = dup_fd(self.fd)?; - let fd = duped.fd; - let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; - std::mem::forget(duped); // don't drop; stdio now owns it - Ok(stdio) - } -} diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs new file mode 100644 index 000000000..7fb65b8c9 --- /dev/null +++ b/filedescriptor/src/unix.rs @@ -0,0 +1,130 @@ +use crate::Pipes; +use failure::{bail, Fallible}; +use std::os::unix::prelude::*; + +pub trait AsRawFileDescriptor: AsRawFd {} + +impl AsRawFileDescriptor for T {} + +#[derive(Debug)] +pub struct FileDescriptor { + fd: RawFd, +} + +impl std::io::Read for FileDescriptor { + fn read(&mut self, buf: &mut [u8]) -> Result { + let size = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut _, buf.len()) }; + if size == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(size as usize) + } + } +} + +impl std::io::Write for FileDescriptor { + fn write(&mut self, buf: &[u8]) -> Result { + let size = unsafe { libc::write(self.fd, buf.as_ptr() as *const _, buf.len()) }; + if size == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(size as usize) + } + } + fn flush(&mut self) -> Result<(), std::io::Error> { + Ok(()) + } +} + +impl Drop for FileDescriptor { + fn drop(&mut self) { + unsafe { + libc::close(self.fd); + } + } +} + +impl AsRawFd for FileDescriptor { + fn as_raw_fd(&self) -> RawFd { + self.fd + } +} + +impl AsRawFd for &FileDescriptor { + fn as_raw_fd(&self) -> RawFd { + self.fd + } +} + +fn dup_fd(fd: RawFd) -> Fallible { + let duped = unsafe { libc::dup(fd) }; + if duped == -1 { + bail!( + "dup of fd {} failed: {:?}", + fd, + std::io::Error::last_os_error() + ) + } else { + let mut owned = FileDescriptor { fd: duped }; + owned.cloexec()?; + Ok(owned) + } +} + +pub fn dup(f: F) -> Fallible { + dup_fd(f.as_raw_fd()) +} + +impl FileDescriptor { + pub fn dup(f: F) -> Fallible { + dup(f) + } + + pub fn try_clone(&self) -> Fallible { + dup(self) + } + + pub fn pipe() -> Fallible { + let mut fds = [-1i32; 2]; + let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; + if res == -1 { + bail!( + "failed to create a pipe: {:?}", + std::io::Error::last_os_error() + ) + } else { + let mut read = FileDescriptor { fd: fds[0] }; + let mut write = FileDescriptor { fd: fds[1] }; + read.cloexec()?; + write.cloexec()?; + Ok(Pipes { read, write }) + } + } + + /// Helper function to set the close-on-exec flag for a raw descriptor + fn cloexec(&mut self) -> Fallible<()> { + let flags = unsafe { libc::fcntl(self.fd, libc::F_GETFD) }; + if flags == -1 { + bail!( + "fcntl to read flags failed: {:?}", + std::io::Error::last_os_error() + ); + } + let result = unsafe { libc::fcntl(self.fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; + if result == -1 { + bail!( + "fcntl to set CLOEXEC failed: {:?}", + std::io::Error::last_os_error() + ); + } + Ok(()) + } + + pub fn as_stdio(&self) -> Fallible { + let duped = dup_fd(self.fd)?; + let fd = duped.fd; + let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; + std::mem::forget(duped); // don't drop; stdio now owns it + Ok(stdio) + } +} diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs new file mode 100644 index 000000000..b8ab0ea2c --- /dev/null +++ b/filedescriptor/src/windows.rs @@ -0,0 +1,134 @@ +use crate::Pipes; +use failure::{bail, Fallible}; +use std::io::{self, Error as IoError}; +use std::os::windows::prelude::*; +use std::os::windows::raw::HANDLE; +use std::ptr; +use winapi::um::fileapi::*; +use winapi::um::handleapi::*; +use winapi::um::namedpipeapi::CreatePipe; +use winapi::um::processthreadsapi::*; + +pub trait AsRawFileDescriptor: AsRawHandle {} + +impl AsRawFileDescriptor for T {} + +#[derive(Debug)] +pub struct FileDescriptor { + pub handle: HANDLE, +} + +unsafe impl Send for FileDescriptor {} + +impl Drop for FileDescriptor { + fn drop(&mut self) { + if self.handle != INVALID_HANDLE_VALUE && !self.handle.is_null() { + unsafe { CloseHandle(self.handle) }; + } + } +} + +fn dup_handle(handle: HANDLE) -> Fallible { + if handle == INVALID_HANDLE_VALUE || handle.is_null() { + return Ok(FileDescriptor { handle: handle }); + } + + let proc = unsafe { GetCurrentProcess() }; + let mut duped = INVALID_HANDLE_VALUE; + let ok = unsafe { + DuplicateHandle( + proc, + handle as *mut _, + proc, + &mut duped, + 0, + 0, + winapi::um::winnt::DUPLICATE_SAME_ACCESS, + ) + }; + if ok == 0 { + Err(IoError::last_os_error().into()) + } else { + Ok(FileDescriptor { + handle: duped as *mut _, + }) + } +} + +pub fn dup(f: F) -> Fallible { + dup_handle(f.as_raw_handle()) +} + +impl FileDescriptor { + pub fn new(handle: HANDLE) -> Self { + Self { handle } + } + + pub fn try_clone(&self) -> Fallible { + dup_handle(self.handle) + } + pub fn as_stdio(&self) -> Fallible { + let duped = dup_handle(self.handle)?; + let handle = duped.handle; + let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; + std::mem::forget(duped); // don't drop; stdio now owns it + Ok(stdio) + } + pub fn pipe() -> Fallible { + let mut read: HANDLE = INVALID_HANDLE_VALUE; + let mut write: HANDLE = INVALID_HANDLE_VALUE; + if unsafe { CreatePipe(&mut read, &mut write, ptr::null_mut(), 0) } == 0 { + bail!("CreatePipe failed: {}", IoError::last_os_error()); + } + Ok(Pipes { + read: FileDescriptor { handle: read }, + write: FileDescriptor { handle: write }, + }) + } + pub fn dup(f: F) -> Fallible { + dup(f) + } +} + +impl io::Read for FileDescriptor { + fn read(&mut self, buf: &mut [u8]) -> Result { + let mut num_read = 0; + let ok = unsafe { + ReadFile( + self.handle as *mut _, + buf.as_mut_ptr() as *mut _, + buf.len() as u32, + &mut num_read, + ptr::null_mut(), + ) + }; + if ok == 0 { + Err(IoError::last_os_error()) + } else { + Ok(num_read as usize) + } + } +} + +impl io::Write for FileDescriptor { + fn write(&mut self, buf: &[u8]) -> Result { + let mut num_wrote = 0; + let ok = unsafe { + WriteFile( + self.handle as *mut _, + buf.as_ptr() as *const _, + buf.len() as u32, + &mut num_wrote, + ptr::null_mut(), + ) + }; + if ok == 0 { + Err(IoError::last_os_error()) + } else { + Ok(num_wrote as usize) + } + } + fn flush(&mut self) -> Result<(), io::Error> { + Ok(()) + } +} From c40af4312a94b46edc774fb7f622bea3257768be Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 18 May 2019 17:10:55 -0700 Subject: [PATCH 05/34] basically functioning on windows (missing some basic builtins like echo though!) --- filedescriptor/src/windows.rs | 60 ++++++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index b8ab0ea2c..d3f52824f 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -14,13 +14,13 @@ pub trait AsRawFileDescriptor: AsRawHandle {} impl AsRawFileDescriptor for T {} #[derive(Debug)] -pub struct FileDescriptor { - pub handle: HANDLE, +pub struct OwnedHandle { + handle: HANDLE, } -unsafe impl Send for FileDescriptor {} +unsafe impl Send for OwnedHandle {} -impl Drop for FileDescriptor { +impl Drop for OwnedHandle { fn drop(&mut self) { if self.handle != INVALID_HANDLE_VALUE && !self.handle.is_null() { unsafe { CloseHandle(self.handle) }; @@ -28,9 +28,30 @@ impl Drop for FileDescriptor { } } -fn dup_handle(handle: HANDLE) -> Fallible { +impl OwnedHandle { + pub fn new(handle: HANDLE) -> Self { + Self { handle } + } + + pub fn try_clone(&self) -> Fallible { + dup_handle(self.handle) + } +} + +impl AsRawHandle for OwnedHandle { + fn as_raw_handle(&self) -> HANDLE { + self.handle + } +} + +#[derive(Debug)] +pub struct FileDescriptor { + handle: OwnedHandle, +} + +fn dup_handle(handle: HANDLE) -> Fallible { if handle == INVALID_HANDLE_VALUE || handle.is_null() { - return Ok(FileDescriptor { handle: handle }); + return Ok(OwnedHandle::new(handle)); } let proc = unsafe { GetCurrentProcess() }; @@ -49,31 +70,36 @@ fn dup_handle(handle: HANDLE) -> Fallible { if ok == 0 { Err(IoError::last_os_error().into()) } else { - Ok(FileDescriptor { + Ok(OwnedHandle { handle: duped as *mut _, }) } } pub fn dup(f: F) -> Fallible { - dup_handle(f.as_raw_handle()) + dup_handle(f.as_raw_handle()).map(|handle| FileDescriptor { handle }) } impl FileDescriptor { pub fn new(handle: HANDLE) -> Self { - Self { handle } + Self { + handle: OwnedHandle::new(handle), + } } pub fn try_clone(&self) -> Fallible { - dup_handle(self.handle) + self.handle + .try_clone() + .map(|handle| FileDescriptor { handle }) } pub fn as_stdio(&self) -> Fallible { - let duped = dup_handle(self.handle)?; + let duped = self.handle.try_clone()?; let handle = duped.handle; let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; std::mem::forget(duped); // don't drop; stdio now owns it Ok(stdio) } + pub fn pipe() -> Fallible { let mut read: HANDLE = INVALID_HANDLE_VALUE; let mut write: HANDLE = INVALID_HANDLE_VALUE; @@ -81,8 +107,12 @@ impl FileDescriptor { bail!("CreatePipe failed: {}", IoError::last_os_error()); } Ok(Pipes { - read: FileDescriptor { handle: read }, - write: FileDescriptor { handle: write }, + read: FileDescriptor { + handle: OwnedHandle::new(read), + }, + write: FileDescriptor { + handle: OwnedHandle::new(write), + }, }) } pub fn dup(f: F) -> Fallible { @@ -95,7 +125,7 @@ impl io::Read for FileDescriptor { let mut num_read = 0; let ok = unsafe { ReadFile( - self.handle as *mut _, + self.handle.as_raw_handle() as *mut _, buf.as_mut_ptr() as *mut _, buf.len() as u32, &mut num_read, @@ -115,7 +145,7 @@ impl io::Write for FileDescriptor { let mut num_wrote = 0; let ok = unsafe { WriteFile( - self.handle as *mut _, + self.handle.as_raw_handle() as *mut _, buf.as_ptr() as *const _, buf.len() as u32, &mut num_wrote, From abdb48469ff3a93a8b5e2c88f261c545e131c945 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 07:10:31 -0700 Subject: [PATCH 06/34] tidy up raw handle conversions for filedescriptor --- filedescriptor/src/windows.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index d3f52824f..920c5a9fe 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -44,6 +44,14 @@ impl AsRawHandle for OwnedHandle { } } +impl IntoRawHandle for OwnedHandle { + fn into_raw_handle(self) -> HANDLE { + let handle = self.handle; + std::mem::forget(self); + handle + } +} + #[derive(Debug)] pub struct FileDescriptor { handle: OwnedHandle, @@ -92,11 +100,11 @@ impl FileDescriptor { .try_clone() .map(|handle| FileDescriptor { handle }) } + pub fn as_stdio(&self) -> Fallible { let duped = self.handle.try_clone()?; - let handle = duped.handle; + let handle = duped.into_raw_handle(); let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; - std::mem::forget(duped); // don't drop; stdio now owns it Ok(stdio) } @@ -120,6 +128,18 @@ impl FileDescriptor { } } +impl IntoRawHandle for FileDescriptor { + fn into_raw_handle(self) -> HANDLE { + self.handle.into_raw_handle() + } +} + +impl AsRawHandle for FileDescriptor { + fn as_raw_handle(&self) -> HANDLE { + self.handle.as_raw_handle() + } +} + impl io::Read for FileDescriptor { fn read(&mut self, buf: &mut [u8]) -> Result { let mut num_read = 0; From a444047e228283d0323ad853e100a341c9347f4c Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 07:51:43 -0700 Subject: [PATCH 07/34] tidy up FileDescriptor safety and interface --- filedescriptor/src/lib.rs | 12 +++++++ filedescriptor/src/unix.rs | 44 ++++++++++++++++++------ filedescriptor/src/windows.rs | 63 ++++++++++++++++++++++++++--------- 3 files changed, 93 insertions(+), 26 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index d7b9bf881..80ba2d3bf 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -8,6 +8,18 @@ mod windows; #[cfg(windows)] pub use crate::windows::*; +pub trait AsRawFileDescriptor { + fn as_raw_file_descriptor(&self) -> RawFileDescriptor; +} + +pub trait IntoRawFileDescriptor { + fn into_raw_file_descriptor(self) -> RawFileDescriptor; +} + +pub trait FromRawFileDescriptor { + unsafe fn from_raw_file_descrptor(fd: RawFileDescriptor) -> Self; +} + pub struct Pipes { pub read: FileDescriptor, pub write: FileDescriptor, diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 7fb65b8c9..fc8b561da 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -1,10 +1,26 @@ -use crate::Pipes; +use crate::{AsRawFileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, Pipes}; use failure::{bail, Fallible}; use std::os::unix::prelude::*; -pub trait AsRawFileDescriptor: AsRawFd {} +pub type RawFileDescriptor = RawFd; -impl AsRawFileDescriptor for T {} +impl AsRawFileDescriptor for T { + fn as_raw_file_descriptor(&self) -> RawFileDescriptor { + self.as_raw_fd() + } +} + +impl IntoRawFileDescriptor for T { + fn into_raw_file_descriptor(self) -> RawFileDescriptor { + self.into_raw_fd() + } +} + +impl FromRawFileDescriptor for T { + unsafe fn from_raw_file_descrptor(fd: RawFileDescriptor) -> Self { + Self::from_raw_fd(fd) + } +} #[derive(Debug)] pub struct FileDescriptor { @@ -56,7 +72,8 @@ impl AsRawFd for &FileDescriptor { } } -fn dup_fd(fd: RawFd) -> Fallible { +fn dup_fd(fd: &F) -> Fallible { + let fd = fd.as_raw_file_descriptor(); let duped = unsafe { libc::dup(fd) }; if duped == -1 { bail!( @@ -71,17 +88,24 @@ fn dup_fd(fd: RawFd) -> Fallible { } } -pub fn dup(f: F) -> Fallible { - dup_fd(f.as_raw_fd()) +impl FromRawFd for FileDescriptor { + unsafe fn from_raw_fd(fd: RawFd) -> Self { + FileDescriptor { fd } + } } impl FileDescriptor { - pub fn dup(f: F) -> Fallible { - dup(f) + pub fn new(f: F) -> Self { + let fd = f.into_raw_file_descriptor(); + Self { fd } + } + + pub fn dup(f: &F) -> Fallible { + dup_fd(f) } pub fn try_clone(&self) -> Fallible { - dup(self) + dup_fd(self) } pub fn pipe() -> Fallible { @@ -121,7 +145,7 @@ impl FileDescriptor { } pub fn as_stdio(&self) -> Fallible { - let duped = dup_fd(self.fd)?; + let duped = dup_fd(self)?; let fd = duped.fd; let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; std::mem::forget(duped); // don't drop; stdio now owns it diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 920c5a9fe..392ee5d75 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -1,4 +1,4 @@ -use crate::Pipes; +use crate::{AsRawFileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, Pipes}; use failure::{bail, Fallible}; use std::io::{self, Error as IoError}; use std::os::windows::prelude::*; @@ -9,13 +9,29 @@ use winapi::um::handleapi::*; use winapi::um::namedpipeapi::CreatePipe; use winapi::um::processthreadsapi::*; -pub trait AsRawFileDescriptor: AsRawHandle {} +pub type RawFileDescriptor = RawHandle; -impl AsRawFileDescriptor for T {} +impl AsRawFileDescriptor for T { + fn as_raw_file_descriptor(&self) -> RawFileDescriptor { + self.as_raw_handle() + } +} + +impl IntoRawFileDescriptor for T { + fn into_raw_file_descriptor(self) -> RawFileDescriptor { + self.into_raw_handle() + } +} + +impl FromRawFileDescriptor for T { + unsafe fn from_raw_file_descrptor(handle: RawHandle) -> Self { + Self::from_raw_handle(handle) + } +} #[derive(Debug)] pub struct OwnedHandle { - handle: HANDLE, + handle: RawHandle, } unsafe impl Send for OwnedHandle {} @@ -28,11 +44,22 @@ impl Drop for OwnedHandle { } } +impl FromRawHandle for OwnedHandle { + unsafe fn from_raw_handle(handle: RawHandle) -> Self { + OwnedHandle { handle } + } +} + impl OwnedHandle { - pub fn new(handle: HANDLE) -> Self { + pub fn new(f: F) -> Self { + let handle = f.into_raw_file_descriptor(); Self { handle } } + pub fn dup(f: &F) -> Fallible { + dup_handle(f.as_raw_file_descriptor()) + } + pub fn try_clone(&self) -> Fallible { dup_handle(self.handle) } @@ -59,7 +86,7 @@ pub struct FileDescriptor { fn dup_handle(handle: HANDLE) -> Fallible { if handle == INVALID_HANDLE_VALUE || handle.is_null() { - return Ok(OwnedHandle::new(handle)); + return Ok(OwnedHandle { handle }); } let proc = unsafe { GetCurrentProcess() }; @@ -84,15 +111,18 @@ fn dup_handle(handle: HANDLE) -> Fallible { } } -pub fn dup(f: F) -> Fallible { - dup_handle(f.as_raw_handle()).map(|handle| FileDescriptor { handle }) +impl FromRawHandle for FileDescriptor { + unsafe fn from_raw_handle(handle: RawHandle) -> FileDescriptor { + Self { + handle: OwnedHandle::from_raw_handle(handle), + } + } } impl FileDescriptor { - pub fn new(handle: HANDLE) -> Self { - Self { - handle: OwnedHandle::new(handle), - } + pub fn new(f: F) -> Self { + let handle = OwnedHandle::new(f); + Self { handle } } pub fn try_clone(&self) -> Fallible { @@ -116,15 +146,16 @@ impl FileDescriptor { } Ok(Pipes { read: FileDescriptor { - handle: OwnedHandle::new(read), + handle: OwnedHandle { handle: read }, }, write: FileDescriptor { - handle: OwnedHandle::new(write), + handle: OwnedHandle { handle: write }, }, }) } - pub fn dup(f: F) -> Fallible { - dup(f) + + pub fn dup(f: &F) -> Fallible { + dup_handle(f.as_raw_file_descriptor()).map(|handle| FileDescriptor { handle }) } } From 9a9fdd5e96d056b1b22c6bd73fa6e934c7c1e888 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 08:15:35 -0700 Subject: [PATCH 08/34] add OwnedHandle concept to the unix flavor of filedescriptor Not strictly needed, but improvess symmetry with the windows flavor. --- filedescriptor/src/unix.rs | 164 +++++++++++++++++++++++-------------- 1 file changed, 103 insertions(+), 61 deletions(-) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index fc8b561da..b6a0c2c2c 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -22,14 +22,94 @@ impl FromRawFileDescriptor for T { } } +#[derive(Debug)] +pub struct OwnedHandle { + handle: RawFileDescriptor, +} + +impl Drop for OwnedHandle { + fn drop(&mut self) { + unsafe { + libc::close(self.handle); + } + } +} + +impl AsRawFd for OwnedHandle { + fn as_raw_fd(&self) -> RawFd { + self.handle + } +} + +impl IntoRawFd for OwnedHandle { + fn into_raw_fd(self) -> RawFd { + let fd = self.handle; + std::mem::forget(self); + fd + } +} + +impl FromRawFd for OwnedHandle { + unsafe fn from_raw_fd(fd: RawFd) -> Self { + Self { handle: fd } + } +} + +impl OwnedHandle { + /// Helper function to set the close-on-exec flag for a raw descriptor + fn cloexec(&mut self) -> Fallible<()> { + let flags = unsafe { libc::fcntl(self.handle, libc::F_GETFD) }; + if flags == -1 { + bail!( + "fcntl to read flags failed: {:?}", + std::io::Error::last_os_error() + ); + } + let result = unsafe { libc::fcntl(self.handle, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; + if result == -1 { + bail!( + "fcntl to set CLOEXEC failed: {:?}", + std::io::Error::last_os_error() + ); + } + Ok(()) + } + + pub fn new(f: F) -> Self { + Self { + handle: f.into_raw_file_descriptor(), + } + } + + pub fn dup(fd: &F) -> Fallible { + let fd = fd.as_raw_file_descriptor(); + let duped = unsafe { libc::dup(fd) }; + if duped == -1 { + bail!( + "dup of fd {} failed: {:?}", + fd, + std::io::Error::last_os_error() + ) + } else { + let mut owned = OwnedHandle { handle: duped }; + owned.cloexec()?; + Ok(owned) + } + } + + pub fn try_clone(&self) -> Fallible { + Self::dup(self) + } +} + #[derive(Debug)] pub struct FileDescriptor { - fd: RawFd, + fd: OwnedHandle, } impl std::io::Read for FileDescriptor { fn read(&mut self, buf: &mut [u8]) -> Result { - let size = unsafe { libc::read(self.fd, buf.as_mut_ptr() as *mut _, buf.len()) }; + let size = unsafe { libc::read(self.fd.handle, buf.as_mut_ptr() as *mut _, buf.len()) }; if size == -1 { Err(std::io::Error::last_os_error()) } else { @@ -40,7 +120,7 @@ impl std::io::Read for FileDescriptor { impl std::io::Write for FileDescriptor { fn write(&mut self, buf: &[u8]) -> Result { - let size = unsafe { libc::write(self.fd, buf.as_ptr() as *const _, buf.len()) }; + let size = unsafe { libc::write(self.fd.handle, buf.as_ptr() as *const _, buf.len()) }; if size == -1 { Err(std::io::Error::last_os_error()) } else { @@ -52,60 +132,38 @@ impl std::io::Write for FileDescriptor { } } -impl Drop for FileDescriptor { - fn drop(&mut self) { - unsafe { - libc::close(self.fd); - } - } -} - impl AsRawFd for FileDescriptor { fn as_raw_fd(&self) -> RawFd { - self.fd + self.fd.as_raw_fd() } } -impl AsRawFd for &FileDescriptor { - fn as_raw_fd(&self) -> RawFd { - self.fd - } -} - -fn dup_fd(fd: &F) -> Fallible { - let fd = fd.as_raw_file_descriptor(); - let duped = unsafe { libc::dup(fd) }; - if duped == -1 { - bail!( - "dup of fd {} failed: {:?}", - fd, - std::io::Error::last_os_error() - ) - } else { - let mut owned = FileDescriptor { fd: duped }; - owned.cloexec()?; - Ok(owned) +impl IntoRawFd for FileDescriptor { + fn into_raw_fd(self) -> RawFd { + self.fd.into_raw_fd() } } impl FromRawFd for FileDescriptor { unsafe fn from_raw_fd(fd: RawFd) -> Self { - FileDescriptor { fd } + Self { + fd: OwnedHandle::from_raw_fd(fd), + } } } impl FileDescriptor { pub fn new(f: F) -> Self { - let fd = f.into_raw_file_descriptor(); + let fd = OwnedHandle::new(f); Self { fd } } pub fn dup(f: &F) -> Fallible { - dup_fd(f) + OwnedHandle::dup(f).map(|fd| Self { fd }) } pub fn try_clone(&self) -> Fallible { - dup_fd(self) + self.fd.try_clone().map(|fd| Self { fd }) } pub fn pipe() -> Fallible { @@ -117,38 +175,22 @@ impl FileDescriptor { std::io::Error::last_os_error() ) } else { - let mut read = FileDescriptor { fd: fds[0] }; - let mut write = FileDescriptor { fd: fds[1] }; - read.cloexec()?; - write.cloexec()?; + let mut read = FileDescriptor { + fd: OwnedHandle { handle: fds[0] }, + }; + let mut write = FileDescriptor { + fd: OwnedHandle { handle: fds[1] }, + }; + read.fd.cloexec()?; + write.fd.cloexec()?; Ok(Pipes { read, write }) } } - /// Helper function to set the close-on-exec flag for a raw descriptor - fn cloexec(&mut self) -> Fallible<()> { - let flags = unsafe { libc::fcntl(self.fd, libc::F_GETFD) }; - if flags == -1 { - bail!( - "fcntl to read flags failed: {:?}", - std::io::Error::last_os_error() - ); - } - let result = unsafe { libc::fcntl(self.fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) }; - if result == -1 { - bail!( - "fcntl to set CLOEXEC failed: {:?}", - std::io::Error::last_os_error() - ); - } - Ok(()) - } - pub fn as_stdio(&self) -> Fallible { - let duped = dup_fd(self)?; - let fd = duped.fd; + let duped = OwnedHandle::dup(self)?; + let fd = duped.into_raw_fd(); let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; - std::mem::forget(duped); // don't drop; stdio now owns it Ok(stdio) } } From ed4a6053552a434be00718fd389f7ad82099129e Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 08:21:35 -0700 Subject: [PATCH 09/34] rename FileDescript::fd -> handle on unix --- filedescriptor/src/unix.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index b6a0c2c2c..88aab8c39 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -104,12 +104,12 @@ impl OwnedHandle { #[derive(Debug)] pub struct FileDescriptor { - fd: OwnedHandle, + handle: OwnedHandle, } impl std::io::Read for FileDescriptor { fn read(&mut self, buf: &mut [u8]) -> Result { - let size = unsafe { libc::read(self.fd.handle, buf.as_mut_ptr() as *mut _, buf.len()) }; + let size = unsafe { libc::read(self.handle.handle, buf.as_mut_ptr() as *mut _, buf.len()) }; if size == -1 { Err(std::io::Error::last_os_error()) } else { @@ -120,7 +120,7 @@ impl std::io::Read for FileDescriptor { impl std::io::Write for FileDescriptor { fn write(&mut self, buf: &[u8]) -> Result { - let size = unsafe { libc::write(self.fd.handle, buf.as_ptr() as *const _, buf.len()) }; + let size = unsafe { libc::write(self.handle.handle, buf.as_ptr() as *const _, buf.len()) }; if size == -1 { Err(std::io::Error::last_os_error()) } else { @@ -134,36 +134,36 @@ impl std::io::Write for FileDescriptor { impl AsRawFd for FileDescriptor { fn as_raw_fd(&self) -> RawFd { - self.fd.as_raw_fd() + self.handle.as_raw_fd() } } impl IntoRawFd for FileDescriptor { fn into_raw_fd(self) -> RawFd { - self.fd.into_raw_fd() + self.handle.into_raw_fd() } } impl FromRawFd for FileDescriptor { unsafe fn from_raw_fd(fd: RawFd) -> Self { Self { - fd: OwnedHandle::from_raw_fd(fd), + handle: OwnedHandle::from_raw_fd(fd), } } } impl FileDescriptor { pub fn new(f: F) -> Self { - let fd = OwnedHandle::new(f); - Self { fd } + let handle = OwnedHandle::new(f); + Self { handle } } pub fn dup(f: &F) -> Fallible { - OwnedHandle::dup(f).map(|fd| Self { fd }) + OwnedHandle::dup(f).map(|handle| Self { handle }) } pub fn try_clone(&self) -> Fallible { - self.fd.try_clone().map(|fd| Self { fd }) + self.handle.try_clone().map(|handle| Self { handle }) } pub fn pipe() -> Fallible { @@ -176,13 +176,13 @@ impl FileDescriptor { ) } else { let mut read = FileDescriptor { - fd: OwnedHandle { handle: fds[0] }, + handle: OwnedHandle { handle: fds[0] }, }; let mut write = FileDescriptor { - fd: OwnedHandle { handle: fds[1] }, + handle: OwnedHandle { handle: fds[1] }, }; - read.fd.cloexec()?; - write.fd.cloexec()?; + read.handle.cloexec()?; + write.handle.cloexec()?; Ok(Pipes { read, write }) } } From 0f83309b585ed6a0a382f478e3caa11cedeba2c4 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 08:40:38 -0700 Subject: [PATCH 10/34] centralize/share some filedescriptor bits --- filedescriptor/src/lib.rs | 38 ++++++++++++ filedescriptor/src/unix.rs | 38 ++---------- filedescriptor/src/windows.rs | 106 ++++++++++++---------------------- 3 files changed, 78 insertions(+), 104 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 80ba2d3bf..b49ddc347 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -1,3 +1,4 @@ +use failure::Fallible; #[cfg(unix)] mod unix; #[cfg(unix)] @@ -20,7 +21,44 @@ pub trait FromRawFileDescriptor { unsafe fn from_raw_file_descrptor(fd: RawFileDescriptor) -> Self; } +#[derive(Debug)] +pub struct OwnedHandle { + handle: RawFileDescriptor, +} + +impl OwnedHandle { + pub fn new(f: F) -> Self { + Self { + handle: f.into_raw_file_descriptor(), + } + } + + pub fn try_clone(&self) -> Fallible { + Self::dup(self) + } +} + +#[derive(Debug)] +pub struct FileDescriptor { + handle: OwnedHandle, +} + pub struct Pipes { pub read: FileDescriptor, pub write: FileDescriptor, } + +impl FileDescriptor { + pub fn new(f: F) -> Self { + let handle = OwnedHandle::new(f); + Self { handle } + } + + pub fn dup(f: &F) -> Fallible { + OwnedHandle::dup(f).map(|handle| Self { handle }) + } + + pub fn try_clone(&self) -> Fallible { + self.handle.try_clone().map(|handle| Self { handle }) + } +} diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 88aab8c39..4627ebb0b 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -1,4 +1,7 @@ -use crate::{AsRawFileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, Pipes}; +use crate::{ + AsRawFileDescriptor, FileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, OwnedHandle, + Pipes, +}; use failure::{bail, Fallible}; use std::os::unix::prelude::*; @@ -22,11 +25,6 @@ impl FromRawFileDescriptor for T { } } -#[derive(Debug)] -pub struct OwnedHandle { - handle: RawFileDescriptor, -} - impl Drop for OwnedHandle { fn drop(&mut self) { unsafe { @@ -75,12 +73,6 @@ impl OwnedHandle { Ok(()) } - pub fn new(f: F) -> Self { - Self { - handle: f.into_raw_file_descriptor(), - } - } - pub fn dup(fd: &F) -> Fallible { let fd = fd.as_raw_file_descriptor(); let duped = unsafe { libc::dup(fd) }; @@ -96,15 +88,6 @@ impl OwnedHandle { Ok(owned) } } - - pub fn try_clone(&self) -> Fallible { - Self::dup(self) - } -} - -#[derive(Debug)] -pub struct FileDescriptor { - handle: OwnedHandle, } impl std::io::Read for FileDescriptor { @@ -153,19 +136,6 @@ impl FromRawFd for FileDescriptor { } impl FileDescriptor { - pub fn new(f: F) -> Self { - let handle = OwnedHandle::new(f); - Self { handle } - } - - pub fn dup(f: &F) -> Fallible { - OwnedHandle::dup(f).map(|handle| Self { handle }) - } - - pub fn try_clone(&self) -> Fallible { - self.handle.try_clone().map(|handle| Self { handle }) - } - pub fn pipe() -> Fallible { let mut fds = [-1i32; 2]; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 392ee5d75..b9ead60f3 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -1,4 +1,7 @@ -use crate::{AsRawFileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, Pipes}; +use crate::{ + AsRawFileDescriptor, FileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, OwnedHandle, + Pipes, +}; use failure::{bail, Fallible}; use std::io::{self, Error as IoError}; use std::os::windows::prelude::*; @@ -29,11 +32,6 @@ impl FromRawFileDescriptor for T { } } -#[derive(Debug)] -pub struct OwnedHandle { - handle: RawHandle, -} - unsafe impl Send for OwnedHandle {} impl Drop for OwnedHandle { @@ -51,17 +49,32 @@ impl FromRawHandle for OwnedHandle { } impl OwnedHandle { - pub fn new(f: F) -> Self { - let handle = f.into_raw_file_descriptor(); - Self { handle } - } - pub fn dup(f: &F) -> Fallible { - dup_handle(f.as_raw_file_descriptor()) - } + let handle = f.as_raw_file_descriptor(); + if handle == INVALID_HANDLE_VALUE || handle.is_null() { + return Ok(OwnedHandle { handle }); + } - pub fn try_clone(&self) -> Fallible { - dup_handle(self.handle) + let proc = unsafe { GetCurrentProcess() }; + let mut duped = INVALID_HANDLE_VALUE; + let ok = unsafe { + DuplicateHandle( + proc, + handle as *mut _, + proc, + &mut duped, + 0, + 0, + winapi::um::winnt::DUPLICATE_SAME_ACCESS, + ) + }; + if ok == 0 { + Err(IoError::last_os_error().into()) + } else { + Ok(OwnedHandle { + handle: duped as *mut _, + }) + } } } @@ -79,58 +92,7 @@ impl IntoRawHandle for OwnedHandle { } } -#[derive(Debug)] -pub struct FileDescriptor { - handle: OwnedHandle, -} - -fn dup_handle(handle: HANDLE) -> Fallible { - if handle == INVALID_HANDLE_VALUE || handle.is_null() { - return Ok(OwnedHandle { handle }); - } - - let proc = unsafe { GetCurrentProcess() }; - let mut duped = INVALID_HANDLE_VALUE; - let ok = unsafe { - DuplicateHandle( - proc, - handle as *mut _, - proc, - &mut duped, - 0, - 0, - winapi::um::winnt::DUPLICATE_SAME_ACCESS, - ) - }; - if ok == 0 { - Err(IoError::last_os_error().into()) - } else { - Ok(OwnedHandle { - handle: duped as *mut _, - }) - } -} - -impl FromRawHandle for FileDescriptor { - unsafe fn from_raw_handle(handle: RawHandle) -> FileDescriptor { - Self { - handle: OwnedHandle::from_raw_handle(handle), - } - } -} - impl FileDescriptor { - pub fn new(f: F) -> Self { - let handle = OwnedHandle::new(f); - Self { handle } - } - - pub fn try_clone(&self) -> Fallible { - self.handle - .try_clone() - .map(|handle| FileDescriptor { handle }) - } - pub fn as_stdio(&self) -> Fallible { let duped = self.handle.try_clone()?; let handle = duped.into_raw_handle(); @@ -153,10 +115,6 @@ impl FileDescriptor { }, }) } - - pub fn dup(f: &F) -> Fallible { - dup_handle(f.as_raw_file_descriptor()).map(|handle| FileDescriptor { handle }) - } } impl IntoRawHandle for FileDescriptor { @@ -171,6 +129,14 @@ impl AsRawHandle for FileDescriptor { } } +impl FromRawHandle for FileDescriptor { + unsafe fn from_raw_handle(handle: RawHandle) -> FileDescriptor { + Self { + handle: OwnedHandle::from_raw_handle(handle), + } + } +} + impl io::Read for FileDescriptor { fn read(&mut self, buf: &mut [u8]) -> Result { let mut num_read = 0; From 143617155e1d72b3613882ec6a7a8fcf50addf82 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 09:04:47 -0700 Subject: [PATCH 11/34] filedescriptor: add some doc comments --- filedescriptor/src/lib.rs | 83 ++++++++++++++++++++++++++++------- filedescriptor/src/unix.rs | 6 ++- filedescriptor/src/windows.rs | 6 ++- 3 files changed, 78 insertions(+), 17 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index b49ddc347..1fe09f1eb 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -9,56 +9,109 @@ mod windows; #[cfg(windows)] pub use crate::windows::*; +/// `AsRawFileDescriptor` is a platform independent trait for returning +/// a non-owning reference to the underlying platform file descriptor +/// type. pub trait AsRawFileDescriptor { fn as_raw_file_descriptor(&self) -> RawFileDescriptor; } +/// `IntoRawFileDescriptor` is a platform independent trait for converting +/// an instance into the underlying platform file descriptor type. pub trait IntoRawFileDescriptor { fn into_raw_file_descriptor(self) -> RawFileDescriptor; } +/// `FromRawFileDescriptor` is a platform independent trait for creating +/// an instance from the underlying platform file descriptor type. +/// Because the platform file descriptor type has no inherent ownership +/// management, the `from_raw_file_descrptor` function is marked as unsafe +/// to indicate that care must be taken by the caller to ensure that it +/// is used appropriately. pub trait FromRawFileDescriptor { unsafe fn from_raw_file_descrptor(fd: RawFileDescriptor) -> Self; } +/// `OwnedHandle` allows managing the lifetime of the platform `RawFileDescriptor` +/// type. It is exposed in the interface of this crate primarily for convenience +/// on Windows where the system handle type is used for a variety of objects +/// that don't support reading and writing. #[derive(Debug)] pub struct OwnedHandle { handle: RawFileDescriptor, } impl OwnedHandle { + /// Create a new handle from some object that is convertible into + /// the system `RawFileDescriptor` type. This consumes the parameter + /// and replaces it with an `OwnedHandle` instance. pub fn new(f: F) -> Self { Self { handle: f.into_raw_file_descriptor(), } } + /// Attempt to duplicate the underlying handle and return an + /// `OwnedHandle` wrapped around the duplicate. Since the duplication + /// requires kernel resources that may not be available, this is a + /// potentially fallible operation. + /// The returned handle has a separate lifetime from the source, but + /// references the same object at the kernel level. pub fn try_clone(&self) -> Fallible { Self::dup(self) } + + /// Attempt to duplicate the underlying handle from an object that is + /// representable as the systemm `RawFileDescriptor` type and return an + /// `OwnedHandle` wrapped around the duplicate. Since the duplication + /// requires kernel resources that may not be available, this is a + /// potentially fallible operation. + /// The returned handle has a separate lifetime from the source, but + /// references the same object at the kernel level. + pub fn dup(f: &F) -> Fallible { + Self::dup_impl(f) + } } +/// `FileDescriptor` is a thin wrapper on top of the `OwnedHandle` type that +/// exposes the ability to Read and Write to the platform `RawFileDescriptor`. #[derive(Debug)] pub struct FileDescriptor { handle: OwnedHandle, } +impl FileDescriptor { + /// Create a new descriptor from some object that is convertible into + /// the system `RawFileDescriptor` type. This consumes the parameter + /// and replaces it with a `FileDescriptor` instance. + pub fn new(f: F) -> Self { + let handle = OwnedHandle::new(f); + Self { handle } + } + + /// Attempt to duplicate the underlying handle from an object that is + /// representable as the systemm `RawFileDescriptor` type and return a + /// `FileDescriptor` wrapped around the duplicate. Since the duplication + /// requires kernel resources that may not be available, this is a + /// potentially fallible operation. + /// The returned handle has a separate lifetime from the source, but + /// references the same object at the kernel level. + pub fn dup(f: &F) -> Fallible { + OwnedHandle::dup(f).map(|handle| Self { handle }) + } + + /// Attempt to duplicate the underlying handle and return a + /// `FileDescriptor` wrapped around the duplicate. Since the duplication + /// requires kernel resources that may not be available, this is a + /// potentially fallible operation. + /// The returned handle has a separate lifetime from the source, but + /// references the same object at the kernel level. + pub fn try_clone(&self) -> Fallible { + self.handle.try_clone().map(|handle| Self { handle }) + } +} + pub struct Pipes { pub read: FileDescriptor, pub write: FileDescriptor, } - -impl FileDescriptor { - pub fn new(f: F) -> Self { - let handle = OwnedHandle::new(f); - Self { handle } - } - - pub fn dup(f: &F) -> Fallible { - OwnedHandle::dup(f).map(|handle| Self { handle }) - } - - pub fn try_clone(&self) -> Fallible { - self.handle.try_clone().map(|handle| Self { handle }) - } -} diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 4627ebb0b..ca1c6ba9a 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -5,6 +5,9 @@ use crate::{ use failure::{bail, Fallible}; use std::os::unix::prelude::*; +/// `RawFileDescriptor` is a platform independent type alias for the +/// underlying platform file descriptor type. It is primarily useful +/// for avoiding using `cfg` blocks in platform independent code. pub type RawFileDescriptor = RawFd; impl AsRawFileDescriptor for T { @@ -73,7 +76,8 @@ impl OwnedHandle { Ok(()) } - pub fn dup(fd: &F) -> Fallible { + #[inline] + pub(crate) fn dup_impl(fd: &F) -> Fallible { let fd = fd.as_raw_file_descriptor(); let duped = unsafe { libc::dup(fd) }; if duped == -1 { diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index b9ead60f3..3b6fd586b 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -12,6 +12,9 @@ use winapi::um::handleapi::*; use winapi::um::namedpipeapi::CreatePipe; use winapi::um::processthreadsapi::*; +/// `RawFileDescriptor` is a platform independent type alias for the +/// underlying platform file descriptor type. It is primarily useful +/// for avoiding using `cfg` blocks in platform independent code. pub type RawFileDescriptor = RawHandle; impl AsRawFileDescriptor for T { @@ -49,7 +52,8 @@ impl FromRawHandle for OwnedHandle { } impl OwnedHandle { - pub fn dup(f: &F) -> Fallible { + #[inline] + pub(crate) fn dup_impl(f: &F) -> Fallible { let handle = f.as_raw_file_descriptor(); if handle == INVALID_HANDLE_VALUE || handle.is_null() { return Ok(OwnedHandle { handle }); From ee9b5c7a685f2099fd41c1b33b5439027fd223ce Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 09:14:40 -0700 Subject: [PATCH 12/34] add docs for as_stdio --- filedescriptor/src/lib.rs | 8 ++++++++ filedescriptor/src/unix.rs | 3 ++- filedescriptor/src/windows.rs | 3 ++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 1fe09f1eb..50dcab9ab 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -109,6 +109,14 @@ impl FileDescriptor { pub fn try_clone(&self) -> Fallible { self.handle.try_clone().map(|handle| Self { handle }) } + + /// A convenience method for creating a `std::process::Stdio` object + /// to be used for eg: redirecting the stdio streams of a child + /// process. The `Stdio` is created using a duplicated handle so + /// that the source handle remains alive. + pub fn as_stdio(&self) -> Fallible { + self.as_stdio_impl() + } } pub struct Pipes { diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index ca1c6ba9a..00dd4f87d 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -161,7 +161,8 @@ impl FileDescriptor { } } - pub fn as_stdio(&self) -> Fallible { + #[inline] + pub(crate) fn as_stdio_impl(&self) -> Fallible { let duped = OwnedHandle::dup(self)?; let fd = duped.into_raw_fd(); let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 3b6fd586b..be6d857fc 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -97,7 +97,8 @@ impl IntoRawHandle for OwnedHandle { } impl FileDescriptor { - pub fn as_stdio(&self) -> Fallible { + #[inline] + pub(crate) fn as_stdio_impl(&self) -> Fallible { let duped = self.handle.try_clone()?; let handle = duped.into_raw_handle(); let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; From c0f4e4907d89dae577e65398da4caccb8afab03a Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 09:39:34 -0700 Subject: [PATCH 13/34] Tidy up the Pipe interface --- filedescriptor/src/lib.rs | 4 +++- filedescriptor/src/unix.rs | 24 ++++++++++++----------- filedescriptor/src/windows.rs | 36 ++++++++++++++++++----------------- 3 files changed, 35 insertions(+), 29 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 50dcab9ab..540d6ea3d 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -119,7 +119,9 @@ impl FileDescriptor { } } -pub struct Pipes { +/// Represents the readable and writable ends of a pair of descriptors +/// connected via a kernel pipe. +pub struct Pipe { pub read: FileDescriptor, pub write: FileDescriptor, } diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 00dd4f87d..1a81bb6cf 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -1,6 +1,6 @@ use crate::{ AsRawFileDescriptor, FileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, OwnedHandle, - Pipes, + Pipe, }; use failure::{bail, Fallible}; use std::os::unix::prelude::*; @@ -140,7 +140,17 @@ impl FromRawFd for FileDescriptor { } impl FileDescriptor { - pub fn pipe() -> Fallible { + #[inline] + pub(crate) fn as_stdio_impl(&self) -> Fallible { + let duped = OwnedHandle::dup(self)?; + let fd = duped.into_raw_fd(); + let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; + Ok(stdio) + } +} + +impl Pipe { + pub fn new() -> Fallible { let mut fds = [-1i32; 2]; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; if res == -1 { @@ -157,15 +167,7 @@ impl FileDescriptor { }; read.handle.cloexec()?; write.handle.cloexec()?; - Ok(Pipes { read, write }) + Ok(Pipe { read, write }) } } - - #[inline] - pub(crate) fn as_stdio_impl(&self) -> Fallible { - let duped = OwnedHandle::dup(self)?; - let fd = duped.into_raw_fd(); - let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; - Ok(stdio) - } } diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index be6d857fc..5c0a31123 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -1,6 +1,6 @@ use crate::{ AsRawFileDescriptor, FileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, OwnedHandle, - Pipes, + Pipe, }; use failure::{bail, Fallible}; use std::io::{self, Error as IoError}; @@ -104,22 +104,6 @@ impl FileDescriptor { let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; Ok(stdio) } - - pub fn pipe() -> Fallible { - let mut read: HANDLE = INVALID_HANDLE_VALUE; - let mut write: HANDLE = INVALID_HANDLE_VALUE; - if unsafe { CreatePipe(&mut read, &mut write, ptr::null_mut(), 0) } == 0 { - bail!("CreatePipe failed: {}", IoError::last_os_error()); - } - Ok(Pipes { - read: FileDescriptor { - handle: OwnedHandle { handle: read }, - }, - write: FileDescriptor { - handle: OwnedHandle { handle: write }, - }, - }) - } } impl IntoRawHandle for FileDescriptor { @@ -184,3 +168,21 @@ impl io::Write for FileDescriptor { Ok(()) } } + +impl Pipe { + pub fn new() -> Fallible { + let mut read: HANDLE = INVALID_HANDLE_VALUE; + let mut write: HANDLE = INVALID_HANDLE_VALUE; + if unsafe { CreatePipe(&mut read, &mut write, ptr::null_mut(), 0) } == 0 { + bail!("CreatePipe failed: {}", IoError::last_os_error()); + } + Ok(Pipe { + read: FileDescriptor { + handle: OwnedHandle { handle: read }, + }, + write: FileDescriptor { + handle: OwnedHandle { handle: write }, + }, + }) + } +} From 32389ee980dce058667860f532d112a4d05420af Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 10:09:11 -0700 Subject: [PATCH 14/34] use pipe2() for atomic cloexec on linux --- filedescriptor/src/unix.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 1a81bb6cf..eb692e342 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -150,6 +150,27 @@ impl FileDescriptor { } impl Pipe { + #[cfg(target_os = "linux")] + pub fn new() -> Fallible { + let mut fds = [-1i32; 2]; + let res = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }; + if res == -1 { + bail!( + "failed to create a pipe: {:?}", + std::io::Error::last_os_error() + ) + } else { + let read = FileDescriptor { + handle: OwnedHandle { handle: fds[0] }, + }; + let write = FileDescriptor { + handle: OwnedHandle { handle: fds[1] }, + }; + Ok(Pipe { read, write }) + } + } + + #[cfg(not(target_os = "linux"))] pub fn new() -> Fallible { let mut fds = [-1i32; 2]; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; From b4056f6c96e0db54db7fa6241f85c42587b2e06b Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 10:49:09 -0700 Subject: [PATCH 15/34] potentially support atomic dup on linux I'm testing this under WSL which doesn't seem to support it, so I'm committing this so I can try it on a real linux system. --- filedescriptor/src/unix.rs | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index eb692e342..5863139e6 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -76,9 +76,7 @@ impl OwnedHandle { Ok(()) } - #[inline] - pub(crate) fn dup_impl(fd: &F) -> Fallible { - let fd = fd.as_raw_file_descriptor(); + fn non_atomic_dup(fd: RawFd) -> Fallible { let duped = unsafe { libc::dup(fd) }; if duped == -1 { bail!( @@ -92,6 +90,32 @@ impl OwnedHandle { Ok(owned) } } + + #[inline] + #[cfg(not(target_os = "linux"))] + pub(crate) fn dup_impl(fd: &F) -> Fallible { + let fd = fd.as_raw_file_descriptor(); + Self::non_atomic_dup(fd) + } + + #[inline] + #[cfg(target_os = "linux")] + pub(crate) fn dup_impl(fd: &F) -> Fallible { + let fd = fd.as_raw_file_descriptor(); + let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC) }; + if duped == -1 { + let err = std::io::Error::last_os_error(); + if let Some(libc::EINVAL) = err.raw_os_error() { + // We may be running on eg: WSL or an old kernel that + // doesn't support F_DUPFD_CLOEXEC; fall back. + return Self::non_atomic_dup(fd); + } else { + bail!("dup of fd {} failed: {:?}", fd, err) + } + } else { + Ok(OwnedHandle { handle: duped }) + } + } } impl std::io::Read for FileDescriptor { From ca15d6da1aa3173cc92b2fb5ae26292fbb8dc053 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 10:53:51 -0700 Subject: [PATCH 16/34] explicit comment about not inheriting in DuplicateHandle --- filedescriptor/src/windows.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 5c0a31123..25109a392 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -68,7 +68,7 @@ impl OwnedHandle { proc, &mut duped, 0, - 0, + 0, // not inheritable winapi::um::winnt::DUPLICATE_SAME_ACCESS, ) }; From 135a191b579376527b7e007d9c9643a48417cd41 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 11:54:05 -0700 Subject: [PATCH 17/34] fix F_DUPFD_CLOEXEC usage --- filedescriptor/src/unix.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 5863139e6..305d97e28 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -102,7 +102,7 @@ impl OwnedHandle { #[cfg(target_os = "linux")] pub(crate) fn dup_impl(fd: &F) -> Fallible { let fd = fd.as_raw_file_descriptor(); - let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC) }; + let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }; if duped == -1 { let err = std::io::Error::last_os_error(); if let Some(libc::EINVAL) = err.raw_os_error() { From 0d07c1e6b957a39e89eafb25b7253704cd75c03d Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 11:57:44 -0700 Subject: [PATCH 18/34] F_DUPFD_CLOEXEC is posix, so just assume we have it on unix --- filedescriptor/src/unix.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 305d97e28..e1e1df097 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -92,14 +92,6 @@ impl OwnedHandle { } #[inline] - #[cfg(not(target_os = "linux"))] - pub(crate) fn dup_impl(fd: &F) -> Fallible { - let fd = fd.as_raw_file_descriptor(); - Self::non_atomic_dup(fd) - } - - #[inline] - #[cfg(target_os = "linux")] pub(crate) fn dup_impl(fd: &F) -> Fallible { let fd = fd.as_raw_file_descriptor(); let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }; From a9fd3180951cceb9edccfeaf99fdbd3aac1c09d4 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 19 May 2019 14:27:11 -0700 Subject: [PATCH 19/34] prep for publishing filedescriptor to crates.io --- filedescriptor/Cargo.toml | 5 +++++ filedescriptor/src/lib.rs | 7 +++++++ filedescriptor/src/windows.rs | 24 ++++++++++++------------ 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 130a4ad59..808126699 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -3,6 +3,10 @@ name = "filedescriptor" version = "0.1.0" authors = ["Wez Furlong"] edition = "2018" +repository = "https://github.com/wez/wzsh" +description = "More ergonomic wrappers around RawFd and RawHandle" +license = "MIT" +documentation = "https://docs.rs/filedescriptor" [dependencies] failure = "0.1" @@ -15,4 +19,5 @@ winapi = { version = "0.3", features = [ "handleapi", "fileapi", "namedpipeapi", + "processthreadsapi" ]} diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 540d6ea3d..c2877eccd 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -1,3 +1,10 @@ +//! The purpose of this crate is to make it a bit more ergonomic for portable +//! applications that need to work with the platform level `RawFd` and +//! `RawHandle` types. +//! Rather than conditionally using `RawFd` and `RawHandle`, the `FileDescriptor` +//! type can be used to manage ownership, duplicate, read and write. +//! The `Pipe` type makes it more convenient to create a pipe and manage +//! the lifetime of both the read and write ends of that pipe. use failure::Fallible; #[cfg(unix)] mod unix; diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 25109a392..35ab991d8 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -5,12 +5,12 @@ use crate::{ use failure::{bail, Fallible}; use std::io::{self, Error as IoError}; use std::os::windows::prelude::*; -use std::os::windows::raw::HANDLE; use std::ptr; use winapi::um::fileapi::*; use winapi::um::handleapi::*; use winapi::um::namedpipeapi::CreatePipe; use winapi::um::processthreadsapi::*; +use winapi::um::winnt::HANDLE; /// `RawFileDescriptor` is a platform independent type alias for the /// underlying platform file descriptor type. It is primarily useful @@ -39,8 +39,8 @@ unsafe impl Send for OwnedHandle {} impl Drop for OwnedHandle { fn drop(&mut self) { - if self.handle != INVALID_HANDLE_VALUE && !self.handle.is_null() { - unsafe { CloseHandle(self.handle) }; + if self.handle != INVALID_HANDLE_VALUE as _ && !self.handle.is_null() { + unsafe { CloseHandle(self.handle as _) }; } } } @@ -55,7 +55,7 @@ impl OwnedHandle { #[inline] pub(crate) fn dup_impl(f: &F) -> Fallible { let handle = f.as_raw_file_descriptor(); - if handle == INVALID_HANDLE_VALUE || handle.is_null() { + if handle == INVALID_HANDLE_VALUE as _ || handle.is_null() { return Ok(OwnedHandle { handle }); } @@ -83,13 +83,13 @@ impl OwnedHandle { } impl AsRawHandle for OwnedHandle { - fn as_raw_handle(&self) -> HANDLE { + fn as_raw_handle(&self) -> RawHandle { self.handle } } impl IntoRawHandle for OwnedHandle { - fn into_raw_handle(self) -> HANDLE { + fn into_raw_handle(self) -> RawHandle { let handle = self.handle; std::mem::forget(self); handle @@ -107,13 +107,13 @@ impl FileDescriptor { } impl IntoRawHandle for FileDescriptor { - fn into_raw_handle(self) -> HANDLE { + fn into_raw_handle(self) -> RawHandle { self.handle.into_raw_handle() } } impl AsRawHandle for FileDescriptor { - fn as_raw_handle(&self) -> HANDLE { + fn as_raw_handle(&self) -> RawHandle { self.handle.as_raw_handle() } } @@ -171,17 +171,17 @@ impl io::Write for FileDescriptor { impl Pipe { pub fn new() -> Fallible { - let mut read: HANDLE = INVALID_HANDLE_VALUE; - let mut write: HANDLE = INVALID_HANDLE_VALUE; + let mut read: HANDLE = INVALID_HANDLE_VALUE as _; + let mut write: HANDLE = INVALID_HANDLE_VALUE as _; if unsafe { CreatePipe(&mut read, &mut write, ptr::null_mut(), 0) } == 0 { bail!("CreatePipe failed: {}", IoError::last_os_error()); } Ok(Pipe { read: FileDescriptor { - handle: OwnedHandle { handle: read }, + handle: OwnedHandle { handle: read as _ }, }, write: FileDescriptor { - handle: OwnedHandle { handle: write }, + handle: OwnedHandle { handle: write as _ }, }, }) } From 2e44af7702f9daf314ffd41f9e9fc8ec082c598a Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 21 May 2019 00:11:12 -0700 Subject: [PATCH 20/34] filedescriptor: pipes should not be inheritable on windows --- filedescriptor/src/windows.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 35ab991d8..2083e161b 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -8,6 +8,7 @@ use std::os::windows::prelude::*; use std::ptr; use winapi::um::fileapi::*; use winapi::um::handleapi::*; +use winapi::um::minwinbase::SECURITY_ATTRIBUTES; use winapi::um::namedpipeapi::CreatePipe; use winapi::um::processthreadsapi::*; use winapi::um::winnt::HANDLE; @@ -171,9 +172,14 @@ impl io::Write for FileDescriptor { impl Pipe { pub fn new() -> Fallible { + let mut sa = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: ptr::null_mut(), + bInheritHandle: 0, + }; let mut read: HANDLE = INVALID_HANDLE_VALUE as _; let mut write: HANDLE = INVALID_HANDLE_VALUE as _; - if unsafe { CreatePipe(&mut read, &mut write, ptr::null_mut(), 0) } == 0 { + if unsafe { CreatePipe(&mut read, &mut write, &mut sa, 0) } == 0 { bail!("CreatePipe failed: {}", IoError::last_os_error()); } Ok(Pipe { From d518c9b2c9499a2e46fb8de90712aad19be778ef Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 21 May 2019 08:43:52 -0700 Subject: [PATCH 21/34] bump filedescriptor crate version to pickup pipe inheritance on windows --- filedescriptor/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 808126699..d193008bf 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.1.0" +version = "0.1.1" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" From 2c8e36648b97b98a85989361bbaa0a3e5bf28b80 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 1 Jun 2019 08:19:18 -0700 Subject: [PATCH 22/34] filedescriptor: fix a silly typo, enhance docs --- filedescriptor/Cargo.toml | 3 +- filedescriptor/README.md | 49 ++++++++++++++++++++ filedescriptor/src/lib.rs | 87 +++++++++++++++++++++++++++++++++-- filedescriptor/src/unix.rs | 2 +- filedescriptor/src/windows.rs | 2 +- 5 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 filedescriptor/README.md diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index d193008bf..07911f6e1 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,12 +1,13 @@ [package] name = "filedescriptor" -version = "0.1.1" +version = "0.2.0" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" description = "More ergonomic wrappers around RawFd and RawHandle" license = "MIT" documentation = "https://docs.rs/filedescriptor" +readme = "README.md" [dependencies] failure = "0.1" diff --git a/filedescriptor/README.md b/filedescriptor/README.md new file mode 100644 index 000000000..8627c804f --- /dev/null +++ b/filedescriptor/README.md @@ -0,0 +1,49 @@ +The purpose of this crate is to make it a bit more ergonomic for portable +applications that need to work with the platform level `RawFd` and +`RawHandle` types. + +Rather than conditionally using `RawFd` and `RawHandle`, the `FileDescriptor` +type can be used to manage ownership, duplicate, read and write. + +## FileDescriptor + +This is a bit of a contrived example, but demonstrates how to avoid +the conditional code that would otherwise be required to deal with +calling `as_raw_fd` and `as_raw_handle`: + +```rust +use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; +use failure::Fallible; +use std::io::Write; + +fn get_stdout() -> Fallible { + let stdout = std::io::stdout(); + let handle = stdout.lock(); + FileDescriptor::dup(&handle) +} + +fn print_something() -> Fallible<()> { + get_stdout()?.write(b"hello")?; + Ok(()) +} +``` + +## Pipe +The `Pipe` type makes it more convenient to create a pipe and manage +the lifetime of both the read and write ends of that pipe. + +```rust +use filedescriptor::Pipe; +use std::io::{Read,Write}; +use failure::Error; + +let mut pipe = Pipe::new()?; +pipe.write.write(b"hello")?; +drop(pipe.write); + +let mut s = String::new(); +pipe.read.read_to_string(&mut s)?; +assert_eq!(s, "hello"); +# Ok::<(), Error>(()) +``` + diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index c2877eccd..ea82deaad 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -1,10 +1,51 @@ //! The purpose of this crate is to make it a bit more ergonomic for portable //! applications that need to work with the platform level `RawFd` and //! `RawHandle` types. +//! //! Rather than conditionally using `RawFd` and `RawHandle`, the `FileDescriptor` //! type can be used to manage ownership, duplicate, read and write. +//! +//! ## FileDescriptor +//! +//! This is a bit of a contrived example, but demonstrates how to avoid +//! the conditional code that would otherwise be required to deal with +//! calling `as_raw_fd` and `as_raw_handle`: +//! +//! ``` +//! use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; +//! use failure::Fallible; +//! use std::io::Write; +//! +//! fn get_stdout() -> Fallible { +//! let stdout = std::io::stdout(); +//! let handle = stdout.lock(); +//! FileDescriptor::dup(&handle) +//! } +//! +//! fn print_something() -> Fallible<()> { +//! get_stdout()?.write(b"hello")?; +//! Ok(()) +//! } +//! ``` +//! +//! ## Pipe //! The `Pipe` type makes it more convenient to create a pipe and manage //! the lifetime of both the read and write ends of that pipe. +//! +//! ``` +//! use filedescriptor::Pipe; +//! use std::io::{Read,Write}; +//! use failure::Error; +//! +//! let mut pipe = Pipe::new()?; +//! pipe.write.write(b"hello")?; +//! drop(pipe.write); +//! +//! let mut s = String::new(); +//! pipe.read.read_to_string(&mut s)?; +//! assert_eq!(s, "hello"); +//! # Ok::<(), Error>(()) +//! ``` use failure::Fallible; #[cfg(unix)] mod unix; @@ -32,11 +73,11 @@ pub trait IntoRawFileDescriptor { /// `FromRawFileDescriptor` is a platform independent trait for creating /// an instance from the underlying platform file descriptor type. /// Because the platform file descriptor type has no inherent ownership -/// management, the `from_raw_file_descrptor` function is marked as unsafe +/// management, the `from_raw_file_descriptor` function is marked as unsafe /// to indicate that care must be taken by the caller to ensure that it /// is used appropriately. pub trait FromRawFileDescriptor { - unsafe fn from_raw_file_descrptor(fd: RawFileDescriptor) -> Self; + unsafe fn from_raw_file_descriptor(fd: RawFileDescriptor) -> Self; } /// `OwnedHandle` allows managing the lifetime of the platform `RawFileDescriptor` @@ -69,7 +110,7 @@ impl OwnedHandle { } /// Attempt to duplicate the underlying handle from an object that is - /// representable as the systemm `RawFileDescriptor` type and return an + /// representable as the system `RawFileDescriptor` type and return an /// `OwnedHandle` wrapped around the duplicate. Since the duplication /// requires kernel resources that may not be available, this is a /// potentially fallible operation. @@ -82,6 +123,27 @@ impl OwnedHandle { /// `FileDescriptor` is a thin wrapper on top of the `OwnedHandle` type that /// exposes the ability to Read and Write to the platform `RawFileDescriptor`. +/// +/// This is a bit of a contrived example, but demonstrates how to avoid +/// the conditional code that would otherwise be required to deal with +/// calling `as_raw_fd` and `as_raw_handle`: +/// +/// ``` +/// use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; +/// use failure::Fallible; +/// use std::io::Write; +/// +/// fn get_stdout() -> Fallible { +/// let stdout = std::io::stdout(); +/// let handle = stdout.lock(); +/// FileDescriptor::dup(&handle) +/// } +/// +/// fn print_something() -> Fallible<()> { +/// get_stdout()?.write(b"hello")?; +/// Ok(()) +/// } +/// ``` #[derive(Debug)] pub struct FileDescriptor { handle: OwnedHandle, @@ -97,7 +159,7 @@ impl FileDescriptor { } /// Attempt to duplicate the underlying handle from an object that is - /// representable as the systemm `RawFileDescriptor` type and return a + /// representable as the system `RawFileDescriptor` type and return a /// `FileDescriptor` wrapped around the duplicate. Since the duplication /// requires kernel resources that may not be available, this is a /// potentially fallible operation. @@ -128,7 +190,24 @@ impl FileDescriptor { /// Represents the readable and writable ends of a pair of descriptors /// connected via a kernel pipe. +/// +/// ``` +/// use filedescriptor::Pipe; +/// use std::io::{Read,Write}; +/// use failure::Error; +/// +/// let mut pipe = Pipe::new()?; +/// pipe.write.write(b"hello")?; +/// drop(pipe.write); +/// +/// let mut s = String::new(); +/// pipe.read.read_to_string(&mut s)?; +/// assert_eq!(s, "hello"); +/// # Ok::<(), Error>(()) +/// ``` pub struct Pipe { + /// The readable end of the pipe pub read: FileDescriptor, + /// The writable end of the pipe pub write: FileDescriptor, } diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index e1e1df097..1a4a56d20 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -23,7 +23,7 @@ impl IntoRawFileDescriptor for T { } impl FromRawFileDescriptor for T { - unsafe fn from_raw_file_descrptor(fd: RawFileDescriptor) -> Self { + unsafe fn from_raw_file_descriptor(fd: RawFileDescriptor) -> Self { Self::from_raw_fd(fd) } } diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 2083e161b..61a577e6c 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -31,7 +31,7 @@ impl IntoRawFileDescriptor for T { } impl FromRawFileDescriptor for T { - unsafe fn from_raw_file_descrptor(handle: RawHandle) -> Self { + unsafe fn from_raw_file_descriptor(handle: RawHandle) -> Self { Self::from_raw_handle(handle) } } From f3d201a26b81ef1a84856d95d7efe36eff79bd69 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 18 Jun 2019 07:39:24 -0700 Subject: [PATCH 23/34] pull in the poll implementation from wezterm+termwiz --- filedescriptor/src/lib.rs | 30 +++++++ filedescriptor/src/unix.rs | 142 ++++++++++++++++++++++++++++++++++ filedescriptor/src/windows.rs | 19 +++++ 3 files changed, 191 insertions(+) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index ea82deaad..2c0436ce8 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -211,3 +211,33 @@ pub struct Pipe { /// The writable end of the pipe pub write: FileDescriptor, } + +use std::time::Duration; + +/// Examines a set of FileDescriptors to see if some of them are ready for I/O, +/// or if certain events have occurred on them. +/// +/// This uses the system native readiness checking mechanism, which on Windows +/// means that it does NOT use IOCP and that this only works with sockets on +/// Windows. If you need IOCP then the `mio` crate is recommended for a much +/// more scalable solution. +/// +/// On macOS, the `poll(2)` implementation has problems when used with eg: pty +/// descriptors, so this implementation of poll uses the `select(2)` interface +/// under the covers. That places a limit on the maximum file descriptor value +/// that can be passed to poll. If a file descriptor is out of range then an +/// error will returned. This limitation could potentially be lifted in the +/// future. +/// +/// If `duration` is `None`, then `poll` will block until any of the requested +/// events are ready. Otherwise, `duration` specifies how long to wait for +/// readiness before giving up. +/// +/// The return value is the number of entries that were satisfied; `0` means +/// that none were ready after waiting for the specified duration. +/// +/// The `pfd` array is mutated and the `revents` field is updated to indicate +/// which of the events were received. +pub fn poll(pfd: &mut [pollfd], duration: Option) -> Fallible { + poll_impl(pfd, duration) +} diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 1a4a56d20..7eb55ea01 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -208,3 +208,145 @@ impl Pipe { } } } + +pub use libc::{pollfd, POLLERR, POLLHUP, POLLIN, POLLOUT}; +use std::time::Duration; + +#[cfg(not(target_os = "macos"))] +#[doc(hidden)] +pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + let poll_result = unsafe { + libc::poll( + pfd.as_mut_ptr(), + pfd.len() as _, + duration + .map(|wait| wait.as_millis() as libc::c_int) + .unwrap_or(-1), + ) + }; + if poll_result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(poll_result as usize) + } +} + +// macOS has a broken poll(2) implementation, so we introduce a layer to deal with that here +#[cfg(target_os = "macos")] +mod macos { + use super::*; + use libc::{fd_set, timeval, FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO, POLLERR, POLLIN, POLLOUT}; + use std::os::unix::io::RawFd; + + struct FdSet { + set: fd_set, + } + + #[inline] + fn check_fd(fd: RawFd) -> Fallible<()> { + failure::ensure!(fd >= 0, "illegal fd value"); + failure::ensure!( + (fd as usize) < FD_SETSIZE, + "fd value is too large to use with select(2) on macos" + ); + Ok(()) + } + + impl FdSet { + pub fn new() -> Self { + unsafe { + let mut set = std::mem::uninitialized(); + FD_ZERO(&mut set); + Self { set } + } + } + + pub fn add(&mut self, fd: RawFd) -> Fallible<()> { + check_fd(fd)?; + unsafe { + FD_SET(fd, &mut self.set); + } + Ok(()) + } + + pub fn contains(&mut self, fd: RawFd) -> bool { + check_fd(fd).unwrap(); + unsafe { FD_ISSET(fd, &mut self.set) } + } + } + + fn materialize(set: &mut Option) -> &mut FdSet { + set.get_or_insert_with(FdSet::new) + } + + fn set_ptr(set: &mut Option) -> *mut fd_set { + set.as_mut() + .map(|s| &mut s.set as *mut _) + .unwrap_or_else(std::ptr::null_mut) + } + + fn is_set(set: &mut Option, fd: RawFd) -> bool { + set.as_mut().map(|s| s.contains(fd)).unwrap_or(false) + } + + pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + let mut read_set = None; + let mut write_set = None; + let mut exception_set = None; + let mut nfds = 0; + + for item in pfd.iter_mut() { + item.revents = 0; + + nfds = nfds.max(item.fd); + + if item.events & POLLIN != 0 { + materialize(&mut read_set).add(item.fd)?; + } + if item.events & POLLOUT != 0 { + materialize(&mut write_set).add(item.fd)?; + } + materialize(&mut exception_set).add(item.fd)?; + } + + let mut timeout = duration.map(|d| timeval { + tv_sec: d.as_secs() as _, + tv_usec: d.as_micros() as _, + }); + + let res = unsafe { + libc::select( + nfds + 1, + set_ptr(&mut read_set), + set_ptr(&mut write_set), + set_ptr(&mut exception_set), + timeout + .as_mut() + .map(|t| t as *mut _) + .unwrap_or_else(std::ptr::null_mut), + ) + }; + + if res < 0 { + Err(std::io::Error::last_os_error().into()) + } else { + for item in pfd.iter_mut() { + if is_set(&mut read_set, item.fd) { + item.revents |= POLLIN; + } + if is_set(&mut write_set, item.fd) { + item.revents |= POLLOUT; + } + if is_set(&mut exception_set, item.fd) { + item.revents |= POLLERR; + } + } + + Ok(res as usize) + } + } +} + +#[cfg(target_os = "macos")] +#[doc(hidden)] +pub use macos::poll_impl; diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 61a577e6c..56f17268c 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -12,6 +12,7 @@ use winapi::um::minwinbase::SECURITY_ATTRIBUTES; use winapi::um::namedpipeapi::CreatePipe; use winapi::um::processthreadsapi::*; use winapi::um::winnt::HANDLE; +pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd}; /// `RawFileDescriptor` is a platform independent type alias for the /// underlying platform file descriptor type. It is primarily useful @@ -192,3 +193,21 @@ impl Pipe { }) } } + +#[doc(hidden)] +pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + let poll_result = unsafe { + WSAPoll( + pfd.as_mut_ptr(), + pfd.len() as _, + duration + .map(|wait| wait.as_millis() as libc::c_int) + .unwrap_or(-1), + ) + }; + if poll_result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(poll_result as usize) + } +} From 9ff22f9c09f2fddc6d5663a7b9a4b383843b2c9b Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 18 Jun 2019 08:31:27 -0700 Subject: [PATCH 24/34] add socketpair, with wip on windows --- filedescriptor/Cargo.toml | 3 +- filedescriptor/src/lib.rs | 7 +++++ filedescriptor/src/unix.rs | 53 +++++++++++++++++++++++++++++++- filedescriptor/src/windows.rs | 58 +++++++++++++++++++++++++++++++++-- 4 files changed, 117 insertions(+), 4 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 07911f6e1..a4f7327ee 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -20,5 +20,6 @@ winapi = { version = "0.3", features = [ "handleapi", "fileapi", "namedpipeapi", - "processthreadsapi" + "processthreadsapi", + "winsock2" ]} diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 2c0436ce8..b797a9078 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -241,3 +241,10 @@ use std::time::Duration; pub fn poll(pfd: &mut [pollfd], duration: Option) -> Fallible { poll_impl(pfd, duration) } + +/// Create a pair of connected sockets +/// +/// This implementation creates a pair of SOCK_STREAM sockets. +pub fn socketpair() -> Fallible<(FileDescriptor, FileDescriptor)> { + socketpair_impl() +} diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 7eb55ea01..023cfcedc 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -209,6 +209,57 @@ impl Pipe { } } +#[cfg(target_os = "linux")] +#[doc(hidden)] +pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { + let mut fds = [-1i32; 2]; + let res = unsafe { + libc::socketpair( + libc::PF_LOCAL, + libc::SOCK_STREAM | libc::SOCK_CLOEXEC, + 0, + fds.as_mut_ptr(), + ) + }; + if res == -1 { + bail!( + "failed to create a socketpair: {:?}", + std::io::Error::last_os_error() + ) + } else { + let mut read = FileDescriptor { + handle: OwnedHandle { handle: fds[0] }, + }; + let mut write = FileDescriptor { + handle: OwnedHandle { handle: fds[1] }, + }; + Ok((read, write)) + } +} + +#[cfg(not(target_os = "linux"))] +#[doc(hidden)] +pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { + let mut fds = [-1i32; 2]; + let res = unsafe { libc::socketpair(libc::PF_LOCAL, libc::SOCK_STREAM, 0, fds.as_mut_ptr()) }; + if res == -1 { + bail!( + "failed to create a socketpair: {:?}", + std::io::Error::last_os_error() + ) + } else { + let mut read = FileDescriptor { + handle: OwnedHandle { handle: fds[0] }, + }; + let mut write = FileDescriptor { + handle: OwnedHandle { handle: fds[1] }, + }; + read.handle.cloexec()?; + write.handle.cloexec()?; + Ok((read, write)) + } +} + pub use libc::{pollfd, POLLERR, POLLHUP, POLLIN, POLLOUT}; use std::time::Duration; @@ -225,7 +276,7 @@ pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible FromRawFileDescriptor for T { unsafe impl Send for OwnedHandle {} +enum HandleType { + Char, + Disk, + Pipe, + Socket, + Unknown, +} + +fn handle_type(handle: HANDLE) -> HandleType { + match GetFileType(handle) { + FILE_TYPE_CHAR => HandleType::Char, + FILE_TYPE_DISK => HandleType::Disk, + FILE_TYPE_PIPE => { + // Could be a pipe or a socket. Test if for pipeness + let mut flags = 0; + let mut out_buf = 0; + let mut in_buf = 0; + let mut inst = 0; + if GetNamedPipeInfo(handle, &mut flags, &mut out_buf, &mut in_buf, &mut inst) { + HandleType::Pipe + } else { + HandleType::Socket + } + } + _ => HandleType::Unknown, + } +} + impl Drop for OwnedHandle { fn drop(&mut self) { if self.handle != INVALID_HANDLE_VALUE as _ && !self.handle.is_null() { - unsafe { CloseHandle(self.handle as _) }; + unsafe { + if handle_type(self.handle as _) == HandleType::Socket { + closesocket(self.handle as _); + } else { + CloseHandle(self.handle as _); + } + }; } } } @@ -194,6 +230,24 @@ impl Pipe { } } +fn init_winsock() { + static START: Once = Once::new(); + START.call_once(|| unsafe { + let mut data: WSADATA = mem::zeroed(); + let ret = WSAStartup( + 0x202, // version 2.2 + &mut data, + ); + assert_eq!(ret, 0, "failed to initialize winsock"); + }); +} + +#[doc(hidden)] +pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { + init_winsock(); + bail!("not implemented yet"); +} + #[doc(hidden)] pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { let poll_result = unsafe { @@ -206,7 +260,7 @@ pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible Date: Tue, 18 Jun 2019 09:20:17 -0700 Subject: [PATCH 25/34] fixup windows impl --- filedescriptor/src/windows.rs | 118 ++++++++++++++++++++++++++++++++-- 1 file changed, 112 insertions(+), 6 deletions(-) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index b6a81ed44..354452d20 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -6,14 +6,22 @@ use failure::{bail, Fallible}; use std::io::{self, Error as IoError}; use std::os::windows::prelude::*; use std::ptr; +use std::sync::Once; +use std::time::Duration; +use winapi::shared::ws2def::AF_INET; +use winapi::shared::ws2def::INADDR_LOOPBACK; +use winapi::shared::ws2def::SOCKADDR_IN; use winapi::um::fileapi::*; use winapi::um::handleapi::*; use winapi::um::minwinbase::SECURITY_ATTRIBUTES; -use winapi::um::namedpipeapi::CreatePipe; +use winapi::um::namedpipeapi::{CreatePipe, GetNamedPipeInfo}; use winapi::um::processthreadsapi::*; use winapi::um::winbase::{FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE}; use winapi::um::winnt::HANDLE; -use winapi::um::winsock2::{closesocket, WSAPoll}; +use winapi::um::winsock2::{ + accept, bind, closesocket, connect, getsockname, htonl, listen, WSAPoll, WSASocketW, + WSAStartup, INVALID_SOCKET, SOCK_STREAM, WSADATA, WSA_FLAG_NO_HANDLE_INHERIT, +}; pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd}; /// `RawFileDescriptor` is a platform independent type alias for the @@ -41,6 +49,7 @@ impl FromRawFileDescriptor for T { unsafe impl Send for OwnedHandle {} +#[derive(Clone, Copy, PartialEq, Eq)] enum HandleType { Char, Disk, @@ -50,7 +59,7 @@ enum HandleType { } fn handle_type(handle: HANDLE) -> HandleType { - match GetFileType(handle) { + match unsafe { GetFileType(handle) } { FILE_TYPE_CHAR => HandleType::Char, FILE_TYPE_DISK => HandleType::Disk, FILE_TYPE_PIPE => { @@ -59,7 +68,9 @@ fn handle_type(handle: HANDLE) -> HandleType { let mut out_buf = 0; let mut in_buf = 0; let mut inst = 0; - if GetNamedPipeInfo(handle, &mut flags, &mut out_buf, &mut in_buf, &mut inst) { + if unsafe { GetNamedPipeInfo(handle, &mut flags, &mut out_buf, &mut in_buf, &mut inst) } + != 0 + { HandleType::Pipe } else { HandleType::Socket @@ -233,7 +244,7 @@ impl Pipe { fn init_winsock() { static START: Once = Once::new(); START.call_once(|| unsafe { - let mut data: WSADATA = mem::zeroed(); + let mut data: WSADATA = std::mem::zeroed(); let ret = WSAStartup( 0x202, // version 2.2 &mut data, @@ -242,10 +253,91 @@ fn init_winsock() { }); } +fn socket(af: i32, sock_type: i32, proto: i32) -> Fallible { + let s = unsafe { + WSASocketW( + af, + sock_type, + proto, + ptr::null_mut(), + 0, + WSA_FLAG_NO_HANDLE_INHERIT, + ) + }; + if s == INVALID_SOCKET { + bail!("socket failed: {}", IoError::last_os_error()); + } + Ok(FileDescriptor { + handle: OwnedHandle { handle: s as _ }, + }) +} + #[doc(hidden)] pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { init_winsock(); - bail!("not implemented yet"); + + let s = socket(AF_INET, SOCK_STREAM, 0)?; + + let mut in_addr: SOCKADDR_IN = unsafe { std::mem::zeroed() }; + in_addr.sin_family = AF_INET as _; + unsafe { + *in_addr.sin_addr.S_un.S_addr_mut() = htonl(INADDR_LOOPBACK); + } + + unsafe { + if bind( + s.as_raw_handle() as _, + std::mem::transmute(&in_addr), + std::mem::size_of_val(&in_addr) as _, + ) != 0 + { + bail!("bind failed: {}", IoError::last_os_error()); + } + } + + let mut addr_len = std::mem::size_of_val(&in_addr) as i32; + + unsafe { + if getsockname( + s.as_raw_handle() as _, + std::mem::transmute(&mut in_addr), + &mut addr_len, + ) != 0 + { + bail!("getsockname failed: {}", IoError::last_os_error()); + } + } + + unsafe { + if listen(s.as_raw_handle() as _, 1) != 0 { + bail!("listen failed: {}", IoError::last_os_error()); + } + } + + let client = socket(AF_INET, SOCK_STREAM, 0)?; + + unsafe { + if connect( + client.as_raw_handle() as _, + std::mem::transmute(&in_addr), + addr_len, + ) != 0 + { + bail!("connect failed: {}", IoError::last_os_error()); + } + } + + let server = unsafe { accept(s.as_raw_handle() as _, ptr::null_mut(), ptr::null_mut()) }; + if server == INVALID_SOCKET { + bail!("socket failed: {}", IoError::last_os_error()); + } + let server = FileDescriptor { + handle: OwnedHandle { + handle: server as _, + }, + }; + + Ok((server, client)) } #[doc(hidden)] @@ -265,3 +357,17 @@ pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible Date: Tue, 18 Jun 2019 20:05:47 -0700 Subject: [PATCH 26/34] windows: handle broken pipe on read and treat as 0 bytes read --- filedescriptor/src/windows.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 354452d20..adcfdc890 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -188,7 +188,12 @@ impl io::Read for FileDescriptor { ) }; if ok == 0 { - Err(IoError::last_os_error()) + let err = IoError::last_os_error(); + if err.kind() == std::io::ErrorKind::BrokenPipe { + Ok(0) + } else { + Err(err) + } } else { Ok(num_read as usize) } From 240bc8033cff904ffeeda2261ee612d750b55802 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 18 Jun 2019 23:35:53 -0700 Subject: [PATCH 27/34] prep for filedescriptor release --- filedescriptor/Cargo.toml | 3 +- filedescriptor/README.md | 58 ++++++++++++++++++++++++++++++++--- filedescriptor/src/lib.rs | 58 ++++++++++++++++++++++++++++++++++- filedescriptor/src/unix.rs | 5 +++ filedescriptor/src/windows.rs | 7 ++++- 5 files changed, 124 insertions(+), 7 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index a4f7327ee..320462d18 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.2.0" +version = "0.3.0" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" @@ -8,6 +8,7 @@ description = "More ergonomic wrappers around RawFd and RawHandle" license = "MIT" documentation = "https://docs.rs/filedescriptor" readme = "README.md" +keywords = ["socketpair", "pipe", "poll", "filedescriptor"] [dependencies] failure = "0.1" diff --git a/filedescriptor/README.md b/filedescriptor/README.md index 8627c804f..45d9c196c 100644 --- a/filedescriptor/README.md +++ b/filedescriptor/README.md @@ -1,3 +1,5 @@ + + The purpose of this crate is to make it a bit more ergonomic for portable applications that need to work with the platform level `RawFd` and `RawHandle` types. @@ -11,7 +13,7 @@ This is a bit of a contrived example, but demonstrates how to avoid the conditional code that would otherwise be required to deal with calling `as_raw_fd` and `as_raw_handle`: -```rust +``` use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; use failure::Fallible; use std::io::Write; @@ -32,9 +34,9 @@ fn print_something() -> Fallible<()> { The `Pipe` type makes it more convenient to create a pipe and manage the lifetime of both the read and write ends of that pipe. -```rust +``` use filedescriptor::Pipe; -use std::io::{Read,Write}; +use std::io::{Read, Write}; use failure::Error; let mut pipe = Pipe::new()?; @@ -44,6 +46,54 @@ drop(pipe.write); let mut s = String::new(); pipe.read.read_to_string(&mut s)?; assert_eq!(s, "hello"); -# Ok::<(), Error>(()) ``` +## Socketpair +The `socketpair` function returns a pair of connected `SOCK_STREAM` +sockets and functions both on posix and windows systems. + +``` +use std::io::{Read, Write}; +use failure::Error; + +let (mut a, mut b) = filedescriptor::socketpair()?; +a.write(b"hello")?; +drop(a); + +let mut s = String::new(); +b.read_to_string(&mut s)?; +assert_eq!(s, "hello"); +``` + +## Polling +The `mio` crate offers powerful and scalable IO multiplexing, but there +are some situations where `mio` doesn't fit. The `filedescriptor` crate +offers a `poll(2)` compatible interface suitable for testing the readiness +of a set of file descriptors. On unix systems this is a very thin wrapper +around `poll(2)`, except on macOS where it is actually a wrapper around +the `select(2)` interface. On Windows systems the winsock `WSAPoll` +function is used instead. + +``` +use filedescriptor::*; +use failure::Error; +use std::time::Duration; +use std::io::{Read, Write}; + +let (mut a, mut b) = filedescriptor::socketpair()?; +let mut poll_array = [pollfd { + fd: a.as_socket_descriptor(), + events: POLLIN, + revents: 0 +}]; +// sleeps for 20 milliseconds because `a` is not yet ready +assert_eq!(poll(&mut poll_array, Some(Duration::from_millis(20)))?, 0); + +b.write(b"hello")?; + +// Now a is ready for read +assert_eq!(poll(&mut poll_array, Some(Duration::from_millis(20)))?, 1); + +``` + + diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index b797a9078..903d41296 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -34,7 +34,7 @@ //! //! ``` //! use filedescriptor::Pipe; -//! use std::io::{Read,Write}; +//! use std::io::{Read, Write}; //! use failure::Error; //! //! let mut pipe = Pipe::new()?; @@ -46,6 +46,56 @@ //! assert_eq!(s, "hello"); //! # Ok::<(), Error>(()) //! ``` +//! +//! ## Socketpair +//! The `socketpair` function returns a pair of connected `SOCK_STREAM` +//! sockets and functions both on posix and windows systems. +//! +//! ``` +//! use std::io::{Read, Write}; +//! use failure::Error; +//! +//! let (mut a, mut b) = filedescriptor::socketpair()?; +//! a.write(b"hello")?; +//! drop(a); +//! +//! let mut s = String::new(); +//! b.read_to_string(&mut s)?; +//! assert_eq!(s, "hello"); +//! # Ok::<(), Error>(()) +//! ``` +//! +//! ## Polling +//! The `mio` crate offers powerful and scalable IO multiplexing, but there +//! are some situations where `mio` doesn't fit. The `filedescriptor` crate +//! offers a `poll(2)` compatible interface suitable for testing the readiness +//! of a set of file descriptors. On unix systems this is a very thin wrapper +//! around `poll(2)`, except on macOS where it is actually a wrapper around +//! the `select(2)` interface. On Windows systems the winsock `WSAPoll` +//! function is used instead. +//! +//! ``` +//! use filedescriptor::*; +//! use failure::Error; +//! use std::time::Duration; +//! use std::io::{Read, Write}; +//! +//! let (mut a, mut b) = filedescriptor::socketpair()?; +//! let mut poll_array = [pollfd { +//! fd: a.as_socket_descriptor(), +//! events: POLLIN, +//! revents: 0 +//! }]; +//! // sleeps for 20 milliseconds because `a` is not yet ready +//! assert_eq!(poll(&mut poll_array, Some(Duration::from_millis(20)))?, 0); +//! +//! b.write(b"hello")?; +//! +//! // Now a is ready for read +//! assert_eq!(poll(&mut poll_array, Some(Duration::from_millis(20)))?, 1); +//! +//! # Ok::<(), Error>(()) +//! ``` use failure::Fallible; #[cfg(unix)] mod unix; @@ -62,6 +112,9 @@ pub use crate::windows::*; /// type. pub trait AsRawFileDescriptor { fn as_raw_file_descriptor(&self) -> RawFileDescriptor; + fn as_socket_descriptor(&self) -> SocketDescriptor { + self.as_raw_file_descriptor() as SocketDescriptor + } } /// `IntoRawFileDescriptor` is a platform independent trait for converting @@ -229,6 +282,9 @@ use std::time::Duration; /// error will returned. This limitation could potentially be lifted in the /// future. /// +/// On Windows, `WSAPoll` is used to implement readiness checking, which has +/// the consequence that it can only be used with sockets. +/// /// If `duration` is `None`, then `poll` will block until any of the requested /// events are ready. Otherwise, `duration` specifies how long to wait for /// readiness before giving up. diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 023cfcedc..860dcc8c8 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -10,6 +10,11 @@ use std::os::unix::prelude::*; /// for avoiding using `cfg` blocks in platform independent code. pub type RawFileDescriptor = RawFd; +/// `SocketDescriptor` is a platform independent type alias for the +/// underlying platform socket descriptor type. It is primarily useful +/// for avoiding using `cfg` blocks in platform independent code. +pub type SocketDescriptor = RawFd; + impl AsRawFileDescriptor for T { fn as_raw_file_descriptor(&self) -> RawFileDescriptor { self.as_raw_fd() diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index adcfdc890..dba192f71 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -20,7 +20,7 @@ use winapi::um::winbase::{FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE}; use winapi::um::winnt::HANDLE; use winapi::um::winsock2::{ accept, bind, closesocket, connect, getsockname, htonl, listen, WSAPoll, WSASocketW, - WSAStartup, INVALID_SOCKET, SOCK_STREAM, WSADATA, WSA_FLAG_NO_HANDLE_INHERIT, + WSAStartup, INVALID_SOCKET, SOCKET, SOCK_STREAM, WSADATA, WSA_FLAG_NO_HANDLE_INHERIT, }; pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd}; @@ -29,6 +29,11 @@ pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as p /// for avoiding using `cfg` blocks in platform independent code. pub type RawFileDescriptor = RawHandle; +/// `SocketDescriptor` is a platform independent type alias for the +/// underlying platform socket descriptor type. It is primarily useful +/// for avoiding using `cfg` blocks in platform independent code. +pub type SocketDescriptor = SOCKET; + impl AsRawFileDescriptor for T { fn as_raw_file_descriptor(&self) -> RawFileDescriptor { self.as_raw_handle() From 5ac61ec8d38a862ab2888ded9a0d0b834719b446 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Wed, 19 Jun 2019 11:11:06 -0700 Subject: [PATCH 28/34] expand socket descriptor concept I didn't notice that windows has separate traits for raw sockets, so blanket impls for things that returned RawHandle's were not applying on windows in the same way that they were on unix systems. --- filedescriptor/Cargo.toml | 2 +- filedescriptor/src/lib.rs | 13 ++++++++++--- filedescriptor/src/unix.rs | 26 ++++++++++++++++++++++---- filedescriptor/src/windows.rs | 22 ++++++++++++++++++++-- 4 files changed, 53 insertions(+), 10 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 320462d18..8778920bd 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.3.0" +version = "0.4.0" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 903d41296..0e9a7976f 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -112,9 +112,6 @@ pub use crate::windows::*; /// type. pub trait AsRawFileDescriptor { fn as_raw_file_descriptor(&self) -> RawFileDescriptor; - fn as_socket_descriptor(&self) -> SocketDescriptor { - self.as_raw_file_descriptor() as SocketDescriptor - } } /// `IntoRawFileDescriptor` is a platform independent trait for converting @@ -133,6 +130,16 @@ pub trait FromRawFileDescriptor { unsafe fn from_raw_file_descriptor(fd: RawFileDescriptor) -> Self; } +pub trait AsRawSocketDescriptor { + fn as_raw_socket_descriptor(&self) -> SocketDescriptor; +} +pub trait IntoRawSocketDescriptor { + fn into_raw_socket_descriptor(self) -> SocketDescriptor; +} +pub trait FromRawSocketDescriptor { + unsafe fn from_raw_socket_descriptor(fd: SocketDescriptor) -> Self; +} + /// `OwnedHandle` allows managing the lifetime of the platform `RawFileDescriptor` /// type. It is exposed in the interface of this crate primarily for convenience /// on Windows where the system handle type is used for a variety of objects diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 860dcc8c8..7512c2332 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -1,6 +1,6 @@ use crate::{ - AsRawFileDescriptor, FileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, OwnedHandle, - Pipe, + AsRawFileDescriptor, AsRawSocketDescriptor, FileDescriptor, FromRawFileDescriptor, + FromRawSocketDescriptor, IntoRawFileDescriptor, IntoRawSocketDescriptor, OwnedHandle, Pipe, }; use failure::{bail, Fallible}; use std::os::unix::prelude::*; @@ -33,6 +33,24 @@ impl FromRawFileDescriptor for T { } } +impl AsRawSocketDescriptor for T { + fn as_raw_socket_descriptor(&self) -> SocketDescriptor { + self.as_raw_fd() + } +} + +impl IntoRawSocketDescriptor for T { + fn into_raw_socket_descriptor(self) -> SocketDescriptor { + self.into_raw_fd() + } +} + +impl FromRawSocketDescriptor for T { + unsafe fn from_raw_socket_descriptor(fd: SocketDescriptor) -> Self { + Self::from_raw_fd(fd) + } +} + impl Drop for OwnedHandle { fn drop(&mut self) { unsafe { @@ -232,10 +250,10 @@ pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { std::io::Error::last_os_error() ) } else { - let mut read = FileDescriptor { + let read = FileDescriptor { handle: OwnedHandle { handle: fds[0] }, }; - let mut write = FileDescriptor { + let write = FileDescriptor { handle: OwnedHandle { handle: fds[1] }, }; Ok((read, write)) diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index dba192f71..e36b9881b 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -1,6 +1,6 @@ use crate::{ - AsRawFileDescriptor, FileDescriptor, FromRawFileDescriptor, IntoRawFileDescriptor, OwnedHandle, - Pipe, + AsRawFileDescriptor, AsRawSocketDescriptor, FileDescriptor, FromRawFileDescriptor, + FromRawSocketDescriptor, IntoRawFileDescriptor, IntoRawSocketDescriptor, OwnedHandle, Pipe, }; use failure::{bail, Fallible}; use std::io::{self, Error as IoError}; @@ -52,6 +52,24 @@ impl FromRawFileDescriptor for T { } } +impl AsRawSocketDescriptor for T { + fn as_raw_socket_descriptor(&self) -> SocketDescriptor { + self.as_raw_socket() as SocketDescriptor + } +} + +impl IntoRawSocketDescriptor for T { + fn into_raw_socket_descriptor(self) -> SocketDescriptor { + self.into_raw_socket() as SocketDescriptor + } +} + +impl FromRawSocketDescriptor for T { + unsafe fn from_raw_socket_descriptor(handle: SocketDescriptor) -> Self { + Self::from_raw_socket(handle as _) + } +} + unsafe impl Send for OwnedHandle {} #[derive(Clone, Copy, PartialEq, Eq)] From 5f9bb5c3b0676f0073fd0bf70affa0d8a512be9c Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Wed, 19 Jun 2019 11:22:26 -0700 Subject: [PATCH 29/34] fixup naming and impl for socket traits --- filedescriptor/src/lib.rs | 6 +++--- filedescriptor/src/unix.rs | 6 +++--- filedescriptor/src/windows.rs | 38 +++++++++++++++++++++++++++++++---- 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 0e9a7976f..8bd9223de 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -131,13 +131,13 @@ pub trait FromRawFileDescriptor { } pub trait AsRawSocketDescriptor { - fn as_raw_socket_descriptor(&self) -> SocketDescriptor; + fn as_socket_descriptor(&self) -> SocketDescriptor; } pub trait IntoRawSocketDescriptor { - fn into_raw_socket_descriptor(self) -> SocketDescriptor; + fn into_socket_descriptor(self) -> SocketDescriptor; } pub trait FromRawSocketDescriptor { - unsafe fn from_raw_socket_descriptor(fd: SocketDescriptor) -> Self; + unsafe fn from_socket_descriptor(fd: SocketDescriptor) -> Self; } /// `OwnedHandle` allows managing the lifetime of the platform `RawFileDescriptor` diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 7512c2332..d1b142741 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -34,19 +34,19 @@ impl FromRawFileDescriptor for T { } impl AsRawSocketDescriptor for T { - fn as_raw_socket_descriptor(&self) -> SocketDescriptor { + fn as_socket_descriptor(&self) -> SocketDescriptor { self.as_raw_fd() } } impl IntoRawSocketDescriptor for T { - fn into_raw_socket_descriptor(self) -> SocketDescriptor { + fn into_socket_descriptor(self) -> SocketDescriptor { self.into_raw_fd() } } impl FromRawSocketDescriptor for T { - unsafe fn from_raw_socket_descriptor(fd: SocketDescriptor) -> Self { + unsafe fn from_socket_descriptor(fd: SocketDescriptor) -> Self { Self::from_raw_fd(fd) } } diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index e36b9881b..d3536411c 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -53,26 +53,26 @@ impl FromRawFileDescriptor for T { } impl AsRawSocketDescriptor for T { - fn as_raw_socket_descriptor(&self) -> SocketDescriptor { + fn as_socket_descriptor(&self) -> SocketDescriptor { self.as_raw_socket() as SocketDescriptor } } impl IntoRawSocketDescriptor for T { - fn into_raw_socket_descriptor(self) -> SocketDescriptor { + fn into_socket_descriptor(self) -> SocketDescriptor { self.into_raw_socket() as SocketDescriptor } } impl FromRawSocketDescriptor for T { - unsafe fn from_raw_socket_descriptor(handle: SocketDescriptor) -> Self { + unsafe fn from_socket_descriptor(handle: SocketDescriptor) -> Self { Self::from_raw_socket(handle as _) } } unsafe impl Send for OwnedHandle {} -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] enum HandleType { Char, Disk, @@ -198,6 +198,36 @@ impl FromRawHandle for FileDescriptor { } } +impl IntoRawSocket for FileDescriptor { + fn into_raw_socket(self) -> RawSocket { + // FIXME: this isn't a guaranteed conversion! + debug_assert_eq!( + handle_type(self.handle.as_raw_handle() as _), + HandleType::Socket + ); + self.handle.into_raw_handle() as RawSocket + } +} + +impl AsRawSocket for FileDescriptor { + fn as_raw_socket(&self) -> RawSocket { + // FIXME: this isn't a guaranteed conversion! + debug_assert_eq!( + handle_type(self.handle.as_raw_handle() as _), + HandleType::Socket + ); + self.handle.as_raw_handle() as RawSocket + } +} + +impl FromRawSocket for FileDescriptor { + unsafe fn from_raw_socket(handle: RawSocket) -> FileDescriptor { + Self { + handle: OwnedHandle::from_raw_handle(handle as RawHandle), + } + } +} + impl io::Read for FileDescriptor { fn read(&mut self, buf: &mut [u8]) -> Result { let mut num_read = 0; From 33933ec523de5ecdea9fa8fb85438f34ddd7ff43 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 16 Jul 2019 00:22:49 -0700 Subject: [PATCH 30/34] filedescriptor: probe and remember filetype at construction This avoids a deadlock waiting for the named pipe information to be returned if we're probing during drop(). This does make the OwnedHandle struct slightly larger on windows. --- filedescriptor/Cargo.toml | 2 +- filedescriptor/src/lib.rs | 10 ++- filedescriptor/src/unix.rs | 46 ++++++++++--- filedescriptor/src/windows.rs | 120 ++++++++++++++++++++++------------ 4 files changed, 126 insertions(+), 52 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 8778920bd..8c937257c 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.4.0" +version = "0.5.0" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 8bd9223de..bed2bee1c 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -97,6 +97,7 @@ //! # Ok::<(), Error>(()) //! ``` use failure::Fallible; + #[cfg(unix)] mod unix; #[cfg(unix)] @@ -147,6 +148,7 @@ pub trait FromRawSocketDescriptor { #[derive(Debug)] pub struct OwnedHandle { handle: RawFileDescriptor, + handle_type: HandleType, } impl OwnedHandle { @@ -154,8 +156,10 @@ impl OwnedHandle { /// the system `RawFileDescriptor` type. This consumes the parameter /// and replaces it with an `OwnedHandle` instance. pub fn new(f: F) -> Self { + let handle = f.into_raw_file_descriptor(); Self { - handle: f.into_raw_file_descriptor(), + handle, + handle_type: Self::probe_handle_type(handle), } } @@ -166,7 +170,7 @@ impl OwnedHandle { /// The returned handle has a separate lifetime from the source, but /// references the same object at the kernel level. pub fn try_clone(&self) -> Fallible { - Self::dup(self) + Self::dup_impl(self, self.handle_type) } /// Attempt to duplicate the underlying handle from an object that is @@ -177,7 +181,7 @@ impl OwnedHandle { /// The returned handle has a separate lifetime from the source, but /// references the same object at the kernel level. pub fn dup(f: &F) -> Fallible { - Self::dup_impl(f) + Self::dup_impl(f, Default::default()) } } diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index d1b142741..d64214ec4 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -5,6 +5,8 @@ use crate::{ use failure::{bail, Fallible}; use std::os::unix::prelude::*; +pub(crate) type HandleType = (); + /// `RawFileDescriptor` is a platform independent type alias for the /// underlying platform file descriptor type. It is primarily useful /// for avoiding using `cfg` blocks in platform independent code. @@ -75,7 +77,10 @@ impl IntoRawFd for OwnedHandle { impl FromRawFd for OwnedHandle { unsafe fn from_raw_fd(fd: RawFd) -> Self { - Self { handle: fd } + Self { + handle: fd, + handle_type: (), + } } } @@ -108,14 +113,20 @@ impl OwnedHandle { std::io::Error::last_os_error() ) } else { - let mut owned = OwnedHandle { handle: duped }; + let mut owned = OwnedHandle { + handle: duped, + handle_type: (), + }; owned.cloexec()?; Ok(owned) } } #[inline] - pub(crate) fn dup_impl(fd: &F) -> Fallible { + pub(crate) fn dup_impl( + fd: &F, + handle_type: HandleType, + ) -> Fallible { let fd = fd.as_raw_file_descriptor(); let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }; if duped == -1 { @@ -128,9 +139,16 @@ impl OwnedHandle { bail!("dup of fd {} failed: {:?}", fd, err) } } else { - Ok(OwnedHandle { handle: duped }) + Ok(OwnedHandle { + handle: duped, + handle_type, + }) } } + + pub(crate) fn probe_handle_type(_handle: RawFileDescriptor) -> HandleType { + () + } } impl std::io::Read for FileDescriptor { @@ -200,10 +218,16 @@ impl Pipe { ) } else { let read = FileDescriptor { - handle: OwnedHandle { handle: fds[0] }, + handle: OwnedHandle { + handle: fds[0], + handle_type: (), + }, }; let write = FileDescriptor { - handle: OwnedHandle { handle: fds[1] }, + handle: OwnedHandle { + handle: fds[1], + handle_type: (), + }, }; Ok(Pipe { read, write }) } @@ -251,10 +275,16 @@ pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { ) } else { let read = FileDescriptor { - handle: OwnedHandle { handle: fds[0] }, + handle: OwnedHandle { + handle: fds[0], + handle_type: (), + }, }; let write = FileDescriptor { - handle: OwnedHandle { handle: fds[1] }, + handle: OwnedHandle { + handle: fds[1], + handle_type: (), + }, }; Ok((read, write)) } diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index d3536411c..712d80609 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -34,6 +34,21 @@ pub type RawFileDescriptor = RawHandle; /// for avoiding using `cfg` blocks in platform independent code. pub type SocketDescriptor = SOCKET; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HandleType { + Char, + Disk, + Pipe, + Socket, + Unknown, +} + +impl Default for HandleType { + fn default() -> Self { + HandleType::Unknown + } +} + impl AsRawFileDescriptor for T { fn as_raw_file_descriptor(&self) -> RawFileDescriptor { self.as_raw_handle() @@ -72,34 +87,43 @@ impl FromRawSocketDescriptor for T { unsafe impl Send for OwnedHandle {} -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum HandleType { - Char, - Disk, - Pipe, - Socket, - Unknown, -} +impl OwnedHandle { + fn probe_handle_type_if_unknown(handle: HANDLE, handle_type: HandleType) -> HandleType { + match handle_type { + HandleType::Unknown => Self::probe_handle_type(handle), + t => t, + } + } -fn handle_type(handle: HANDLE) -> HandleType { - match unsafe { GetFileType(handle) } { - FILE_TYPE_CHAR => HandleType::Char, - FILE_TYPE_DISK => HandleType::Disk, - FILE_TYPE_PIPE => { - // Could be a pipe or a socket. Test if for pipeness - let mut flags = 0; - let mut out_buf = 0; - let mut in_buf = 0; - let mut inst = 0; - if unsafe { GetNamedPipeInfo(handle, &mut flags, &mut out_buf, &mut in_buf, &mut inst) } - != 0 - { - HandleType::Pipe - } else { - HandleType::Socket + pub(crate) fn probe_handle_type(handle: HANDLE) -> HandleType { + match unsafe { GetFileType(handle) } { + FILE_TYPE_CHAR => HandleType::Char, + FILE_TYPE_DISK => HandleType::Disk, + FILE_TYPE_PIPE => { + // Could be a pipe or a socket. Test if for pipeness + let mut flags = 0; + let mut out_buf = 0; + let mut in_buf = 0; + let mut inst = 0; + if unsafe { + GetNamedPipeInfo(handle, &mut flags, &mut out_buf, &mut in_buf, &mut inst) + } != 0 + { + HandleType::Pipe + } else { + HandleType::Socket + } } + _ => HandleType::Unknown, + } + } + + fn is_socket_handle(&self) -> bool { + match self.handle_type { + HandleType::Socket => true, + HandleType::Unknown => Self::probe_handle_type(self.handle) == HandleType::Socket, + _ => false, } - _ => HandleType::Unknown, } } @@ -107,7 +131,7 @@ impl Drop for OwnedHandle { fn drop(&mut self) { if self.handle != INVALID_HANDLE_VALUE as _ && !self.handle.is_null() { unsafe { - if handle_type(self.handle as _) == HandleType::Socket { + if self.is_socket_handle() { closesocket(self.handle as _); } else { CloseHandle(self.handle as _); @@ -119,18 +143,29 @@ impl Drop for OwnedHandle { impl FromRawHandle for OwnedHandle { unsafe fn from_raw_handle(handle: RawHandle) -> Self { - OwnedHandle { handle } + OwnedHandle { + handle, + handle_type: Self::probe_handle_type(handle), + } } } impl OwnedHandle { #[inline] - pub(crate) fn dup_impl(f: &F) -> Fallible { + pub(crate) fn dup_impl( + f: &F, + handle_type: HandleType, + ) -> Fallible { let handle = f.as_raw_file_descriptor(); if handle == INVALID_HANDLE_VALUE as _ || handle.is_null() { - return Ok(OwnedHandle { handle }); + return Ok(OwnedHandle { + handle, + handle_type, + }); } + let handle_type = Self::probe_handle_type_if_unknown(handle, handle_type); + let proc = unsafe { GetCurrentProcess() }; let mut duped = INVALID_HANDLE_VALUE; let ok = unsafe { @@ -149,6 +184,7 @@ impl OwnedHandle { } else { Ok(OwnedHandle { handle: duped as *mut _, + handle_type, }) } } @@ -201,10 +237,7 @@ impl FromRawHandle for FileDescriptor { impl IntoRawSocket for FileDescriptor { fn into_raw_socket(self) -> RawSocket { // FIXME: this isn't a guaranteed conversion! - debug_assert_eq!( - handle_type(self.handle.as_raw_handle() as _), - HandleType::Socket - ); + debug_assert!(self.handle.is_socket_handle()); self.handle.into_raw_handle() as RawSocket } } @@ -212,10 +245,7 @@ impl IntoRawSocket for FileDescriptor { impl AsRawSocket for FileDescriptor { fn as_raw_socket(&self) -> RawSocket { // FIXME: this isn't a guaranteed conversion! - debug_assert_eq!( - handle_type(self.handle.as_raw_handle() as _), - HandleType::Socket - ); + debug_assert!(self.handle.is_socket_handle()); self.handle.as_raw_handle() as RawSocket } } @@ -290,10 +320,16 @@ impl Pipe { } Ok(Pipe { read: FileDescriptor { - handle: OwnedHandle { handle: read as _ }, + handle: OwnedHandle { + handle: read as _, + handle_type: HandleType::Pipe, + }, }, write: FileDescriptor { - handle: OwnedHandle { handle: write as _ }, + handle: OwnedHandle { + handle: write as _, + handle_type: HandleType::Pipe, + }, }, }) } @@ -326,7 +362,10 @@ fn socket(af: i32, sock_type: i32, proto: i32) -> Fallible { bail!("socket failed: {}", IoError::last_os_error()); } Ok(FileDescriptor { - handle: OwnedHandle { handle: s as _ }, + handle: OwnedHandle { + handle: s as _, + handle_type: HandleType::Socket, + }, }) } @@ -392,6 +431,7 @@ pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { let server = FileDescriptor { handle: OwnedHandle { handle: server as _, + handle_type: HandleType::Socket, }, }; From b9ae1a709de4f39d48e183968f42147880e62c22 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Tue, 16 Jul 2019 07:06:50 -0700 Subject: [PATCH 31/34] fix macos build --- filedescriptor/Cargo.toml | 2 +- filedescriptor/src/unix.rs | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 8c937257c..30f3a764f 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.5.0" +version = "0.5.1" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index d64214ec4..63cefbbcd 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -244,10 +244,16 @@ impl Pipe { ) } else { let mut read = FileDescriptor { - handle: OwnedHandle { handle: fds[0] }, + handle: OwnedHandle { + handle: fds[0], + handle_type: (), + }, }; let mut write = FileDescriptor { - handle: OwnedHandle { handle: fds[1] }, + handle: OwnedHandle { + handle: fds[1], + handle_type: (), + }, }; read.handle.cloexec()?; write.handle.cloexec()?; @@ -302,10 +308,16 @@ pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { ) } else { let mut read = FileDescriptor { - handle: OwnedHandle { handle: fds[0] }, + handle: OwnedHandle { + handle: fds[0], + handle_type: (), + }, }; let mut write = FileDescriptor { - handle: OwnedHandle { handle: fds[1] }, + handle: OwnedHandle { + handle: fds[1], + handle_type: (), + }, }; read.handle.cloexec()?; write.handle.cloexec()?; From 55b4a08131a873d37ac676b9e5d1d8cd5d30e71a Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 14 Dec 2019 20:06:25 -0800 Subject: [PATCH 32/34] failure -> anyhow + thiserror --- filedescriptor/Cargo.toml | 6 +++--- filedescriptor/README.md | 11 +++++------ filedescriptor/src/lib.rs | 33 +++++++++++++++------------------ filedescriptor/src/unix.rs | 30 +++++++++++++++--------------- filedescriptor/src/windows.rs | 14 +++++++------- 5 files changed, 45 insertions(+), 49 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 30f3a764f..133e49382 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.5.1" +version = "0.6.0" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" @@ -11,8 +11,8 @@ readme = "README.md" keywords = ["socketpair", "pipe", "poll", "filedescriptor"] [dependencies] -failure = "0.1" -failure_derive = "0.1" +anyhow = "1.0" +thiserror = "1.0" libc = "0.2" [target."cfg(windows)".dependencies] diff --git a/filedescriptor/README.md b/filedescriptor/README.md index 45d9c196c..4da9a8ce3 100644 --- a/filedescriptor/README.md +++ b/filedescriptor/README.md @@ -15,16 +15,15 @@ calling `as_raw_fd` and `as_raw_handle`: ``` use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; -use failure::Fallible; use std::io::Write; -fn get_stdout() -> Fallible { +fn get_stdout() -> anyhow::Result { let stdout = std::io::stdout(); let handle = stdout.lock(); FileDescriptor::dup(&handle) } -fn print_something() -> Fallible<()> { +fn print_something() -> anyhow::Result<()> { get_stdout()?.write(b"hello")?; Ok(()) } @@ -37,7 +36,7 @@ the lifetime of both the read and write ends of that pipe. ``` use filedescriptor::Pipe; use std::io::{Read, Write}; -use failure::Error; +use anyhow::Error; let mut pipe = Pipe::new()?; pipe.write.write(b"hello")?; @@ -54,7 +53,7 @@ sockets and functions both on posix and windows systems. ``` use std::io::{Read, Write}; -use failure::Error; +use anyhow::Error; let (mut a, mut b) = filedescriptor::socketpair()?; a.write(b"hello")?; @@ -76,7 +75,7 @@ function is used instead. ``` use filedescriptor::*; -use failure::Error; +use anyhow::Error; use std::time::Duration; use std::io::{Read, Write}; diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index bed2bee1c..5fce1f4f2 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -13,16 +13,15 @@ //! //! ``` //! use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; -//! use failure::Fallible; //! use std::io::Write; //! -//! fn get_stdout() -> Fallible { +//! fn get_stdout() -> anyhow::Result { //! let stdout = std::io::stdout(); //! let handle = stdout.lock(); //! FileDescriptor::dup(&handle) //! } //! -//! fn print_something() -> Fallible<()> { +//! fn print_something() -> anyhow::Result<()> { //! get_stdout()?.write(b"hello")?; //! Ok(()) //! } @@ -35,7 +34,7 @@ //! ``` //! use filedescriptor::Pipe; //! use std::io::{Read, Write}; -//! use failure::Error; +//! use anyhow::Error; //! //! let mut pipe = Pipe::new()?; //! pipe.write.write(b"hello")?; @@ -53,7 +52,7 @@ //! //! ``` //! use std::io::{Read, Write}; -//! use failure::Error; +//! use anyhow::Error; //! //! let (mut a, mut b) = filedescriptor::socketpair()?; //! a.write(b"hello")?; @@ -76,7 +75,7 @@ //! //! ``` //! use filedescriptor::*; -//! use failure::Error; +//! use anyhow::Error; //! use std::time::Duration; //! use std::io::{Read, Write}; //! @@ -96,7 +95,6 @@ //! //! # Ok::<(), Error>(()) //! ``` -use failure::Fallible; #[cfg(unix)] mod unix; @@ -169,7 +167,7 @@ impl OwnedHandle { /// potentially fallible operation. /// The returned handle has a separate lifetime from the source, but /// references the same object at the kernel level. - pub fn try_clone(&self) -> Fallible { + pub fn try_clone(&self) -> anyhow::Result { Self::dup_impl(self, self.handle_type) } @@ -180,7 +178,7 @@ impl OwnedHandle { /// potentially fallible operation. /// The returned handle has a separate lifetime from the source, but /// references the same object at the kernel level. - pub fn dup(f: &F) -> Fallible { + pub fn dup(f: &F) -> anyhow::Result { Self::dup_impl(f, Default::default()) } } @@ -194,16 +192,15 @@ impl OwnedHandle { /// /// ``` /// use filedescriptor::{FileDescriptor, FromRawFileDescriptor}; -/// use failure::Fallible; /// use std::io::Write; /// -/// fn get_stdout() -> Fallible { +/// fn get_stdout() -> anyhow::Result { /// let stdout = std::io::stdout(); /// let handle = stdout.lock(); /// FileDescriptor::dup(&handle) /// } /// -/// fn print_something() -> Fallible<()> { +/// fn print_something() -> anyhow::Result<()> { /// get_stdout()?.write(b"hello")?; /// Ok(()) /// } @@ -229,7 +226,7 @@ impl FileDescriptor { /// potentially fallible operation. /// The returned handle has a separate lifetime from the source, but /// references the same object at the kernel level. - pub fn dup(f: &F) -> Fallible { + pub fn dup(f: &F) -> anyhow::Result { OwnedHandle::dup(f).map(|handle| Self { handle }) } @@ -239,7 +236,7 @@ impl FileDescriptor { /// potentially fallible operation. /// The returned handle has a separate lifetime from the source, but /// references the same object at the kernel level. - pub fn try_clone(&self) -> Fallible { + pub fn try_clone(&self) -> anyhow::Result { self.handle.try_clone().map(|handle| Self { handle }) } @@ -247,7 +244,7 @@ impl FileDescriptor { /// to be used for eg: redirecting the stdio streams of a child /// process. The `Stdio` is created using a duplicated handle so /// that the source handle remains alive. - pub fn as_stdio(&self) -> Fallible { + pub fn as_stdio(&self) -> anyhow::Result { self.as_stdio_impl() } } @@ -258,7 +255,7 @@ impl FileDescriptor { /// ``` /// use filedescriptor::Pipe; /// use std::io::{Read,Write}; -/// use failure::Error; +/// use anyhow::Error; /// /// let mut pipe = Pipe::new()?; /// pipe.write.write(b"hello")?; @@ -305,13 +302,13 @@ use std::time::Duration; /// /// The `pfd` array is mutated and the `revents` field is updated to indicate /// which of the events were received. -pub fn poll(pfd: &mut [pollfd], duration: Option) -> Fallible { +pub fn poll(pfd: &mut [pollfd], duration: Option) -> anyhow::Result { poll_impl(pfd, duration) } /// Create a pair of connected sockets /// /// This implementation creates a pair of SOCK_STREAM sockets. -pub fn socketpair() -> Fallible<(FileDescriptor, FileDescriptor)> { +pub fn socketpair() -> anyhow::Result<(FileDescriptor, FileDescriptor)> { socketpair_impl() } diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index 63cefbbcd..af613ae4d 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -2,7 +2,7 @@ use crate::{ AsRawFileDescriptor, AsRawSocketDescriptor, FileDescriptor, FromRawFileDescriptor, FromRawSocketDescriptor, IntoRawFileDescriptor, IntoRawSocketDescriptor, OwnedHandle, Pipe, }; -use failure::{bail, Fallible}; +use anyhow::bail; use std::os::unix::prelude::*; pub(crate) type HandleType = (); @@ -86,7 +86,7 @@ impl FromRawFd for OwnedHandle { impl OwnedHandle { /// Helper function to set the close-on-exec flag for a raw descriptor - fn cloexec(&mut self) -> Fallible<()> { + fn cloexec(&mut self) -> anyhow::Result<()> { let flags = unsafe { libc::fcntl(self.handle, libc::F_GETFD) }; if flags == -1 { bail!( @@ -104,7 +104,7 @@ impl OwnedHandle { Ok(()) } - fn non_atomic_dup(fd: RawFd) -> Fallible { + fn non_atomic_dup(fd: RawFd) -> anyhow::Result { let duped = unsafe { libc::dup(fd) }; if duped == -1 { bail!( @@ -126,7 +126,7 @@ impl OwnedHandle { pub(crate) fn dup_impl( fd: &F, handle_type: HandleType, - ) -> Fallible { + ) -> anyhow::Result { let fd = fd.as_raw_file_descriptor(); let duped = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }; if duped == -1 { @@ -198,7 +198,7 @@ impl FromRawFd for FileDescriptor { impl FileDescriptor { #[inline] - pub(crate) fn as_stdio_impl(&self) -> Fallible { + pub(crate) fn as_stdio_impl(&self) -> anyhow::Result { let duped = OwnedHandle::dup(self)?; let fd = duped.into_raw_fd(); let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; @@ -208,7 +208,7 @@ impl FileDescriptor { impl Pipe { #[cfg(target_os = "linux")] - pub fn new() -> Fallible { + pub fn new() -> anyhow::Result { let mut fds = [-1i32; 2]; let res = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }; if res == -1 { @@ -234,7 +234,7 @@ impl Pipe { } #[cfg(not(target_os = "linux"))] - pub fn new() -> Fallible { + pub fn new() -> anyhow::Result { let mut fds = [-1i32; 2]; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; if res == -1 { @@ -264,7 +264,7 @@ impl Pipe { #[cfg(target_os = "linux")] #[doc(hidden)] -pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { +pub fn socketpair_impl() -> anyhow::Result<(FileDescriptor, FileDescriptor)> { let mut fds = [-1i32; 2]; let res = unsafe { libc::socketpair( @@ -298,7 +298,7 @@ pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { #[cfg(not(target_os = "linux"))] #[doc(hidden)] -pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { +pub fn socketpair_impl() -> anyhow::Result<(FileDescriptor, FileDescriptor)> { let mut fds = [-1i32; 2]; let res = unsafe { libc::socketpair(libc::PF_LOCAL, libc::SOCK_STREAM, 0, fds.as_mut_ptr()) }; if res == -1 { @@ -330,7 +330,7 @@ use std::time::Duration; #[cfg(not(target_os = "macos"))] #[doc(hidden)] -pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { +pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> anyhow::Result { let poll_result = unsafe { libc::poll( pfd.as_mut_ptr(), @@ -359,9 +359,9 @@ mod macos { } #[inline] - fn check_fd(fd: RawFd) -> Fallible<()> { - failure::ensure!(fd >= 0, "illegal fd value"); - failure::ensure!( + fn check_fd(fd: RawFd) -> anyhow::Result<()> { + anyhow::ensure!(fd >= 0, "illegal fd value"); + anyhow::ensure!( (fd as usize) < FD_SETSIZE, "fd value is too large to use with select(2) on macos" ); @@ -377,7 +377,7 @@ mod macos { } } - pub fn add(&mut self, fd: RawFd) -> Fallible<()> { + pub fn add(&mut self, fd: RawFd) -> anyhow::Result<()> { check_fd(fd)?; unsafe { FD_SET(fd, &mut self.set); @@ -405,7 +405,7 @@ mod macos { set.as_mut().map(|s| s.contains(fd)).unwrap_or(false) } - pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { + pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> anyhow::Result { let mut read_set = None; let mut write_set = None; let mut exception_set = None; diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 712d80609..3261770fb 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -2,7 +2,7 @@ use crate::{ AsRawFileDescriptor, AsRawSocketDescriptor, FileDescriptor, FromRawFileDescriptor, FromRawSocketDescriptor, IntoRawFileDescriptor, IntoRawSocketDescriptor, OwnedHandle, Pipe, }; -use failure::{bail, Fallible}; +use anyhow::bail; use std::io::{self, Error as IoError}; use std::os::windows::prelude::*; use std::ptr; @@ -155,7 +155,7 @@ impl OwnedHandle { pub(crate) fn dup_impl( f: &F, handle_type: HandleType, - ) -> Fallible { + ) -> anyhow::Result { let handle = f.as_raw_file_descriptor(); if handle == INVALID_HANDLE_VALUE as _ || handle.is_null() { return Ok(OwnedHandle { @@ -206,7 +206,7 @@ impl IntoRawHandle for OwnedHandle { impl FileDescriptor { #[inline] - pub(crate) fn as_stdio_impl(&self) -> Fallible { + pub(crate) fn as_stdio_impl(&self) -> anyhow::Result { let duped = self.handle.try_clone()?; let handle = duped.into_raw_handle(); let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; @@ -307,7 +307,7 @@ impl io::Write for FileDescriptor { } impl Pipe { - pub fn new() -> Fallible { + pub fn new() -> anyhow::Result { let mut sa = SECURITY_ATTRIBUTES { nLength: std::mem::size_of::() as u32, lpSecurityDescriptor: ptr::null_mut(), @@ -347,7 +347,7 @@ fn init_winsock() { }); } -fn socket(af: i32, sock_type: i32, proto: i32) -> Fallible { +fn socket(af: i32, sock_type: i32, proto: i32) -> anyhow::Result { let s = unsafe { WSASocketW( af, @@ -370,7 +370,7 @@ fn socket(af: i32, sock_type: i32, proto: i32) -> Fallible { } #[doc(hidden)] -pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { +pub fn socketpair_impl() -> anyhow::Result<(FileDescriptor, FileDescriptor)> { init_winsock(); let s = socket(AF_INET, SOCK_STREAM, 0)?; @@ -439,7 +439,7 @@ pub fn socketpair_impl() -> Fallible<(FileDescriptor, FileDescriptor)> { } #[doc(hidden)] -pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> Fallible { +pub fn poll_impl(pfd: &mut [pollfd], duration: Option) -> anyhow::Result { let poll_result = unsafe { WSAPoll( pfd.as_mut_ptr(), From 08b0017c160da1e5ea5670112b7301601c2eefe6 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Wed, 15 Jan 2020 08:24:41 -0800 Subject: [PATCH 33/34] add FileDescriptor::set_non_blocking --- filedescriptor/Cargo.toml | 2 +- filedescriptor/src/lib.rs | 10 ++++++++++ filedescriptor/src/unix.rs | 13 +++++++++++++ filedescriptor/src/windows.rs | 33 +++++++++++++++++++++++++++++---- 4 files changed, 53 insertions(+), 5 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 133e49382..415c31005 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.6.0" +version = "0.7.0" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" diff --git a/filedescriptor/src/lib.rs b/filedescriptor/src/lib.rs index 5fce1f4f2..a2da16369 100644 --- a/filedescriptor/src/lib.rs +++ b/filedescriptor/src/lib.rs @@ -247,6 +247,16 @@ impl FileDescriptor { pub fn as_stdio(&self) -> anyhow::Result { self.as_stdio_impl() } + + /// Attempt to change the non-blocking IO mode of the file descriptor. + /// Not all kinds of file descriptor can be placed in non-blocking mode + /// on all systems, and some file descriptors will claim to be in + /// non-blocking mode but it will have no effect. + /// File descriptors based on sockets are the most portable type + /// that can be successfully made non-blocking. + pub fn set_non_blocking(&mut self, non_blocking: bool) -> anyhow::Result<()> { + self.set_non_blocking_impl(non_blocking) + } } /// Represents the readable and writable ends of a pair of descriptors diff --git a/filedescriptor/src/unix.rs b/filedescriptor/src/unix.rs index af613ae4d..b97dee4ca 100644 --- a/filedescriptor/src/unix.rs +++ b/filedescriptor/src/unix.rs @@ -204,6 +204,19 @@ impl FileDescriptor { let stdio = unsafe { std::process::Stdio::from_raw_fd(fd) }; Ok(stdio) } + + #[inline] + pub(crate) fn set_non_blocking_impl(&mut self, non_blocking: bool) -> anyhow::Result<()> { + let on = if non_blocking { 1 } else { 0 }; + let res = unsafe { libc::ioctl(self.handle.as_raw_file_descriptor(), libc::FIONBIO, &on) }; + if res != 0 { + bail!( + "failed to change non-blocking mode: {:?}", + std::io::Error::last_os_error() + ); + } + Ok(()) + } } impl Pipe { diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 3261770fb..3022185c6 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -19,8 +19,9 @@ use winapi::um::processthreadsapi::*; use winapi::um::winbase::{FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE}; use winapi::um::winnt::HANDLE; use winapi::um::winsock2::{ - accept, bind, closesocket, connect, getsockname, htonl, listen, WSAPoll, WSASocketW, - WSAStartup, INVALID_SOCKET, SOCKET, SOCK_STREAM, WSADATA, WSA_FLAG_NO_HANDLE_INHERIT, + accept, bind, closesocket, connect, getsockname, htonl, ioctlsocket, listen, WSAPoll, + WSASocketW, WSAStartup, INVALID_SOCKET, SOCKET, SOCK_STREAM, WSADATA, + WSA_FLAG_NO_HANDLE_INHERIT, }; pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd}; @@ -88,14 +89,15 @@ impl FromRawSocketDescriptor for T { unsafe impl Send for OwnedHandle {} impl OwnedHandle { - fn probe_handle_type_if_unknown(handle: HANDLE, handle_type: HandleType) -> HandleType { + fn probe_handle_type_if_unknown(handle: RawHandle, handle_type: HandleType) -> HandleType { match handle_type { HandleType::Unknown => Self::probe_handle_type(handle), t => t, } } - pub(crate) fn probe_handle_type(handle: HANDLE) -> HandleType { + pub(crate) fn probe_handle_type(handle: RawHandle) -> HandleType { + let handle = handle as HANDLE; match unsafe { GetFileType(handle) } { FILE_TYPE_CHAR => HandleType::Char, FILE_TYPE_DISK => HandleType::Disk, @@ -212,6 +214,29 @@ impl FileDescriptor { let stdio = unsafe { std::process::Stdio::from_raw_handle(handle) }; Ok(stdio) } + + #[inline] + pub(crate) fn set_non_blocking_impl(&mut self, non_blocking: bool) -> anyhow::Result<()> { + if !self.handle.is_socket_handle() { + bail!("only socket descriptors can change their non-blocking mode on windows"); + } + + let mut on = if non_blocking { 1 } else { 0 }; + let res = unsafe { + ioctlsocket( + self.as_raw_socket() as SOCKET, + winapi::um::winsock2::FIONBIO, + &mut on, + ) + }; + if res != 0 { + bail!( + "failed to change non-blocking mode: {:?}", + std::io::Error::last_os_error() + ); + } + Ok(()) + } } impl IntoRawHandle for FileDescriptor { From 8f1878c92cb8847e45f54c8d4e78eed6973af0c8 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Wed, 15 Jan 2020 22:55:36 -0800 Subject: [PATCH 34/34] filedescriptor: use winsock send/recv and respect non-blocking mode --- filedescriptor/Cargo.toml | 2 +- filedescriptor/src/windows.rs | 97 ++++++++++++++++++++++++----------- 2 files changed, 67 insertions(+), 32 deletions(-) diff --git a/filedescriptor/Cargo.toml b/filedescriptor/Cargo.toml index 415c31005..4840f9fdb 100644 --- a/filedescriptor/Cargo.toml +++ b/filedescriptor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "filedescriptor" -version = "0.7.0" +version = "0.7.1" authors = ["Wez Furlong"] edition = "2018" repository = "https://github.com/wez/wzsh" diff --git a/filedescriptor/src/windows.rs b/filedescriptor/src/windows.rs index 3022185c6..37030ee8d 100644 --- a/filedescriptor/src/windows.rs +++ b/filedescriptor/src/windows.rs @@ -19,8 +19,8 @@ use winapi::um::processthreadsapi::*; use winapi::um::winbase::{FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE}; use winapi::um::winnt::HANDLE; use winapi::um::winsock2::{ - accept, bind, closesocket, connect, getsockname, htonl, ioctlsocket, listen, WSAPoll, - WSASocketW, WSAStartup, INVALID_SOCKET, SOCKET, SOCK_STREAM, WSADATA, + accept, bind, closesocket, connect, getsockname, htonl, ioctlsocket, listen, recv, send, + WSAPoll, WSASocketW, WSAStartup, INVALID_SOCKET, SOCKET, SOCK_STREAM, WSADATA, WSA_FLAG_NO_HANDLE_INHERIT, }; pub use winapi::um::winsock2::{POLLERR, POLLHUP, POLLIN, POLLOUT, WSAPOLLFD as pollfd}; @@ -285,45 +285,80 @@ impl FromRawSocket for FileDescriptor { impl io::Read for FileDescriptor { fn read(&mut self, buf: &mut [u8]) -> Result { - let mut num_read = 0; - let ok = unsafe { - ReadFile( - self.handle.as_raw_handle() as *mut _, - buf.as_mut_ptr() as *mut _, - buf.len() as u32, - &mut num_read, - ptr::null_mut(), - ) - }; - if ok == 0 { - let err = IoError::last_os_error(); - if err.kind() == std::io::ErrorKind::BrokenPipe { - Ok(0) + if self.handle.is_socket_handle() { + // It's important to use the winsock functions to read/write + // even though ReadFile and WriteFile technically work; only + // the winsock functions respect non-blocking mode. + let num_read = unsafe { + recv( + self.as_socket_descriptor(), + buf.as_mut_ptr() as *mut _, + buf.len() as _, + 0, + ) + }; + if num_read < 0 { + Err(IoError::last_os_error()) } else { - Err(err) + Ok(num_read as usize) } } else { - Ok(num_read as usize) + let mut num_read = 0; + let ok = unsafe { + ReadFile( + self.handle.as_raw_handle() as *mut _, + buf.as_mut_ptr() as *mut _, + buf.len() as _, + &mut num_read, + ptr::null_mut(), + ) + }; + if ok == 0 { + let err = IoError::last_os_error(); + if err.kind() == std::io::ErrorKind::BrokenPipe { + Ok(0) + } else { + Err(err) + } + } else { + Ok(num_read as usize) + } } } } impl io::Write for FileDescriptor { fn write(&mut self, buf: &[u8]) -> Result { - let mut num_wrote = 0; - let ok = unsafe { - WriteFile( - self.handle.as_raw_handle() as *mut _, - buf.as_ptr() as *const _, - buf.len() as u32, - &mut num_wrote, - ptr::null_mut(), - ) - }; - if ok == 0 { - Err(IoError::last_os_error()) + if self.handle.is_socket_handle() { + let num_wrote = unsafe { + send( + self.as_socket_descriptor(), + buf.as_ptr() as *const _, + buf.len() as _, + 0, + ) + }; + if num_wrote < 0 { + Err(IoError::last_os_error()) + } else { + Ok(num_wrote as usize) + } } else { - Ok(num_wrote as usize) + let mut num_wrote = 0; + let ok = unsafe { + WriteFile( + self.handle.as_raw_handle() as *mut _, + buf.as_ptr() as *const _, + buf.len() as u32, + &mut num_wrote, + ptr::null_mut(), + ) + }; + if ok == 0 { + Err(IoError::last_os_error()) + } else { + Ok(num_wrote as usize) + } } } fn flush(&mut self) -> Result<(), io::Error> {