//! Small filesystem primitives shared by every module that writes state: //! atomic replace-on-write, directory fsync, cross-process locks for //! read-modify-write updates, and quarantining unreadable files so a bad //! file is kept for inspection instead of being overwritten. use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; /// Writes `bytes` to `path` atomically: a temporary file in the same /// directory is written, flushed to disk and renamed over the target, so a /// reader (or a crash) only ever sees the old or the new contents. /// /// `mode` sets unix permissions on the new file before any byte is written; /// it is ignored on other platforms. pub(crate) fn write_atomic(path: &Path, bytes: &[u8], mode: Option) -> io::Result<()> { let dir = parent_dir(path)?; std::fs::create_dir_all(dir)?; let mut builder = tempfile::Builder::new(); builder.prefix(".libbui-").suffix(".tmp"); #[cfg(unix)] if let Some(mode) = mode { use std::os::unix::fs::PermissionsExt; builder.permissions(std::fs::Permissions::from_mode(mode)); } #[cfg(not(unix))] let _ = mode; let mut tmp = builder.tempfile_in(dir)?; tmp.write_all(bytes)?; tmp.as_file().sync_all()?; tmp.persist(path).map_err(|e| e.error)?; sync_dir(dir) } /// How long a read-modify-write waits for another process to finish its own /// update of the same file. Updates take milliseconds, so running out means /// something is stuck, and that is reported rather than written past. pub(crate) const LOCK_WAIT: Duration = Duration::from_secs(10); /// How often a blocked writer retries the lock. const LOCK_POLL: Duration = Duration::from_millis(20); /// An exclusive advisory lock, released when dropped (closing the handle /// releases it, also when the process dies). #[derive(Debug)] pub(crate) struct FileLock { _file: std::fs::File, } /// The lock file guarding `path`: a sibling named `.lock`. /// /// The lock lives in its own file rather than on `path` itself because /// `path` is replaced by rename on every write, which would leave the next /// writer locking a different inode. Lock files are never deleted: removing /// one while another process waits on it would let two writers in. pub(crate) fn lock_path(path: &Path) -> io::Result { let name = path .file_name() .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no file name"))?; let mut lock = name.to_os_string(); lock.push(".lock"); Ok(path.with_file_name(lock)) } /// Takes the exclusive lock guarding `path` (see [`lock_path`]), waiting up /// to `wait` for another holder to let go. /// /// The lock is advisory (`flock` on unix, `LockFileEx` on Windows): it /// keeps libbui processes from interleaving, not other programs. /// /// # Errors /// The lock file cannot be created or locked, or `wait` ran out /// ([`io::ErrorKind::TimedOut`]). pub(crate) fn lock_exclusive(path: &Path, wait: Duration) -> io::Result { let lock = lock_path(path)?; std::fs::create_dir_all(parent_dir(&lock)?)?; let file = std::fs::OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .open(&lock)?; let deadline = Instant::now() + wait; loop { match file.try_lock() { Ok(()) => return Ok(FileLock { _file: file }), Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => { std::thread::sleep(LOCK_POLL); } Err(std::fs::TryLockError::WouldBlock) => { return Err(io::Error::new( io::ErrorKind::TimedOut, format!( "another libbui process has held {} for over {}s", lock.display(), wait.as_secs() ), )); } Err(std::fs::TryLockError::Error(e)) => return Err(e), } } } /// The directory containing `path`, or an error for a bare root/empty path. pub(crate) fn parent_dir(path: &Path) -> io::Result<&Path> { match path.parent() { Some(p) if !p.as_os_str().is_empty() => Ok(p), _ => Err(io::Error::new( io::ErrorKind::InvalidInput, format!("{} has no parent directory", path.display()), )), } } /// Flushes a directory entry to disk so a rename inside it survives a crash. /// /// Only meaningful on unix; Windows has no directory handles to sync. pub(crate) fn sync_dir(dir: &Path) -> io::Result<()> { #[cfg(unix)] { std::fs::File::open(dir)?.sync_all() } #[cfg(not(unix))] { let _ = dir; Ok(()) } } /// Renames an unreadable file aside (`.corrupt-`) and /// returns where it went, so the caller can surface the error and start /// fresh without destroying the evidence. pub(crate) fn quarantine(path: &Path) -> io::Result { let stamp = jiff::Timestamp::now().as_second(); let file_name = path .file_name() .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no file name"))? .to_string_lossy() .into_owned(); let mut n = 0u32; loop { let candidate = if n == 0 { path.with_file_name(format!("{file_name}.corrupt-{stamp}")) } else { path.with_file_name(format!("{file_name}.corrupt-{stamp}-{n}")) }; if !candidate.exists() { std::fs::rename(path, &candidate)?; return Ok(candidate); } n += 1; } } /// Files [`quarantine`] has set aside for `path` (`.corrupt-*` /// siblings), in no particular order. /// /// # Errors /// The parent directory exists but cannot be listed. pub(crate) fn quarantined(path: &Path) -> io::Result> { let dir = parent_dir(path)?; let mut prefix = path .file_name() .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no file name"))? .to_os_string(); prefix.push(".corrupt-"); let prefix = prefix.as_encoded_bytes(); let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e), }; let mut found = Vec::new(); for entry in entries { let entry = entry?; if entry.file_name().as_encoded_bytes().starts_with(prefix) { found.push(entry.path()); } } Ok(found) } /// A JSON state file (download queue, library index) could not be used. #[derive(Debug, thiserror::Error)] pub enum StateFileError { /// Reading or writing failed. #[error("{}: {source}", path.display())] Io { /// The state file. path: PathBuf, /// The underlying error. #[source] source: io::Error, }, /// The file exists but cannot be parsed. It was renamed to `moved_to` /// so nothing is lost; starting again begins with an empty state. #[error( "{} is unreadable ({message}); it was moved to {} and a fresh one will be started", path.display(), moved_to.display() )] Corrupt { /// Where the file was. path: PathBuf, /// Where the unreadable file was preserved. moved_to: PathBuf, /// The parser's description. message: String, }, /// The file was written by a newer libbui (its `version` is higher than /// this build understands). It is left where it is, untouched, so the /// newer libbui can still use it. #[error( "{} was written by a newer libbui (format version {version}); upgrade libbui to use it", path.display() )] NewerVersion { /// The state file. path: PathBuf, /// The version the file declares. version: u32, }, /// The state could not be encoded. #[error("cannot encode {}: {source}", path.display())] Encode { /// The state file. path: PathBuf, /// The underlying error. #[source] source: serde_json::Error, }, } /// Reads a JSON state file. A missing file is `Ok(None)`; one from a newer /// libbui is [`StateFileError::NewerVersion`] and left in place; any other /// unparsable one is quarantined with [`quarantine`] and reported as /// [`StateFileError::Corrupt`], never overwritten. pub(crate) fn read_json_or_quarantine( path: &Path, ) -> Result, StateFileError> { let bytes = match std::fs::read(path) { Ok(b) => b, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(source) => { return Err(StateFileError::Io { path: path.to_path_buf(), source, }); } }; match serde_json::from_slice(&bytes) { Ok(v) => Ok(Some(v)), Err(e) => { if let Some(version) = newer_version(&bytes) { tracing::error!(path = %path.display(), version, "state file is from a newer libbui"); return Err(StateFileError::NewerVersion { path: path.to_path_buf(), version, }); } let moved_to = quarantine(path).map_err(|source| StateFileError::Io { path: path.to_path_buf(), source, })?; tracing::error!(path = %path.display(), moved_to = %moved_to.display(), error = %e, "state file is corrupt"); Err(StateFileError::Corrupt { path: path.to_path_buf(), moved_to, message: e.to_string(), }) } } } /// The `version` a state file declares, when it is one this build does not /// know yet. Only the version is looked at: a newer format may change /// everything else. fn newer_version(bytes: &[u8]) -> Option { #[derive(serde::Deserialize)] struct Probe { version: u32, } serde_json::from_slice::(bytes) .ok() .map(|p| p.version) .filter(|&v| v > FORMAT_VERSION) } /// The only state-file format version this build reads and writes. const FORMAT_VERSION: u32 = 1; /// Serializes `value` as pretty JSON and writes it with [`write_atomic`]. pub(crate) fn write_json( path: &Path, value: &T, ) -> Result<(), StateFileError> { let bytes = serde_json::to_vec_pretty(value).map_err(|source| StateFileError::Encode { path: path.to_path_buf(), source, })?; write_atomic(path, &bytes, None).map_err(|source| StateFileError::Io { path: path.to_path_buf(), source, }) } /// The `version` field of a JSON state file. Only `1` deserializes, so a /// file written by an incompatible libbui is reported (see /// [`read_json_or_quarantine`]) instead of being misread. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(try_from = "u32", into = "u32")] pub(crate) struct FormatV1; impl TryFrom for FormatV1 { type Error = String; fn try_from(v: u32) -> Result { if v == FORMAT_VERSION { Ok(Self) } else { Err(format!("unsupported format version {v}")) } } } impl From for u32 { fn from(_: FormatV1) -> Self { 1 } } /// Lowercase hex encoding of a digest. pub(crate) fn hex(bytes: &[u8]) -> String { use std::fmt::Write as _; let mut out = String::with_capacity(bytes.len() * 2); for b in bytes { // Writing to a String cannot fail. let _ = write!(out, "{b:02x}"); } out } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn atomic_write_replaces_contents() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("nested/file.json"); write_atomic(&path, b"one", None).unwrap(); write_atomic(&path, b"two", None).unwrap(); assert_eq!(std::fs::read(&path).unwrap(), b"two"); // No temporary files are left behind. let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap()) .unwrap() .filter_map(Result::ok) .filter(|e| e.file_name().to_string_lossy().starts_with(".libbui-")) .collect(); assert!(leftovers.is_empty()); } #[cfg(unix)] #[test] fn atomic_write_applies_mode() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("secret"); write_atomic(&path, b"x", Some(0o600)).unwrap(); let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); } #[test] fn quarantine_keeps_the_bytes() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("queue.json"); std::fs::write(&path, b"garbage").unwrap(); let moved = quarantine(&path).unwrap(); assert!(!path.exists()); assert_eq!(std::fs::read(moved).unwrap(), b"garbage"); } #[test] fn read_json_quarantines_garbage_and_old_versions() { #[derive(serde::Deserialize)] struct Doc { #[allow(dead_code)] version: FormatV1, } let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("state.json"); assert!(read_json_or_quarantine::(&path).unwrap().is_none()); std::fs::write(&path, br#"{"version":1}"#).unwrap(); assert!(read_json_or_quarantine::(&path).unwrap().is_some()); std::fs::write(&path, br#"{"version":0}"#).unwrap(); let err = read_json_or_quarantine::(&path).err().unwrap(); let StateFileError::Corrupt { moved_to, message, .. } = err else { panic!("{err:?}") }; assert!( message.contains("unsupported format version 0"), "{message}" ); assert!(!path.exists()); assert_eq!(std::fs::read(moved_to).unwrap(), br#"{"version":0}"#); } #[test] fn read_json_leaves_newer_versions_in_place() { #[derive(Debug, serde::Deserialize)] struct Doc { #[allow(dead_code)] version: FormatV1, } let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("state.json"); // A newer format may reshape everything but the version. let newer = br#"{"version":2,"entries":{"renamed":true}}"#; std::fs::write(&path, newer).unwrap(); let err = read_json_or_quarantine::(&path).unwrap_err(); assert!( matches!(err, StateFileError::NewerVersion { version: 2, .. }), "{err:?}" ); assert_eq!(std::fs::read(&path).unwrap(), newer); assert!(quarantined(&path).unwrap().is_empty()); } #[test] fn quarantined_lists_only_this_files_siblings() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("queue.json"); assert!( quarantined(&dir.path().join("absent/queue.json")) .unwrap() .is_empty() ); std::fs::write(&path, b"garbage").unwrap(); std::fs::write(dir.path().join("other.json.corrupt-1"), b"x").unwrap(); assert!(quarantined(&path).unwrap().is_empty()); let moved = quarantine(&path).unwrap(); assert_eq!(quarantined(&path).unwrap(), [moved]); } #[test] fn lock_is_exclusive_and_waits_are_bounded() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("nested/state.json"); assert_eq!( lock_path(&path).unwrap(), dir.path().join("nested/state.json.lock") ); let held = lock_exclusive(&path, Duration::ZERO).unwrap(); let err = lock_exclusive(&path, Duration::from_millis(50)).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}"); drop(held); // Released on drop; the lock file itself stays. drop(lock_exclusive(&path, Duration::ZERO).unwrap()); assert!(lock_path(&path).unwrap().exists()); } #[test] fn hex_encodes() { assert_eq!(hex(&[0x00, 0xab, 0xff]), "00abff"); } }