use crate::error::Result;
use std::fs;
use std::io::Write;
use std::path::Path;
pub const SIDE_EXT: &str = "tmp";
pub fn ensure_dir(d: &Path) -> Result<()> {
if !d.exists() {
fs::create_dir_all(d)?;
}
set_mode(d, 0o700)
}
#[cfg(unix)]
pub fn set_mode(p: &Path, mode: u32) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(p, fs::Permissions::from_mode(mode))?;
Ok(())
}
#[cfg(not(unix))]
pub fn set_mode(_p: &Path, _mode: u32) -> Result<()> {
Ok(())
}
pub fn create_private(p: &Path) -> Result<fs::File> {
let mut o = fs::OpenOptions::new();
o.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
o.mode(0o600);
}
let f = o.open(p)?;
set_mode(p, 0o600)?;
Ok(f)
}
pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
write_private_with(path, bytes, SIDE_EXT)
}
pub fn write_private_with(path: &Path, bytes: &[u8], side_ext: &str) -> Result<()> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
&& !parent.exists()
{
fs::create_dir_all(parent)?;
}
let tmp = path.with_extension(side_ext);
if tmp.exists() {
fs::remove_file(&tmp)?;
}
let r = (|| -> Result<()> {
let mut f = create_private(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
drop(f);
fs::rename(&tmp, path)?;
Ok(())
})();
if r.is_err() {
let _ = fs::remove_file(&tmp);
}
r?;
sync_parent(path);
Ok(())
}
pub(crate) fn sync_parent(path: &Path) {
#[cfg(unix)]
if let Some(parent) = path.parent()
&& let Ok(d) = fs::File::open(if parent.as_os_str().is_empty() { Path::new(".") } else { parent })
{
let _ = d.sync_all();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn private_writes_replace_atomically() {
let t = tempfile::tempdir().unwrap();
let p = t.path().join("a").join("secret.bin");
write_private(&p, b"one").unwrap();
write_private_with(&p, b"two", "side").unwrap();
assert_eq!(fs::read(&p).unwrap(), b"two");
assert!(!p.with_extension(SIDE_EXT).exists() && !p.with_extension("side").exists());
let dir_as_target = t.path().join("a");
assert!(write_private(&dir_as_target, b"x").is_err());
assert!(!dir_as_target.with_extension(SIDE_EXT).exists());
assert_eq!(fs::read(&p).unwrap(), b"two");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
ensure_dir(&t.path().join("b/c")).unwrap();
assert_eq!(fs::metadata(t.path().join("b/c")).unwrap().permissions().mode() & 0o777, 0o700);
}
}
}