Skip to main content

paper/daemon/
ipc.rs

1//! IPC server for the paperscope daemon.
2//!
3//! JSON lines over a Unix socket (Linux/macOS). Each line is a JSON-encoded
4//! [`DaemonRequest`] or [`DaemonResponse`].
5
6use crate::core::index::IndexStats;
7#[cfg(unix)]
8use anyhow::Context;
9use anyhow::Result;
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12#[cfg(unix)]
13use std::os::raw::c_int;
14#[cfg(any(target_os = "linux", target_os = "android"))]
15use std::os::raw::{c_uint, c_void};
16#[cfg(unix)]
17use std::os::unix::io::AsRawFd;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20#[cfg(unix)]
21use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
22
23/// UID of the daemon process, used to authorize IPC peers (C3).
24///
25/// On Unix every connected peer must run under the same UID as the daemon;
26/// otherwise the connection is dropped before any request is handled.
27#[cfg(unix)]
28fn current_uid() -> Option<u32> {
29    unsafe { Some(getuid()) }
30}
31
32#[cfg(unix)]
33unsafe extern "C" {
34    fn getuid() -> u32;
35}
36
37/// Peer UID of a connected Unix stream socket.
38///
39/// Uses `SO_PEERCRED` on Linux/Android and `getpeereid` on BSD/macOS.
40#[cfg(unix)]
41fn peer_uid(stream: &tokio::net::UnixStream) -> std::io::Result<Option<u32>> {
42    peer_uid_fd(stream.as_raw_fd())
43}
44
45#[cfg(unix)]
46#[cfg(any(target_os = "linux", target_os = "android"))]
47fn peer_uid_fd(fd: c_int) -> std::io::Result<Option<u32>> {
48    const SOL_SOCKET: c_int = 1;
49    const SO_PEERCRED: c_int = 17;
50
51    #[repr(C)]
52    struct UCred {
53        pid: c_int,
54        uid: u32,
55        gid: u32,
56    }
57
58    unsafe extern "C" {
59        fn getsockopt(
60            sockfd: c_int,
61            level: c_int,
62            optname: c_int,
63            optval: *mut c_void,
64            optlen: *mut c_uint,
65        ) -> c_int;
66    }
67
68    let mut cred = UCred {
69        pid: 0,
70        uid: 0,
71        gid: 0,
72    };
73    let mut len: c_uint = std::mem::size_of::<UCred>() as c_uint;
74    let rc = unsafe {
75        getsockopt(
76            fd,
77            SOL_SOCKET,
78            SO_PEERCRED,
79            &mut cred as *mut UCred as *mut c_void,
80            &mut len,
81        )
82    };
83    if rc == 0 {
84        Ok(Some(cred.uid))
85    } else {
86        Err(std::io::Error::last_os_error())
87    }
88}
89
90#[cfg(unix)]
91#[cfg(not(any(target_os = "linux", target_os = "android")))]
92fn peer_uid_fd(fd: c_int) -> std::io::Result<Option<u32>> {
93    unsafe extern "C" {
94        fn getpeereid(fd: c_int, uid: *mut u32, gid: *mut u32) -> c_int;
95    }
96    let mut uid: u32 = 0;
97    let mut gid: u32 = 0;
98    let rc = unsafe { getpeereid(fd, &mut uid, &mut gid) };
99    if rc == 0 {
100        Ok(Some(uid))
101    } else {
102        Err(std::io::Error::last_os_error())
103    }
104}
105
106/// Requests sent from clients to the daemon.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108#[serde(tag = "type", rename_all = "snake_case")]
109pub enum DaemonRequest {
110    /// Index the given roots (empty = all configured roots).
111    IndexRoots { roots: Vec<PathBuf> },
112    /// Add a new root to watch and index.
113    AddRoot { path: PathBuf },
114    /// Remove a root from watching and indexing.
115    RemoveRoot { path: PathBuf },
116    /// Get current daemon status.
117    GetStatus,
118    /// Pause indexing (respects resource guard).
119    Pause,
120    /// Resume indexing.
121    Resume,
122    /// Shutdown the daemon gracefully.
123    Shutdown,
124}
125
126/// Responses sent from the daemon to clients.
127#[derive(Debug, Clone, Serialize, Deserialize)]
128#[serde(tag = "type", rename_all = "snake_case")]
129pub enum DaemonResponse {
130    /// Indexing completed with statistics.
131    IndexRoots { stats: IndexStats },
132    /// Current daemon status.
133    Status {
134        indexed_files: usize,
135        queued: usize,
136        paused: bool,
137        model: Option<String>,
138    },
139    /// Generic success.
140    Ok,
141    /// Error with message.
142    Error { msg: String },
143}
144
145/// Trait for handling daemon requests. Implement this to provide custom behavior.
146#[async_trait]
147pub trait DaemonHandler: Send + Sync {
148    /// Handle a daemon request and return a response.
149    async fn handle(&self, request: DaemonRequest) -> DaemonResponse;
150}
151
152/// Run the IPC server on the given socket path.
153///
154/// Binds to the Unix socket and serves requests until the task is aborted.
155/// Each connection is handled in its own task with a shared handler.
156#[cfg(unix)]
157pub async fn run_ipc_server(socket_path: &Path, handler: Arc<dyn DaemonHandler>) -> Result<()> {
158    use tokio::net::UnixListener;
159
160    // Remove any stale socket file
161    let _ = tokio::fs::remove_file(socket_path).await;
162    if let Some(parent) = socket_path.parent() {
163        tokio::fs::create_dir_all(parent).await?;
164    }
165
166    let listener = UnixListener::bind(socket_path)
167        .with_context(|| format!("binding to {}", socket_path.display()))?;
168
169    tracing::info!("Daemon IPC server listening on {}", socket_path.display());
170
171    loop {
172        let (stream, _) = listener.accept().await?;
173        // C3: only accept connections from the same UID as the daemon.
174        if let Some(daemon_uid) = current_uid() {
175            match peer_uid(&stream) {
176                Ok(Some(uid)) if uid == daemon_uid => {}
177                Ok(Some(uid)) => {
178                    tracing::warn!(
179                        "rejecting IPC connection from peer uid {uid} (daemon uid {daemon_uid})"
180                    );
181                    continue;
182                }
183                Ok(None) | Err(_) => {
184                    tracing::warn!(
185                        "rejecting IPC connection: unable to determine peer credentials"
186                    );
187                    continue;
188                }
189            }
190        }
191        let handler = handler.clone();
192        tokio::spawn(async move {
193            if let Err(e) = handle_connection(stream, handler).await {
194                tracing::warn!("IPC connection error: {e}");
195            }
196        });
197    }
198}
199
200/// Windows named-pipe support is not implemented yet.
201#[cfg(windows)]
202pub async fn run_ipc_server(_socket_path: &Path, _handler: Arc<dyn DaemonHandler>) -> Result<()> {
203    anyhow::bail!("daemon IPC is not yet supported on Windows")
204}
205
206#[cfg(unix)]
207async fn handle_connection(
208    stream: tokio::net::UnixStream,
209    handler: Arc<dyn DaemonHandler>,
210) -> Result<()> {
211    let (reader, mut writer) = stream.into_split();
212    let mut reader = BufReader::new(reader);
213    let mut line = String::new();
214
215    loop {
216        line.clear();
217        let bytes_read = reader.read_line(&mut line).await?;
218        if bytes_read == 0 {
219            break; // Client disconnected
220        }
221
222        let request: DaemonRequest = match serde_json::from_str(line.trim()) {
223            Ok(req) => req,
224            Err(e) => {
225                let response = DaemonResponse::Error {
226                    msg: format!("Invalid request: {e}"),
227                };
228                let json = serde_json::to_string(&response)?;
229                writer.write_all(json.as_bytes()).await?;
230                writer.write_all(b"\n").await?;
231                writer.flush().await?;
232                continue;
233            }
234        };
235
236        let response = handler.handle(request).await;
237
238        let json = serde_json::to_string(&response)?;
239        writer.write_all(json.as_bytes()).await?;
240        writer.write_all(b"\n").await?;
241        writer.flush().await?;
242    }
243
244    Ok(())
245}
246
247/// Client for connecting to the daemon IPC server.
248pub struct IpcClient {
249    #[cfg(unix)]
250    reader: BufReader<tokio::net::unix::OwnedReadHalf>,
251    #[cfg(unix)]
252    writer: tokio::net::unix::OwnedWriteHalf,
253}
254
255impl IpcClient {
256    /// Connect to the daemon IPC server.
257    #[cfg(unix)]
258    pub async fn connect(socket_path: &Path) -> Result<Self> {
259        let stream = tokio::net::UnixStream::connect(socket_path)
260            .await
261            .with_context(|| format!("connecting to {}", socket_path.display()))?;
262        let (reader, writer) = stream.into_split();
263        Ok(Self {
264            reader: BufReader::new(reader),
265            writer,
266        })
267    }
268
269    /// Windows named-pipe support is not implemented yet.
270    #[cfg(windows)]
271    pub async fn connect(_socket_path: &Path) -> Result<Self> {
272        anyhow::bail!("daemon IPC is not yet supported on Windows")
273    }
274
275    /// Send a request and wait for the response.
276    #[cfg(unix)]
277    pub async fn send(&mut self, request: DaemonRequest) -> Result<DaemonResponse> {
278        let json = serde_json::to_string(&request)?;
279        self.writer.write_all(json.as_bytes()).await?;
280        self.writer.write_all(b"\n").await?;
281        self.writer.flush().await?;
282
283        let mut line = String::new();
284        self.reader.read_line(&mut line).await?;
285        let response: DaemonResponse = serde_json::from_str(line.trim())?;
286        Ok(response)
287    }
288}