use futures::{Stream, StreamExt, stream::SelectAll}; #[cfg(unix)] use std::path::PathBuf; use std::{ io::ErrorKind, pin::Pin, task::{Context, Poll}, }; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, ReadHalf, WriteHalf}; use tokio_stream::wrappers::LinesStream; #[cfg(unix)] use tokio::net::UnixListener; #[cfg(unix)] use tokio::net::UnixStream; #[cfg(windows)] use tokio::net::TcpListener; #[cfg(windows)] use tokio::net::TcpStream; use crate::{FrontendEvent, FrontendRequest, IpcError, IpcListenerCreationError}; pub struct AsyncFrontendListener { #[cfg(windows)] listener: TcpListener, #[cfg(unix)] listener: UnixListener, #[cfg(unix)] socket_path: PathBuf, #[cfg(unix)] line_streams: SelectAll>>>, #[cfg(windows)] line_streams: SelectAll>>>, #[cfg(unix)] tx_streams: Vec>, #[cfg(windows)] tx_streams: Vec>, } impl AsyncFrontendListener { pub async fn new() -> Result { #[cfg(unix)] let (socket_path, listener) = { let socket_path = crate::default_socket_path()?; log::debug!("remove socket: {socket_path:?}"); if socket_path.exists() { // try to connect to see if some other instance // of lan-mouse is already running match UnixStream::connect(&socket_path).await { // connected -> lan-mouse is already running Ok(_) => return Err(IpcListenerCreationError::AlreadyRunning), // lan-mouse is not running but a socket was left behind Err(e) => { log::debug!("{socket_path:?}: {e} - removing left behind socket"); let _ = std::fs::remove_file(&socket_path); } } } let listener = match UnixListener::bind(&socket_path) { Ok(ls) => ls, // some other lan-mouse instance has bound the socket in the meantime Err(e) if e.kind() == ErrorKind::AddrInUse => { return Err(IpcListenerCreationError::AlreadyRunning); } Err(e) => return Err(IpcListenerCreationError::Bind(e)), }; (socket_path, listener) }; #[cfg(windows)] let listener = match TcpListener::bind("127.0.0.1:5252").await { Ok(ls) => ls, // some other lan-mouse instance has bound the socket in the meantime Err(e) if e.kind() == ErrorKind::AddrInUse => { return Err(IpcListenerCreationError::AlreadyRunning); } Err(e) => return Err(IpcListenerCreationError::Bind(e)), }; let adapter = Self { listener, #[cfg(unix)] socket_path, line_streams: SelectAll::new(), tx_streams: vec![], }; Ok(adapter) } pub async fn broadcast(&mut self, notify: FrontendEvent) { // encode event let mut json = serde_json::to_string(¬ify).unwrap(); json.push('\n'); let mut keep = vec![]; // TODO do simultaneously for tx in self.tx_streams.iter_mut() { // write len + payload if tx.write(json.as_bytes()).await.is_err() { keep.push(false); continue; } keep.push(true); } // could not find a better solution because async let mut keep = keep.into_iter(); self.tx_streams.retain(|_| keep.next().unwrap()); } } #[cfg(unix)] impl Drop for AsyncFrontendListener { fn drop(&mut self) { log::debug!("remove socket: {:?}", self.socket_path); let _ = std::fs::remove_file(&self.socket_path); } } impl Stream for AsyncFrontendListener { type Item = Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if let Poll::Ready(Some(Ok(l))) = self.line_streams.poll_next_unpin(cx) { let request = serde_json::from_str(l.as_str()).map_err(|e| e.into()); return Poll::Ready(Some(request)); } let mut sync = false; while let Poll::Ready(Ok((stream, _))) = self.listener.poll_accept(cx) { let (rx, tx) = tokio::io::split(stream); let buf_reader = BufReader::new(rx); let lines = buf_reader.lines(); let lines = LinesStream::new(lines); self.line_streams.push(lines); self.tx_streams.push(tx); sync = true; } if sync { Poll::Ready(Some(Ok(FrontendRequest::Sync))) } else { Poll::Pending } } }