use std::fs;
use std::path::Path;
pub(super) fn create_private(path: &Path) -> std::io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
private(&mut options);
let file = options.open(path)?;
claim(&file);
Ok(file)
}
pub(super) fn create_staged(path: &Path) -> std::io::Result<fs::File> {
match create_private(path) {
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
fs::remove_file(path)?;
create_private(path)
}
other => other,
}
}
pub(super) fn append_existing(path: &Path) -> std::io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options.append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW);
}
options.open(path)
}
pub(super) fn open_existing(path: &Path) -> std::io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options.read(true).write(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW);
}
options.open(path)
}
pub(super) fn open_or_create_private(path: &Path) -> std::io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options.read(true).write(true).create(true);
private(&mut options);
let file = options.open(path)?;
claim(&file);
Ok(file)
}
#[cfg(unix)]
fn private(options: &mut fs::OpenOptions) {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
#[cfg(not(unix))]
fn private(_options: &mut fs::OpenOptions) {}
#[cfg(unix)]
pub(super) fn claim_directory_for_invoking_user(path: &Path) {
use std::os::unix::fs::OpenOptionsExt;
let opened = fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_DIRECTORY)
.open(path);
if let Ok(directory) = opened {
claim(&directory);
}
}
#[cfg(not(unix))]
pub(super) fn claim_directory_for_invoking_user(_path: &Path) {}
#[cfg(unix)]
fn claim(file: &fs::File) {
use std::os::unix::io::AsRawFd;
use std::sync::OnceLock;
static INVOKING: OnceLock<Option<super::paths::InvokingUser>> = OnceLock::new();
let Some(user) = INVOKING.get_or_init(super::paths::invoking_user) else {
return;
};
unsafe {
libc::fchown(file.as_raw_fd(), user.uid, user.gid);
}
}
#[cfg(not(unix))]
fn claim(_file: &fs::File) {}
#[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_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");
create_staged(&temporary)
.expect("a leftover staging file is discarded")
.write_all(b"the next one")
.expect("writes");
assert_eq!(fs::read(&temporary).expect("reads"), b"the next one");
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");
create_staged(&linked).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();
}
}