use std::fs::{self, File, OpenOptions}; use std::io::Write; use std::os::unix::fs::OpenOptionsExt; use std::path::Path; use anyhow::{bail, Context, Result}; /// Writes `bytes` to `path` atomically: private temp file (0600, create_new), fsync, rename, fsync dir. pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { let dir = path.parent().context("Path has no parent")?; let name = path.file_name().context("Path has no file name")?.to_string_lossy(); let tmp = dir.join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4())); let result = (|| -> Result<()> { let mut file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?; file.write_all(bytes)?; file.sync_all()?; fs::rename(&tmp, path)?; File::open(dir)?.sync_all()?; Ok(()) })(); if result.is_err() { let _ = fs::remove_file(&tmp); } result.with_context(|| format!("Cannot write {}", path.display())) } pub fn write_json_atomic(path: &Path, value: &T) -> Result<()> { let mut bytes = serde_json::to_vec_pretty(value)?; bytes.push(b'\n'); write_atomic(path, &bytes) } /// Reads a regular, non-symlink file of at most `max` bytes. `Ok(None)` when it does not exist. pub fn read_regular(path: &Path, max: u64) -> Result>> { let meta = match fs::symlink_metadata(path) { Ok(meta) => meta, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(e.into()), }; if !meta.file_type().is_file() { bail!("{} is not a regular file", path.display()); } if meta.len() > max { bail!("{} exceeds {max} bytes", path.display()); } let file = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(path)?; let mut bytes = Vec::with_capacity(meta.len() as usize); std::io::Read::read_to_end(&mut std::io::Read::take(file, max + 1), &mut bytes)?; if bytes.len() as u64 > max { bail!("{} exceeds {max} bytes", path.display()); } Ok(Some(bytes)) } #[cfg(test)] mod tests { use super::*; #[test] fn atomic_write_then_read() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.json"); write_atomic(&path, b"hello").unwrap(); assert_eq!(read_regular(&path, 10).unwrap().unwrap(), b"hello"); assert!(read_regular(&path, 2).is_err()); assert!(read_regular(&dir.path().join("missing"), 10).unwrap().is_none()); std::os::unix::fs::symlink(&path, dir.path().join("link")).unwrap(); assert!(read_regular(&dir.path().join("link"), 10).is_err()); } }