use std::{
ffi::{OsStr, OsString},
fs::File,
io,
os::windows::{fs::OpenOptionsExt, io::AsRawHandle},
time::{Duration, Instant},
};
use tokio::net::windows::named_pipe::{
ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions,
};
use windows_sys::Win32::{
Foundation::{ERROR_NO_DATA, ERROR_PIPE_BUSY},
Storage::FileSystem::SECURITY_IDENTIFICATION,
};
use super::security::{owned_by_current_user, OwnerOnly};
const PIPE_BUSY_TIMEOUT: Duration = Duration::from_secs(5);
const PIPE_BUSY_POLL_INTERVAL: Duration = Duration::from_millis(5);
pub(super) struct PipeServer {
name: OsString,
security: OwnerOnly,
next: Option<NamedPipeServer>,
}
impl PipeServer {
pub(super) fn create(name: &OsStr) -> io::Result<Self> {
let security = OwnerOnly::new()?;
let next = instance(name, &security, Instance::First)?;
Ok(Self {
name: name.to_owned(),
security,
next: Some(next),
})
}
pub(super) async fn accept(&mut self) -> io::Result<NamedPipeServer> {
let Some(waiting) = &self.next else {
return std::future::pending().await;
};
match waiting.connect().await {
Ok(()) => {}
Err(error) if error.raw_os_error() == Some(ERROR_NO_DATA as i32) => {}
Err(error) => return Err(error),
}
let next = instance(&self.name, &self.security, Instance::Another)?;
Ok(self
.next
.replace(next)
.expect("the instance that connected was there"))
}
}
impl Drop for PipeServer {
fn drop(&mut self) {
drop(self.next.take());
let _ = probe(&self.name);
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Instance {
First,
Another,
}
fn instance(name: &OsStr, security: &OwnerOnly, which: Instance) -> io::Result<NamedPipeServer> {
let mut attributes = security.attributes();
unsafe {
ServerOptions::new()
.first_pipe_instance(which == Instance::First)
.reject_remote_clients(true)
.create_with_security_attributes_raw(name, (&raw mut attributes).cast())
}
}
pub(super) enum Opened<Client> {
Client(Client),
Missing,
Busy,
Foreign,
}
fn opened<Client: AsRawHandle>(result: io::Result<Client>) -> io::Result<Opened<Client>> {
match result {
Ok(client) => Ok(if owned_by_current_user(client.as_raw_handle())? {
Opened::Client(client)
} else {
Opened::Foreign
}),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Opened::Missing),
Err(error) if error.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) => Ok(Opened::Busy),
Err(error) => Err(error),
}
}
pub(super) fn probe(name: &OsStr) -> io::Result<Opened<File>> {
opened(
File::options()
.read(true)
.write(true)
.security_qos_flags(SECURITY_IDENTIFICATION)
.open(name),
)
}
pub(super) fn try_open(name: &OsStr) -> io::Result<Opened<NamedPipeClient>> {
opened(ClientOptions::new().open(name))
}
pub(super) async fn open(name: &OsStr) -> io::Result<Option<NamedPipeClient>> {
let started = Instant::now();
loop {
match try_open(name)? {
Opened::Client(client) => return Ok(Some(client)),
Opened::Missing => return Ok(None),
Opened::Foreign => return Err(foreign(name)),
Opened::Busy => {}
}
let elapsed = started.elapsed();
if elapsed >= PIPE_BUSY_TIMEOUT {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
format!(
"every instance of {} stayed taken for PIPE_BUSY_TIMEOUT ({PIPE_BUSY_TIMEOUT:?}; waited {elapsed:?})",
name.display()
),
));
}
tokio::time::sleep(PIPE_BUSY_POLL_INTERVAL).await;
}
}
pub(super) fn foreign(name: &OsStr) -> io::Error {
io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"{} was created by another user, so it is not this user's rho daemon",
name.display()
),
)
}
#[cfg(test)]
#[path = "pipe_tests.rs"]
mod tests;