@@ -0,0 +1,258 @@ |
| 1 | +//! IPC server for garlock daemon mode |
| 2 | +//! |
| 3 | +//! Unix domain socket server that listens for commands from clients. |
| 4 | + |
| 5 | +use std::fs; |
| 6 | +use std::io::{BufRead, BufReader, Write}; |
| 7 | +use std::os::unix::net::{UnixListener, UnixStream}; |
| 8 | +use std::path::PathBuf; |
| 9 | +use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; |
| 10 | +use std::thread; |
| 11 | +use std::time::Duration; |
| 12 | + |
| 13 | +use anyhow::{Context, Result}; |
| 14 | + |
| 15 | +use super::protocol::{Command, Response}; |
| 16 | + |
| 17 | +/// Get the socket path for garlock IPC |
| 18 | +pub fn socket_path() -> PathBuf { |
| 19 | + std::env::var("XDG_RUNTIME_DIR") |
| 20 | + .map(PathBuf::from) |
| 21 | + .unwrap_or_else(|_| PathBuf::from("/tmp")) |
| 22 | + .join("garlock.sock") |
| 23 | +} |
| 24 | + |
| 25 | +/// IPC server for daemon mode |
| 26 | +pub struct IpcServer { |
| 27 | + listener: UnixListener, |
| 28 | + socket_path: PathBuf, |
| 29 | +} |
| 30 | + |
| 31 | +impl IpcServer { |
| 32 | + /// Create a new IPC server |
| 33 | + /// |
| 34 | + /// Binds to the socket path and starts listening. |
| 35 | + pub fn new() -> Result<Self> { |
| 36 | + let socket_path = socket_path(); |
| 37 | + |
| 38 | + // Remove existing socket if present |
| 39 | + if socket_path.exists() { |
| 40 | + fs::remove_file(&socket_path) |
| 41 | + .with_context(|| format!("Failed to remove existing socket: {:?}", socket_path))?; |
| 42 | + } |
| 43 | + |
| 44 | + // Create parent directory if needed |
| 45 | + if let Some(parent) = socket_path.parent() { |
| 46 | + fs::create_dir_all(parent).ok(); |
| 47 | + } |
| 48 | + |
| 49 | + let listener = UnixListener::bind(&socket_path) |
| 50 | + .with_context(|| format!("Failed to bind to socket: {:?}", socket_path))?; |
| 51 | + |
| 52 | + // Set non-blocking so we can poll |
| 53 | + listener.set_nonblocking(true)?; |
| 54 | + |
| 55 | + tracing::info!(?socket_path, "IPC server listening"); |
| 56 | + |
| 57 | + Ok(Self { |
| 58 | + listener, |
| 59 | + socket_path, |
| 60 | + }) |
| 61 | + } |
| 62 | + |
| 63 | + /// Get the socket path |
| 64 | + pub fn socket_path(&self) -> &PathBuf { |
| 65 | + &self.socket_path |
| 66 | + } |
| 67 | + |
| 68 | + /// Poll for incoming connections and commands |
| 69 | + /// |
| 70 | + /// Returns a command if one was received, None otherwise. |
| 71 | + /// This is non-blocking. |
| 72 | + pub fn poll(&self) -> Option<(Command, ClientConnection)> { |
| 73 | + match self.listener.accept() { |
| 74 | + Ok((stream, _addr)) => { |
| 75 | + // Set blocking for the connection itself |
| 76 | + stream.set_nonblocking(false).ok(); |
| 77 | + stream |
| 78 | + .set_read_timeout(Some(Duration::from_secs(5))) |
| 79 | + .ok(); |
| 80 | + stream |
| 81 | + .set_write_timeout(Some(Duration::from_secs(5))) |
| 82 | + .ok(); |
| 83 | + |
| 84 | + match Self::read_command(&stream) { |
| 85 | + Ok(cmd) => { |
| 86 | + tracing::debug!(?cmd, "Received IPC command"); |
| 87 | + Some((cmd, ClientConnection { stream })) |
| 88 | + } |
| 89 | + Err(e) => { |
| 90 | + tracing::warn!("Failed to read IPC command: {}", e); |
| 91 | + None |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => None, |
| 96 | + Err(e) => { |
| 97 | + tracing::warn!("Failed to accept connection: {}", e); |
| 98 | + None |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /// Read a command from a stream |
| 104 | + fn read_command(stream: &UnixStream) -> Result<Command> { |
| 105 | + let mut reader = BufReader::new(stream); |
| 106 | + let mut line = String::new(); |
| 107 | + reader.read_line(&mut line)?; |
| 108 | + |
| 109 | + let cmd: Command = serde_json::from_str(line.trim()) |
| 110 | + .with_context(|| format!("Failed to parse command: {}", line.trim()))?; |
| 111 | + |
| 112 | + Ok(cmd) |
| 113 | + } |
| 114 | + |
| 115 | + /// Clean up the socket file |
| 116 | + pub fn cleanup(&self) { |
| 117 | + if self.socket_path.exists() { |
| 118 | + if let Err(e) = fs::remove_file(&self.socket_path) { |
| 119 | + tracing::warn!(?self.socket_path, "Failed to remove socket: {}", e); |
| 120 | + } else { |
| 121 | + tracing::debug!(?self.socket_path, "Socket removed"); |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +impl Drop for IpcServer { |
| 128 | + fn drop(&mut self) { |
| 129 | + self.cleanup(); |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +/// A connected client that can receive responses |
| 134 | +pub struct ClientConnection { |
| 135 | + stream: UnixStream, |
| 136 | +} |
| 137 | + |
| 138 | +impl ClientConnection { |
| 139 | + /// Send a response to the client |
| 140 | + pub fn respond(&mut self, response: Response) -> Result<()> { |
| 141 | + let json = serde_json::to_string(&response)?; |
| 142 | + writeln!(self.stream, "{}", json)?; |
| 143 | + self.stream.flush()?; |
| 144 | + Ok(()) |
| 145 | + } |
| 146 | +} |
| 147 | + |
| 148 | +/// IPC client for sending commands to the daemon |
| 149 | +pub struct IpcClient { |
| 150 | + stream: UnixStream, |
| 151 | +} |
| 152 | + |
| 153 | +impl IpcClient { |
| 154 | + /// Connect to the garlock daemon |
| 155 | + pub fn connect() -> Result<Self> { |
| 156 | + let socket_path = socket_path(); |
| 157 | + |
| 158 | + let stream = UnixStream::connect(&socket_path) |
| 159 | + .with_context(|| format!("Failed to connect to socket: {:?}", socket_path))?; |
| 160 | + |
| 161 | + stream.set_read_timeout(Some(Duration::from_secs(5)))?; |
| 162 | + stream.set_write_timeout(Some(Duration::from_secs(5)))?; |
| 163 | + |
| 164 | + Ok(Self { stream }) |
| 165 | + } |
| 166 | + |
| 167 | + /// Send a command and receive a response |
| 168 | + pub fn send(&mut self, command: Command) -> Result<Response> { |
| 169 | + // Send command |
| 170 | + let json = serde_json::to_string(&command)?; |
| 171 | + writeln!(self.stream, "{}", json)?; |
| 172 | + self.stream.flush()?; |
| 173 | + |
| 174 | + // Read response |
| 175 | + let mut reader = BufReader::new(&self.stream); |
| 176 | + let mut line = String::new(); |
| 177 | + reader.read_line(&mut line)?; |
| 178 | + |
| 179 | + let response: Response = serde_json::from_str(line.trim()) |
| 180 | + .with_context(|| format!("Failed to parse response: {}", line.trim()))?; |
| 181 | + |
| 182 | + Ok(response) |
| 183 | + } |
| 184 | + |
| 185 | + /// Send lock command |
| 186 | + pub fn lock(&mut self) -> Result<Response> { |
| 187 | + self.send(Command::Lock) |
| 188 | + } |
| 189 | + |
| 190 | + /// Query current state |
| 191 | + pub fn query_state(&mut self) -> Result<Response> { |
| 192 | + self.send(Command::QueryState) |
| 193 | + } |
| 194 | + |
| 195 | + /// Request daemon shutdown |
| 196 | + pub fn shutdown(&mut self) -> Result<Response> { |
| 197 | + self.send(Command::Shutdown) |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +/// Channel-based command receiver for integration with event loop |
| 202 | +pub struct CommandReceiver { |
| 203 | + rx: Receiver<(Command, Sender<Response>)>, |
| 204 | + _server_thread: thread::JoinHandle<()>, |
| 205 | +} |
| 206 | + |
| 207 | +impl CommandReceiver { |
| 208 | + /// Start a background thread to handle IPC connections |
| 209 | + pub fn start() -> Result<Self> { |
| 210 | + let server = IpcServer::new()?; |
| 211 | + let (tx, rx) = mpsc::channel(); |
| 212 | + |
| 213 | + let handle = thread::spawn(move || { |
| 214 | + loop { |
| 215 | + if let Some((cmd, mut client)) = server.poll() { |
| 216 | + let (resp_tx, resp_rx) = mpsc::channel(); |
| 217 | + |
| 218 | + // Send command to main thread |
| 219 | + if tx.send((cmd, resp_tx)).is_err() { |
| 220 | + // Main thread closed, exit |
| 221 | + break; |
| 222 | + } |
| 223 | + |
| 224 | + // Wait for response from main thread |
| 225 | + match resp_rx.recv_timeout(Duration::from_secs(30)) { |
| 226 | + Ok(response) => { |
| 227 | + if let Err(e) = client.respond(response) { |
| 228 | + tracing::warn!("Failed to send response: {}", e); |
| 229 | + } |
| 230 | + } |
| 231 | + Err(_) => { |
| 232 | + let _ = client.respond(Response::error("Timeout waiting for response")); |
| 233 | + } |
| 234 | + } |
| 235 | + } |
| 236 | + |
| 237 | + // Small sleep to avoid busy loop |
| 238 | + thread::sleep(Duration::from_millis(10)); |
| 239 | + } |
| 240 | + |
| 241 | + server.cleanup(); |
| 242 | + }); |
| 243 | + |
| 244 | + Ok(Self { |
| 245 | + rx, |
| 246 | + _server_thread: handle, |
| 247 | + }) |
| 248 | + } |
| 249 | + |
| 250 | + /// Try to receive a command (non-blocking) |
| 251 | + pub fn try_recv(&self) -> Option<(Command, Sender<Response>)> { |
| 252 | + match self.rx.try_recv() { |
| 253 | + Ok(cmd) => Some(cmd), |
| 254 | + Err(TryRecvError::Empty) => None, |
| 255 | + Err(TryRecvError::Disconnected) => None, |
| 256 | + } |
| 257 | + } |
| 258 | +} |