//! Server side of the big-indexd protocol: accept connections, admit same-UID //! peers, parse newline-delimited versioned requests, and reply. The wire types //! and the client live in the shared `big-indexd-client` crate; this module //! only serves. use crate::watch::{WatchControlCommand, WatchMessage}; use crate::{catalogue, config, index, origin, query, settings}; use anyhow::{Context, Result}; use big_indexd_client::{PROTOCOL_VERSION, Reply, Request, RequestBody}; use std::io::{self, BufRead, BufReader, Write}; use std::os::fd::AsRawFd; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::mpsc::Sender; use tantivy::IndexReader; /// Handle the IPC thread uses to drive the watcher: deliver lifecycle commands and /// read the live `paused` flag for `status`. pub struct Control { pub commands: Sender, pub paused: Arc, pub activity: Arc, /// Files whose content extraction is deferred by the edit cooldown or by /// another process holding them busy; query and status replies carry it /// so a client can say content is still being indexed. pub pending_content: Arc, /// Folders the watcher could not watch. pub unwatched_dirs: Arc, } /// Upper bound on a single request line. A query is a few bytes; this only refuses a /// client that streams an endless line (local DoS; the socket is 0600, same-user). const MAX_REQUEST_BYTES: u64 = 64 * 1024; /// Connections served at once. Each costs a thread; the clients are a CLI and a /// couple of desktop integrations, so this is generous and still bounds a client /// that leaks connections. const MAX_LIVE_CONNECTIONS: usize = 16; /// How long a connection may sit silent before we hang up. Clients are allowed to /// keep a connection open between a user's keystrokes, so this is minutes rather /// than seconds; it only reclaims threads from clients that died without closing. const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300); /// How long a reply may take to drain. Bounds a client that connects, asks, then /// stops reading: without it that client owns its thread forever. const WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15); /// Decrements the live-connection count however the thread ends, including a panic. struct ConnectionSlot(Arc); impl Drop for ConnectionSlot { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::Relaxed); } } fn err(message: impl Into) -> Reply { Reply::Error { v: PROTOCOL_VERSION, message: message.into(), } } /// Serve requests on `sock` until killed. Holds the index open; clients may send /// multiple newline-delimited requests per connection. Only same-UID peers are /// admitted (defense in depth over 0600). /// /// # Errors /// /// Returns an error when the socket cannot be prepared or bound. pub fn serve( index: IndexReader, content_index: IndexReader, sock: &Path, control: Control, origin_db: PathBuf, state_db: PathBuf, history: crate::history::SharedHistory, ) -> Result<()> { let listener = bind_private_socket(sock)?; // One thread per connection. Served inline, a client holding its connection // open (which the client crate supports) would block every other client, and // a handler panic would take the whole daemon down; a connection thread only // takes itself. let live = Arc::new(std::sync::atomic::AtomicUsize::new(0)); for stream in listener.incoming() { let s = match stream { Ok(s) => s, Err(e) => { log::warn!("accept error: {e}"); // Out of descriptors or memory: the pending connection stays // queued and accept fails again at once, so wait for a // connection thread to finish instead of spinning. if matches!( e.raw_os_error(), Some(libc::EMFILE | libc::ENFILE | libc::ENOBUFS | libc::ENOMEM) ) { std::thread::sleep(std::time::Duration::from_millis(100)); } continue; } }; if !peer_is_self(&s) { log::warn!("rejected connection from a different uid"); continue; } let _ = s.set_read_timeout(Some(IDLE_TIMEOUT)); let _ = s.set_write_timeout(Some(WRITE_TIMEOUT)); if live.load(Ordering::Relaxed) >= MAX_LIVE_CONNECTIONS { refuse_busy(s); continue; } live.fetch_add(1, Ordering::Relaxed); let slot = ConnectionSlot(live.clone()); spawn_connection( s, slot, &index, &content_index, &control, &origin_db, &state_db, &history, ); } Ok(()) } /// Bind the socket in a runtime directory that only this user can reach. fn bind_private_socket(sock: &Path) -> Result { if let Some(dir) = sock.parent() { std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?; // Must be ours, a real directory, and private: clients do not // authenticate the server, so whoever owns the directory could replace // the socket. The runtime directory comes from the environment, which // the daemon does not control. // // Checked before the chmod, and with `symlink_metadata`: the other order // followed a planted symlink and changed the mode of someone else's // directory on the way to refusing. let entry = std::fs::symlink_metadata(dir).with_context(|| format!("stat {}", dir.display()))?; if entry.file_type().is_symlink() { anyhow::bail!("{} is a symlink; refusing to bind inside it", dir.display()); } // SAFETY: getuid is always safe; it reads the calling process's own uid. let us = unsafe { libc::getuid() }; if entry.uid() != us { anyhow::bail!( "{} is owned by uid {}, not us ({us})", dir.display(), entry.uid() ); } std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)) .with_context(|| format!("restrict {}", dir.display()))?; } // A socket left by a stopped daemon; the bind below reports what stays. let _ = std::fs::remove_file(sock); let listener = UnixListener::bind(sock).with_context(|| format!("bind {}", sock.display()))?; std::fs::set_permissions(sock, std::fs::Permissions::from_mode(0o600)) .context("socket perms 0600")?; log::info!( "listening on {} (protocol v{PROTOCOL_VERSION})", sock.display() ); Ok(listener) } /// Say so instead of closing silently: a bare EOF looks to the client like a /// crashed daemon, and the caller cannot tell "busy" from "gone". fn refuse_busy(mut s: UnixStream) { log::warn!("refusing connection: {MAX_LIVE_CONNECTIONS} already live"); let busy = err(format!( "daemon busy: {MAX_LIVE_CONNECTIONS} connections already open" )); let _ = serde_json::to_writer(&mut s, &busy); let _ = s.write_all(b"\n"); } /// Serve one admitted connection on its own thread; `slot` is released when the /// thread ends. fn spawn_connection( s: UnixStream, slot: ConnectionSlot, index: &IndexReader, content_index: &IndexReader, control: &Control, origin_db: &Path, state_db: &Path, history: &crate::history::SharedHistory, ) { let index = index.clone(); let content_index = content_index.clone(); let control = Control { commands: control.commands.clone(), paused: control.paused.clone(), activity: control.activity.clone(), pending_content: control.pending_content.clone(), unwatched_dirs: control.unwatched_dirs.clone(), }; // One reader per connection: it holds a `RefCell`, so it is // not shareable, and it opens nothing until first use. let origin_reader = origin::OriginReader::new(origin_db.to_path_buf()); let catalogue = catalogue::CatalogueReader::new(state_db); // Shared with the versions writer: only it knows whether reflinks work // and whether space ran out. let history = history.clone(); let spawned = std::thread::Builder::new() .name("ipc-conn".into()) .spawn(move || { let _slot = slot; if let Err(e) = handle( &index, &content_index, s, &control, &origin_reader, &catalogue, &history, ) { log::warn!("connection error: {e:#}"); } }); if let Err(e) = spawned { // The closure (and with it the slot guard) is dropped on failure, so // the count is already corrected; decrementing here would underflow. log::warn!("could not spawn connection thread: {e}"); } } /// Whether the connected peer runs as the same UID as this daemon (SO_PEERCRED). fn peer_is_self(stream: &UnixStream) -> bool { // SAFETY: an all-zero `ucred` is a valid value of the C struct. let mut cred: libc::ucred = unsafe { std::mem::zeroed() }; let mut len = std::mem::size_of::() as libc::socklen_t; // SAFETY: the fd is the stream's, alive for the call; `cred` and `len` are // valid for writes of the size `len` states. let rc = unsafe { libc::getsockopt( stream.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED, (&mut cred as *mut libc::ucred).cast(), &mut len, ) }; // SAFETY: getuid(2) has no arguments and cannot fail. rc == 0 && cred.uid == unsafe { libc::getuid() } } fn handle( index: &IndexReader, content_index: &IndexReader, stream: UnixStream, control: &Control, origin_reader: &origin::OriginReader, catalogue: &catalogue::CatalogueReader, history: &crate::history::SharedHistory, ) -> Result<()> { let mut reader = BufReader::new(stream.try_clone()?); // Buffered on purpose: `serde_json::to_writer` emits every brace, key, comma // and value as its own `write`, so an unbuffered socket would turn one reply // into thousands of syscalls. let mut out = std::io::BufWriter::new(stream); let mut line = Vec::new(); loop { let bytes_read = read_capped_line(&mut reader, &mut line)?; if bytes_read == 0 { break; } let request_text = String::from_utf8_lossy(&line); let request_text = request_text.trim(); if request_text.is_empty() { continue; } let reply = match serde_json::from_str::(request_text) { Ok(request) if request.v != PROTOCOL_VERSION => err(format!( "unsupported protocol v{}; daemon speaks v{PROTOCOL_VERSION}", request.v )), Ok(request) => dispatch( index, content_index, request.body, control, origin_reader, catalogue, history, ), Err(e) => err(format!("bad request: {e}")), }; serde_json::to_writer(&mut out, &reply)?; out.write_all(b"\n")?; out.flush()?; } Ok(()) } fn read_capped_line(reader: &mut BufReader, line: &mut Vec) -> io::Result { line.clear(); let cap = MAX_REQUEST_BYTES as usize; loop { let available = reader.fill_buf()?; if available.is_empty() { return Ok(line.len()); } if let Some(newline) = available.iter().position(|&byte| byte == b'\n') { let take = newline + 1; if line.len().saturating_add(take) > cap { return Err(io::Error::new( io::ErrorKind::InvalidData, "request line exceeds maximum size", )); } line.extend_from_slice(&available[..take]); reader.consume(take); return Ok(line.len()); } if line.len().saturating_add(available.len()) > cap { return Err(io::Error::new( io::ErrorKind::InvalidData, "request line exceeds maximum size", )); } let take = available.len(); line.extend_from_slice(available); reader.consume(take); } } // shape: maps fields: each request to the reply that answers it. fn dispatch( index: &IndexReader, content_index: &IndexReader, body: RequestBody, control: &Control, origin_reader: &origin::OriginReader, catalogue: &catalogue::CatalogueReader, history: &crate::history::SharedHistory, ) -> Reply { match body { RequestBody::Query(query_request) => query_reply( index, content_index, query_request, control, origin_reader, catalogue, ), RequestBody::Origin(origin_request) => Reply::Origin { v: PROTOCOL_VERSION, origin: origin_reader.origin(Path::new(&origin_request.path)), }, RequestBody::RegisterCopy(request) => register_copy_reply(request), RequestBody::RegisterMove(request) => register_move_reply(request), RequestBody::RegisterCreated(request) => register_created_reply(request), RequestBody::RegisterDerived(request) => register_derived_reply(request), RequestBody::Status => status_reply(index, content_index, control), // Hand the command to the watcher thread over the shared channel; it applies // it between batches. Accepted asynchronously (the work may be long). // The flag flips here, the moment the command is accepted, so a // request right after it sees the new state; the watcher only reads it. RequestBody::Pause => { control.paused.store(true, Ordering::Relaxed); send_control_command(control, WatchControlCommand::Pause) } RequestBody::Resume => { control.paused.store(false, Ordering::Relaxed); send_control_command(control, WatchControlCommand::Resume) } RequestBody::Rescan if control.paused.load(Ordering::Relaxed) => { err("indexing is paused; `big-search resume` resumes it and rescans") } RequestBody::Rescan => send_control_command(control, WatchControlCommand::Rescan), RequestBody::Rebuild => send_control_command(control, WatchControlCommand::Rebuild), RequestBody::Reindex(request) => reindex_reply(control, request), // Done here so the reply says whether the rows are gone. RequestBody::ClearOrigin => clear_origin_reply(), RequestBody::Versions(request) => versions_reply(history, request), // Done here rather than handed to the worker: a file manager asks for // this immediately before it overwrites the document, and an answer that // arrives after the overwrite is no answer at all. RequestBody::SaveVersion(request) => save_version_reply(history, request), RequestBody::ForgetVersions(request) => { let Some(spellings) = version_spellings(&request.path) else { return err(format!("{} is relative or holds ..", request.path)); }; // The file the path leads to now: its versions kept under a path // it had before go too. let resolved = settings::sources().resolved_client_path(Path::new(&request.path)); history_reply(history, |store| { store.forget(&spellings, resolved.as_deref()) }) } RequestBody::ClearHistory => { history_reply(history, crate::history::History::forget_everything) } RequestBody::Sources => Reply::Sources { v: PROTOCOL_VERSION, roots: indexed_roots(), }, } } fn query_reply( index: &IndexReader, content_index: &IndexReader, query_request: big_indexd_client::QueryRequest, control: &Control, origin_reader: &origin::OriginReader, catalogue: &catalogue::CatalogueReader, ) -> Reply { let wants_content = matches!(query_request.mode.as_str(), "content" | "both"); if wants_content { // A content search is the strongest signal that deferred bodies // are wanted now: nudge the watcher to extract them, cooldown-free. let _ = control.commands.send(WatchMessage::ControlCommand( WatchControlCommand::WarmContent, )); } match query::run_query( query::QueryIndexes { name: index, content: Some(content_index), catalogue, }, &query_request.q, &query_request.mode, &query_request.filter, &query_request.page, query_request.include_origin, Some(origin_reader), ) { Ok(mut query_outcome) => { if wants_content { query_outcome.content_pending = control.pending_content.load(Ordering::Relaxed); } Reply::Query { v: PROTOCOL_VERSION, outcome: query_outcome, } } Err(e) => err(format!("query failed: {e}")), } } fn register_copy_reply(register_copy_request: big_indexd_client::RegisterCopyRequest) -> Reply { register_origin(|writer| { writer.register_copy( Path::new(®ister_copy_request.src), Path::new(®ister_copy_request.dst), register_copy_request.app_id.as_deref(), ) }) } fn register_move_reply(register_move_request: big_indexd_client::RegisterMoveRequest) -> Reply { register_origin(|writer| { writer.register_move( Path::new(®ister_move_request.src), Path::new(®ister_move_request.dst), register_move_request.app_id.as_deref(), ) }) } fn register_created_reply( register_created_request: big_indexd_client::RegisterCreatedRequest, ) -> Reply { register_origin(|writer| { writer.register_created( Path::new(®ister_created_request.path), register_created_request.app_id.as_deref(), ) }) } fn register_derived_reply( register_derived_request: big_indexd_client::RegisterDerivedRequest, ) -> Reply { register_origin(|writer| { writer.register_derived( Path::new(®ister_derived_request.src), Path::new(®ister_derived_request.dst), register_derived_request.app_id.as_deref(), ) }) } fn status_reply(index: &IndexReader, content_index: &IndexReader, control: &Control) -> Reply { let paused = control.paused.load(Ordering::Relaxed); Reply::Status { v: PROTOCOL_VERSION, indexed: index::document_count(index), paused, activity: crate::watch::activity_label(paused, control.activity.load(Ordering::Relaxed)) .to_string(), capabilities: daemon_capabilities(content_index), pending_content: control.pending_content.load(Ordering::Relaxed), content_docs: index::document_count(content_index), name_index_bytes: flat_directory_file_bytes(&config::index_dir()), content_index_bytes: flat_directory_file_bytes(&config::content_index_dir()), unwatched_dirs: control.unwatched_dirs.load(Ordering::Relaxed), } } fn reindex_reply(control: &Control, request: big_indexd_client::ReindexRequest) -> Reply { if control.paused.load(Ordering::Relaxed) { return err("indexing is paused".to_string()); } // A forced read walks and watches the path: never one the person // did not ask to have searched, nor one relative to the daemon. let Some(path) = settings::sources().resolved_client_path(Path::new(&request.path)) else { return err(format!("{} is not in a searched folder", request.path)); }; send_control_command(control, WatchControlCommand::ReindexPath(path)) } fn clear_origin_reply() -> Reply { match origin::forget_all(&config::origin_db_path()) { Ok(()) => Reply::Ok { v: PROTOCOL_VERSION, }, Err(e) => err(format!("origins could not be forgotten: {e:#}")), } } fn versions_reply( history: &crate::history::SharedHistory, request: big_indexd_client::PathRequest, ) -> Reply { let Some(spellings) = version_spellings(&request.path) else { return err(format!("{} is relative or holds ..", request.path)); }; let store = history.lock(); let versions = match store.versions(&spellings) { Ok(versions) => versions, Err(e) => return err(format!("versions: {e:#}")), }; let versions = versions .into_iter() .map(|version| big_indexd_client::FileVersion { id: version.id, saved_at: version.saved_at, size: version.size, reason: version.reason.as_str().to_string(), object: version.object.to_string_lossy().into_owned(), was_named: version.was_named, }) .collect(); Reply::Versions { v: PROTOCOL_VERSION, versions, unavailable: match store.support() { crate::history::Support::Unavailable(reason) => reason.as_str().to_string(), _ => String::new(), }, paused_for_space: store.is_paused_for_space(), } } /// The keys a client path may have versions under, in order: as spelled (a /// stored key was a real path when kept, and a symlink put in its place later /// leads to another document), then resolved inside a source, as /// [`save_version_reply`] keys it. `None` when relative or holding `..`. fn version_spellings(path: &str) -> Option> { let spelled = settings::normalized_client_path(Path::new(path))?; let resolved = settings::sources().resolved_client_path(&spelled); Some(std::iter::once(spelled).chain(resolved).collect()) } fn save_version_reply( history: &crate::history::SharedHistory, request: big_indexd_client::PathRequest, ) -> Reply { // The copy reads the file: never one outside the searched folders. let Some(path) = settings::sources().resolved_client_path(Path::new(&request.path)) else { return err(format!("{} is not in a searched folder", request.path)); }; let spelled = settings::normalized_client_path(Path::new(&request.path)); history_reply(history, |store| { if let Some(spelled) = spelled.filter(|spelled| *spelled != path) { store.check_restore_through(&spelled, &path)?; } store .save_version(&path, crate::history::Reason::BeforeRestore) .map(|_| ()) }) } /// The catalogued directories. `content` is per source: off when `names_only` /// is set globally or the source disables extraction. fn indexed_roots() -> Vec { let names_only = settings::names_only(); settings::sources() .all() .iter() .map(|source| big_indexd_client::IndexedRoot { path: source.path.to_string_lossy().into_owned(), name: source.name.clone(), content: !names_only && source.content(), available: settings::is_available(source), }) .collect() } fn flat_directory_file_bytes(dir: &Path) -> u64 { let Ok(entries) = std::fs::read_dir(dir) else { return 0; }; let mut total = 0u64; for entry in entries { let Ok(entry) = entry else { return 0; }; let Ok(metadata) = entry.metadata() else { return 0; }; if metadata.is_file() { total = total.saturating_add(metadata.len()); } } total } fn daemon_capabilities(content_index: &IndexReader) -> Vec { let mut capabilities = origin::capabilities(); if settings::content_index_enabled() { let mode = index::stored_content_mode(content_index.searcher().index()) .unwrap_or_else(settings::resolved_content_index_mode); capabilities.push(format!("content-index-mode:{}", mode.as_str())); capabilities.push(format!("extract-cap:{}", settings::extract_max_mb_label())); } else { capabilities.push(big_indexd_client::NAMES_ONLY.to_string()); } // Advertised so clients can detect support without a round trip. capabilities.push("sources".to_string()); // `list` mode filters by `under` and `ext`. capabilities.push("list-filtered".to_string()); // The `largest` mode: the `list` mode by recorded size. capabilities.push("list-largest".to_string()); // `filter.mime` (a type or `major/*`) is answered, and hits carry `mime`. capabilities.push("mime-filter".to_string()); // `filter.kind` keeps folders or files. capabilities.push(big_indexd_client::KIND_FILTER.to_string()); // The `rescan` command. capabilities.push(big_indexd_client::RESCAN.to_string()); capabilities } fn register_origin(f: impl FnOnce(&origin::OriginWriter) -> Result<()>) -> Reply { match origin::OriginWriter::open(config::origin_db_path()).and_then(|writer| f(&writer)) { Ok(()) => Reply::Ok { v: PROTOCOL_VERSION, }, Err(e) => err(format!("origin registration failed: {e:#}")), } } fn send_control_command(control: &Control, control_command: WatchControlCommand) -> Reply { match control .commands .send(WatchMessage::ControlCommand(control_command)) { Ok(()) => Reply::Ok { v: PROTOCOL_VERSION, }, Err(_) => err("watcher thread is gone; daemon is shutting down"), } } /// Run one change against the versions store and answer plainly. fn history_reply( history: &crate::history::SharedHistory, change: impl FnOnce(&mut crate::history::History) -> anyhow::Result<()>, ) -> Reply { let mut store = history.lock(); match change(&mut store) { Ok(()) => Reply::Ok { v: PROTOCOL_VERSION, }, Err(error) => err(format!("{error:#}")), } } #[cfg(test)] #[cfg(not(miri))] mod tests;