mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 04:52:54 -05:00
Merge pull request #10540 from dotCooCoo/fix/script-write-holds-checked-folder
Save: checked writes go into the folder that was checked
This commit is contained in:
4 files changed
+827
-60
No files matched your search
@@ -1,5 +1,3 @@
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::write_atomic;
|
||||
use super::{EngineError, Result, Session, Value, bad, json};
|
||||
|
||||
// ---------- the file system (none on the web, where commands take and return bytes) ----------
|
||||
@@ -325,8 +323,30 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
// Work that stops early for a cancel can leave a truncated result: none of it is written.
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
// Never a half-written file: see [`write_atomic`].
|
||||
write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e))
|
||||
// Never a half-written file: see [`vectorcraft_format::write_atomic`].
|
||||
write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes
|
||||
/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is
|
||||
/// checked again as it is opened, and the file goes into that open folder
|
||||
/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the
|
||||
/// check does not redirect the write.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> {
|
||||
let path = std::path::Path::new(path);
|
||||
if !crate::file_access::writes_checked() {
|
||||
return vectorcraft_format::write_atomic_with(path, fill);
|
||||
}
|
||||
vectorcraft_format::write_atomic_checked(path, fill, |opened| {
|
||||
// On Unix `opened` is the open folder's real path with the file's name: compared as it is,
|
||||
// without looking the folder up again. Elsewhere it is `path` itself.
|
||||
#[cfg(unix)]
|
||||
let checked = crate::file_access::check_write_real(opened);
|
||||
#[cfg(not(unix))]
|
||||
let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy());
|
||||
checked.map_err(std::io::Error::other)
|
||||
})
|
||||
}
|
||||
|
||||
/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the
|
||||
@@ -344,7 +364,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError {
|
||||
pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e))
|
||||
}
|
||||
|
||||
/// The save commands' writer: preserves a filesystem location refusal as a typed error. Other
|
||||
@@ -358,7 +378,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> {
|
||||
pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
may_write(path)?;
|
||||
vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -751,4 +771,43 @@ mod tests {
|
||||
assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The second check of a checked write compares the open folder's real path as it is: a folder
|
||||
/// on that path replaced afterwards by a link into the write root does not make a place outside
|
||||
/// the root pass.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() {
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let (root, out) = (base.join("root"), base.join("out"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(out.join("x")).unwrap();
|
||||
let real = out.join("x/doc.svg");
|
||||
std::fs::remove_dir(out.join("x")).unwrap();
|
||||
std::os::unix::fs::symlink(&root, out.join("x")).unwrap();
|
||||
let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap();
|
||||
assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes");
|
||||
let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real));
|
||||
assert!(checked.is_err_and(|e| e.contains("outside the write root")));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A checked write through a link to a folder whose name is not valid UTF-8, inside the write
|
||||
/// root, is saved.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff"));
|
||||
std::fs::create_dir_all(&bytes).unwrap();
|
||||
std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap();
|
||||
let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap();
|
||||
let path = base.join("text/doc.svg").to_string_lossy().into_owned();
|
||||
confine(roots.as_ref(), || write_file(&path, b"new")).unwrap();
|
||||
assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
@@ -100,16 +100,9 @@ impl AutomationRoots {
|
||||
/// May the file or folder at `path` be read (or written)? It must lie inside one of the roots
|
||||
/// of that kind. `Err` says why not.
|
||||
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
|
||||
let roots = match access {
|
||||
Access::Read => &self.read,
|
||||
Access::Write => &self.write,
|
||||
};
|
||||
// The messages are spelled out whole, as the translation catalogs match them.
|
||||
let roots = self.of(access);
|
||||
if roots.is_empty() {
|
||||
return match access {
|
||||
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
|
||||
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
|
||||
};
|
||||
return Err(refused(roots, path, access));
|
||||
}
|
||||
// Resolving a path on another computer connects to it: unless a root is on a network
|
||||
// share, such a path is refused by its name before anything is looked up.
|
||||
@@ -120,12 +113,22 @@ impl AutomationRoots {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
|
||||
match (shown.as_slice(), access) {
|
||||
([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")),
|
||||
([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")),
|
||||
(_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))),
|
||||
(_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))),
|
||||
Err(refused(roots, path, access))
|
||||
}
|
||||
|
||||
/// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is
|
||||
/// compared with the roots as it is, and not looked up again.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
|
||||
let roots = self.of(access);
|
||||
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
|
||||
}
|
||||
|
||||
/// The roots of the kind `access`.
|
||||
fn of(&self, access: Access) -> &[Root] {
|
||||
match access {
|
||||
Access::Read => &self.read,
|
||||
Access::Write => &self.write,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +160,24 @@ impl AutomationRoots {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `path` is refused `access` under `roots`, the roots of that kind.
|
||||
fn refused(roots: &[Root], path: &str, access: Access) -> String {
|
||||
// The messages are spelled out whole, as the translation catalogs match them.
|
||||
if roots.is_empty() {
|
||||
return match access {
|
||||
Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"),
|
||||
Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"),
|
||||
};
|
||||
}
|
||||
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
|
||||
match (shown.as_slice(), access) {
|
||||
([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"),
|
||||
([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"),
|
||||
(_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")),
|
||||
(_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
|
||||
#[derive(Clone, Debug)]
|
||||
enum Scope {
|
||||
@@ -371,18 +392,34 @@ impl ScriptGate {
|
||||
also.check(path, access)?;
|
||||
}
|
||||
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
|
||||
let allowed = real.is_some_and(|real| {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(&real) || self.write.allows(&real),
|
||||
Access::Write => self.write.allows(&real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.contains(&real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
|
||||
/// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is
|
||||
/// compared as it is, and not looked up again.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
|
||||
if let Some(also) = &self.also {
|
||||
also.check_real(real, access)?;
|
||||
}
|
||||
if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Script file access denied: {}", real.display()))
|
||||
}
|
||||
}
|
||||
|
||||
/// May the place at the real path `real` be read (or written) through this gate alone?
|
||||
fn allows_real(&self, real: &Path, access: Access) -> bool {
|
||||
let scoped = match access {
|
||||
Access::Read => self.read.allows(real) || self.write.allows(real),
|
||||
Access::Write => self.write.allows(real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real);
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,8 +499,7 @@ pub fn is_path_key(key: &str) -> bool {
|
||||
/// May `path` be written here? Always, without roots in force and outside a script's command
|
||||
/// ([`with_script_gate`]).
|
||||
pub fn check_write(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)?;
|
||||
check_write_unrecorded(path)?;
|
||||
WRITES.with(|w| {
|
||||
if let Some(paths) = w.borrow_mut().as_mut()
|
||||
&& !paths.iter().any(|(p, _)| p == path)
|
||||
@@ -474,6 +510,26 @@ pub fn check_write(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_write`] without recording `path` as written.
|
||||
pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)
|
||||
}
|
||||
|
||||
/// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been
|
||||
/// followed already (the folder a checked write has opened): it is compared as it is, so the folder
|
||||
/// is not looked up again by its path.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn check_write_real(real: &Path) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?;
|
||||
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))
|
||||
}
|
||||
|
||||
/// Whether a write here is checked: roots are in force, or a script's command runs.
|
||||
pub(crate) fn writes_checked() -> bool {
|
||||
current().is_some() || in_script_command()
|
||||
}
|
||||
|
||||
/// A file's modification time and length; `None` when there is no file at `path`.
|
||||
type Stamp = Option<(Option<std::time::SystemTime>, u64)>;
|
||||
|
||||
|
||||
+676
-24
@@ -82,6 +82,285 @@ 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. 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 FnOnce(&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);
|
||||
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> {
|
||||
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)?))
|
||||
};
|
||||
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());
|
||||
if let Err(e) = filled {
|
||||
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);
|
||||
#[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,
|
||||
synced: &synced,
|
||||
};
|
||||
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 {
|
||||
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,
|
||||
synced: &synced,
|
||||
};
|
||||
write_over_in(&over, refused.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// See the Unix version.
|
||||
#[cfg(not(unix))]
|
||||
pub fn write_atomic_checked(
|
||||
path: &Path,
|
||||
fill: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
allowed: impl FnOnce(&Path) -> io::Result<()>,
|
||||
) -> io::Result<()> {
|
||||
allowed(path)?;
|
||||
write_atomic_with(path, fill)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
@@ -130,47 +409,114 @@ fn write_atomic_stepping(
|
||||
/// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the
|
||||
/// error says where they are.
|
||||
fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
|
||||
let opened = File::open(tmp).and_then(|from| Ok((from, OpenOptions::new().write(true).create(true).truncate(false).open(target)?)));
|
||||
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);
|
||||
},
|
||||
open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) },
|
||||
synced: &|| sync_written_parent(target),
|
||||
};
|
||||
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(),
|
||||
/// The target for writing (created when missing, not truncated) when `true`, for reading when
|
||||
/// `false`.
|
||||
open_target: &'a dyn Fn(bool) -> io::Result<File>,
|
||||
/// The target's folder flushed, after the target is written.
|
||||
synced: &'a dyn Fn() -> io::Result<()>,
|
||||
}
|
||||
|
||||
/// [`write_over`] through `over`.
|
||||
fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
|
||||
let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?)));
|
||||
let Ok((mut from, mut to)) = opened else {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
(over.remove_tmp)();
|
||||
return Err(refused);
|
||||
};
|
||||
// Nothing to keep of a file that is new or empty.
|
||||
let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| tmp.with_extension("old"));
|
||||
if let Some(old) = &old
|
||||
&& let Err(e) = keep_old(target, old)
|
||||
// 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.metadata().map_or(true, |m| m.len() > 0);
|
||||
if kept
|
||||
&& let Err(e) = (over.open_target)(false).and_then(|mut target| {
|
||||
if !same_file(&target, &to) {
|
||||
return Err(io::Error::other("the file was replaced while it was opened"));
|
||||
}
|
||||
keep_old(&mut target, over)
|
||||
})
|
||||
{
|
||||
// Best effort: a partial copy is of no use.
|
||||
let _ = std::fs::remove_file(old);
|
||||
let why =
|
||||
format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display());
|
||||
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)));
|
||||
}
|
||||
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
|
||||
drop((from, to));
|
||||
match (copied, old) {
|
||||
(Ok(()), old) => {
|
||||
match (copied, kept) {
|
||||
(Ok(()), kept) => {
|
||||
// Best effort: the file is saved, so the copies are no longer needed.
|
||||
let _ = std::fs::remove_file(tmp);
|
||||
if let Some(old) = old {
|
||||
let _ = std::fs::remove_file(old);
|
||||
(over.remove_tmp)();
|
||||
if kept {
|
||||
(over.remove_old)();
|
||||
}
|
||||
sync_written_parent(target)
|
||||
(over.synced)()
|
||||
}
|
||||
(Err(e), Some(old)) => Err(io::Error::new(
|
||||
(Err(e), true) => Err(io::Error::new(
|
||||
e.kind(),
|
||||
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())),
|
||||
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), (over.old)().display())),
|
||||
)),
|
||||
(Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.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 `target` as it is, at `old` (for its owner only).
|
||||
fn keep_old(target: &Path, old: &Path) -> io::Result<()> {
|
||||
let mut to = create_private(old)?;
|
||||
io::copy(&mut File::open(target)?, &mut to)?;
|
||||
sync_file(&to)
|
||||
/// 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.
|
||||
@@ -325,6 +671,9 @@ thread_local! {
|
||||
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.
|
||||
@@ -466,6 +815,282 @@ mod tests {
|
||||
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)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn under(root: &Path) -> impl FnOnce(&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 check = under(&root);
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
std::fs::rename(root.join("inside"), root.join("moved"))?;
|
||||
std::os::unix::fs::symlink(&outside, root.join("inside"))
|
||||
},
|
||||
);
|
||||
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 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 checked write whose folder moved after it was opened, refused the rename, and failed to
|
||||
/// copy into the file: the temporary file and the copy of the old content stay in that folder,
|
||||
/// and the error names them where they are now. (FreeBSD does not say where an open folder is
|
||||
/// now: there the error names them where the folder was opened.)
|
||||
#[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 check = under(&root);
|
||||
let r = write_atomic_checked(
|
||||
&root.join("inside/doc.txt"),
|
||||
|f| f.write_all(b"new"),
|
||||
|p| {
|
||||
check(p)?;
|
||||
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)));
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
FLUSHES_LEFT.with(|c| c.set(None));
|
||||
let message = r.unwrap_err().to_string();
|
||||
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()));
|
||||
let named_in =
|
||||
if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") };
|
||||
for file in [&tmp, &old] {
|
||||
let named = named_in.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 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) },
|
||||
synced: &|| 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()
|
||||
@@ -722,6 +1347,33 @@ mod tests {
|
||||
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.
|
||||
|
||||
@@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob};
|
||||
#[cfg(all(unix, not(target_arch = "wasm32")))]
|
||||
pub use atomic::sync_parent;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
|
||||
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_checked, write_atomic_with, write_new_with};
|
||||
use craft_gzip::Gz;
|
||||
pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode};
|
||||
use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};
|
||||
|
||||
Reference in new issue
Block a user