use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
pub const LOCK_FILE: &str = "memfork.lock";
pub const ENDPOINT_FILE: &str = "memfork.endpoint";
pub const PROBE_GRACE: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Endpoint {
pub version: u32,
pub pid: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub port: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_token: Option<String>,
pub started_unix: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub memfork_version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub page_build: Option<String>,
}
pub const ENDPOINT_VERSION: u32 = 1;
impl Endpoint {
pub fn for_this_process() -> Self {
Endpoint {
version: ENDPOINT_VERSION,
pid: std::process::id(),
port: None,
token: None,
read_token: None,
started_unix: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),
memfork_version: Some(crate::VERSION.to_owned()),
page_build: this_page_build(),
}
}
}
fn this_page_build() -> Option<String> {
#[cfg(feature = "brain")]
{
Some(crate::brain::page_build().to_owned())
}
#[cfg(not(feature = "brain"))]
{
None
}
}
#[derive(Debug, thiserror::Error)]
pub enum LockError {
#[error(
"this data directory is in use by process {pid}{}.\n\
Only one process can write to a MemFork data directory at a time.",
.hint.as_deref().unwrap_or("")
)]
InUse {
pid: u32,
hint: Option<String>,
},
#[error("{context}: {source}")]
Io {
context: String,
#[source]
source: std::io::Error,
},
}
fn io(context: impl Into<String>) -> impl FnOnce(std::io::Error) -> LockError {
let context = context.into();
move |source| LockError::Io { context, source }
}
#[derive(Debug)]
pub struct DirLock {
dir: PathBuf,
file: File,
}
impl DirLock {
pub fn acquire(dir: &Path) -> Result<Self, LockError> {
std::fs::create_dir_all(dir).map_err(io(format!("cannot create {}", dir.display())))?;
let path = dir.join(LOCK_FILE);
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.map_err(io(format!("cannot open {}", path.display())))?;
let deadline = Instant::now() + PROBE_GRACE;
let taken = loop {
match file.try_lock() {
Ok(()) => break true,
Err(_) if Instant::now() < deadline && read_endpoint(dir).is_none() => {
std::thread::sleep(Duration::from_millis(5));
}
Err(_) => break false,
}
};
match taken {
true => {}
false => {
let existing = read_endpoint(dir);
return Err(LockError::InUse {
pid: existing.as_ref().map_or(0, |e| e.pid),
hint: existing
.as_ref()
.and_then(|e| e.port.map(|p| format!(", serving on 127.0.0.1:{p}"))),
});
}
}
let _ = std::fs::remove_file(dir.join(ENDPOINT_FILE));
Ok(DirLock {
dir: dir.to_path_buf(),
file,
})
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn publish(&self, endpoint: &Endpoint) -> Result<(), LockError> {
let final_path = self.dir.join(ENDPOINT_FILE);
let tmp_path = self.dir.join(format!("{ENDPOINT_FILE}.tmp"));
let mut json = serde_json::to_string_pretty(endpoint).map_err(|e| LockError::Io {
context: "cannot render the endpoint file".to_owned(),
source: std::io::Error::other(e),
})?;
json.push('\n');
{
let mut file = create_private(&tmp_path)?;
file.write_all(json.as_bytes())
.map_err(io(format!("cannot write {}", tmp_path.display())))?;
file.sync_all()
.map_err(io(format!("cannot flush {}", tmp_path.display())))?;
}
std::fs::rename(&tmp_path, &final_path)
.map_err(io(format!("cannot install {}", final_path.display())))?;
sync_dir(&self.dir);
Ok(())
}
}
impl Drop for DirLock {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.dir.join(ENDPOINT_FILE));
let _ = self.file.unlock();
}
}
fn create_private(path: &Path) -> Result<File, LockError> {
let mut options = OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options
.open(path)
.map_err(io(format!("cannot create {}", path.display())))
}
pub fn sync_dir(dir: &Path) {
#[cfg(unix)]
{
if let Ok(handle) = File::open(dir) {
let _ = handle.sync_all();
}
}
#[cfg(not(unix))]
{
let _ = dir;
}
}
pub fn read_endpoint(dir: &Path) -> Option<Endpoint> {
let text = std::fs::read_to_string(dir.join(ENDPOINT_FILE)).ok()?;
serde_json::from_str(&text).ok()
}
pub fn owner(dir: &Path) -> Option<Endpoint> {
let path = dir.join(LOCK_FILE);
let file = OpenOptions::new()
.read(true)
.write(true)
.create(false)
.open(&path)
.ok()?;
match file.try_lock() {
Ok(()) => {
let _ = std::fs::remove_file(dir.join(ENDPOINT_FILE));
let _ = file.unlock();
None
}
Err(_) => read_endpoint(dir),
}
}
pub fn new_token() -> Result<String, LockError> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|e| LockError::Io {
context: "cannot read random bytes for the daemon token".to_owned(),
source: std::io::Error::other(e),
})?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn losing_to_an_owner_that_has_said_so_gives_up_at_once() {
let dir = tempfile::tempdir().expect("tempdir");
let owner = DirLock::acquire(dir.path()).expect("first acquire");
owner
.publish(&Endpoint::for_this_process())
.expect("published");
let started = Instant::now();
let loser = {
let path = dir.path().to_path_buf();
std::thread::spawn(move || DirLock::acquire(&path).map(|_| ()))
};
let lost = loser.join().expect("loser");
assert!(matches!(lost, Err(LockError::InUse { .. })), "{lost:?}");
assert!(
started.elapsed() < PROBE_GRACE / 2,
"the loser waited {:?} for an owner that had said so",
started.elapsed()
);
drop(owner);
}
#[test]
fn asking_who_owns_a_directory_never_stops_a_daemon_taking_it() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().to_path_buf();
std::fs::write(path.join(LOCK_FILE), b"").expect("lock file");
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let asker = {
let path = path.clone();
let stop = std::sync::Arc::clone(&stop);
std::thread::spawn(move || {
let mut asked = 0u64;
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
let _ = owner(&path);
asked += 1;
}
asked
})
};
for round in 0..200 {
let held = DirLock::acquire(&path)
.unwrap_or_else(|e| panic!("round {round}: a question kept the owner out: {e}"));
let mut endpoint = Endpoint::for_this_process();
endpoint.port = Some(1);
held.publish(&endpoint).expect("published");
for _ in 0..20 {
assert!(
read_endpoint(&path).is_some(),
"round {round}: a question removed a held endpoint"
);
}
drop(held);
}
stop.store(true, std::sync::atomic::Ordering::Relaxed);
assert!(asker.join().expect("asker") > 0);
}
#[test]
fn the_lock_keeps_a_second_owner_out_and_names_the_first() {
let dir = tempfile::tempdir().expect("tempdir");
let held = DirLock::acquire(dir.path()).expect("first acquire");
held.publish(&Endpoint::for_this_process())
.expect("published");
match DirLock::acquire(dir.path()) {
Err(LockError::InUse { pid, .. }) => assert_eq!(pid, std::process::id()),
other => panic!("a second owner got in: {other:?}"),
}
drop(held);
DirLock::acquire(dir.path()).expect("acquire after release");
}
#[test]
fn a_released_lock_takes_the_endpoint_file_with_it() {
let dir = tempfile::tempdir().expect("tempdir");
let held = DirLock::acquire(dir.path()).expect("acquired");
held.publish(&Endpoint::for_this_process())
.expect("published");
assert!(dir.path().join(ENDPOINT_FILE).exists());
drop(held);
assert!(
!dir.path().join(ENDPOINT_FILE).exists(),
"a stale endpoint was left behind"
);
}
#[test]
fn an_endpoint_left_by_a_dead_owner_is_ignored_and_removed() {
let dir = tempfile::tempdir().expect("tempdir");
DirLock::acquire(dir.path())
.expect("acquired")
.publish(&Endpoint {
version: ENDPOINT_VERSION,
pid: 999_999,
port: Some(1234),
token: Some("stale".to_owned()),
read_token: None,
started_unix: 0,
memfork_version: Some(crate::VERSION.to_owned()),
page_build: None,
})
.expect("published");
std::fs::write(
dir.path().join(ENDPOINT_FILE),
r#"{"version":1,"pid":999999,"port":1234,"token":"stale","started_unix":0}"#,
)
.expect("written");
assert!(
owner(dir.path()).is_none(),
"a stale endpoint was reported as a running owner"
);
assert!(
!dir.path().join(ENDPOINT_FILE).exists(),
"the stale endpoint was not cleaned up"
);
}
#[test]
fn a_running_owner_is_reported_with_its_details() {
let dir = tempfile::tempdir().expect("tempdir");
let held = DirLock::acquire(dir.path()).expect("acquired");
let mut endpoint = Endpoint::for_this_process();
endpoint.port = Some(4321);
endpoint.token = Some("a-token".to_owned());
held.publish(&endpoint).expect("published");
let seen = owner(dir.path()).expect("an owner");
assert_eq!(seen.pid, std::process::id());
assert_eq!(seen.port, Some(4321));
assert_eq!(seen.token.as_deref(), Some("a-token"));
}
#[test]
fn the_endpoint_file_is_readable_while_the_lock_is_held() {
let dir = tempfile::tempdir().expect("tempdir");
let held = DirLock::acquire(dir.path()).expect("acquired");
held.publish(&Endpoint::for_this_process())
.expect("published");
let text = std::fs::read_to_string(dir.path().join(ENDPOINT_FILE))
.expect("the endpoint file is readable while the lock is held");
assert!(text.contains("\"pid\""));
}
#[test]
#[cfg(unix)]
fn the_endpoint_file_is_private_to_this_user() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let held = DirLock::acquire(dir.path()).expect("acquired");
held.publish(&Endpoint::for_this_process())
.expect("published");
let mode = std::fs::metadata(dir.path().join(ENDPOINT_FILE))
.expect("metadata")
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600, "the token file is readable by others");
}
#[test]
fn the_endpoint_says_which_build_wrote_it() {
let dir = tempfile::tempdir().expect("tempdir");
let held = DirLock::acquire(dir.path()).expect("acquired");
held.publish(&Endpoint::for_this_process())
.expect("published");
let seen = read_endpoint(dir.path()).expect("an endpoint");
assert_eq!(seen.memfork_version.as_deref(), Some(crate::VERSION));
}
#[test]
fn tokens_are_long_and_do_not_repeat() {
let a = new_token().expect("a token");
let b = new_token().expect("another token");
assert_eq!(a.len(), 64);
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
assert_ne!(a, b);
}
#[test]
fn an_unreadable_endpoint_file_is_not_a_crash() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join(ENDPOINT_FILE), "not json at all").expect("written");
assert!(read_endpoint(dir.path()).is_none());
}
}