@@ -0,0 +1,201 @@ |
| 1 | +use std::collections::HashSet; |
| 2 | +use std::io::{BufRead, BufReader, Write}; |
| 3 | +use std::os::unix::net::{UnixListener, UnixStream}; |
| 4 | +use std::path::PathBuf; |
| 5 | + |
| 6 | +use serde_json::Value; |
| 7 | + |
| 8 | +use super::protocol::{Event, Request, Response}; |
| 9 | + |
| 10 | +/// Result of reading from a client |
| 11 | +enum ReadResult { |
| 12 | + Request(Request), |
| 13 | + WouldBlock, |
| 14 | + Disconnected, |
| 15 | +} |
| 16 | + |
| 17 | +/// A connected IPC client |
| 18 | +struct Client { |
| 19 | + stream: UnixStream, |
| 20 | + reader: BufReader<UnixStream>, |
| 21 | + subscriptions: HashSet<String>, |
| 22 | +} |
| 23 | + |
| 24 | +impl Client { |
| 25 | + fn new(stream: UnixStream) -> std::io::Result<Self> { |
| 26 | + stream.set_nonblocking(true)?; |
| 27 | + let reader = BufReader::new(stream.try_clone()?); |
| 28 | + Ok(Self { |
| 29 | + stream, |
| 30 | + reader, |
| 31 | + subscriptions: HashSet::new(), |
| 32 | + }) |
| 33 | + } |
| 34 | + |
| 35 | + fn read_request(&mut self) -> ReadResult { |
| 36 | + let mut line = String::new(); |
| 37 | + match self.reader.read_line(&mut line) { |
| 38 | + Ok(0) => ReadResult::Disconnected, |
| 39 | + Ok(_) => { |
| 40 | + match serde_json::from_str(&line) { |
| 41 | + Ok(req) => ReadResult::Request(req), |
| 42 | + Err(_) => ReadResult::WouldBlock, // Malformed, ignore |
| 43 | + } |
| 44 | + } |
| 45 | + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => ReadResult::WouldBlock, |
| 46 | + Err(_) => ReadResult::Disconnected, |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + fn send_response(&mut self, response: &Response) -> std::io::Result<()> { |
| 51 | + let json = serde_json::to_string(response)?; |
| 52 | + writeln!(self.stream, "{}", json)?; |
| 53 | + self.stream.flush() |
| 54 | + } |
| 55 | + |
| 56 | + fn send_event(&mut self, event: &Event) -> std::io::Result<()> { |
| 57 | + let json = serde_json::to_string(event)?; |
| 58 | + writeln!(self.stream, "{}", json)?; |
| 59 | + self.stream.flush() |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +/// IPC server for external control |
| 64 | +pub struct IpcServer { |
| 65 | + listener: UnixListener, |
| 66 | + clients: Vec<Client>, |
| 67 | + socket_path: PathBuf, |
| 68 | +} |
| 69 | + |
| 70 | +impl IpcServer { |
| 71 | + /// Create a new IPC server |
| 72 | + pub fn new() -> std::io::Result<Self> { |
| 73 | + let socket_path = Self::socket_path(); |
| 74 | + |
| 75 | + // Remove existing socket |
| 76 | + let _ = std::fs::remove_file(&socket_path); |
| 77 | + |
| 78 | + // Create parent directory if needed |
| 79 | + if let Some(parent) = socket_path.parent() { |
| 80 | + std::fs::create_dir_all(parent)?; |
| 81 | + } |
| 82 | + |
| 83 | + let listener = UnixListener::bind(&socket_path)?; |
| 84 | + listener.set_nonblocking(true)?; |
| 85 | + |
| 86 | + // Set socket permissions to user-only |
| 87 | + #[cfg(unix)] |
| 88 | + { |
| 89 | + use std::os::unix::fs::PermissionsExt; |
| 90 | + std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600))?; |
| 91 | + } |
| 92 | + |
| 93 | + tracing::info!("IPC server listening on {:?}", socket_path); |
| 94 | + |
| 95 | + Ok(Self { |
| 96 | + listener, |
| 97 | + clients: Vec::new(), |
| 98 | + socket_path, |
| 99 | + }) |
| 100 | + } |
| 101 | + |
| 102 | + /// Get the socket path |
| 103 | + fn socket_path() -> PathBuf { |
| 104 | + std::env::var("XDG_RUNTIME_DIR") |
| 105 | + .map(|dir| PathBuf::from(dir).join("gar.sock")) |
| 106 | + .unwrap_or_else(|_| PathBuf::from("/tmp/gar.sock")) |
| 107 | + } |
| 108 | + |
| 109 | + /// Accept new connections (non-blocking) |
| 110 | + pub fn accept_connections(&mut self) { |
| 111 | + loop { |
| 112 | + match self.listener.accept() { |
| 113 | + Ok((stream, _addr)) => { |
| 114 | + tracing::debug!("New IPC client connected"); |
| 115 | + match Client::new(stream) { |
| 116 | + Ok(client) => self.clients.push(client), |
| 117 | + Err(e) => tracing::warn!("Failed to setup client: {}", e), |
| 118 | + } |
| 119 | + } |
| 120 | + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break, |
| 121 | + Err(e) => { |
| 122 | + tracing::warn!("Failed to accept connection: {}", e); |
| 123 | + break; |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + /// Process incoming requests from all clients |
| 130 | + /// Returns a list of (client_index, request) pairs |
| 131 | + pub fn poll_requests(&mut self) -> Vec<(usize, Request)> { |
| 132 | + let mut requests = Vec::new(); |
| 133 | + let mut disconnected = Vec::new(); |
| 134 | + |
| 135 | + for (i, client) in self.clients.iter_mut().enumerate() { |
| 136 | + match client.read_request() { |
| 137 | + ReadResult::Request(req) => requests.push((i, req)), |
| 138 | + ReadResult::Disconnected => disconnected.push(i), |
| 139 | + ReadResult::WouldBlock => {} |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + // Remove disconnected clients (in reverse order to preserve indices) |
| 144 | + for i in disconnected.into_iter().rev() { |
| 145 | + tracing::debug!("IPC client disconnected"); |
| 146 | + self.clients.remove(i); |
| 147 | + } |
| 148 | + |
| 149 | + requests |
| 150 | + } |
| 151 | + |
| 152 | + /// Send a response to a specific client |
| 153 | + pub fn send_response(&mut self, client_idx: usize, response: Response) { |
| 154 | + if let Some(client) = self.clients.get_mut(client_idx) { |
| 155 | + if let Err(e) = client.send_response(&response) { |
| 156 | + tracing::warn!("Failed to send response: {}", e); |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + /// Subscribe a client to events |
| 162 | + pub fn subscribe(&mut self, client_idx: usize, events: Vec<String>) { |
| 163 | + if let Some(client) = self.clients.get_mut(client_idx) { |
| 164 | + for event in events { |
| 165 | + client.subscriptions.insert(event); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + /// Broadcast an event to all subscribed clients |
| 171 | + pub fn broadcast_event(&mut self, event_name: &str, data: Value) { |
| 172 | + let event = Event::new(event_name, data); |
| 173 | + let mut disconnected = Vec::new(); |
| 174 | + |
| 175 | + for (i, client) in self.clients.iter_mut().enumerate() { |
| 176 | + if client.subscriptions.contains(event_name) || client.subscriptions.contains("*") { |
| 177 | + if let Err(_) = client.send_event(&event) { |
| 178 | + disconnected.push(i); |
| 179 | + } |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + // Remove failed clients |
| 184 | + for i in disconnected.into_iter().rev() { |
| 185 | + self.clients.remove(i); |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + /// Get client count |
| 190 | + pub fn client_count(&self) -> usize { |
| 191 | + self.clients.len() |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +impl Drop for IpcServer { |
| 196 | + fn drop(&mut self) { |
| 197 | + // Clean up socket file |
| 198 | + let _ = std::fs::remove_file(&self.socket_path); |
| 199 | + tracing::debug!("IPC server shutdown, socket removed"); |
| 200 | + } |
| 201 | +} |