Skip to main content

relate_core/
file_identity.rs

1//! Physical file identity for storage ownership (ADR-0097) and LOAD CSV open-then-verify (ADR-0108).
2use std::fs::{File, OpenOptions};
3use std::io;
4use std::path::Path;
5
6#[cfg(windows)]
7const FILE_READ_ATTRIBUTES: u32 = 0x80;
8#[cfg(windows)]
9const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
10#[cfg(windows)]
11const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
12
13/// A final-component symlink must not be followed between inspection and open
14/// (ADR-0097, ADR-0108). Windows opens the reparse point itself and validates
15/// the returned handle.
16pub fn nofollow(opts: &mut OpenOptions) {
17    #[cfg(unix)]
18    {
19        use std::os::unix::fs::OpenOptionsExt;
20        opts.custom_flags(libc::O_NOFOLLOW);
21    }
22    #[cfg(windows)]
23    {
24        use std::os::windows::fs::OpenOptionsExt;
25        opts.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
26    }
27    #[cfg(not(any(unix, windows)))]
28    let _ = opts;
29}
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub struct FileIdentity {
33    volume: u64,
34    index: u64,
35}
36
37pub fn of_path(path: &Path) -> io::Result<FileIdentity> {
38    #[cfg(unix)]
39    {
40        use std::os::unix::fs::MetadataExt;
41        let meta = std::fs::symlink_metadata(path)?;
42        Ok(FileIdentity {
43            volume: meta.dev(),
44            index: meta.ino(),
45        })
46    }
47    #[cfg(windows)]
48    {
49        use std::os::windows::fs::OpenOptionsExt;
50        let mut opts = std::fs::OpenOptions::new();
51        // FILE_READ_ATTRIBUTES, not GENERIC_READ. LockFileEx makes a second
52        // handle's read of the locked range return ERROR_LOCK_VIOLATION;
53        // attributes do not touch that range. FILE_FLAG_BACKUP_SEMANTICS
54        // permits directory handles, and FILE_FLAG_OPEN_REPARSE_POINT
55        // identifies the reparse point itself.
56        opts.access_mode(FILE_READ_ATTRIBUTES)
57            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
58        of_file(&opts.open(path)?)
59    }
60    #[cfg(not(any(unix, windows)))]
61    {
62        let _ = path;
63        Err(io::Error::new(
64            io::ErrorKind::Unsupported,
65            "file identity unavailable",
66        ))
67    }
68}
69
70pub fn of_file(file: &File) -> io::Result<FileIdentity> {
71    #[cfg(unix)]
72    {
73        use std::os::unix::fs::MetadataExt;
74        let meta = file.metadata()?;
75        Ok(FileIdentity {
76            volume: meta.dev(),
77            index: meta.ino(),
78        })
79    }
80    #[cfg(windows)]
81    {
82        use std::os::windows::io::AsRawHandle;
83        use windows_sys::Win32::Storage::FileSystem::{
84            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
85        };
86
87        let mut info = std::mem::MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
88        // SAFETY: File owns a valid OS handle throughout this call. The API
89        // writes the complete info struct on success and retains no pointers;
90        // we only assume initialization after a successful return.
91        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) } == 0 {
92            return Err(io::Error::last_os_error());
93        }
94        // SAFETY: the successful API call initialized every field of `info`.
95        let info = unsafe { info.assume_init() };
96        Ok(FileIdentity {
97            volume: u64::from(info.dwVolumeSerialNumber),
98            index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
99        })
100    }
101    #[cfg(not(any(unix, windows)))]
102    {
103        let _ = file;
104        Err(io::Error::new(
105            io::ErrorKind::Unsupported,
106            "file identity unavailable",
107        ))
108    }
109}
110
111#[cfg(all(test, windows))]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn file_and_directory_identities_are_physical() {
117        let tmp = tempfile::tempdir().unwrap();
118        let file = tmp.path().join("file");
119        let hard_link = tmp.path().join("hard-link");
120        let other = tmp.path().join("other");
121        std::fs::write(&file, b"same").unwrap();
122        std::fs::hard_link(&file, &hard_link).unwrap();
123        std::fs::write(&other, b"same").unwrap();
124        assert_eq!(of_path(&file).unwrap(), of_path(&hard_link).unwrap());
125        assert_eq!(
126            of_file(&File::open(&file).unwrap()).unwrap(),
127            of_path(&file).unwrap()
128        );
129        assert_ne!(of_path(&file).unwrap(), of_path(&other).unwrap());
130
131        let one = tmp.path().join("one");
132        let two = tmp.path().join("two");
133        std::fs::create_dir(&one).unwrap();
134        std::fs::create_dir(&two).unwrap();
135        assert_ne!(of_path(&one).unwrap(), of_path(&two).unwrap());
136
137        let junction = tmp.path().join("junction");
138        let status = std::process::Command::new("cmd")
139            .args(["/C", "mklink", "/J"])
140            .arg(&junction)
141            .arg(&one)
142            .status()
143            .unwrap();
144        assert!(status.success());
145        assert_ne!(of_path(&junction).unwrap(), of_path(&one).unwrap());
146    }
147}