//! One companion per data folder (spec 09 RT-14, RT-20): an exclusive `flock` on //! `RUN/instance.lock`, a control socket `RUN/control.sock` for `show`, `stop` and `status` //! (same user only, checked with `SO_PEERCRED`), and a `RUN/desktop.json` process marker used //! by `capri stop` when the socket does not answer. use std::io::Write; use std::os::fd::AsRawFd; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use anyhow::{bail, Context, Result}; use capri_core::Paths; use serde_json::{json, Value}; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::net::{UnixListener, UnixStream}; /// Answers one control request (`{"cmd": "show" | "stop" | "status" | "toggle"}`). pub type Handler = Arc Value + Send + Sync>; /// Held for the companion's lifetime; dropping it releases the lock and removes the socket. pub struct Instance { lock: std::fs::File, dir: PathBuf, data: PathBuf, } pub enum Launch { Owner(Instance), /// Another Capri holds the lock for this data folder. Running, } fn ensure_dir(dir: &Path) -> Result<()> { std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir).with_context(|| format!("cannot create {}", dir.display()))?; let meta = std::fs::symlink_metadata(dir)?; if !meta.is_dir() || meta.permissions().mode() & 0o077 != 0 { bail!("{} must be a private folder (mode 0700).", dir.display()); } Ok(()) } fn try_lock(file: &std::fs::File) -> bool { unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) == 0 } } fn open_lock(dir: &Path) -> Result { ensure_dir(dir)?; std::fs::OpenOptions::new().create(true).truncate(false).read(true).write(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(dir.join("instance.lock")).context("instance lock") } /// Takes the instance lock, or reports that another Capri runs on this data folder. pub fn acquire(paths: &Paths) -> Result { let dir = paths.run(); let lock = open_lock(&dir)?; if !try_lock(&lock) { return Ok(Launch::Running); } Ok(Launch::Owner(Instance { lock, dir, data: std::fs::canonicalize(&paths.data).unwrap_or_else(|_| paths.data.clone()) })) } /// `true` while some Capri holds the lock (checked without keeping it). pub fn running(paths: &Paths) -> bool { let Ok(lock) = open_lock(&paths.run()) else { return false }; if try_lock(&lock) { unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_UN) }; return false; } true } /// Start time of `pid` in clock ticks since boot (`/proc//stat` field 22), the identity /// that makes a recycled pid detectable. fn start_ticks(pid: u32) -> Option { let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; stat.rsplit_once(')')?.1.split_whitespace().nth(19)?.parse().ok() } impl Instance { fn socket(&self) -> PathBuf { self.dir.join("control.sock") } /// Writes the `desktop` marker and answers control requests until the runtime stops. pub fn serve(&self, rt: &tokio::runtime::Handle, handler: Handler) -> Result<()> { let pid = std::process::id(); let marker = json!({ "pid": pid, "startedAt": start_ticks(pid).map(|t| t.to_string()), "executable": std::env::current_exe().ok(), "dataRoot": self.data, "privateLogSchema": 1, }); let path = self.dir.join("desktop.json"); let mut file = std::fs::OpenOptions::new().create(true).truncate(true).write(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(&path)?; file.write_all(marker.to_string().as_bytes())?; let socket = self.socket(); // We hold the lock: a socket file left here is stale. let _ = std::fs::remove_file(&socket); let _guard = rt.enter(); let listener = UnixListener::bind(&socket).with_context(|| format!("cannot listen on {}", socket.display()))?; std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?; let uid = unsafe { libc::getuid() }; rt.spawn(async move { while let Ok((stream, _)) = listener.accept().await { if !stream.peer_cred().is_ok_and(|c| c.uid() == uid) { continue; } let handler = handler.clone(); tokio::spawn(async move { let (read, mut write) = stream.into_split(); let mut line = String::new(); let mut reader = BufReader::new(read.take(4096)); let Ok(Ok(_)) = tokio::time::timeout(Duration::from_secs(5), reader.read_line(&mut line)).await else { return }; let cmd = serde_json::from_str::(&line).ok().and_then(|v| v["cmd"].as_str().map(str::to_string)).unwrap_or_default(); let reply = match cmd.as_str() { "show" | "stop" | "status" | "toggle" => handler(&cmd), _ => json!({"ok": false, "error": "Unknown command."}), }; let _ = write.write_all(format!("{reply}\n").as_bytes()).await; }); } }); Ok(()) } } impl Drop for Instance { fn drop(&mut self) { let _ = std::fs::remove_file(self.socket()); let _ = std::fs::remove_file(self.dir.join("desktop.json")); unsafe { libc::flock(self.lock.as_raw_fd(), libc::LOCK_UN) }; } } /// Sends one command to the running companion; `Err` when it does not answer within 5 s. pub async fn request(paths: &Paths, cmd: &str) -> Result { let socket = paths.run().join("control.sock"); let exchange = async { let mut stream = UnixStream::connect(&socket).await?; stream.write_all(format!("{}\n", json!({ "cmd": cmd })).as_bytes()).await?; let mut line = String::new(); BufReader::new(stream).read_line(&mut line).await?; anyhow::Ok(serde_json::from_str::(&line)?) }; match tokio::time::timeout(Duration::from_secs(5), exchange).await { Ok(result) => result, Err(_) => bail!("no answer within 5 s"), } } /// Pid from the `desktop` marker, only while that process is still the one that wrote it. pub fn marker_pid(paths: &Paths) -> Option { let text = std::fs::read_to_string(paths.run().join("desktop.json")).ok().filter(|t| t.len() <= 65536)?; let marker: Value = serde_json::from_str(&text).ok()?; let pid = u32::try_from(marker["pid"].as_u64()?).ok().filter(|p| *p > 0)?; let started: u64 = marker["startedAt"].as_str()?.parse().ok()?; (start_ticks(pid) == Some(started)).then_some(pid) } #[cfg(test)] mod tests { use super::*; #[test] fn single_owner_and_control_socket() { let dir = tempfile::tempdir().unwrap(); let paths = Paths::under(dir.path().to_path_buf()); paths.ensure().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap(); let Launch::Owner(owner) = acquire(&paths).unwrap() else { panic!("first launch owns the lock") }; assert!(matches!(acquire(&paths).unwrap(), Launch::Running)); assert!(running(&paths)); owner.serve(rt.handle(), Arc::new(|cmd| json!({"ok": true, "cmd": cmd}))).unwrap(); assert_eq!(rt.block_on(request(&paths, "status")).unwrap()["cmd"], "status"); assert_eq!(rt.block_on(request(&paths, "reboot")).unwrap()["ok"], false); assert_eq!(marker_pid(&paths), Some(std::process::id())); drop(owner); assert!(!running(&paths)); assert!(rt.block_on(request(&paths, "show")).is_err()); assert_eq!(marker_pid(&paths), None); } }