Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Reject unavailable Windows file identities in strict comparisons

dotCooCoo0c7640f7d398
diff --cc crates/catalog/src/safe_file.rs
index bc05d4139,fa067de0f..2ed0acb5e
--- a/crates/catalog/src/safe_file.rs
+++ b/crates/catalog/src/safe_file.rs
@@@ -268,28 -267,9 +268,28 @@@ fn same_content(path: &Path, data: &[u8
}
}
-/// Do `a` and `b` name the same existing file (through links, `..`, case-insensitive names)?
+/// Do `a` and `b` name the same existing file (through hard links, symlinks, `..`,
+/// case-insensitive names)?
pub fn same_file(a: &Path, b: &Path) -> bool {
- let (Ok(ma), Ok(mb)) = (fs::metadata(a), fs::metadata(b)) else { return false };
+ compare_files(a, b, false).unwrap_or(false)
+}
+
+/// [`same_file`] for a check that must not let an unknown identity pass: `Err` when the metadata
+/// of either path cannot be read for a reason other than the path not existing (for example a
+/// folder it cannot enter), or when both paths exist with the same length but the file identity
- /// of either cannot be read (on Windows, when either file cannot be opened). A path that does not
++/// of either cannot be read (on Windows, when either file cannot be opened or reports file index 0). A path that does not
+/// exist is still `Ok(false)`.
+pub fn same_file_strict(a: &Path, b: &Path) -> io::Result<bool> {
+ compare_files(a, b, true)
+}
+
+fn compare_files(a: &Path, b: &Path, strict: bool) -> io::Result<bool> {
+ let missing = |e: &io::Error| matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::NotADirectory);
+ let (ma, mb) = match (fs::metadata(a), fs::metadata(b)) {
+ (Ok(ma), Ok(mb)) => (ma, mb),
+ (Err(e), _) | (_, Err(e)) if strict && !missing(&e) => return Err(e),
+ _ => return Ok(false),
+ };
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
@@@ -298,41 -278,13 +298,43 @@@
#[cfg(not(unix))]
{
if ma.len() != mb.len() {
- return false;
+ return Ok(false);
+ }
+ // A hard link has its own path but shares the volume serial number and file index with
- // its original. A volume that reports file index 0 is compared by resolved path below.
++ // its original. A file index of 0 produces an error in strict mode. Lenient mode compares resolved paths.
+ // On ReFS two files can share the 64-bit file index, so the lengths are compared first.
+ #[cfg(windows)]
+ {
- match file_ids(a, b) {
- Ok((ia, ib)) if same_file_id(ia, ib) => return Ok(true),
++ match file_ids(a, b).and_then(|(ia, ib)| same_file_id(ia, ib, strict)) {
++ Ok(true) => return Ok(true),
+ Ok(_) => {}
+ Err(e) if strict => return Err(e),
+ Err(_) => {}
+ }
}
- match (fs::canonicalize(a), fs::canonicalize(b)) {
+ Ok(match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(x), Ok(y)) => x == y || x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase(),
_ => false,
- }
+ })
+ }
+}
+
+/// The volume serial number and file index of `a` and `b`, read while both files are open.
+#[cfg(windows)]
+fn file_ids(a: &Path, b: &Path) -> io::Result<((u64, u64), (u64, u64))> {
+ use winapi_util::{Handle, file::information};
+ let (ha, hb) = (Handle::from_path_any(a)?, Handle::from_path_any(b)?);
+ let (ia, ib) = (information(&ha)?, information(&hb)?);
+ Ok(((ia.volume_serial_number(), ia.file_index()), (ib.volume_serial_number(), ib.file_index())))
+}
+
- /// Whether two (volume serial number, file index) pairs name one file. A file index of 0 is not
- /// an identity and matches nothing.
++/// The comparison uses each file's volume serial number and file index. Strict mode returns an error for file index 0.
+#[cfg(any(windows, test))]
- fn same_file_id(a: (u64, u64), b: (u64, u64)) -> bool {
- a.1 != 0 && b.1 != 0 && a == b
++fn same_file_id(a: (u64, u64), b: (u64, u64), strict: bool) -> io::Result<bool> {
++ if strict && (a.1 == 0 || b.1 == 0) {
++ return Err(io::Error::other("file identity is unavailable"));
+ }
++ Ok(a.1 != 0 && b.1 != 0 && a == b)
}
#[cfg(test)]
@@@ -480,29 -409,4 +482,33 @@@ mod tests
assert!(!same_file(&p, &d.join("missing.jpg")));
let _ = fs::remove_dir_all(&d);
}
+
+ #[test]
+ fn strict_comparison_reports_a_path_it_cannot_query() {
+ let d = temp("strict-query");
+ let p = d.join("x.jpg");
+ fs::write(&p, b"x").unwrap();
+ // A NUL byte makes the metadata lookup fail with an error other than "not found" on
+ // every platform, as a folder the process cannot enter does.
+ let unreadable = Path::new("IMG_1\0.jpg");
+ assert!(same_file_strict(unreadable, &p).is_err());
+ assert!(same_file_strict(&p, unreadable).is_err());
+ assert!(!same_file(unreadable, &p), "the lenient comparison still answers false");
+ assert!(!same_file_strict(&d.join("missing.jpg"), &p).unwrap(), "a missing original is another file");
+ assert!(!same_file_strict(&p.join("under-a-file.jpg"), &p).unwrap());
+ let _ = fs::remove_dir_all(&d);
+ }
+
+ #[test]
+ fn a_zero_file_index_is_not_a_file_identity() {
- assert!(same_file_id((7, 42), (7, 42)));
- assert!(!same_file_id((7, 42), (7, 43)));
- assert!(!same_file_id((7, 42), (8, 42)));
- assert!(!same_file_id((7, 0), (7, 0)), "two files on a volume that reports index 0 are not the same file");
- assert!(!same_file_id((0, 0), (0, 0)));
++ for strict in [false, true] {
++ assert!(same_file_id((7, 42), (7, 42), strict).unwrap());
++ assert!(!same_file_id((7, 42), (7, 43), strict).unwrap());
++ assert!(!same_file_id((7, 42), (8, 42), strict).unwrap());
++ }
++ for (a, b) in [((7, 0), (7, 0)), ((0, 0), (0, 0)), ((7, 42), (7, 0)), ((7, 0), (7, 42))] {
++ assert!(same_file_id(a, b, true).is_err(), "strict comparison must reject an unavailable identity: {a:?}, {b:?}");
++ assert!(!same_file_id(a, b, false).unwrap(), "lenient comparison can fall back to resolved paths");
++ }
+ }
}
diff --cc crates/engine/src/originals.rs
index e20a9378b,890e98f81..af2fc5d14
--- a/crates/engine/src/originals.rs
+++ b/crates/engine/src/originals.rs
@@@ -350,30 -339,4 +350,32 @@@ mod tests
}
let _ = std::fs::remove_dir_all(&d);
}
+
+ #[cfg(windows)]
+ #[test]
+ fn a_hard_link_whose_identity_cannot_be_read_is_refused() {
+ use std::os::windows::fs::OpenOptionsExt;
+ let d = std::env::temp_dir().join(format!("lc-unreadable-link-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ let mut s = crate::Session::new();
+ let original = d.join("IMG_1.jpg");
+ std::fs::write(&original, b"original").unwrap();
+ let photo = Photo::new(PhotoId(1), Source::File { path: original.to_string_lossy().to_string() }, "IMG_1.jpg", "JPEG", 10, 10, "2026-01-01");
+ s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
+ let linked = d.join("shot.png");
+ std::fs::hard_link(&original, &linked).unwrap();
+
+ // A handle that shares nothing makes every other open of the file fail, so the file
+ // identity of either name cannot be read while it is held.
+ let held = std::fs::OpenOptions::new().read(true).share_mode(0).open(&original).unwrap();
+ let refused = s.pin_write_target(&linked.to_string_lossy()).unwrap_err();
- assert!(refused.contains("original"), "{refused}");
++ assert!(refused.contains("cannot tell whether"), "{refused}");
+ drop(held);
+
- assert!(s.pin_write_target(&linked.to_string_lossy()).unwrap_err().contains("original"));
++ let refused = s.pin_write_target(&linked.to_string_lossy()).unwrap_err();
++ assert!(refused.contains("original"), "{refused}");
++ assert!(!refused.contains("cannot tell whether"), "{refused}");
+ let _ = std::fs::remove_dir_all(&d);
+ }
}