use std::io;
use tokio::io::{AsyncRead, AsyncWrite};
pub trait Accept {
type Conn: AsyncRead + AsyncWrite + Unpin + Send + 'static;
fn accept(&mut self) -> impl std::future::Future<Output = io::Result<Self::Conn>> + Send;
}
pub fn is_not_running(e: &io::Error) -> bool {
matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused)
|| cfg!(windows) && e.raw_os_error() == Some(2) }
#[cfg(windows)]
pub use windows_impl::*;
#[cfg(windows)]
mod windows_impl {
use super::*;
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::time::Duration;
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions};
pub type Conn = NamedPipeServer;
#[repr(C)]
struct RawSecurityAttributes {
n_length: u32,
lp_security_descriptor: *mut core::ffi::c_void,
b_inherit_handle: i32,
}
struct SecurityDescriptor {
ptr: *mut core::ffi::c_void,
}
unsafe impl Send for SecurityDescriptor {}
unsafe impl Sync for SecurityDescriptor {}
impl SecurityDescriptor {
fn owner_only() -> io::Result<Self> {
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
let sddl: Vec<u16> = OsStr::new("D:P(A;;GA;;;OW)\0").encode_wide().collect();
let mut psd: *mut core::ffi::c_void = std::ptr::null_mut();
let ok = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), 1 , &mut psd as *mut _ as *mut _, std::ptr::null_mut())
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
Ok(Self { ptr: psd })
}
fn as_attrs(&self) -> RawSecurityAttributes {
RawSecurityAttributes {
n_length: std::mem::size_of::<RawSecurityAttributes>() as u32,
lp_security_descriptor: self.ptr,
b_inherit_handle: 0,
}
}
}
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
unsafe {
windows_sys::Win32::Foundation::LocalFree(self.ptr);
}
}
}
pub struct Listener {
name: String,
sd: SecurityDescriptor,
next: Option<NamedPipeServer>,
}
pub fn bind(name: &str) -> io::Result<Listener> {
let sd = SecurityDescriptor::owner_only()?;
let attrs = sd.as_attrs();
let first = unsafe {
ServerOptions::new().first_pipe_instance(true).create_with_security_attributes_raw(name, &attrs as *const _ as *mut core::ffi::c_void)?
};
Ok(Listener { name: name.to_string(), sd, next: Some(first) })
}
impl super::Accept for Listener {
type Conn = Conn;
async fn accept(&mut self) -> io::Result<Conn> {
if self.next.is_none() {
let attrs = self.sd.as_attrs();
self.next = Some(unsafe { ServerOptions::new().create_with_security_attributes_raw(&self.name, &attrs as *const _ as *mut core::ffi::c_void)? });
}
let server = self.next.take().unwrap();
server.connect().await?;
let attrs = self.sd.as_attrs();
match unsafe { ServerOptions::new().create_with_security_attributes_raw(&self.name, &attrs as *const _ as *mut core::ffi::c_void) } {
Ok(inst) => self.next = Some(inst),
Err(e) => log::warn!("ripindex daemon: failed to queue the next pipe instance ({e}); will retry on the next accept"),
}
Ok(server)
}
}
pub async fn connect(name: &str) -> io::Result<NamedPipeClient> {
let deadline = tokio::time::Instant::now() + Duration::from_millis(500);
loop {
match ClientOptions::new().open(name) {
Ok(c) => return Ok(c),
Err(e) if e.raw_os_error() == Some(231) && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(20)).await;
}
Err(e) => return Err(e),
}
}
}
}
#[cfg(unix)]
pub use unix_impl::*;
#[cfg(unix)]
mod unix_impl {
use super::*;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use tokio::net::{UnixListener, UnixStream};
pub type Conn = UnixStream;
pub struct Listener(UnixListener);
pub async fn bind(path: &Path) -> io::Result<Listener> {
if path.exists() {
if UnixStream::connect(path).await.is_ok() {
return Err(io::Error::new(io::ErrorKind::AddrInUse, "a daemon is already listening"));
}
let _ = fs::remove_file(path);
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let listener = UnixListener::bind(path)?;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
Ok(Listener(listener))
}
impl super::Accept for Listener {
type Conn = Conn;
async fn accept(&mut self) -> io::Result<Conn> {
let (stream, _addr) = self.0.accept().await?;
Ok(stream)
}
}
pub async fn connect(path: &Path) -> io::Result<Conn> {
UnixStream::connect(path).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn not_running_classification() {
assert!(is_not_running(&io::Error::from(io::ErrorKind::NotFound)));
assert!(is_not_running(&io::Error::from(io::ErrorKind::ConnectionRefused)));
assert!(!is_not_running(&io::Error::from(io::ErrorKind::PermissionDenied)));
}
#[cfg(windows)]
#[tokio::test]
async fn bind_accept_connect_roundtrip_over_a_real_pipe() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let name = format!(r"\\.\pipe\ripindex-test-{}", std::process::id());
let mut listener = bind(&name).unwrap();
let server_task = tokio::spawn(async move {
let mut conn = listener.accept().await.unwrap();
let mut buf = [0u8; 5];
conn.read_exact(&mut buf).await.unwrap();
conn.write_all(b"world").await.unwrap();
});
let mut client = connect(&name).await.unwrap();
client.write_all(b"hello").await.unwrap();
let mut buf = [0u8; 5];
client.read_exact(&mut buf).await.unwrap();
assert_eq!(&buf, b"world");
server_task.await.unwrap();
}
#[cfg(windows)]
#[tokio::test]
async fn a_second_bind_of_the_same_name_fails() {
let name = format!(r"\\.\pipe\ripindex-test2-{}", std::process::id());
let _first = bind(&name).unwrap();
let second = bind(&name);
assert!(second.is_err(), "first_pipe_instance must refuse a duplicate name");
}
#[cfg(windows)]
#[tokio::test]
async fn connecting_with_no_listener_is_classified_as_not_running() {
let name = format!(r"\\.\pipe\ripindex-test-nobody-{}", std::process::id());
let err = connect(&name).await.unwrap_err();
assert!(is_not_running(&err), "{err:?}");
}
}