Files
vectorcraft/crates/format/src/atomic.rs
T
dotCooCoo ade0e47f48 Scripts: refused writes create no file; Linux reads the casefold flag
A refused rename that falls back to copying into the target no longer
creates a missing target before the final authorization check. The
target is created only after that check, on every platform, so a
refusal at the final check leaves the path absent. An existing target
is still opened with O_CREAT, so Linux's fs.protected_regular applies.

imageCapture no longer treats an empty Linux folder as ignoring the
Unicode normalization form. It reads the folder's casefold inode flag
(FS_IOC_GETFLAGS) instead, so a missing linked cafe\u{301}.png no longer
matches cafe\u{e9}.png in an ordinary folder, and a casefolded folder
still matches both spellings.
2026-12-03 02:35:18 -08:00

1910 lines
92 KiB
Rust

//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination.
//! A failure while writing or flushing the temporary file leaves the original file unchanged.
//! On Unix, saves also flush the destination directory after the complete file is written.
//! An error at that step reports that the file was written.
//! [`write_new_with`] creates a file the same way without ever replacing one.
//!
//! Where a folder refuses the temporary file or the rename (some network shares, a file another
//! program holds open), the new content is first written and flushed elsewhere and only then copied
//! into the file itself. That copy isn't atomic, so the file as it was is copied and flushed beside
//! the temporary file first (#1695): if the copy into the file fails or is cut short, both versions
//! are on disk, and the error names them. Where that copy of the old file can't be made, the file
//! is left as it was and the save fails.
//!
//! Work canceled ([`vectorcraft_doc::cancel`]) by the time the temporary file is written and flushed
//! puts nothing in place: the temporary file is removed, the file stays as it was (or absent), and
//! the error wraps [`vectorcraft_doc::cancel::Cancelled`].
//!
//! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with
//! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain
//! `fsync` works: [`sync_file`] falls back to the plain one there (#1620).
use std::fs::{File, OpenOptions};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Reports whether a write error identifies a read-only location.
/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied.
pub fn read_only_location(error: &io::Error) -> bool {
matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied)
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>() || e.is::<WrittenError>())
}
#[derive(Debug)]
struct WrittenError {
path: PathBuf,
error: io::Error,
}
impl std::fmt::Display for WrittenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error)
}
}
impl std::error::Error for WrittenError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
/// Marks the existing recovery message without changing its text or the returned error kind.
#[derive(Debug)]
struct RecoveryError(String);
impl std::fmt::Display for RecoveryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for RecoveryError {}
/// Write `bytes` to `path` atomically (see the module docs).
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
write_atomic_with(path, |f| f.write_all(bytes))
}
/// This function writes `path` atomically with `fill`, which writes content into a temporary file.
/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged.
/// Cleanup attempts to remove the temporary file and ignores removal errors.
/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs).
pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
// Replacing a file: its staging copy starts owner-only, so a private document is never readable
// beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode.
let replacing = path.exists();
let create = |tmp: &Path| if replacing { create_private(tmp) } else { create_new(tmp) };
write_atomic_stepping(path, fill, create, |tmp, target| std::fs::rename(tmp, target))
}
fn create_new(path: &Path) -> io::Result<File> {
OpenOptions::new().write(true).create_new(true).open(path)
}
/// [`write_atomic_with`] for a `path` the caller has allowed by its name. On Unix the folder that
/// holds the file is opened once, and `allowed` is asked again with the path that open folder has
/// then, joined with the file's name. The temporary file, the replacement, a copy over the file
/// where the folder refuses the replacement, and the folder flush all go through that open folder,
/// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is
/// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at
/// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it;
/// a link put there later is replaced, never followed. A folder that moved after it was opened is
/// checked with `allowed` again at its new path right before the file is put in place, and a folder
/// whose new path the system does not report fails. Elsewhere this is `allowed(path)` followed by
/// [`write_atomic_with`].
#[cfg(unix)]
pub fn write_atomic_checked(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
allowed: impl Fn(&Path) -> io::Result<()>,
) -> io::Result<()> {
use rustix::fs::{AtFlags, Mode, OFlags};
// A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name`
// would drop the slash and save `draft.svg`.
let spelled = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str());
if spelled.ends_with(b"/") || spelled.ends_with(b"/.") || spelled == b"." {
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())));
}
let resolved = resolve_link(path)?;
let name = resolved
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", resolved.display())))?
.to_os_string();
let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
let dir = open_folder(parent)?;
let real = opened_folder_path(&dir, parent)?;
let target = real.join(stored_name(&dir, &real, &name));
allowed(&target)?;
// Only whether a file is there: its permissions are read again once it is about to be replaced.
let replacing = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).is_ok();
let tmp_name = temp_path(&target)?.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_default();
// Replacing a file: owner-only while it is written, as in `write_atomic_with`.
let mode = if replacing { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH };
let new_file = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
let remove_tmp = || {
// Best effort: the temporary file is all there is to clean up.
let _ = rustix::fs::unlinkat(&dir, &tmp_name, AtFlags::empty());
};
// The folder may have moved since it was opened: messages name it where it is now.
let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file);
// Right before the file is put in place: a folder that moved since it was opened is checked
// again where it is now, so a move out of the allowed folders does not receive the file.
let still_allowed = || -> io::Result<()> {
let here = folder_now(&dir, &real);
let open = rustix::fs::fstat(&dir)?;
// The path itself, not a link that leads to the folder from elsewhere.
let same = |p: &Path| {
std::fs::canonicalize(p).is_ok_and(|c| c == p) && rustix::fs::stat(p).is_ok_and(|s| (s.st_dev, s.st_ino) == (open.st_dev, open.st_ino))
};
if here == real && same(&real) {
return Ok(());
}
if here == real || !same(&here) {
return Err(io::Error::other(format!("{}: the folder moved while the file was written", target.display())));
}
allowed(&here.join(stored_name(&dir, &here, &name)))
.map_err(|_| io::Error::other(format!("{}: the folder moved while the file was written", target.display())))
};
let synced = || {
// Opened for reading here: the folder handle above may allow name lookups only.
let flushed =
rustix::fs::openat(&dir, ".", OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).and_then(|d| rustix::fs::fsync(&d));
flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() }))
};
let open_target = |write: bool| -> io::Result<File> {
// A missing target is created by `create_target`, after the last check. An existing one is
// opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it.
if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) {
return Err(io::ErrorKind::NotFound.into());
}
let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY };
Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?))
};
let create_target = || -> io::Result<File> { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) };
match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) {
Ok(mut f) => {
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
// Checked before the temporary file takes the old file's wider permissions, and again
// right before the rename.
if let Err(e) = filled.and_then(|()| still_allowed()) {
drop(f);
remove_tmp();
return Err(e);
}
// The file's permissions as they are now, after `fill`, as in `write_atomic_with`: a
// change made to them meanwhile is kept. Best effort; a file that can't be looked at
// leaves the replacement owner-only.
if let Ok(old) = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW) {
let _ = keep_permissions_at(&dir, &name, &old, &f);
}
drop(f);
if let Err(e) = still_allowed() {
remove_tmp();
return Err(e);
}
#[cfg(test)]
let refuse = RENAME_REFUSED.with(std::cell::Cell::get);
#[cfg(not(test))]
let refuse = false;
let renamed = if refuse { Err(rustix::io::Errno::ACCESS) } else { rustix::fs::renameat(&dir, &tmp_name, &dir, &name) };
let Err(refused) = renamed else { return synced() };
// The file as it was is copied beside the temporary file, through the open folder, or
// to the system's folder where the open folder takes no new file.
let old_name = Path::new(&tmp_name).with_extension("old").into_os_string();
let old_elsewhere = std::env::temp_dir().join(&old_name);
let old_in_folder = std::cell::Cell::new(true);
let over = Over {
tmp: &|| now(&tmp_name),
create_old: &|| match rustix::fs::openat(&dir, &old_name, new_file, Mode::RUSR | Mode::WUSR) {
Ok(f) => {
old_in_folder.set(true);
Ok(File::from(f))
}
Err(e) if e == rustix::io::Errno::EXIST => Err(e.into()),
Err(_) => {
old_in_folder.set(false);
create_private(&old_elsewhere)
}
},
old: &|| if old_in_folder.get() { now(&old_name) } else { old_elsewhere.clone() },
remove_old: &|| {
// Best effort: an unfinished copy is of no use.
if old_in_folder.get() {
let _ = rustix::fs::unlinkat(&dir, &old_name, AtFlags::empty());
} else {
let _ = std::fs::remove_file(&old_elsewhere);
}
},
open_tmp: &|| {
Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?))
},
remove_tmp: &remove_tmp,
open_target: &open_target,
create_target: &create_target,
synced: &synced,
still_allowed: &still_allowed,
};
write_over_in(&over, refused.into())
}
// A folder that isn't there, a full volume: nothing can be saved there.
Err(e) if matches!(io::Error::from(e).kind(), io::ErrorKind::NotFound | io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded) => {
Err(e.into())
}
Err(refused) => {
// The folder takes no temporary file: it is written in the system's folder and copied in.
let elsewhere = std::env::temp_dir().join(&tmp_name);
let mut f = create_private(&elsewhere).map_err(|_| io::Error::from(refused))?;
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
drop(f);
let remove = || {
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&elsewhere);
};
if let Err(e) = filled.and_then(|()| still_allowed()) {
remove();
return Err(e);
}
let old = elsewhere.with_extension("old");
let over = Over {
tmp: &|| elsewhere.clone(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(&elsewhere),
remove_tmp: &remove,
open_target: &open_target,
create_target: &create_target,
synced: &synced,
still_allowed: &still_allowed,
};
write_over_in(&over, refused.into())
}
}
}
/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is
/// filled, right before it is put in place; a refusal then removes the temporary file and leaves
/// `path` unchanged.
#[cfg(not(unix))]
pub fn write_atomic_checked(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
allowed: impl Fn(&Path) -> io::Result<()>,
) -> io::Result<()> {
allowed(path)?;
let replacing = path.exists();
let create = |tmp: &Path| if replacing { create_private(tmp) } else { create_new(tmp) };
write_atomic_staged(path, fill, create, || allowed(path), |tmp, target| std::fs::rename(tmp, target))
}
/// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links
/// followed, when that is still the folder `dir` holds (the same device and inode). A folder
/// replaced in between is an error.
#[cfg(unix)]
fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result<PathBuf> {
let real = std::fs::canonicalize(parent)?;
let (open, now) = (rustix::fs::fstat(dir)?, rustix::fs::stat(&real)?);
if (open.st_dev, open.st_ino) != (now.st_dev, now.st_ino) {
// Not a permission the file system refused: [`read_only_location`] does not take it for one.
return Err(io::Error::other(format!("{}: the folder changed while it was opened", parent.display())));
}
Ok(real)
}
/// The name the entry `name` in the open folder `dir`, whose real path is `real`, is stored under.
/// On a volume that ignores letter case, `report.svg` can be stored as `Report.svg`, the name a
/// grant for that file was given. `name` itself when nothing is there, or when the entry the path
/// leads to is not the one in `dir` (the same device and inode, links not followed).
#[cfg(unix)]
fn stored_name(dir: &std::os::fd::OwnedFd, real: &Path, name: &std::ffi::OsStr) -> std::ffi::OsString {
use rustix::fs::AtFlags;
let Ok(here) = rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) else { return name.to_os_string() };
let Ok(stored) = std::fs::canonicalize(real.join(name)) else { return name.to_os_string() };
let same = stored.parent() == Some(real) && rustix::fs::lstat(&stored).is_ok_and(|s| (s.st_dev, s.st_ino) == (here.st_dev, here.st_ino));
match stored.file_name() {
Some(stored) if same => stored.to_os_string(),
_ => name.to_os_string(),
}
}
/// The folder at `parent`, opened for looking names up in it. On Linux, Android and FreeBSD that
/// is `O_PATH`, and on Apple platforms `O_SEARCH`: neither needs permission to list the folder, so
/// a folder that can be written and searched but not listed still takes the file. Where the system
/// refuses `O_SEARCH`, the folder is opened for reading.
#[cfg(unix)]
fn open_folder(parent: &Path) -> io::Result<std::os::fd::OwnedFd> {
use rustix::fs::{Mode, OFlags};
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
let access = OFlags::PATH;
#[cfg(target_vendor = "apple")]
{
// `O_EXEC`, which with `O_DIRECTORY` is `O_SEARCH` (<sys/fcntl.h>).
let search = OFlags::from_bits_retain(0x4000_0000);
match rustix::fs::open(parent, search | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()) {
Err(e) if e == rustix::io::Errno::INVAL => {}
opened => return Ok(opened?),
}
}
#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd")))]
let access = OFlags::RDONLY;
Ok(rustix::fs::open(parent, access | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?)
}
/// The path the open folder `dir` has now, which may differ from `opened`, its real path when it
/// was opened, after it moved. `opened` where the system does not say.
#[cfg(unix)]
fn folder_now(dir: &std::os::fd::OwnedFd, opened: &Path) -> PathBuf {
#[cfg(any(target_os = "linux", target_os = "android"))]
if let Ok(now) = std::fs::read_link(format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(dir)))
&& now.is_absolute()
{
return now;
}
#[cfg(target_vendor = "apple")]
if let Ok(now) = rustix::fs::getpath(dir) {
return PathBuf::from(<std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(now.into_bytes()));
}
let _ = dir;
opened.to_path_buf()
}
/// [`keep_permissions`] for the temporary file `tmp`, about to replace `name` in folder `dir`, whose
/// file has the status `old`. A name that does not hold a plain file has none to keep. The ACL is
/// read only from that same file (the same device and inode); when it can't be, the replacement
/// keeps no group or other permissions.
#[cfg(unix)]
fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> io::Result<()> {
use rustix::fs::{FileType, Mode};
if FileType::from_raw_mode(old.st_mode) != FileType::RegularFile {
return Ok(());
}
let mut mode = Mode::from_raw_mode(old.st_mode);
let gid = rustix::fs::Gid::from_raw(old.st_gid);
let kept_group = rustix::fs::fstat(tmp).is_ok_and(|t| t.st_gid == old.st_gid) || rustix::fs::fchown(tmp, None, Some(gid)).is_ok();
if !kept_group || !keep_acl_at(dir, name, old, tmp) {
mode.remove(Mode::RWXG | Mode::RWXO);
}
rustix::fs::fchmod(tmp, mode).map_err(io::Error::from)
}
/// [`keep_acl`] for `name` in folder `dir`, when it is still the file with the status `old`. The
/// file is opened with `O_PATH` without following a link, which needs no permission to read it, and
/// its ACL is read through `/proc/self/fd`, which names that open file.
#[cfg(target_os = "linux")]
fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> bool {
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
const ACL: &str = "system.posix_acl_access";
let Ok(target) = rustix::fs::openat(dir, name, OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty()) else {
return false;
};
if !rustix::fs::fstat(&target).is_ok_and(|t| (t.st_dev, t.st_ino) == (old.st_dev, old.st_ino)) {
return false;
}
let opened = format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(&target));
let mut buf = vec![0u8; 64 << 10];
match rustix::fs::getxattr(opened.as_str(), ACL, &mut buf[..]) {
Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()),
Err(e) if e == Errno::NODATA => match rustix::fs::fremovexattr(tmp, ACL) {
Ok(()) => true,
Err(e) => e == Errno::NODATA || e == Errno::NOTSUP,
},
Err(e) => e == Errno::NOTSUP,
}
}
#[cfg(all(unix, not(target_os = "linux")))]
fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &rustix::fs::Stat, _: &File) -> bool {
true
}
/// [`write_atomic_with`], with `create` making the temporary file beside the target and `rename`
/// moving it over the target.
fn write_atomic_stepping(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
create: impl FnOnce(&Path) -> io::Result<File>,
rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
write_atomic_staged(path, fill, create, || Ok(()), rename)
}
/// [`write_atomic_stepping`], with `check` run after the temporary file is filled and right before
/// it is put in place. An error from `check` removes the temporary file and leaves `path` unchanged.
fn write_atomic_staged(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
create: impl FnOnce(&Path) -> io::Result<File>,
check: impl Fn() -> io::Result<()>,
rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
let target = resolve_link(path)?;
let beside = temp_path(&target)?;
// `refused`: why the folder takes no temporary file (it is in the system's folder then).
let (tmp, mut f, refused) = match create(&beside) {
Ok(f) => (beside, f, None),
// A folder that isn't there, a full volume: nothing can be saved there.
Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded) => return Err(e),
Err(e) => {
let Some(tmp) = beside.file_name().map(|n| std::env::temp_dir().join(n)) else { return Err(e) };
let Ok(f) = create_private(&tmp) else { return Err(e) };
(tmp, f, Some(e))
}
};
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
drop(f);
if let Err(e) = filled.and_then(|()| check()) {
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
let refused = match refused {
Some(e) => e,
None => {
// Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none
// to keep.
let _ = keep_permissions(&target, &tmp);
let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) };
e
}
};
write_over(&tmp, &target, refused, &check)
}
/// The content of `tmp`, which is whole and flushed, copied into `target` itself, and `tmp`
/// removed: for a folder that `refused` the atomic replacement. When `target` can't be opened for
/// writing it is untouched: `tmp` is removed and `refused` returned. When what it holds can't be
/// copied aside first ([`keep_old`]) it is untouched too: `tmp` stays and the error names it. When
/// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the
/// error says where they are. `check` runs again right before `target` is overwritten.
fn write_over(tmp: &Path, target: &Path, refused: io::Error, check: &dyn Fn() -> io::Result<()>) -> io::Result<()> {
let old = tmp.with_extension("old");
let over = Over {
tmp: &|| tmp.to_path_buf(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(tmp);
},
// A missing target is created by `create_target`, after the last check. An existing one is
// opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it.
open_target: &|write| {
if !write {
return File::open(target);
}
if matches!(std::fs::symlink_metadata(target), Err(e) if e.kind() == io::ErrorKind::NotFound) {
return Err(io::ErrorKind::NotFound.into());
}
OpenOptions::new().write(true).create(true).truncate(false).open(target)
},
create_target: &|| create_new(target),
synced: &|| sync_written_parent(target),
still_allowed: check,
};
write_over_in(&over, refused)
}
/// How [`write_over_in`] reaches its files: by their paths, or through a folder opened once
/// ([`write_atomic_checked`]).
struct Over<'a> {
/// Where the temporary file is when an error message names it (its folder may have moved).
tmp: &'a dyn Fn() -> PathBuf,
/// A new file, for its owner only and never replacing one, that the file as it was is copied to.
create_old: &'a dyn Fn() -> io::Result<File>,
/// Where the file `create_old` made is when an error message names it.
old: &'a dyn Fn() -> PathBuf,
/// Best effort: removes the file `create_old` made.
remove_old: &'a dyn Fn(),
open_tmp: &'a dyn Fn() -> io::Result<File>,
/// Best effort.
remove_tmp: &'a dyn Fn(),
/// Opens the target without truncating it for writing when `true`, or for reading when `false`.
/// It never creates a missing target: `create_target` does that, after the final check.
open_target: &'a dyn Fn(bool) -> io::Result<File>,
/// Creates a missing target after the final check and fails if its name is taken.
create_target: &'a dyn Fn() -> io::Result<File>,
/// The target's folder flushed, after the target is written.
synced: &'a dyn Fn() -> io::Result<()>,
/// Asked right before the target is overwritten: an error leaves it as it was.
still_allowed: &'a dyn Fn() -> io::Result<()>,
}
/// [`write_over`] through `over`.
fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
// A missing target is created only after the final check.
if let Err(e) = (over.still_allowed)() {
(over.remove_tmp)();
return Err(e);
}
let opened = (over.open_tmp)().and_then(|from| {
let to = match (over.open_target)(true) {
Ok(to) => Some(to),
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
Ok((from, to))
});
let Ok((mut from, to)) = opened else {
// Best effort: the temporary file is all there is to clean up.
(over.remove_tmp)();
return Err(refused);
};
// Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes
// into: one put at its name meanwhile is not copied in its place.
let kept = to.as_ref().is_some_and(|to| to.metadata().map_or(true, |m| m.len() > 0));
if kept
&& let Err(e) = (over.open_target)(false).and_then(|mut target| {
if !to.as_ref().is_some_and(|to| same_file(&target, to)) {
return Err(io::Error::other("the file was replaced while it was opened"));
}
keep_old(&mut target, over)
})
{
#[cfg(unix)]
if let Err(e) = (over.still_allowed)() {
drop((from, to));
(over.remove_tmp)();
return Err(e);
}
let why = format!(
"{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}",
(over.tmp)().display()
);
return Err(io::Error::new(refused.kind(), RecoveryError(why)));
}
if let Err(e) = (over.still_allowed)() {
// Nothing was overwritten: neither copy is needed.
drop((from, to));
(over.remove_tmp)();
if kept {
(over.remove_old)();
}
return Err(e);
}
let mut to = match to {
Some(to) => to,
None => match (over.create_target)() {
Ok(to) => to,
// A file put at the name meanwhile is left alone, and reported as there.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
(over.remove_tmp)();
return Err(e);
}
Err(_) => {
(over.remove_tmp)();
return Err(refused);
}
},
};
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
drop((from, to));
match (copied, kept) {
(Ok(()), kept) => {
// Best effort: the file is saved, so the copies are no longer needed.
(over.remove_tmp)();
if kept {
(over.remove_old)();
}
(over.synced)()
}
(Err(e), true) => Err(io::Error::new(
e.kind(),
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), (over.old)().display())),
)),
(Err(e), false) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))),
}
}
/// A flushed copy of what `target` holds, in the file `over.create_old` makes. A copy this call made
/// and could not finish is removed; a file already at that name is left as it is.
fn keep_old(target: &mut File, over: &Over<'_>) -> io::Result<()> {
let mut to = (over.create_old)()?;
let copied = io::copy(target, &mut to).and_then(|_| sync_file(&to));
if copied.is_err() {
drop(to);
(over.remove_old)();
}
copied
}
/// Whether `a` and `b` are open on the same file (the same device and inode). Always `true` off
/// Unix.
fn same_file(a: &File, b: &File) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
matches!((a.metadata(), b.metadata()), (Ok(a), Ok(b)) if (a.dev(), a.ino()) == (b.dev(), b.ino()))
}
#[cfg(not(unix))]
{
let _ = (a, b);
true
}
}
/// A new file for its owner only (Unix): the system's temporary folder is shared.
fn create_private(path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
options.open(path)
}
/// Create `path` with the content `fill` writes, never replacing a file or a link of that name. The
/// content goes to a temporary file beside it, which is then linked in under `path`
/// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was
/// taken meanwhile). The file appears whole or not at all. Where hard links fail for another
/// reason, `path` is created with `create_new` and the content copied in; a failed copy removes
/// it. Cleanup attempts to remove the temporary file and ignores removal errors.
pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path))
}
/// [`write_new_with`], with `link` linking the temporary file in under `path`.
fn write_new_linking(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
link: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
let tmp = temp_path(path)?;
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled());
drop(f);
let placed = filled.and_then(|()| match link(&tmp, path) {
Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path),
linked => linked,
});
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&tmp);
placed.and_then(|()| sync_written_parent(path))
}
fn sync_written_parent(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error }))
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
/// This function flushes the directory containing `path` with `fsync`.
/// It returns errors from opening or flushing the directory.
#[cfg(unix)]
pub fn sync_parent(path: &Path) -> io::Result<()> {
#[cfg(test)]
if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed"));
}
let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from)
}
/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has
/// been canceled: the last check before a written temporary file is put in place.
fn not_cancelled() -> io::Result<()> {
vectorcraft_doc::cancel::check().map_err(io::Error::other)
}
/// Create `path` (never replacing anything) with the content of the file `from`; a failed copy
/// removes it again.
fn copy_new(from: &Path, path: &Path) -> io::Result<()> {
let mut to = OpenOptions::new().write(true).create_new(true).open(path)?;
let copied = File::open(from).and_then(|mut f| io::copy(&mut f, &mut to)).and_then(|_| sync_file(&to));
drop(to);
if copied.is_err() {
// Best effort: the part copied is all there is to clean up.
let _ = std::fs::remove_file(path);
}
copied
}
/// Flush `file` to stable storage (`sync_all`). On Apple platforms that is a full flush
/// (`F_FULLFSYNC`); where the volume refuses it with `ENOTSUP` (SMB shares) or `ENOTTY` (virtiofs
/// shares, #1620) this falls back to a plain `fsync`. Any other error, and a failed `fsync`, is
/// returned as it is.
pub fn sync_file(file: &File) -> io::Result<()> {
match full_sync(file) {
Err(e) if full_flush_unsupported(&e) => plain_fsync(file),
r => r,
}
}
/// Whether `e` is a volume refusing a full flush. Never off Apple platforms: there `sync_all` is
/// already a plain `fsync`. Checked by its code because std maps `ENOTSUP` and `ENOTTY` to
/// `Uncategorized`.
fn full_flush_unsupported(e: &io::Error) -> bool {
cfg!(target_vendor = "apple") && matches!(e.raw_os_error(), Some(ENOTSUP | ENOTTY))
}
#[cfg(target_vendor = "apple")]
fn plain_fsync(file: &File) -> io::Result<()> {
#[cfg(test)]
{
PLAIN_FSYNCS.with(|c| c.set(c.get() + 1));
if let Some(errno) = PLAIN_FSYNC_FAILS.with(std::cell::Cell::get) {
return Err(io::Error::from_raw_os_error(errno));
}
}
rustix::fs::fsync(file).map_err(io::Error::from)
}
#[cfg(not(target_vendor = "apple"))]
fn plain_fsync(file: &File) -> io::Result<()> {
file.sync_all()
}
fn full_sync(file: &File) -> io::Result<()> {
#[cfg(test)]
{
if REFUSE_FULL_SYNC.with(std::cell::Cell::get) {
return Err(io::Error::from_raw_os_error(ENOTSUP));
}
match FLUSHES_LEFT.with(std::cell::Cell::get) {
Some(0) => return Err(io::Error::other("the connection was lost")),
Some(n) => FLUSHES_LEFT.with(|c| c.set(Some(n - 1))),
None => {}
}
}
file.sync_all()
}
/// What macOS answers when a volume can't make a full flush (SMB shares).
#[cfg(target_vendor = "apple")]
const ENOTSUP: i32 = 45;
#[cfg(not(target_vendor = "apple"))]
const ENOTSUP: i32 = 95;
/// What macOS answers when a virtiofs share (a folder shared into a VM) is asked for a full flush.
/// The same number on every Unix.
const ENOTTY: i32 = 25;
#[cfg(test)]
thread_local! {
#[cfg(unix)]
static DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: every full flush on this thread fails as on an SMB share mounted by macOS.
static REFUSE_FULL_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: the plain `fsync` fallback fails too, with this OS error.
static PLAIN_FSYNC_FAILS: std::cell::Cell<Option<i32>> = const { std::cell::Cell::new(None) };
/// Tests: after this many more flushes on this thread, every flush fails.
static FLUSHES_LEFT: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
/// Tests: how many plain `fsync` fallbacks were made on this thread.
static PLAIN_FSYNCS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
/// Tests: [`write_atomic_checked`]'s folder refuses the rename.
#[cfg(unix)]
static RENAME_REFUSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// A symbolic link keeps pointing at its file: write the file it names.
fn resolve_link(path: &Path) -> io::Result<PathBuf> {
match std::fs::symlink_metadata(path) {
Ok(m) if m.file_type().is_symlink() => std::fs::canonicalize(path),
_ => Ok(path.to_path_buf()),
}
}
/// A fresh hidden name beside `target` (the same folder, so the rename stays on one volume).
fn temp_path(target: &Path) -> io::Result<PathBuf> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", target.display())))?;
let n = NEXT.fetch_add(1, Ordering::Relaxed);
Ok(target.with_file_name(format!(".{}.{}-{n}.tmp", name.to_string_lossy(), std::process::id())))
}
/// The replacement keeps the replaced file's permissions, group and (Linux) access ACL: the same
/// mode bits mean other people when the group differs, and an ACL can narrow who reads the file.
/// When the group or the ACL can't be kept, the replacement is readable by its owner alone rather
/// than by people the old file didn't let in. (Unix; Windows files have none to keep beyond
/// read-only, which makes the save fail as writing in place would.) `tmp` is the file that is about
/// to replace `target`.
#[cfg(unix)]
pub fn keep_permissions(target: &Path, tmp: &Path) -> io::Result<()> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
// A new file: the default permissions.
let Ok(m) = std::fs::metadata(target) else { return Ok(()) };
let mut mode = m.permissions().mode();
let kept_group = std::fs::metadata(tmp).is_ok_and(|t| t.gid() == m.gid()) || std::os::unix::fs::chown(tmp, None, Some(m.gid())).is_ok();
if !kept_group || !keep_acl(target, tmp) {
mode &= !0o077;
}
// After the ACL: the mode's group bits are its mask, kept as they were.
std::fs::set_permissions(tmp, std::fs::Permissions::from_mode(mode))
}
/// Give `tmp` the access ACL of `target`; `true` when it has none (or its volume keeps none).
#[cfg(target_os = "linux")]
fn keep_acl(target: &Path, tmp: &Path) -> bool {
use rustix::io::Errno;
const ACL: &str = "system.posix_acl_access";
let mut buf = vec![0u8; 64 << 10];
match rustix::fs::getxattr(target, ACL, &mut buf[..]) {
Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::setxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()),
// None to keep: drop the one `tmp` may have inherited from the folder's default ACL, which
// the old file's group bits (its mask) would otherwise open to the people it names.
Err(e) if e == Errno::NODATA => match rustix::fs::removexattr(tmp, ACL) {
Ok(()) => true,
Err(e) => e == Errno::NODATA || e == Errno::NOTSUP,
},
Err(e) => e == Errno::NOTSUP,
}
}
#[cfg(all(unix, not(target_os = "linux")))]
fn keep_acl(_: &Path, _: &Path) -> bool {
true
}
/// Windows files have no permissions to keep beyond read-only (see the Unix version).
#[cfg(not(unix))]
pub fn keep_permissions(_: &Path, _: &Path) -> io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn readonly_classification_uses_the_terminal_kind_and_excludes_recovery() {
for (kind, expected) in [
(io::ErrorKind::PermissionDenied, true),
(io::ErrorKind::ReadOnlyFilesystem, true),
(io::ErrorKind::StorageFull, false),
(io::ErrorKind::QuotaExceeded, false),
(io::ErrorKind::NotFound, false),
(io::ErrorKind::Other, false),
] {
assert_eq!(read_only_location(&io::Error::new(kind, "injected")), expected, "{kind:?}");
let recovery = io::Error::new(kind, RecoveryError("the new content is kept in a.tmp".into()));
assert!(!read_only_location(&recovery), "recovery: {kind:?}");
assert_eq!(recovery.kind(), kind);
assert_eq!(recovery.to_string(), "the new content is kept in a.tmp");
}
}
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("vc-atomic-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A replaced file that had no access ACL gets none from the folder's default ACL, whose named
/// users the old file's group bits would let in. The default ACL is set through its extended
/// attribute, so the test runs where the `acl` tools are not installed. (Skipped on a file system
/// without ACLs.)
#[cfg(target_os = "linux")]
#[test]
fn a_replacement_takes_no_inherited_acl_the_old_file_lacked() {
let d = dir("acl");
let f = d.join("doc.vectorcraft");
std::fs::write(&f, b"old").unwrap();
if !set_default_acl_for_nobody(&d) {
let _ = std::fs::remove_dir_all(&d);
return;
}
write_atomic(&f, b"new").unwrap();
let mut buf = vec![0u8; 4096];
assert_eq!(rustix::fs::getxattr(&f, "system.posix_acl_access", &mut buf[..]), Err(rustix::io::Errno::NODATA));
let _ = std::fs::remove_dir_all(&d);
}
/// Give folder `d` the default ACL `u::rw-,u:nobody:rw-,g::r--,m::rw-,o::r--`, written as the
/// kernel's `system.posix_acl_default` attribute (version 2, then tag, permissions and id per entry).
#[cfg(target_os = "linux")]
/// `false` when the folder's file system keeps no ACLs.
fn set_default_acl_for_nobody(d: &Path) -> bool {
const NO_ID: u32 = u32::MAX;
let mut acl = 2u32.to_le_bytes().to_vec();
for (tag, perm, id) in [(0x01u16, 6u16, NO_ID), (0x02, 6, 65534), (0x04, 4, NO_ID), (0x10, 6, NO_ID), (0x20, 4, NO_ID)] {
acl.extend(tag.to_le_bytes());
acl.extend(perm.to_le_bytes());
acl.extend(id.to_le_bytes());
}
match rustix::fs::setxattr(d, "system.posix_acl_default", &acl, rustix::fs::XattrFlags::empty()) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::NOTSUP => return false,
Err(e) => panic!("setting the default ACL: {e}"),
}
let mut buf = vec![0u8; 4096];
let probe = d.join("probe");
std::fs::write(&probe, b"").unwrap();
assert!(rustix::fs::getxattr(&probe, "system.posix_acl_access", &mut buf[..]).is_ok(), "a new file takes the default ACL");
std::fs::remove_file(&probe).unwrap();
true
}
/// A folder `root/inside` and a folder `outside` beside `root`, by their real paths, and a check
/// that allows paths under `root` only.
#[cfg(unix)]
fn checked_folders(name: &str) -> (PathBuf, PathBuf, PathBuf) {
let d = std::fs::canonicalize(dir(name)).unwrap();
let (root, outside) = (d.join("root"), d.join("outside"));
std::fs::create_dir_all(root.join("inside")).unwrap();
std::fs::create_dir_all(&outside).unwrap();
(d, root, outside)
}
/// Whether this system says where an open folder is now: macOS always, Linux and Android through
/// `/proc/self/fd`, which a chroot may lack. Decided without `folder_now`.
#[cfg(unix)]
fn reports_open_folder_paths() -> bool {
if cfg!(target_vendor = "apple") {
return true;
}
cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/proc/self/fd").is_dir()
}
#[cfg(unix)]
fn under(root: &Path) -> impl Fn(&Path) -> io::Result<()> + '_ {
move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) }
}
/// A folder on the path that is a link to a folder outside when the write starts fails the check
/// made on the folder that is opened, and nothing is written outside.
#[cfg(unix)]
#[test]
fn a_checked_write_refuses_a_folder_replaced_before_it_is_opened() {
let (d, root, outside) = checked_folders("checked-before");
std::fs::remove_dir(root.join("inside")).unwrap();
std::os::unix::fs::symlink(&outside, root.join("inside")).unwrap();
let r = write_atomic_checked(&root.join("inside/doc.txt"), |f| f.write_all(b"new"), under(&root));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is outside")), "{r:?}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing is left outside");
let _ = std::fs::remove_dir_all(d);
}
/// A folder on the path replaced by a link to a folder outside after it is checked and opened
/// does not redirect the write: the file goes into the folder that was opened.
#[cfg(unix)]
#[test]
fn a_checked_write_stays_in_the_folder_it_opened() {
let (d, root, outside) = checked_folders("checked-after");
let r = write_atomic_checked(
&root.join("inside/doc.txt"),
|f| {
std::fs::rename(root.join("inside"), root.join("moved"))?;
std::os::unix::fs::symlink(&outside, root.join("inside"))?;
f.write_all(b"new")
},
under(&root),
);
if !reports_open_folder_paths() {
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the folder moved")), "{r:?}");
assert!(!outside.join("doc.txt").exists() && !root.join("moved/doc.txt").exists());
assert!(std::fs::read_dir(root.join("moved")).unwrap().next().is_none());
let _ = std::fs::remove_dir_all(d);
return;
}
r.unwrap();
assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder");
assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// A folder moved out of the allowed root while the file is written receives nothing: the move is
/// caught before the file is put in place, and the temporary file is removed.
#[cfg(unix)]
#[test]
fn a_checked_write_refuses_a_folder_moved_outside_while_it_fills() {
let (d, root, outside) = checked_folders("checked-moved-out");
let r = write_atomic_checked(
&root.join("inside/doc.txt"),
|f| {
f.write_all(b"new")?;
std::fs::rename(root.join("inside"), outside.join("inside"))
},
under(&root),
);
assert!(r.as_ref().is_err_and(|e| !read_only_location(e)), "{r:?}");
let message = r.unwrap_err().to_string();
assert!(message.contains(&root.join("inside/doc.txt").display().to_string()), "{message}");
assert!(message.contains("the folder moved"), "{message}");
assert!(!message.contains(&outside.display().to_string()), "{message}");
assert!(std::fs::read_dir(outside.join("inside")).unwrap().next().is_none(), "nothing is left outside");
let _ = std::fs::remove_dir_all(d);
}
/// A link put at the file's name after the check is replaced by the file, not followed.
#[cfg(unix)]
#[test]
fn a_checked_write_replaces_a_link_put_at_its_name() {
let (d, root, outside) = checked_folders("checked-link");
std::fs::write(outside.join("other.txt"), b"keep").unwrap();
let path = root.join("inside/doc.txt");
let check = under(&root);
write_atomic_checked(
&path,
|f| f.write_all(b"new"),
|p| {
check(p)?;
std::os::unix::fs::symlink(outside.join("other.txt"), &path)
},
)
.unwrap();
assert_eq!(std::fs::read(outside.join("other.txt")).unwrap(), b"keep");
assert!(std::fs::symlink_metadata(&path).unwrap().is_file());
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// Permissions taken away from the file while the new content is written stay taken away.
#[cfg(unix)]
#[test]
fn a_checked_write_keeps_permissions_changed_while_it_fills() {
use std::os::unix::fs::PermissionsExt;
let (d, root, _) = checked_folders("checked-mode");
let path = root.join("inside/doc.txt");
std::fs::write(&path, b"old").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
let fill = |f: &mut File| {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
f.write_all(b"new")
};
write_atomic_checked(&path, fill, under(&root)).unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// A folder that changed between being opened and being looked up by its path is not reported
/// as a read-only location.
#[cfg(unix)]
#[test]
fn a_changed_folder_is_not_a_read_only_location() {
let (d, root, outside) = checked_folders("checked-identity");
let opened = open_folder(&root.join("inside")).unwrap();
let e = opened_folder_path(&opened, &outside).unwrap_err();
assert!(e.to_string().contains("the folder changed while it was opened"), "{e}");
assert!(!read_only_location(&e), "{e:?}");
let _ = std::fs::remove_dir_all(d);
}
/// A failed fallback names the recovery files in the folder's current location when available.
/// A move is refused when the system cannot resolve the open folder's current path.
#[cfg(unix)]
#[test]
fn a_checked_write_names_the_kept_file_where_its_folder_moved() {
let (d, root, _) = checked_folders("checked-moved");
std::fs::write(root.join("inside/doc.txt"), b"original").unwrap();
let r = write_atomic_checked(
&root.join("inside/doc.txt"),
|f| {
std::fs::rename(root.join("inside"), root.join("moved"))?;
RENAME_REFUSED.with(|c| c.set(true));
// The temporary file's flush and the copy of the old content work, the next doesn't.
FLUSHES_LEFT.with(|c| c.set(Some(2)));
f.write_all(b"new")
},
under(&root),
);
RENAME_REFUSED.with(|c| c.set(false));
FLUSHES_LEFT.with(|c| c.set(None));
let message = r.unwrap_err().to_string();
if !reports_open_folder_paths() {
assert!(message.contains("the folder moved"), "{message}");
assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"original");
assert_eq!(std::fs::read_dir(root.join("moved")).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(d);
return;
}
let kept = |ext: &str| -> PathBuf {
let found: Vec<_> = std::fs::read_dir(root.join("moved"))
.unwrap()
.map(|e| e.unwrap().path())
.filter(|p| p.extension().is_some_and(|x| x == ext))
.collect();
let [kept] = found.as_slice() else { panic!("one .{ext} file: {found:?}") };
std::fs::canonicalize(kept).unwrap()
};
let (tmp, old) = (kept("tmp"), kept("old"));
assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec()));
for file in [&tmp, &old] {
let named = root.join("moved").join(file.file_name().unwrap());
assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display());
}
let _ = std::fs::remove_dir_all(d);
}
/// A refused rename onto a missing file that is no longer allowed at the final check does not
/// create the file.
#[test]
fn a_refused_rename_does_not_create_a_missing_file_once_no_longer_allowed() {
let d = dir("no-rename-missing-disallowed");
let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp"));
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let check = || {
checks.set(checks.get() + 1);
if checks.get() == 1 { Ok(()) } else { Err(io::Error::other("moved outside")) }
};
let e = write_over(&tmp, &path, denied::<()>().unwrap_err(), &check).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert!(!path.exists(), "the refused write created {}", path.display());
assert!(!tmp.exists());
let _ = std::fs::remove_dir_all(d);
}
/// A refused rename whose folder is no longer allowed by the time the file would be overwritten
/// leaves the file as it was, and neither copy stays behind.
#[test]
fn a_refused_rename_does_not_overwrite_once_no_longer_allowed() {
let d = dir("no-rename-disallowed");
let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old"));
std::fs::write(&path, b"original").unwrap();
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if checks.get() == 1 {
Ok(())
} else {
assert_eq!(std::fs::read(&old).unwrap(), b"original");
Err(io::Error::other("moved outside"))
}
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), b"original");
assert!(!tmp.exists() && !old.exists());
let _ = std::fs::remove_dir_all(d);
}
/// A backup failure after a folder moves outside removes the new content and reports the refusal.
#[cfg(unix)]
#[test]
fn a_refused_rename_rechecks_authorization_after_a_backup_error() {
let (d, root, outside) = checked_folders("no-rename-backup-moved");
let inside = root.join("inside");
let moved = outside.join("inside");
let path = inside.join("doc.txt");
std::fs::write(&path, b"original").unwrap();
std::fs::write(inside.join("doc.tmp"), b"new").unwrap();
let checks = std::cell::Cell::new(0);
let over = Over {
tmp: &|| moved.join("doc.tmp"),
create_old: &|| {
std::fs::rename(&inside, &moved)?;
Err(io::Error::other("backup failed"))
},
old: &|| moved.join("doc.old"),
remove_old: &|| {},
open_tmp: &|| File::open(inside.join("doc.tmp")),
remove_tmp: &|| {
let _ = std::fs::remove_file(moved.join("doc.tmp"));
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if inside.exists() { Ok(()) } else { Err(io::Error::other("moved outside")) }
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert!(!e.to_string().contains(&outside.display().to_string()), "{e}");
assert!(!e.get_ref().is_some_and(|e| e.is::<RecoveryError>()));
assert_eq!(std::fs::read(moved.join("doc.txt")).unwrap(), b"original");
assert_eq!(std::fs::read_dir(&moved).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(d);
}
/// A refused fallback leaves a missing target absent when the final check fails.
#[cfg(unix)]
#[test]
fn a_refused_rename_leaves_a_missing_target_absent_once_no_longer_allowed() {
let d = dir("no-rename-disallowed-new");
let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old"));
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let created = std::cell::Cell::new(false);
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| {
if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }
},
create_target: &|| {
created.set(true);
create_new(&path)
},
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if checks.get() == 1 {
assert!(!path.exists());
Ok(())
} else {
assert!(!created.get() && !path.exists());
Err(io::Error::other("moved outside"))
}
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert!(!created.get());
assert!(!path.exists());
assert!(!tmp.exists() && !old.exists());
let _ = std::fs::remove_dir_all(d);
}
/// A checked fallback creates a missing target after authorization succeeds.
#[cfg(unix)]
#[test]
fn a_checked_write_creates_a_missing_target_when_the_rename_is_refused() {
let (d, root, _) = checked_folders("checked-new-no-rename");
let path = root.join("inside/doc.txt");
RENAME_REFUSED.with(|c| c.set(true));
let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
RENAME_REFUSED.with(|c| c.set(false));
r.unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert_eq!(std::fs::read_dir(root.join("inside")).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(d);
}
/// A file created by another writer at the final check is preserved whether that check succeeds or fails.
#[cfg(unix)]
#[test]
fn a_refused_rename_preserves_a_target_created_at_the_final_check() {
for allowed in [false, true] {
let d = dir("no-rename-new-target-taken");
let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp"));
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| Err(io::Error::other("no backup expected")),
old: &|| d.join("doc.old"),
remove_old: &|| {},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if checks.get() == 1 {
return Ok(());
}
std::fs::write(&path, b"someone else's")?;
if allowed { Ok(()) } else { Err(io::Error::other("moved outside")) }
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
if !allowed {
assert!(e.to_string().contains("moved outside"), "{e}");
}
assert_eq!(std::fs::read(&path).unwrap(), b"someone else's");
assert!(!tmp.exists() && !d.join("doc.old").exists());
let _ = std::fs::remove_dir_all(d);
}
}
/// A refused rename copies the old content through the file handle it then overwrites: when a
/// different file is at the name by the time it is opened for reading, nothing is overwritten and
/// the new content stays in the temporary file.
#[cfg(unix)]
#[test]
fn a_refused_rename_copies_aside_the_file_it_overwrites() {
let d = dir("no-rename-swapped");
let (path, other, tmp) = (d.join("doc.txt"), d.join("other.txt"), d.join("doc.tmp"));
std::fs::write(&path, b"original").unwrap();
std::fs::write(&other, b"someone else's").unwrap();
std::fs::write(&tmp, b"new").unwrap();
let old = d.join("doc.old");
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| Ok(()),
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), b"original");
assert_eq!(std::fs::read(&tmp).unwrap(), b"new");
assert!(!old.exists());
let _ = std::fs::remove_dir_all(d);
}
/// A path written as a folder is refused, and no file is made under the name before the slash.
#[cfg(unix)]
#[test]
fn a_checked_write_refuses_a_path_written_as_a_folder() {
let (d, root, _) = checked_folders("checked-slash");
for spelled in ["inside/draft.svg/", "inside/draft.svg/."] {
let r = write_atomic_checked(&root.join(spelled), |f| f.write_all(b"new"), under(&root));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::InvalidInput), "{spelled}");
}
assert!(!root.join("inside/draft.svg").exists());
write_atomic_checked(&root.join("inside/draft.svg"), |f| f.write_all(b"new"), under(&root)).unwrap();
assert_eq!(std::fs::read(root.join("inside/draft.svg")).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// On a volume that ignores letter case, a write to `report.txt` where `Report.txt` is stored
/// is checked as `Report.txt`, the name a grant for the file has. (Skipped where the volume keeps
/// letter case apart.)
#[cfg(unix)]
#[test]
fn a_checked_write_checks_the_stored_name_of_the_file() {
let (d, root, _) = checked_folders("checked-case");
let stored = root.join("inside/Report.txt");
std::fs::write(&stored, b"old").unwrap();
if !root.join("inside/report.txt").exists() {
let _ = std::fs::remove_dir_all(d);
return;
}
let exact = |p: &Path| if p == stored { Ok(()) } else { Err(io::Error::other(format!("{} is not granted", p.display()))) };
write_atomic_checked(&root.join("inside/report.txt"), |f| f.write_all(b"new"), exact).unwrap();
assert_eq!(std::fs::read(&stored).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// A replaced file that its owner may write but not read keeps the ACL that lets someone else
/// read it. (Skipped on a file system without ACLs, and for root, which can read any file.)
#[cfg(target_os = "linux")]
#[test]
fn a_checked_write_keeps_the_acl_of_a_file_its_owner_cannot_read() {
use std::os::unix::fs::PermissionsExt;
const ACL: &str = "system.posix_acl_access";
let (d, root, _) = checked_folders("checked-acl-write-only");
let path = root.join("inside/doc.txt");
std::fs::write(&path, b"old").unwrap();
// u::-w-, u:nobody:r--, g::---, m::r--, o::---
let mut acl = 2u32.to_le_bytes().to_vec();
for (tag, perm, id) in [(0x01u16, 2u16, u32::MAX), (0x02, 4, 65534), (0x04, 0, u32::MAX), (0x10, 4, u32::MAX), (0x20, 0, u32::MAX)] {
acl.extend(tag.to_le_bytes());
acl.extend(perm.to_le_bytes());
acl.extend(id.to_le_bytes());
}
match rustix::fs::setxattr(&path, ACL, &acl, rustix::fs::XattrFlags::empty()) {
Ok(()) => {}
Err(e) if e == rustix::io::Errno::NOTSUP => {
let _ = std::fs::remove_dir_all(d);
return;
}
Err(e) => panic!("setting the ACL: {e}"),
}
if File::open(&path).is_ok() {
// Root reads any file.
let _ = std::fs::remove_dir_all(d);
return;
}
write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)).unwrap();
let mut buf = vec![0u8; 4096];
let n = rustix::fs::getxattr(&path, ACL, &mut buf[..]).unwrap();
assert_eq!(buf.get(..n).unwrap(), acl.as_slice(), "the ACL is kept");
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// A folder that can be written and searched but not listed takes the file. (The permission
/// does not hold for root, which can list any folder.)
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
#[test]
fn a_checked_write_saves_into_a_folder_that_cannot_be_listed() {
use std::os::unix::fs::PermissionsExt;
let (d, root, _) = checked_folders("checked-search-only");
let folder = root.join("inside");
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o300)).unwrap();
let r = write_atomic_checked(&folder.join("doc.txt"), |f| f.write_all(b"new"), under(&root));
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
// The folder flush needs it opened for reading: the file is written, and the error says so.
assert!(r.as_ref().map_or_else(|e| e.get_ref().is_some_and(|e| e.is::<WrittenError>()), |()| true), "{r:?}");
assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// The other files in `d` besides `keep`.
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
}
/// Replacing a private file (#1712): the staging file is owner-only while it is written, whatever
/// the umask, and the saved file keeps the old permissions.
#[cfg(unix)]
#[test]
fn staging_of_a_private_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt as _;
let d = dir("private-staging");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"secret").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
let mut staging_mode = 0;
write_atomic_with(&path, |f| {
staging_mode = f.metadata()?.permissions().mode() & 0o777;
f.write_all(b"new")
})
.unwrap();
assert_eq!(staging_mode, 0o600, "the staging file must not be group or world readable");
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(&d);
}
/// Work canceled by the time the temporary file is written and flushed puts nothing in place:
/// the old file stays as it was, also where the folder refuses the rename (no copy over it), a
/// new file is not created, and no temporary file is left.
#[test]
fn canceled_work_puts_nothing_in_place() {
use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope};
fn cancelled(e: &io::Error) -> bool {
e.get_ref().is_some_and(|e| e.is::<Cancelled>())
}
let d = dir("cancel");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let token = CancelToken::new();
let r = scope(&token, None, || {
write_atomic_with(&path, |f| {
f.write_all(b"new")?;
token.cancel();
Ok(())
})
});
assert!(r.as_ref().is_err_and(cancelled), "{r:?}");
let refused = |_: &Path, _: &Path| -> io::Result<()> { Err(io::Error::from(io::ErrorKind::PermissionDenied)) };
let r = scope(&token, None, || write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, refused));
assert!(r.as_ref().is_err_and(cancelled), "{r:?}");
assert_eq!(std::fs::read(&path).unwrap(), b"original");
let new = d.join("new.vectorcraft");
let r = scope(&token, None, || write_new_with(&new, |f| f.write_all(b"new")));
assert!(r.as_ref().is_err_and(cancelled), "{r:?}");
assert!(!new.exists());
assert!(leftovers(&d, "doc.vectorcraft").is_empty(), "{:?}", leftovers(&d, "doc.vectorcraft"));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn the_original_file_survives_a_failed_write() {
let d = dir("fail");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let r = write_atomic_with(&path, |f| {
f.write_all(b"half a fi")?;
Err(io::Error::other("disk full"))
});
assert!(r.is_err());
assert_eq!(std::fs::read(&path).unwrap(), b"original");
assert!(leftovers(&d, "doc.vectorcraft").is_empty(), "the temporary file is removed");
write_atomic(&path, b"new").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert!(leftovers(&d, "doc.vectorcraft").is_empty());
// A folder that doesn't exist: an error, nothing written.
assert!(write_atomic(&d.join("missing").join("x.vectorcraft"), b"x").is_err());
let _ = std::fs::remove_dir_all(&d);
}
#[cfg(unix)]
#[test]
fn a_directory_sync_failure_reports_the_completed_replacement() {
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace");
let path = directory.join("doc.vectorcraft");
std::fs::write(&path, b"old").unwrap();
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let result = write_atomic(&path, b"new");
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
assert!(result.is_err(), "a failed directory flush was reported as success");
let error = result.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(error.to_string().contains("The file was written to"), "{error}");
assert!(!read_only_location(&error), "the file was already replaced: {error}");
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
write_atomic(&path, b"retried").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"retried");
}
#[cfg(unix)]
#[test]
fn a_directory_sync_failure_preserves_the_completed_new_file() {
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create");
let path = directory.join("doc.vectorcraft");
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let result = write_new_with(&path, |file| file.write_all(b"created"));
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
assert!(result.is_err(), "a failed directory flush was reported as success");
let error = result.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(error.to_string().contains("The file was written to"), "{error}");
assert!(!read_only_location(&error), "the file was already created: {error}");
assert_eq!(std::fs::read(&path).unwrap(), b"created");
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
let result = write_new_with(&path, |file| file.write_all(b"replacement"));
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(std::fs::read(&path).unwrap(), b"created");
}
#[cfg(unix)]
#[test]
fn a_directory_sync_failure_is_reported_after_copy_fallbacks() {
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy");
let path = directory.join("doc.vectorcraft");
std::fs::write(&path, b"old").unwrap();
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied());
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
let error = replaced.unwrap_err();
assert!(!read_only_location(&error), "the file was already replaced: {error}");
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let new_path = directory.join("new.vectorcraft");
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied());
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
let error = created.unwrap_err();
assert!(!read_only_location(&error), "the file was already created: {error}");
assert_eq!(std::fs::read(&new_path).unwrap(), b"created");
assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2);
}
/// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the
/// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before,
/// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain
/// `fsync`: a refusal is an error like any other.
#[test]
fn a_volume_that_refuses_the_full_flush_still_saves() {
let d = dir("no-full-sync");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let apple = cfg!(target_vendor = "apple");
REFUSE_FULL_SYNC.with(|c| c.set(true));
let before = PLAIN_FSYNCS.with(std::cell::Cell::get);
let saved = write_atomic(&path, b"new");
let created = write_new_with(&d.join("new.otf"), |f| f.write_all(b"created"));
let fsyncs = PLAIN_FSYNCS.with(std::cell::Cell::get) - before;
PLAIN_FSYNC_FAILS.with(|c| c.set(Some(5)));
let failed = write_atomic(&path, b"lost");
PLAIN_FSYNC_FAILS.with(|c| c.set(None));
REFUSE_FULL_SYNC.with(|c| c.set(false));
assert_eq!(saved.is_ok(), apple, "{saved:?}");
assert_eq!(created.is_ok(), apple, "{created:?}");
assert_eq!(fsyncs, if apple { 2 } else { 0 }, "each refused full flush falls back to fsync");
assert!(failed.is_err(), "a failed fsync still fails the save");
assert_eq!(std::fs::read(&path).unwrap(), if apple { &b"new"[..] } else { b"original" });
let mut left = leftovers(&d, "doc.vectorcraft");
left.retain(|n| n != "new.otf");
assert!(left.is_empty(), "no temporary file is left: {left:?}");
let _ = std::fs::remove_dir_all(&d);
}
/// A save to a virtiofs share (#1620: a folder shared into a macOS VM): macOS refuses the full
/// flush there with `ENOTTY` (os error 25), which falls back to a plain `fsync` as `ENOTSUP` does.
/// Elsewhere neither is a refused full flush, and other errors never are.
#[test]
fn a_full_flush_refused_with_enotty_falls_back_like_enotsup() {
let apple = cfg!(target_vendor = "apple");
assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(25)), apple, "ENOTTY");
assert_eq!(full_flush_unsupported(&io::Error::from_raw_os_error(ENOTSUP)), apple, "ENOTSUP");
assert!(!full_flush_unsupported(&io::Error::other("the connection was lost")));
}
fn denied<T>() -> io::Result<T> {
Err(io::Error::new(io::ErrorKind::PermissionDenied, "refused by the share"))
}
/// A folder that refuses the rename over the file (#1620: some network shares): the new content,
/// whole in the temporary file, is copied into the file itself. A new file is created.
#[test]
fn a_refused_rename_copies_the_content_into_the_file() {
let d = dir("no-rename");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original, and longer").unwrap();
write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, |_, _| denied()).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
write_atomic_stepping(&d.join("other.vectorcraft"), |f| f.write_all(b"other"), create_new, |_, _| denied()).unwrap();
assert_eq!(std::fs::read(d.join("other.vectorcraft")).unwrap(), b"other");
assert_eq!(leftovers(&d, "doc.vectorcraft"), ["other.vectorcraft"], "the temporary files are removed");
// A failed write never gets as far as the file.
let r = write_atomic_stepping(&path, |f| f.write_all(b"half").and(Err(io::Error::other("disk full"))), create_new, |_, _| denied());
assert_eq!(r.unwrap_err().to_string(), "disk full");
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(&d);
}
/// A refused rename where the file can't be written either (here: a folder of that name): the
/// rename's error, nothing changed and no temporary file left.
#[test]
fn a_refused_rename_over_a_file_that_cannot_be_written_changes_nothing() {
let d = dir("no-rename-no-write");
let path = d.join("doc.vectorcraft");
std::fs::create_dir(&path).unwrap();
let r = write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, |_, _| denied());
assert_eq!(r.unwrap_err().to_string(), "refused by the share");
assert!(path.is_dir() && leftovers(&d, "doc.vectorcraft").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// #1695: a refused rename and a copy into the file that fails (here: its flush, after the copy
/// of the old content was flushed): the file is damaged, so the temporary file with the whole
/// new content and the copy of the old one stay, and the error names both.
#[test]
fn a_failed_copy_into_the_file_keeps_the_old_content_and_the_new() {
let d = dir("no-rename-copy-fails-late");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let r = write_atomic_stepping(
&path,
|f| f.write_all(b"new"),
create_new,
|_, _| {
// One more flush works (the copy of the old content), the next doesn't.
FLUSHES_LEFT.with(|c| c.set(Some(1)));
denied()
},
);
FLUSHES_LEFT.with(|c| c.set(None));
let message = r.unwrap_err().to_string();
let mut left = leftovers(&d, "doc.vectorcraft");
left.sort();
let [old, tmp] = left.as_slice() else { panic!("the old content and the new: {left:?}") };
assert!(old.ends_with(".old") && tmp.ends_with(".tmp"), "{left:?}");
assert!(message.contains(tmp.as_str()) && message.contains(old.as_str()), "{message}");
assert_eq!((std::fs::read(d.join(old)).unwrap(), std::fs::read(d.join(tmp)).unwrap()), (b"original".to_vec(), b"new".to_vec()));
// A new file has nothing to keep, and a save that works leaves neither copy.
std::fs::remove_file(d.join(old)).unwrap();
std::fs::remove_file(d.join(tmp)).unwrap();
let fresh = d.join("fresh.vectorcraft");
write_atomic_stepping(&fresh, |f| f.write_all(b"new"), create_new, |_, _| denied()).unwrap();
write_atomic_stepping(&fresh, |f| f.write_all(b"newer"), create_new, |_, _| denied()).unwrap();
assert_eq!(std::fs::read(&fresh).unwrap(), b"newer");
assert_eq!(leftovers(&d, "doc.vectorcraft"), ["fresh.vectorcraft"]);
let _ = std::fs::remove_dir_all(&d);
}
/// A refused rename where a file is already at the name the old content would be copied to:
/// that file is left as it is, and the temporary file with the new content stays.
#[test]
fn a_refused_rename_leaves_a_file_already_at_the_backup_name() {
let d = dir("no-rename-backup-taken");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let r = write_atomic_stepping(
&path,
|f| f.write_all(b"new"),
create_new,
|tmp, _| {
std::fs::write(tmp.with_extension("old"), b"an earlier copy")?;
denied()
},
);
let message = r.unwrap_err().to_string();
let mut left = leftovers(&d, "doc.vectorcraft");
left.sort();
let [old, tmp] = left.as_slice() else { panic!("the earlier copy and the new content: {left:?}") };
assert!(message.contains(tmp.as_str()), "{message}");
assert_eq!(std::fs::read(d.join(old)).unwrap(), b"an earlier copy");
assert_eq!(std::fs::read(d.join(tmp)).unwrap(), b"new");
assert_eq!(std::fs::read(&path).unwrap(), b"original");
let _ = std::fs::remove_dir_all(&d);
}
/// A refused rename where the old content can't be copied aside (here: no flush works): the
/// file is left as it was, the temporary file with the whole new content stays and the error
/// names it.
#[test]
fn a_failed_copy_into_the_file_keeps_the_temporary_file() {
let d = dir("no-rename-copy-fails");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let r = write_atomic_stepping(
&path,
|f| f.write_all(b"new"),
create_new,
|_, _| {
// From here on flushing fails (also the plain `fsync` macOS falls back to).
REFUSE_FULL_SYNC.with(|c| c.set(true));
PLAIN_FSYNC_FAILS.with(|c| c.set(Some(5)));
denied()
},
);
REFUSE_FULL_SYNC.with(|c| c.set(false));
PLAIN_FSYNC_FAILS.with(|c| c.set(None));
let message = r.unwrap_err().to_string();
let left = leftovers(&d, "doc.vectorcraft");
let [tmp] = left.as_slice() else { panic!("one temporary file: {left:?}") };
assert!(message.contains(tmp.as_str()), "{message}");
assert_eq!(std::fs::read(d.join(tmp)).unwrap(), b"new");
assert_eq!(std::fs::read(&path).unwrap(), b"original", "not overwritten without a copy of it");
let _ = std::fs::remove_dir_all(&d);
}
/// A folder that takes no temporary file (#1620: a share that refuses hidden or new names) but
/// lets the file be written: the content goes through the system's temporary folder, and no
/// rename is tried. A folder that isn't there is still an error.
#[test]
fn a_folder_that_refuses_the_temporary_file_still_saves() {
let d = dir("no-temp");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original, and longer").unwrap();
let renamed = std::cell::Cell::new(false);
let rename = |_: &Path, _: &Path| {
renamed.set(true);
Ok(())
};
write_atomic_stepping(&path, |f| f.write_all(b"new"), |_| denied(), rename).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert!(!renamed.get() && leftovers(&d, "doc.vectorcraft").is_empty());
// The file can't be written either (a folder of that name): the folder's error.
let folder = d.join("folder");
std::fs::create_dir(&folder).unwrap();
let r = write_atomic_stepping(&folder, |f| f.write_all(b"new"), |_| denied(), |_, _| Ok(()));
assert_eq!(r.unwrap_err().to_string(), "refused by the share");
let r = write_atomic_stepping(&path, |f| f.write_all(b"lost"), |_| Err(io::Error::from(io::ErrorKind::NotFound)), |_, _| Ok(()));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::NotFound));
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(&d);
}
/// A check that refuses after the file is filled keeps the old file, removes the temporary file
/// and tries no rename, whether the folder takes the temporary file or not.
#[test]
fn a_check_refused_after_the_fill_keeps_the_file() {
let d = dir("staged-check");
let path = d.join("staged-check.vectorcraft");
std::fs::write(&path, b"old").unwrap();
let renamed = std::cell::Cell::new(false);
let rename = |_: &Path, _: &Path| {
renamed.set(true);
Ok(())
};
let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, || Err(io::Error::other("moved away")), rename);
assert_eq!(r.unwrap_err().to_string(), "moved away");
let r = write_atomic_staged(&path, |f| f.write_all(b"new"), |_| denied(), || Err(io::Error::other("moved away")), rename);
assert_eq!(r.unwrap_err().to_string(), "moved away");
assert_eq!(std::fs::read(&path).unwrap(), b"old");
assert!(!renamed.get() && leftovers(&d, "staged-check.vectorcraft").is_empty());
// A folder that refuses the rename: the check runs again before the file is written over.
let calls = std::cell::Cell::new(0);
let check = || {
calls.set(calls.get() + 1);
if calls.get() > 1 { Err(io::Error::other("moved away")) } else { Ok(()) }
};
let r = write_atomic_staged(&path, |f| f.write_all(b"new"), create_new, check, |_, _| denied());
assert!(r.is_err_and(|e| e.to_string().contains("moved away")));
assert_eq!(std::fs::read(&path).unwrap(), b"old");
assert!(leftovers(&d, "staged-check.vectorcraft").is_empty());
let staged = format!(".staged-check.vectorcraft.{}-", std::process::id());
let in_system = std::fs::read_dir(std::env::temp_dir()).unwrap().filter_map(Result::ok);
assert!(!in_system.into_iter().any(|e| e.file_name().to_string_lossy().starts_with(&staged)), "the system's folder keeps no staging file");
let _ = std::fs::remove_dir_all(&d);
}
/// Off Unix the check runs again after the file is filled: a refusal at that point keeps the
/// old file and leaves no temporary file.
#[cfg(not(unix))]
#[test]
fn a_checked_write_checks_again_before_the_file_is_put_in_place() {
let d = dir("checked-twice");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"old").unwrap();
let calls = std::cell::Cell::new(0);
let r = write_atomic_checked(
&path,
|f| f.write_all(b"new"),
|_| {
calls.set(calls.get() + 1);
if calls.get() > 1 { Err(io::Error::other("no longer allowed")) } else { Ok(()) }
},
);
assert_eq!(r.unwrap_err().to_string(), "no longer allowed");
assert_eq!(calls.get(), 2);
assert_eq!(std::fs::read(&path).unwrap(), b"old");
assert!(leftovers(&d, "doc.vectorcraft").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn write_new_never_replaces_what_is_there() {
let d = dir("new");
let path = d.join("a.otf");
write_new_with(&path, |f| f.write_all(b"first")).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"first");
assert!(leftovers(&d, "a.otf").is_empty(), "the temporary file is removed");
let r = write_new_with(&path, |f| f.write_all(b"second"));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert_eq!(std::fs::read(&path).unwrap(), b"first");
assert!(leftovers(&d, "a.otf").is_empty());
// A failed write leaves nothing.
let failed = d.join("b.otf");
assert!(write_new_with(&failed, |f| f.write_all(b"half").and(Err(io::Error::other("disk full")))).is_err());
assert!(!failed.exists() && leftovers(&d, "a.otf").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// Where hard links fail (a file system without them), the content is copied in, and a taken
/// name stays as it was. A link that fails because the name is taken copies nothing.
#[test]
fn write_new_copies_where_hard_links_fail() {
let d = dir("new-copy");
let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported));
let path = d.join("c.otf");
write_new_linking(&path, |f| f.write_all(b"copied"), unsupported).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"copied");
assert!(leftovers(&d, "c.otf").is_empty(), "the temporary file is removed");
let r = write_new_linking(&path, |f| f.write_all(b"second"), unsupported);
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert_eq!(std::fs::read(&path).unwrap(), b"copied");
let taken = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::AlreadyExists));
let other = d.join("d.otf");
let r = write_new_linking(&other, |f| f.write_all(b"other"), taken);
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert!(!other.exists() && leftovers(&d, "c.otf").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// A link of that name, even one to nothing, is never replaced or written through.
#[cfg(unix)]
#[test]
fn write_new_leaves_links_alone() {
let d = dir("new-links");
let target = d.join("target.otf");
std::fs::write(&target, b"target").unwrap();
std::os::unix::fs::symlink(&target, d.join("link.otf")).unwrap();
std::os::unix::fs::symlink(d.join("nothing.otf"), d.join("dangling.otf")).unwrap();
for name in ["link.otf", "dangling.otf"] {
let r = write_new_with(&d.join(name), |f| f.write_all(b"new"));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists), "{name}");
}
assert_eq!(std::fs::read(&target).unwrap(), b"target");
assert!(!d.join("nothing.otf").exists());
let mut names: Vec<String> = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
names.sort();
assert_eq!(names, ["dangling.otf", "link.otf", "target.otf"], "no temporary file is left");
let _ = std::fs::remove_dir_all(&d);
}
}