use std::fs;
use std::path::Path;
use super::ownership::{Directory, Kind, Place};
pub(super) fn create_private(path: &Path) -> std::io::Result<fs::File> {
create_in(&Place::of(path)?, path)
}
fn create_in(place: &Place, path: &Path) -> std::io::Result<fs::File> {
let file = open_in(place, path, Access::CreateNew)?;
claim(&file, path);
Ok(file)
}
fn stage(place: &Place, path: &Path) -> std::io::Result<fs::File> {
match create_in(place, path) {
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
place.remove()?;
create_in(place, path)
}
other => other,
}
}
pub(super) fn replace<T, E: From<std::io::Error>>(
destination: &Path,
staged: &Path,
write: impl FnOnce(fs::File) -> Result<T, E>,
) -> Result<T, E> {
replace_at(&Place::of(destination)?, destination, staged, write)
}
fn replace_at<T, E: From<std::io::Error>>(
target: &Place,
destination: &Path,
staged: &Path,
write: impl FnOnce(fs::File) -> Result<T, E>,
) -> Result<T, E> {
let staging = target.beside(sibling(destination, staged)?)?;
let file = stage(&staging, staged)?;
let replaced = write(file).and_then(|written| {
staging.rename_over(target)?;
Ok(written)
});
if replaced.is_err() {
let _ = staging.remove();
}
replaced
}
pub(super) fn link_new(
destination: &Path,
staged: &Path,
write: impl FnOnce(fs::File) -> std::io::Result<()>,
) -> std::io::Result<()> {
link_new_at(&Place::of(destination)?, destination, staged, write)
}
fn link_new_at(
target: &Place,
destination: &Path,
staged: &Path,
write: impl FnOnce(fs::File) -> std::io::Result<()>,
) -> std::io::Result<()> {
let staging = target.beside(sibling(destination, staged)?)?;
let file = stage(&staging, staged)?;
let linked = write(file).and_then(|()| staging.link_as(target));
let _ = staging.remove();
linked
}
fn sibling<'a>(destination: &Path, staged: &'a Path) -> std::io::Result<&'a std::ffi::OsStr> {
debug_assert_eq!(
destination.parent(),
staged.parent(),
"a file is staged beside its destination"
);
staged.file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("{} names no file", staged.display()),
)
})
}
pub(super) fn append_existing(path: &Path) -> std::io::Result<fs::File> {
open(path, Access::Append)
}
pub(super) fn open_existing(path: &Path) -> std::io::Result<fs::File> {
open(path, Access::ReadWrite)
}
pub(super) fn open_or_create_private(path: &Path) -> std::io::Result<fs::File> {
let file = open(path, Access::CreateOrOpen)?;
claim(&file, path);
Ok(file)
}
pub(super) fn remove(path: &Path) -> std::io::Result<()> {
Place::of(path)?.remove()
}
pub(super) fn remove_directory(path: &Path) -> std::io::Result<()> {
Place::of(path)?.remove_tree()
}
#[cfg(unix)]
pub(super) fn create_private_directory(path: &Path) -> std::io::Result<()> {
Place::of(path)?.create_directory(0o700)
}
#[cfg(not(unix))]
pub(super) fn create_private_directory(path: &Path) -> std::io::Result<()> {
fs::create_dir(path)
}
pub(super) fn open_to_read(path: &Path) -> std::io::Result<fs::File> {
open(path, Access::Read)
}
pub(super) fn names(path: &Path) -> std::io::Result<Vec<std::ffi::OsString>> {
Directory::of(path)?.names()
}
pub(super) fn kinds(path: &Path) -> std::io::Result<Vec<(std::ffi::OsString, Kind)>> {
let directory = Directory::of(path)?;
Ok(directory
.names()?
.into_iter()
.filter_map(|name| {
let kind = directory.entry(&name).and_then(|entry| entry.kind()).ok()?;
Some((name, kind))
})
.collect())
}
pub(super) fn exists(path: &Path) -> std::io::Result<bool> {
match Place::of(path) {
Ok(place) => place.exists(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
}
}
#[derive(Clone, Copy)]
enum Access {
CreateNew,
CreateOrOpen,
Append,
ReadWrite,
Read,
}
fn open(path: &Path, how: Access) -> std::io::Result<fs::File> {
open_in(&Place::of(path)?, path, how)
}
#[cfg(unix)]
fn open_in(place: &Place, path: &Path, how: Access) -> std::io::Result<fs::File> {
let flags = match how {
Access::CreateNew => libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
Access::CreateOrOpen => libc::O_RDWR | libc::O_CREAT,
Access::Append => libc::O_WRONLY | libc::O_APPEND,
Access::ReadWrite => libc::O_RDWR,
Access::Read => libc::O_RDONLY,
};
place.open(flags, 0o600).map_err(|error| {
let linked = error.raw_os_error() == Some(libc::ELOOP)
&& place.kind().is_ok_and(|kind| kind == Kind::Link);
if linked {
std::io::Error::other(format!(
"{} is a link, not a journal file (not followed)",
path.display()
))
} else {
error
}
})
}
#[cfg(not(unix))]
fn open_in(place: &Place, _path: &Path, how: Access) -> std::io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
match how {
Access::CreateNew => options.write(true).create_new(true),
Access::CreateOrOpen => options.read(true).write(true).create(true),
Access::Append => options.append(true),
Access::ReadWrite => options.read(true).write(true),
Access::Read => options.read(true),
};
options.open(place.path())
}
pub(super) fn claim_directory_for_invoking_user(path: &Path) {
super::ownership::give(path);
}
fn claim(file: &fs::File, path: &Path) {
super::ownership::give_open(file, path);
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::io::Write;
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("zond-file-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("a scratch directory");
dir
}
#[test]
fn a_link_where_a_journal_file_should_be_is_refused() {
let dir = scratch("nofollow");
let elsewhere = dir.join("elsewhere");
fs::write(&elsewhere, b"not the journal's to touch").expect("writes");
let planted = dir.join("cursor.json.tmp");
std::os::unix::fs::symlink(&elsewhere, &planted).expect("links");
for opened in [
create_private(&planted).err(),
append_existing(&planted).err(),
] {
assert!(opened.is_some(), "a link was opened as a journal file");
}
assert_eq!(
fs::read(&elsewhere).expect("reads"),
b"not the journal's to touch",
"the file behind the link was written through"
);
fs::remove_dir_all(&dir).ok();
}
#[test]
fn an_ordinary_journal_file_opens_and_is_private() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch("ordinary");
let path = dir.join("findings");
create_private(&path)
.expect("creates")
.write_all(b"one")
.expect("writes");
append_existing(&path)
.expect("appends")
.write_all(b"two")
.expect("writes");
assert_eq!(fs::read(&path).expect("reads"), b"onetwo");
assert_eq!(
fs::metadata(&path).expect("stats").permissions().mode() & 0o777,
0o600
);
fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_file_already_at_a_journal_name_is_refused_rather_than_emptied() {
let dir = scratch("create-only");
let planted = dir.join("manifest.json");
fs::write(&planted, b"somebody else's bytes").expect("writes");
let refusal = create_private(&planted).expect_err("a name that exists was created over");
assert_eq!(refusal.kind(), std::io::ErrorKind::AlreadyExists);
assert_eq!(
fs::read(&planted).expect("reads"),
b"somebody else's bytes",
"the planted file was truncated"
);
fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_staged_file_is_put_in_place_where_it_was_staged_whatever_moves_above_it() {
use crate::journal::paths::InvokingUser;
let dir = scratch("walked");
let home = dir.join("home");
let elsewhere = dir.join("elsewhere");
fs::create_dir_all(home.join("state/journal")).expect("a journal");
fs::create_dir_all(elsewhere.join("journal")).expect("a directory outside");
for name in ["cursor.tmp", "LOCK.lock-1"] {
fs::write(elsewhere.join("journal").join(name), b"bait").expect("writes");
}
let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
let user = InvokingUser::new(uid, gid, home.clone());
let redirect = || -> std::io::Result<()> {
fs::rename(home.join("state"), home.join("kept"))?;
std::os::unix::fs::symlink(&elsewhere, home.join("state"))
};
let restore = || {
fs::remove_file(home.join("state")).expect("removes the link");
fs::rename(home.join("kept"), home.join("state")).expect("restores");
};
let cursor = home.join("state/journal/cursor.json");
let target = Place::of_as(Some(&user), &cursor).expect("reached");
replace_at(
&target,
&cursor,
&cursor.with_extension("tmp"),
|mut file| {
file.write_all(b"the journal's")?;
redirect()
},
)
.expect("replaces");
restore();
assert_eq!(fs::read(&cursor).expect("reads"), b"the journal's");
let lock = home.join("state/journal/LOCK");
let target = Place::of_as(Some(&user), &lock).expect("reached");
link_new_at(
&target,
&lock,
&lock.with_extension("lock-1"),
|mut file| {
file.write_all(b"held")?;
redirect()
},
)
.expect("links");
restore();
assert_eq!(fs::read(&lock).expect("reads"), b"held");
let outside: Vec<_> = fs::read_dir(elsewhere.join("journal"))
.expect("lists")
.map(|entry| entry.expect("an entry").file_name())
.collect();
assert_eq!(
outside.len(),
2,
"renamed or linked out of the home: {outside:?}"
);
for name in ["cursor.tmp", "LOCK.lock-1"] {
assert_eq!(
fs::read(elsewhere.join("journal").join(name)).expect("reads"),
b"bait",
"{name} was changed out of the home"
);
}
fs::remove_dir_all(&dir).ok();
}
#[test]
fn a_staged_name_left_by_a_crashed_run_is_discarded_rather_than_wedging() {
let dir = scratch("staged");
let temporary = dir.join("cursor.json.tmp");
fs::write(&temporary, b"a checkpoint that never got renamed").expect("writes");
let destination = dir.join("cursor.json");
replace(&destination, &temporary, |mut file| {
file.write_all(b"the next one")
})
.expect("a leftover staging file is discarded");
assert_eq!(fs::read(&destination).expect("reads"), b"the next one");
assert!(!temporary.exists(), "the staged name was renamed away");
let elsewhere = dir.join("elsewhere");
fs::write(&elsewhere, b"not the journal's to touch").expect("writes");
let linked = dir.join("hosts.jsonl-tmp");
std::os::unix::fs::symlink(&elsewhere, &linked).expect("links");
replace(&dir.join("hosts.jsonl"), &linked, |mut file| {
file.write_all(b"compacted")
})
.expect("the link is unlinked and a real file created");
assert_eq!(
fs::read(&elsewhere).expect("reads"),
b"not the journal's to touch",
"the file behind the link was written through"
);
fs::remove_dir_all(&dir).ok();
}
}