Visual Studio Code, rebuilt in Rust
Rust
//! Named pipes, the IPC handles ipc.net.ts uses on Windows (`createRandomIPCHandle`, `createStaticIPCHandle`): the
//! extension host connection and the single instance pipe. The handles are overlapped, so one thread reads while
//! another writes; synchronous I/O on one pipe handle is serialized by Windows.
use std::io::{Error, ErrorKind, Read, Result, Write};
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::Path;
use std::ptr::{null, null_mut};
use std::time::Duration;
use windows_sys::Win32::Foundation::{ERROR_BROKEN_PIPE, ERROR_IO_PENDING, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE, WAIT_TIMEOUT};
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, FILE_FLAGS_AND_ATTRIBUTES, OPEN_EXISTING, PIPE_ACCESS_DUPLEX, ReadFile, SECURITY_IDENTIFICATION, SECURITY_SQOS_PRESENT, WriteFile};
use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED};
use windows_sys::Win32::System::Pipes::{ConnectNamedPipe, CreateNamedPipeW, GetNamedPipeServerProcessId, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, PIPE_WAIT, WaitNamedPipeW};
use windows_sys::Win32::System::Threading::{CreateEventW, INFINITE};
/// libuv's pipe buffer size (uv_pipe_bind on Windows).
const BUFFER_SIZE: u32 = 65536;
pub struct Listener {
name: Vec<u16>,
pending: OwnedHandle,
}
impl Listener {
/// Fails when another process already listens on `name` (`FILE_FLAG_FIRST_PIPE_INSTANCE`), as Node's `listen` on a
/// taken pipe fails with EADDRINUSE.
pub fn bind(name: &Path) -> Result<Listener> {
let name = wide(name);
let pending = create_instance(&name, FILE_FLAG_FIRST_PIPE_INSTANCE)?;
Ok(Listener { name, pending })
}
/// Waits for a client, then listens on a new instance for the next one.
pub fn accept(&mut self, timeout: Option<Duration>) -> Result<Stream> {
let handle = self.pending.as_raw_handle();
// SAFETY: `handle` is the pending instance, open while `self` lives; `overlapped` stays valid until the operation ends (overlapped()).
let connected = match overlapped(handle, timeout, |overlapped| unsafe { ConnectNamedPipe(handle, overlapped) }) {
Ok(_) => Ok(()),
// A client that connected before the call, or connected and closed: the stream reads its data or EOF.
Err(error) if [ERROR_PIPE_CONNECTED, ERROR_NO_DATA].map(|code| Some(code as i32)).contains(&error.raw_os_error()) => Ok(()),
Err(error) => Err(error),
};
if let Err(error) = connected {
if error.kind() != ErrorKind::TimedOut {
self.pending = create_instance(&self.name, 0)?;
}
return Err(error);
}
let next = create_instance(&self.name, 0)?;
Ok(Stream(std::mem::replace(&mut self.pending, next)))
}
}
pub struct Stream(OwnedHandle);
impl Stream {
/// `net.connect` to a pipe: waits while every instance is busy, fails when none listens.
pub fn connect(name: &Path) -> Result<Stream> {
let name = wide(name);
loop {
// SECURITY_IDENTIFICATION: the server learns who connects but cannot act as this process.
let flags = FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION;
// SAFETY: `name` is NUL-terminated UTF-16, alive for the call; the security and template arguments may be null.
let handle = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, null(), OPEN_EXISTING, flags, null_mut()) };
if handle != INVALID_HANDLE_VALUE {
// SAFETY: a valid handle (checked above) that nothing else owns.
return Ok(Stream(unsafe { OwnedHandle::from_raw_handle(handle) }));
}
let error = Error::last_os_error();
if error.raw_os_error() != Some(ERROR_PIPE_BUSY as i32) {
return Err(error);
}
// SAFETY: `name` is NUL-terminated UTF-16, alive for the call.
if unsafe { WaitNamedPipeW(name.as_ptr(), 5000) } == 0 {
return Err(Error::last_os_error());
}
}
}
#[cfg(test)]
pub fn pair() -> Result<(Stream, Stream)> {
let name = random_ipc_handle();
let mut listener = Listener::bind(Path::new(&name))?;
let client = Stream::connect(Path::new(&name))?;
Ok((listener.accept(None)?, client))
}
pub fn try_clone(&self) -> Result<Stream> {
self.0.try_clone().map(Stream)
}
/// The process that listens on the pipe this client connected to.
pub fn server_process_id(&self) -> Result<u32> {
let mut pid = 0;
// SAFETY: the handle is open while `self` lives; `pid` is a local the call fills.
if unsafe { GetNamedPipeServerProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
return Err(Error::last_os_error());
}
Ok(pid)
}
}
/// ipc.net.ts `createRandomIPCHandle` on Windows.
pub fn random_ipc_handle() -> String {
format!(r"\\.\pipe\vscode-ipc-{}-sock", crate::main_thread_storage::generate_uuid())
}
impl Read for &Stream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let handle = self.0.as_raw_handle();
let length = u32::try_from(buf.len()).unwrap_or(u32::MAX);
// SAFETY: `buf` is writable for `length` bytes and outlives the operation: overlapped() returns only once it ended.
match overlapped(handle, None, |overlapped| unsafe { ReadFile(handle, buf.as_mut_ptr(), length, null_mut(), overlapped) }) {
Ok(read) => Ok(read as usize),
Err(error) if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) => Ok(0),
Err(error) => Err(error),
}
}
}
impl Write for &Stream {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let handle = self.0.as_raw_handle();
let length = u32::try_from(buf.len()).unwrap_or(u32::MAX);
// SAFETY: `buf` is readable for `length` bytes and outlives the operation: overlapped() returns only once it ended.
overlapped(handle, None, |overlapped| unsafe { WriteFile(handle, buf.as_ptr(), length, null_mut(), overlapped) }).map(|written| written as usize)
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
impl Read for Stream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
(&*self).read(buf)
}
}
impl Write for Stream {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
(&*self).write(buf)
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
fn wide(name: &Path) -> Vec<u16> {
name.as_os_str().encode_wide().chain([0]).collect()
}
/// One pipe instance as libuv's server creates them (`uv_pipe_bind`, `pipe_alloc_accept`): duplex, byte mode, local
/// clients only.
fn create_instance(name: &[u16], flags: FILE_FLAGS_AND_ATTRIBUTES) -> Result<OwnedHandle> {
let mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS;
// SAFETY: `name` is NUL-terminated UTF-16, alive for the call; null security attributes are allowed.
let handle = unsafe { CreateNamedPipeW(name.as_ptr(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | flags, mode, PIPE_UNLIMITED_INSTANCES, BUFFER_SIZE, BUFFER_SIZE, 0, null()) };
if handle == INVALID_HANDLE_VALUE {
return Err(Error::last_os_error());
}
// SAFETY: a valid handle (checked above) that nothing else owns.
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
}
/// Starts one overlapped operation and waits for it, at most `timeout`; the bytes it moved.
fn overlapped(handle: HANDLE, timeout: Option<Duration>, start: impl FnOnce(*mut OVERLAPPED) -> i32) -> Result<u32> {
// SAFETY: null arguments make an unnamed manual-reset event.
let event = unsafe { CreateEventW(null(), 1, 0, null()) };
if event.is_null() {
return Err(Error::last_os_error());
}
// SAFETY: a non-null event handle (checked above) that nothing else owns.
let event = unsafe { OwnedHandle::from_raw_handle(event) };
// SAFETY: OVERLAPPED is integers and pointers, valid when zeroed.
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
overlapped.hEvent = event.as_raw_handle();
if start(&mut overlapped) == 0 {
let error = Error::last_os_error();
if error.raw_os_error() != Some(ERROR_IO_PENDING as i32) {
return Err(error);
}
}
let milliseconds = timeout.map_or(INFINITE, |timeout| u32::try_from(timeout.as_millis()).unwrap_or(INFINITE - 1));
let mut transferred = 0;
// SAFETY: `overlapped` is the structure the operation started with; `transferred` is a local.
if unsafe { GetOverlappedResultEx(handle, &overlapped, &mut transferred, milliseconds, 0) } != 0 {
return Ok(transferred);
}
let error = Error::last_os_error();
if error.raw_os_error() == Some(WAIT_TIMEOUT as i32) {
// SAFETY: the OVERLAPPED lives on this stack: the cancelled operation must end before it goes.
unsafe {
CancelIoEx(handle, &overlapped);
GetOverlappedResult(handle, &overlapped, &mut transferred, 1);
}
return Err(Error::new(ErrorKind::TimedOut, "the pipe operation timed out"));
}
Err(error)
}