Skip to main content

aft_base/
file_identity.rs

1//! A file's identity on its volume, for in-memory change stamps.
2//!
3//! A stamp built only from a file's size and times misses a replacement that
4//! keeps the size and lands within one tick of the filesystem clock. Windows
5//! stamps file times from a clock that ticks about every 15.6 ms, and Linux
6//! filesystems take theirs from the kernel's coarse clock, which ticks every
7//! few milliseconds. AFT and Git replace files atomically (write a temporary
8//! file, then rename it over the old name), and the renamed file is a
9//! different file, so its identity differs even when every time and the size
10//! match.
11//!
12//! Unix reports the identity in every `stat`: the device and inode numbers.
13//! Rust's stable Windows API exposes no file index, so on Windows it is read
14//! with `GetFileInformationByHandle` from a handle that requests no data
15//! access, the same kind of handle `std::fs::metadata` opens internally.
16//!
17//! An identity is only meaningful on the machine that read it. Do not use it
18//! as a portable file identifier. A per-machine callgraph cache may persist it
19//! as a stat hint alongside size and mtime; a missing or unavailable identity
20//! must still fall back to checking the contents.
21
22use std::fs::{File, Metadata};
23use std::io;
24use std::path::Path;
25
26/// Which volume a file lives on and which file it is on that volume.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
28pub enum FileIdentity {
29    /// Unix: device and inode numbers. Windows: volume serial number and
30    /// file index.
31    Known { volume: u64, index: u64 },
32    /// The platform or filesystem did not report an identity. Two unavailable
33    /// identities compare equal, so a stamp holding one detects changes only
34    /// through its other fields, exactly as it did before it held an identity.
35    Unavailable,
36}
37
38impl FileIdentity {
39    /// The identity of an open file.
40    pub fn of_file(file: &File) -> Self {
41        #[cfg(unix)]
42        {
43            file.metadata().map_or(Self::Unavailable, |metadata| {
44                Self::of_unix_metadata(&metadata)
45            })
46        }
47        #[cfg(windows)]
48        {
49            windows_identity(file).0
50        }
51        #[cfg(not(any(unix, windows)))]
52        {
53            let _ = file;
54            Self::Unavailable
55        }
56    }
57
58    /// Unix `stat` results carry the identity, so no extra system call is
59    /// needed. Windows metadata does not, which is why this exists only on
60    /// Unix: Windows callers use [`metadata`], [`symlink_metadata`] or
61    /// [`FileIdentity::of_file`].
62    #[cfg(unix)]
63    pub(crate) fn of_unix_metadata(metadata: &Metadata) -> Self {
64        use std::os::unix::fs::MetadataExt;
65        Self::Known {
66            volume: metadata.dev(),
67            index: metadata.ino(),
68        }
69    }
70}
71
72/// Count links on the same open file that will be modified.
73pub fn link_count(file: &File) -> io::Result<u64> {
74    #[cfg(unix)]
75    {
76        use std::os::unix::fs::MetadataExt;
77        Ok(file.metadata()?.nlink())
78    }
79    #[cfg(windows)]
80    {
81        let (identity, links) = windows_identity(file);
82        if identity == FileIdentity::Unavailable {
83            Err(io::Error::last_os_error())
84        } else {
85            Ok(links)
86        }
87    }
88    #[cfg(not(any(unix, windows)))]
89    {
90        let _ = file;
91        Err(io::ErrorKind::Unsupported.into())
92    }
93}
94
95/// Like `std::fs::metadata` (follows symlinks), plus the identity of the same
96/// file.
97pub fn metadata(path: &Path) -> io::Result<(Metadata, FileIdentity)> {
98    stat(path, true).map(|(metadata, identity, _)| (metadata, identity))
99}
100
101/// Like `std::fs::symlink_metadata` (describes a symlink itself rather than
102/// its target), plus the identity of the same file.
103pub fn symlink_metadata(path: &Path) -> io::Result<(Metadata, FileIdentity)> {
104    stat(path, false).map(|(metadata, identity, _)| (metadata, identity))
105}
106
107/// Read identity and link count in the same metadata query. SQLite alias
108/// admission uses the count to avoid refreshing sidecars for ordinary files.
109pub(crate) fn metadata_with_link_count(path: &Path) -> io::Result<(Metadata, FileIdentity, u64)> {
110    stat(path, true)
111}
112
113#[cfg(unix)]
114fn stat(path: &Path, follow_symlinks: bool) -> io::Result<(Metadata, FileIdentity, u64)> {
115    use std::os::unix::fs::MetadataExt;
116    let metadata = if follow_symlinks {
117        std::fs::metadata(path)?
118    } else {
119        std::fs::symlink_metadata(path)?
120    };
121    let identity = FileIdentity::of_unix_metadata(&metadata);
122    let links = metadata.nlink();
123    Ok((metadata, identity, links))
124}
125
126/// One handle supplies both the metadata and the identity, so they always
127/// describe the same file. Like `std::fs::metadata`, the handle requests no
128/// data access, shares read, write and delete, and can open a directory, so
129/// it neither blocks a concurrent writer's rename over the file nor costs
130/// more than the metadata read it replaces.
131#[cfg(windows)]
132fn stat(path: &Path, follow_symlinks: bool) -> io::Result<(Metadata, FileIdentity, u64)> {
133    use std::os::windows::fs::OpenOptionsExt;
134    use windows_sys::Win32::Storage::FileSystem::{
135        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
136    };
137    let flags = FILE_FLAG_BACKUP_SEMANTICS
138        | if follow_symlinks {
139            0
140        } else {
141            FILE_FLAG_OPEN_REPARSE_POINT
142        };
143    match std::fs::OpenOptions::new()
144        .access_mode(0)
145        .custom_flags(flags)
146        .open(path)
147    {
148        Ok(file) => {
149            let metadata = file.metadata()?;
150            let (identity, links) = windows_identity(&file);
151            Ok((metadata, identity, links))
152        }
153        Err(error) if error.kind() == io::ErrorKind::NotFound => Err(error),
154        // `std::fs::metadata` falls back to reading the directory entry when
155        // the file cannot be opened (for example while it is being deleted).
156        // Keep that behavior; a directory entry carries no file index.
157        Err(_) => {
158            let metadata = if follow_symlinks {
159                std::fs::metadata(path)?
160            } else {
161                std::fs::symlink_metadata(path)?
162            };
163            Ok((metadata, FileIdentity::Unavailable, 1))
164        }
165    }
166}
167
168#[cfg(not(any(unix, windows)))]
169fn stat(path: &Path, follow_symlinks: bool) -> io::Result<(Metadata, FileIdentity, u64)> {
170    let metadata = if follow_symlinks {
171        std::fs::metadata(path)?
172    } else {
173        std::fs::symlink_metadata(path)?
174    };
175    Ok((metadata, FileIdentity::Unavailable, 1))
176}
177
178#[cfg(windows)]
179fn windows_identity(file: &File) -> (FileIdentity, u64) {
180    use std::os::windows::io::AsRawHandle;
181    use windows_sys::Win32::Storage::FileSystem::{
182        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
183    };
184    let mut info = std::mem::MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
185    // SAFETY: the open file owns a valid handle and `info` is writable. A
186    // successful call initializes the structure before it is read below.
187    let info = unsafe {
188        if GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) == 0 {
189            return (FileIdentity::Unavailable, 1);
190        }
191        info.assume_init()
192    };
193    (
194        FileIdentity::Known {
195            volume: u64::from(info.dwVolumeSerialNumber),
196            index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
197        },
198        u64::from(info.nNumberOfLinks),
199    )
200}
201
202/// Atomically replaces the file at `path` with `contents` of the same length,
203/// giving the replacement the original's access, modification and (on
204/// Windows) creation times. Size and times then all match, as they do when a
205/// replacement lands within one clock tick, so only the file identity can
206/// tell the two files apart.
207#[cfg(any(test, feature = "test-support"))]
208pub fn replace_keeping_times(path: &Path, contents: &[u8]) {
209    let metadata = std::fs::metadata(path).unwrap();
210    assert_eq!(
211        metadata.len(),
212        contents.len() as u64,
213        "the replacement must keep the original's length"
214    );
215    let mut name = path.file_name().unwrap().to_os_string();
216    name.push(".replacement");
217    let replacement = path.with_file_name(name);
218    std::fs::write(&replacement, contents).unwrap();
219    let times = std::fs::FileTimes::new()
220        .set_accessed(metadata.accessed().unwrap())
221        .set_modified(metadata.modified().unwrap());
222    #[cfg(windows)]
223    let times = {
224        use std::os::windows::fs::FileTimesExt;
225        times.set_created(metadata.created().unwrap())
226    };
227    std::fs::OpenOptions::new()
228        .write(true)
229        .open(&replacement)
230        .unwrap()
231        .set_times(times)
232        .unwrap();
233    std::fs::rename(&replacement, path).unwrap();
234    let after = std::fs::metadata(path).unwrap();
235    assert_eq!(after.len(), metadata.len());
236    assert_eq!(after.modified().unwrap(), metadata.modified().unwrap());
237    #[cfg(windows)]
238    assert_eq!(after.created().unwrap(), metadata.created().unwrap());
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn replacement_with_identical_size_and_times_has_a_new_identity() {
247        let directory = tempfile::tempdir().unwrap();
248        let path = directory.path().join("record");
249        std::fs::write(&path, b"first").unwrap();
250        let (_, before) = metadata(&path).unwrap();
251        assert!(
252            cfg!(not(any(unix, windows))) || matches!(before, FileIdentity::Known { .. }),
253            "a local temporary file must report its identity: {before:?}"
254        );
255        assert_eq!(metadata(&path).unwrap().1, before, "an unchanged file");
256        assert_eq!(
257            FileIdentity::of_file(&File::open(&path).unwrap()),
258            before,
259            "a path and an open handle name the same file"
260        );
261        replace_keeping_times(&path, b"other");
262        if cfg!(any(unix, windows)) {
263            assert_ne!(metadata(&path).unwrap().1, before);
264        }
265    }
266
267    #[test]
268    fn directories_and_missing_paths() {
269        let directory = tempfile::tempdir().unwrap();
270        let (metadata, identity) = symlink_metadata(directory.path()).unwrap();
271        assert!(metadata.is_dir());
272        assert!(cfg!(not(any(unix, windows))) || matches!(identity, FileIdentity::Known { .. }));
273        let missing = directory.path().join("missing");
274        assert_eq!(
275            super::metadata(&missing).unwrap_err().kind(),
276            io::ErrorKind::NotFound
277        );
278        assert_eq!(
279            symlink_metadata(&missing).unwrap_err().kind(),
280            io::ErrorKind::NotFound
281        );
282    }
283
284    #[test]
285    fn symlink_metadata_describes_the_link_and_metadata_its_target() {
286        let directory = tempfile::tempdir().unwrap();
287        let target = directory.path().join("target");
288        std::fs::write(&target, b"target").unwrap();
289        let link = directory.path().join("link");
290        #[cfg(unix)]
291        std::os::unix::fs::symlink(&target, &link).unwrap();
292        #[cfg(windows)]
293        if std::os::windows::fs::symlink_file(&target, &link).is_err() {
294            // Creating a symlink needs Developer Mode or an elevated account.
295            return;
296        }
297        #[cfg(not(any(unix, windows)))]
298        return;
299        let (link_metadata, link_identity) = symlink_metadata(&link).unwrap();
300        assert!(link_metadata.file_type().is_symlink());
301        let (target_metadata, target_identity) = metadata(&link).unwrap();
302        assert!(target_metadata.is_file());
303        assert_eq!(target_identity, metadata(&target).unwrap().1);
304        assert_ne!(link_identity, target_identity);
305    }
306}