PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Saving onto a dangling symlink writes through to its target (#6605) (#6649)
mroxsocc772ad9dc82
diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rsindex 348374d3c..8a02ce5c7 100644--- a/crates/format/src/atomic.rs+++ b/crates/format/src/atomic.rs@@ -175,7 +175,7 @@ pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, byt/// [`atomic_write_with`] reporting write progress (see [`atomic_write_progress`]).pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> {- let target = resolve_symlink(path);+ let target = resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))?;let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?;let dir = match target.parent() {Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),@@ -245,12 +245,37 @@ fn sleep_ms(ms: u64) {#[cfg(target_arch = "wasm32")]fn sleep_ms(_ms: u64) {}+/// How deep a symlink chain we follow before giving up, like the OS limit.+const MAX_LINK_DEPTH: u32 = 40;+/// Write through a symlink to the file it points at, instead of replacing the link.-fn resolve_symlink(path: &Path) -> PathBuf {- match std::fs::symlink_metadata(path) {- Ok(m) if m.file_type().is_symlink() => std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()),- _ => path.to_path_buf(),+///+/// A dangling link (its target, or a folder on the way to it, doesn't exist yet) resolves to its+/// target too, so saving through one creates the target instead of silently turning the link+/// into a regular file (#6605). A chain that never ends is an error, never a link replacement.+fn resolve_symlink(path: &Path) -> io::Result<PathBuf> {+ if !std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {+ return Ok(path.to_path_buf());+ }+ // A resolvable chain: canonicalize follows every link and relative target in one go.+ if let Ok(real) = std::fs::canonicalize(path) {+ return Ok(real);+ }+ // Dangling chain: walk the links lexically; the final target may not exist yet.+ let mut current = path.to_path_buf();+ for _ in 0..MAX_LINK_DEPTH {+ let Ok(link) = std::fs::read_link(¤t) else {+ return Ok(current); // not (or no longer) a link: the chain ends here+ };+ let base = current.parent().unwrap_or(Path::new(".")).to_path_buf();+ // `..` stays in the path for the OS to resolve: folding it by text is wrong when a folder+ // on the way is itself a symlink.+ current = if link.is_absolute() { link } else { base.join(link) };+ if !std::fs::symlink_metadata(¤t).is_ok_and(|m| m.file_type().is_symlink()) {+ return Ok(current);+ }}+ Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: too many levels of symbolic links", path.display())))}/// A unique hidden temporary file name to write beside `file` before renaming over it.diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rsindex a85f998a1..ce3ed1b7c 100644--- a/crates/format/src/atomic/tests.rs+++ b/crates/format/src/atomic/tests.rs@@ -296,6 +296,52 @@ fn writes_through_a_symlink() {assert_eq!(std::fs::read(&real).unwrap(), b"new");}+/// #6605: saving onto a dangling symlink writes through to its target instead of replacing the+/// link with a regular file, even when a folder on the way to the target doesn't exist yet.+#[cfg(unix)]+#[test]+fn writes_through_a_dangling_symlink() {+ let d = TempDir::new("dangling");+ let real = d.0.join("missing/dir/a.psd");+ let link = d.0.join("link.psd");+ std::os::unix::fs::symlink(&real, &link).unwrap();+ atomic_write(&link, b"new").unwrap();+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link survives");+ assert_eq!(std::fs::read(&real).unwrap(), b"new", "the bytes land at the target");+ assert_no_temp(real.parent().unwrap_or(Path::new(".")));+}++/// A dangling link with a relative target resolves against the link's own folder.+#[cfg(unix)]+#[test]+fn writes_through_a_dangling_relative_symlink() {+ let d = TempDir::new("dangling-rel");+ let here = d.0.join("here");+ std::fs::create_dir(&here).unwrap();+ let link = here.join("link.psd");+ std::os::unix::fs::symlink("../elsewhere/real.psd", &link).unwrap();+ atomic_write(&link, b"new").unwrap();+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link survives");+ assert_eq!(std::fs::read(d.0.join("elsewhere/real.psd")).unwrap(), b"new");+ assert_no_temp(&d.0.join("elsewhere"));+}++/// A symlink loop is an error; it never replaces either link.+#[cfg(unix)]+#[test]+fn symlink_loop_errors_without_replacing_the_links() {+ let d = TempDir::new("loop");+ let a = d.0.join("a.psd");+ let b = d.0.join("b.psd");+ std::os::unix::fs::symlink(&b, &a).unwrap();+ std::os::unix::fs::symlink(&a, &b).unwrap();+ let e = atomic_write(&a, b"new").unwrap_err();+ assert!(e.to_string().contains("symbolic links"), "{e}");+ assert!(std::fs::symlink_metadata(&a).unwrap().file_type().is_symlink());+ assert!(std::fs::symlink_metadata(&b).unwrap().file_type().is_symlink());+ assert_no_temp(&d.0);+}+#[test]fn directory_target_or_bare_root_is_an_error_not_a_panic() {let d = TempDir::new("dir");