171 lines
5.6 KiB
Rust
171 lines
5.6 KiB
Rust
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
//! Small shared helpers: time, randomness, hashing, atomic file writes.
|
|
|
|
use std::io::Write;
|
|
use std::path::Path;
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
use ring::rand::{SecureRandom, SystemRandom};
|
|
use serde::Serialize;
|
|
use serde::de::DeserializeOwned;
|
|
|
|
pub fn now() -> u64 {
|
|
SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|d| d.as_secs())
|
|
.unwrap_or(0)
|
|
}
|
|
|
|
pub fn rfc3339(t: u64) -> String {
|
|
ianitor_core::time::rfc3339(t)
|
|
}
|
|
|
|
pub fn random<const N: usize>() -> Result<[u8; N], std::io::Error> {
|
|
let mut b = [0u8; N];
|
|
SystemRandom::new()
|
|
.fill(&mut b)
|
|
.map_err(|_| std::io::Error::other("the system random generator failed"))?;
|
|
Ok(b)
|
|
}
|
|
|
|
pub fn hex(bytes: &[u8]) -> String {
|
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
pub fn sha256_hex(data: &[u8]) -> String {
|
|
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
|
|
}
|
|
|
|
/// Compare two byte strings in time that depends only on their length.
|
|
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
|
if a.len() != b.len() {
|
|
return false;
|
|
}
|
|
let mut d = 0u8;
|
|
for (x, y) in a.iter().zip(b) {
|
|
d |= x ^ y;
|
|
}
|
|
std::hint::black_box(d) == 0
|
|
}
|
|
|
|
/// Write `data` to `path` so that readers see the old or the new content, never a mix, and
|
|
/// the new content survives a crash once this returns: temporary file in the same directory,
|
|
/// fsync, rename, fsync of the directory.
|
|
pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> {
|
|
crate::crash::fail_write(path).map_err(std::io::Error::other)?;
|
|
let dir = path
|
|
.parent()
|
|
.filter(|p| !p.as_os_str().is_empty())
|
|
.unwrap_or(Path::new("."));
|
|
std::fs::create_dir_all(dir)?;
|
|
let mut name = path.file_name().unwrap_or_default().to_os_string();
|
|
// Unique per write (process, counter, random), so two writers of the same file never
|
|
// share a temporary file.
|
|
static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
let r = random::<4>().map(|b| hex(&b))?;
|
|
name.push(format!(".tmp-{}-{n}-{r}", std::process::id()));
|
|
let tmp = dir.join(name);
|
|
{
|
|
let mut opts = std::fs::OpenOptions::new();
|
|
opts.write(true).create(true).truncate(true);
|
|
#[cfg(unix)]
|
|
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, mode);
|
|
#[cfg(not(unix))]
|
|
let _ = mode;
|
|
let mut f = opts.open(&tmp)?;
|
|
f.write_all(data)?;
|
|
f.sync_all()?;
|
|
}
|
|
std::fs::rename(&tmp, path)?;
|
|
sync_dir(dir)
|
|
}
|
|
|
|
/// Rename `from` to `to` atomically and durably.
|
|
pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> {
|
|
crate::crash::fail_write(to).map_err(std::io::Error::other)?;
|
|
std::fs::rename(from, to)?;
|
|
sync_dir(to.parent().unwrap_or(Path::new(".")))
|
|
}
|
|
|
|
pub fn sync_dir(dir: &Path) -> std::io::Result<()> {
|
|
#[cfg(unix)]
|
|
{
|
|
std::fs::File::open(dir)?.sync_all()?;
|
|
}
|
|
#[cfg(not(unix))]
|
|
let _ = dir;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn remove_if_exists(path: &Path) -> std::io::Result<()> {
|
|
match std::fs::remove_file(path) {
|
|
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
|
|
_ => Ok(()),
|
|
}
|
|
}
|
|
|
|
/// Read a JSON state file; `Ok(None)` when it does not exist.
|
|
pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String> {
|
|
match std::fs::read(path) {
|
|
Ok(b) => serde_json::from_slice(&b)
|
|
.map(Some)
|
|
.map_err(|e| format!("{} is damaged: {e}", path.display())),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
|
Err(e) => Err(format!("cannot read {}: {e}", path.display())),
|
|
}
|
|
}
|
|
|
|
/// Write a JSON state file atomically, readable by its owner only.
|
|
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
|
|
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
|
|
text.push(b'\n');
|
|
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#![allow(clippy::unwrap_used)]
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn constant_time_compare() {
|
|
assert!(ct_eq(b"abc", b"abc"));
|
|
assert!(!ct_eq(b"abc", b"abd"));
|
|
assert!(!ct_eq(b"abc", b"ab"));
|
|
}
|
|
|
|
#[test]
|
|
fn concurrent_atomic_writes_of_one_file_all_succeed() {
|
|
let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id()));
|
|
let p = d.join("paused.json");
|
|
let threads: Vec<_> = (0..16)
|
|
.map(|i| {
|
|
let p = p.clone();
|
|
std::thread::spawn(move || {
|
|
(0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok())
|
|
})
|
|
})
|
|
.collect();
|
|
for t in threads {
|
|
assert!(t.join().unwrap(), "a write failed");
|
|
}
|
|
let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect();
|
|
assert_eq!(left.len(), 1, "no temporary files left");
|
|
let _ = std::fs::remove_dir_all(&d);
|
|
}
|
|
|
|
#[test]
|
|
fn atomic_write_replaces() {
|
|
let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id()));
|
|
let p = d.join("f.json");
|
|
write_atomic(&p, b"one", 0o600).unwrap();
|
|
write_atomic(&p, b"two", 0o600).unwrap();
|
|
assert_eq!(std::fs::read(&p).unwrap(), b"two");
|
|
let _ = std::fs::remove_dir_all(&d);
|
|
}
|
|
}
|