Files
regent/src/instance.rs

91 lines
3.2 KiB
Rust

//! The single-instance lock.
//!
//! Two Regents on one device key would both answer requests and race on
//! `apps.json`/`keys.json`, so exactly one process may run — GUI or headless.
//! The app's D-Bus name catches a second **GUI**, but a headless run owns no
//! name, and on a machine with no session bus neither check works at all. An
//! exclusive `flock` on `regent.lock` is the one mechanism that covers every
//! combination, so both the GUI and headless take it. The kernel drops the lock
//! when the process exits, so it cannot go stale.
use std::fs::File;
use std::path::Path;
use std::sync::OnceLock;
use crate::store::keys::KeyStore;
/// The held lock file, kept for the life of the process. `flock` conflicts
/// across two descriptors even within one process, so re-claiming has to be a
/// memo, not a second open.
static LOCK: OnceLock<File> = OnceLock::new();
/// Take the process-wide single-instance lock.
///
/// `true` when this process now holds it — including a repeat call in the same
/// process. **Fails closed:** a lock file that cannot be created or locked
/// returns `false`, so an unreadable data directory refuses to run rather than
/// running unlocked; `WouldBlock` (another process holds it) is the ordinary
/// `false`.
pub fn claim() -> bool {
if LOCK.get().is_some() {
return true;
}
let path = KeyStore::default_path().with_file_name("regent.lock");
match claim_at(&path) {
Ok(file) => {
let _ = LOCK.set(file);
true
}
Err(_) => false,
}
}
/// Open `path` (creating it and its directory, mode 0600) and take an exclusive,
/// non-blocking lock on it. The returned `File` **holds** the lock until it is
/// dropped; the caller keeps it for the life of the process.
fn claim_at(path: &Path) -> std::io::Result<File> {
if let Some(parent) = path.parent() {
// The claim runs before the vault is opened, so on a fresh machine the
// data directory may not exist yet.
crate::store::create_private_dir(parent)?;
}
let mut options = std::fs::OpenOptions::new();
options.create(true).write(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = options.open(path)?;
file.try_lock()?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
/// A second, independent open of the same lock file is refused while the
/// first is held, and succeeds again once it is dropped. Tested on a temp
/// path so it never touches (or races with) the real data directory.
#[test]
fn a_second_lock_on_the_same_file_is_refused() {
let dir = std::env::temp_dir().join(format!("regent-lock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("regent.lock");
let held = claim_at(&path).expect("the first claim succeeds");
assert!(
claim_at(&path).is_err(),
"a second claim must be refused while the first is held"
);
drop(held);
assert!(claim_at(&path).is_ok(), "the lock is free again once dropped");
let _ = std::fs::remove_dir_all(&dir);
}
}