//! Line-delimited JSON over a named pipe (Windows) or a Unix socket (elsewhere). use std::path::PathBuf; use serde::Serialize; use serde::de::DeserializeOwned; use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadHalf, WriteHalf}; use crate::{IpcError, Peer, Request, Response}; /// Where the service listens. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Address { Pipe(String), Unix(PathBuf), } impl Address { /// `PROXY_SUITE_SOCKET` if set, else the platform's default. pub fn default_for_platform() -> Self { if let Ok(s) = std::env::var("PROXY_SUITE_SOCKET") { return if cfg!(windows) { Address::Pipe(s) } else { Address::Unix(s.into()) }; } if cfg!(windows) { Address::Pipe(crate::PIPE_NAME.into()) } else { Address::Unix(std::env::temp_dir().join("proxy-suite.sock")) } } } trait Stream: AsyncRead + AsyncWrite + Send + Unpin + 'static {} impl Stream for T {} /// One connection, either end. pub struct Conn { reader: BufReader>>, writer: WriteHalf>, identity: Identity, } enum Identity { Client, #[cfg(unix)] Unix(Option), #[cfg(windows)] Pipe(isize), } impl Conn { fn new(stream: Box, identity: Identity) -> Self { let (r, w) = tokio::io::split(stream); Self { reader: BufReader::new(r), writer: w, identity } } /// The next message, or `None` once the other end closed. pub async fn read_json(&mut self) -> Result, IpcError> { let mut line = String::new(); // A request is a configuration at most: 16 MiB is far past any. let n = (&mut self.reader).take(16 * 1024 * 1024).read_line(&mut line).await?; if n == 0 { return Ok(None); } Ok(Some(serde_json::from_str(line.trim_end())?)) } pub async fn write_json(&mut self, value: &T) -> Result<(), IpcError> { let mut line = serde_json::to_vec(value)?; line.push(b'\n'); self.writer.write_all(&line).await?; self.writer.flush().await?; Ok(()) } /// Who the other end is. On Windows the client must have sent its first message: only /// then can the server impersonate it. pub fn peer(&self) -> Peer { match &self.identity { Identity::Client => Peer { admin: false, user: "client".into() }, #[cfg(unix)] Identity::Unix(uid) => Peer { admin: *uid == Some(0), user: uid.map_or_else(|| "unknown".into(), |u| format!("uid {u}")), }, #[cfg(windows)] Identity::Pipe(handle) => windows::peer(*handle), } } } /// The listening end. pub struct Server { #[cfg(unix)] listener: tokio::net::UnixListener, #[cfg(windows)] next: tokio::net::windows::named_pipe::NamedPipeServer, #[cfg(windows)] name: String, #[cfg(windows)] sddl: String, } impl Server { /// Listens on `address`. `interactive`: whether signed-in users may connect, besides /// SYSTEM and Administrators (`userControl.enable`); on Unix the socket's mode does it. pub fn bind(address: &Address, interactive: bool) -> std::io::Result { match address { #[cfg(unix)] Address::Unix(path) => { use std::os::unix::fs::PermissionsExt; let _ = std::fs::remove_file(path); let listener = tokio::net::UnixListener::bind(path)?; std::fs::set_permissions(path, std::fs::Permissions::from_mode(if interactive { 0o666 } else { 0o600 }))?; Ok(Self { listener }) } #[cfg(windows)] Address::Pipe(name) => { let sddl = windows::sddl(interactive); let next = windows::create(name, &sddl, true)?; Ok(Self { next, name: name.clone(), sddl }) } #[allow(unreachable_patterns)] _ => Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "this address does not exist on this platform")), } } pub async fn accept(&mut self) -> std::io::Result { #[cfg(unix)] { let (stream, _) = self.listener.accept().await?; let uid = stream.peer_cred().ok().map(|c| c.uid()); Ok(Conn::new(Box::new(stream), Identity::Unix(uid))) } #[cfg(windows)] { use std::os::windows::io::AsRawHandle; self.next.connect().await?; let connected = std::mem::replace(&mut self.next, windows::create(&self.name, &self.sddl, false)?); let handle = connected.as_raw_handle() as isize; Ok(Conn::new(Box::new(connected), Identity::Pipe(handle))) } } } pub async fn connect(address: &Address) -> Result { match address { #[cfg(unix)] Address::Unix(path) => { let stream = tokio::net::UnixStream::connect(path).await.map_err(IpcError::Connect)?; Ok(Conn::new(Box::new(stream), Identity::Client)) } #[cfg(windows)] Address::Pipe(name) => { use tokio::net::windows::named_pipe::ClientOptions; let client = loop { match ClientOptions::new().open(name) { Ok(c) => break c, // Every instance busy: the next is a moment away. Err(e) if e.raw_os_error() == Some(231) => tokio::time::sleep(std::time::Duration::from_millis(50)).await, Err(e) => return Err(IpcError::Connect(e)), } }; Ok(Conn::new(Box::new(client), Identity::Client)) } #[allow(unreachable_patterns)] _ => Err(IpcError::Connect(std::io::Error::new(std::io::ErrorKind::Unsupported, "no such transport here"))), } } /// One request, its one answer. pub async fn call(address: &Address, request: &Request) -> Result { let mut conn = connect(address).await?; conn.write_json(request).await?; conn.read_json().await?.ok_or(IpcError::Closed) } /// One request, every answer until the last (a log follow), each handed to `each`. pub async fn stream(address: &Address, request: &Request, mut each: impl FnMut(Response) -> bool) -> Result<(), IpcError> { let mut conn = connect(address).await?; conn.write_json(request).await?; while let Some(response) = conn.read_json::().await? { let more = response.more; if !each(response) || !more { break; } } Ok(()) } #[cfg(windows)] mod windows { use std::ffi::c_void; use std::ptr::null_mut; use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; use windows_sys::Win32::Foundation::{CloseHandle, FALSE, HANDLE, LocalFree, TRUE}; use windows_sys::Win32::Security::Authorization::{ ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, }; use windows_sys::Win32::Security::{ CheckTokenMembership, CreateWellKnownSid, GetTokenInformation, LookupAccountSidW, RevertToSelf, SECURITY_ATTRIBUTES, SID_NAME_USE, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid, }; use windows_sys::Win32::System::Pipes::ImpersonateNamedPipeClient; use windows_sys::Win32::System::Threading::{GetCurrentThread, OpenThreadToken}; use crate::Peer; /// SYSTEM and Administrators get everything; the interactive user read and write. pub fn sddl(interactive: bool) -> String { let mut s = String::from("D:P(A;;GA;;;SY)(A;;GA;;;BA)"); if interactive { s.push_str("(A;;GRGW;;;IU)"); } s } fn wide(s: &str) -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() } pub fn create(name: &str, sddl: &str, first: bool) -> std::io::Result { let sddl_w = wide(sddl); let mut descriptor: *mut c_void = null_mut(); // SAFETY: a NUL-terminated string in, a descriptor LocalFree'd below out. let ok = unsafe { ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl_w.as_ptr(), SDDL_REVISION_1, &mut descriptor, null_mut()) }; if ok == 0 { return Err(std::io::Error::last_os_error()); } let mut attrs = SECURITY_ATTRIBUTES { nLength: std::mem::size_of::() as u32, lpSecurityDescriptor: descriptor, bInheritHandle: FALSE, }; // SAFETY: attrs and the descriptor it points at outlive the call. let server = unsafe { ServerOptions::new() // The first instance: nobody else may have made the pipe first (squatting). .first_pipe_instance(first) .reject_remote_clients(true) .create_with_security_attributes_raw(name, &mut attrs as *mut _ as *mut c_void) }; // SAFETY: allocated by ConvertStringSecurityDescriptorToSecurityDescriptorW. unsafe { LocalFree(descriptor) }; server } /// The client of the pipe, impersonated to read its token: an administrator only when /// its token holds Administrators enabled (elevated), never as it claims. pub fn peer(pipe: isize) -> Peer { let unknown = Peer { admin: false, user: "unknown".into() }; // SAFETY: the pipe handle is live for the connection; the impersonation is undone // before anything else runs on this thread. unsafe { if ImpersonateNamedPipeClient(pipe as HANDLE) == 0 { return unknown; } let mut token: HANDLE = null_mut(); let opened = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &mut token); RevertToSelf(); if opened == 0 { return unknown; } let mut sid = [0u8; 68]; let mut size = sid.len() as u32; let mut admin = 0; if CreateWellKnownSid(WinBuiltinAdministratorsSid, null_mut(), sid.as_mut_ptr() as *mut c_void, &mut size) != 0 { CheckTokenMembership(token, sid.as_mut_ptr() as *mut c_void, &mut admin); } let user = token_user(token).unwrap_or_else(|| "unknown".into()); CloseHandle(token); Peer { admin: admin != 0, user } } } unsafe fn token_user(token: HANDLE) -> Option { let mut buf = vec![0u8; 256]; let mut len = 0u32; // SAFETY: buf is as long as said. if unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) } == 0 { return None; } let user = unsafe { &*(buf.as_ptr() as *const TOKEN_USER) }; let mut name = vec![0u16; 256]; let mut domain = vec![0u16; 256]; let (mut nlen, mut dlen) = (name.len() as u32, domain.len() as u32); let mut kind: SID_NAME_USE = 0; // SAFETY: the SID points into buf, which is alive; the buffers are as long as said. let ok = unsafe { LookupAccountSidW(null_mut(), user.User.Sid, name.as_mut_ptr(), &mut nlen, domain.as_mut_ptr(), &mut dlen, &mut kind) }; if ok == 0 { return None; } let name = String::from_utf16_lossy(&name[..nlen as usize]); let domain = String::from_utf16_lossy(&domain[..dlen as usize]); Some(if domain.is_empty() { name } else { format!("{domain}\\{name}") }) } } #[cfg(test)] mod tests { use super::*; #[cfg(unix)] #[tokio::test] async fn a_round_trip_over_a_socket() { let path = std::env::temp_dir().join(format!("ps-ipc-test-{}.sock", std::process::id())); let address = Address::Unix(path.clone()); let mut server = Server::bind(&address, true).unwrap(); let handle = tokio::spawn(async move { let mut conn = server.accept().await.unwrap(); let req: Request = conn.read_json().await.unwrap().unwrap(); let peer = conn.peer(); conn.write_json(&Response::ok(serde_json::json!({ "echo": req, "uid": peer.user }))).await.unwrap(); }); let resp = call(&address, &Request::Status).await.unwrap(); assert!(resp.ok); assert_eq!(resp.data["echo"]["op"], "status"); assert!(resp.data["uid"].as_str().unwrap().starts_with("uid ")); handle.await.unwrap(); let _ = std::fs::remove_file(path); } }