1use 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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize)]
108#[serde(tag = "type", rename_all = "snake_case")]
109pub enum DaemonRequest {
110 IndexRoots { roots: Vec<PathBuf> },
112 AddRoot { path: PathBuf },
114 RemoveRoot { path: PathBuf },
116 GetStatus,
118 Pause,
120 Resume,
122 Shutdown,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
128#[serde(tag = "type", rename_all = "snake_case")]
129pub enum DaemonResponse {
130 IndexRoots { stats: IndexStats },
132 Status {
134 indexed_files: usize,
135 queued: usize,
136 paused: bool,
137 model: Option<String>,
138 },
139 Ok,
141 Error { msg: String },
143}
144
145#[async_trait]
147pub trait DaemonHandler: Send + Sync {
148 async fn handle(&self, request: DaemonRequest) -> DaemonResponse;
150}
151
152#[cfg(unix)]
157pub async fn run_ipc_server(socket_path: &Path, handler: Arc<dyn DaemonHandler>) -> Result<()> {
158 use tokio::net::UnixListener;
159
160 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 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#[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; }
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
247pub 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 #[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 #[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 #[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}