1use std::fs;
7use std::io;
8use std::path::Path;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use serde::{Deserialize, Serialize};
12
13use crate::io_accounting::at;
14
15#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
16pub enum FileIdentity {
17 Unix {
18 dev: u64,
19 ino: u64,
20 birth: Option<u128>,
21 },
22 Windows {
23 volume: u64,
24 id: [u8; 16],
25 creation: i64,
26 },
27 StrictOnly {
28 volume: u64,
29 index: u64,
30 birth: Option<u128>,
31 },
32}
33
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35pub struct NativeStat {
36 pub identity: FileIdentity,
37 pub size: u64,
38 pub modified_ns: i128,
39 pub changed_ns: i128,
40 pub mode: u32,
41 pub reuse_supported: bool,
42}
43
44impl NativeStat {
45 pub fn read_open_file(file: &fs::File, path: &Path) -> io::Result<Self> {
48 #[cfg(unix)]
49 {
50 Self::from_unix_metadata(&file.metadata()?, path)
51 }
52 #[cfg(windows)]
53 {
54 let _ = path;
55 windows_file_stat(file)
56 }
57 #[cfg(not(any(unix, windows)))]
58 {
59 let _ = (file, path);
60 Err(io::Error::new(
61 io::ErrorKind::Unsupported,
62 "stable file identity unavailable",
63 ))
64 }
65 }
66
67 #[cfg(unix)]
68 fn from_unix_metadata(m: &fs::Metadata, path: &Path) -> io::Result<Self> {
69 use std::os::unix::fs::MetadataExt;
70 Ok(Self {
71 identity: FileIdentity::Unix {
72 dev: m.dev(),
73 ino: m.ino(),
74 birth: m
75 .created()
76 .ok()
77 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
78 .map(|d| d.as_nanos()),
79 },
80 size: m.len(),
81 modified_ns: i128::from(m.mtime()) * 1_000_000_000 + i128::from(m.mtime_nsec()),
82 changed_ns: i128::from(m.ctime()) * 1_000_000_000 + i128::from(m.ctime_nsec()),
83 mode: m.mode(),
84 reuse_supported: local_precise_filesystem(path),
85 })
86 }
87
88 pub fn read(path: &Path) -> io::Result<Self> {
89 #[cfg(unix)]
90 {
91 let m = fs::symlink_metadata(path).map_err(|e| at("reading metadata", path, e))?;
92 Self::from_unix_metadata(&m, path)
93 }
94 #[cfg(windows)]
95 {
96 windows_stat(path).map_err(|e| at("reading native metadata", path, e))
97 }
98 #[cfg(not(any(unix, windows)))]
99 {
100 let _ = path;
101 Err(io::Error::new(
102 io::ErrorKind::Unsupported,
103 "stable file identity unavailable",
104 ))
105 }
106 }
107 pub fn reusable(&self, current: &Self, observed_ns: u128) -> bool {
108 self.reuse_supported
109 && self == current
110 && self.modified_ns >= 0
111 && (self.modified_ns as u128) < observed_ns
112 }
113}
114
115#[cfg(unix)]
116fn local_precise_filesystem(path: &Path) -> bool {
117 use std::os::unix::ffi::OsStrExt;
118 let Ok(path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
119 return false;
120 };
121 let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
122 if unsafe { libc::statfs(path.as_ptr(), &mut stat) } != 0 {
123 return false;
124 }
125 #[cfg(target_os = "linux")]
126 {
127 matches!(
128 stat.f_type as u64,
129 0xef53 | 0x9123683e | 0x58465342 | 0x794c7630 | 0x01021994 | 0x2fc12fc1
130 )
131 }
132 #[cfg(target_os = "macos")]
133 {
134 unsafe { std::ffi::CStr::from_ptr(stat.f_fstypename.as_ptr()) }.to_bytes() == b"apfs"
135 }
136 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
137 {
138 false
139 }
140}
141
142#[cfg(windows)]
143fn windows_stat(path: &Path) -> io::Result<NativeStat> {
144 use std::os::windows::fs::OpenOptionsExt;
145 use windows_sys::Win32::Storage::FileSystem::{
146 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,
147 };
148 let file = fs::OpenOptions::new()
149 .read(true)
150 .access_mode(FILE_READ_ATTRIBUTES)
151 .share_mode(7)
152 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
153 .open(path)?;
154 windows_file_stat(&file)
155}
156
157#[cfg(windows)]
158fn windows_file_stat(file: &fs::File) -> io::Result<NativeStat> {
159 use std::os::windows::io::AsRawHandle;
160 use windows_sys::Win32::Storage::FileSystem::{
161 FileBasicInfo, FileIdInfo, GetFileInformationByHandleEx, GetVolumeInformationByHandleW,
162 FILE_BASIC_INFO, FILE_ID_INFO,
163 };
164 let handle = file.as_raw_handle();
165 let mut id: FILE_ID_INFO = unsafe { std::mem::zeroed() };
166 let mut basic: FILE_BASIC_INFO = unsafe { std::mem::zeroed() };
167 let mut filesystem = [0u16; 32];
168 let ok = unsafe {
171 GetFileInformationByHandleEx(
172 handle,
173 FileIdInfo,
174 &mut id as *mut _ as _,
175 std::mem::size_of::<FILE_ID_INFO>() as u32,
176 ) != 0
177 && GetFileInformationByHandleEx(
178 handle,
179 FileBasicInfo,
180 &mut basic as *mut _ as _,
181 std::mem::size_of::<FILE_BASIC_INFO>() as u32,
182 ) != 0
183 && GetVolumeInformationByHandleW(
184 handle,
185 std::ptr::null_mut(),
186 0,
187 std::ptr::null_mut(),
188 std::ptr::null_mut(),
189 std::ptr::null_mut(),
190 filesystem.as_mut_ptr(),
191 filesystem.len() as u32,
192 ) != 0
193 };
194 if !ok {
195 return Err(io::Error::last_os_error());
196 }
197 let end = filesystem
198 .iter()
199 .position(|c| *c == 0)
200 .unwrap_or(filesystem.len());
201 let name = String::from_utf16_lossy(&filesystem[..end]);
202 if !matches!(name.as_str(), "NTFS" | "ReFS") {
203 return Err(io::Error::new(
204 io::ErrorKind::Unsupported,
205 "stat reuse requires NTFS or ReFS",
206 ));
207 }
208 let unix_ns = |ticks: i64| (i128::from(ticks) - 116_444_736_000_000_000i128) * 100;
209 Ok(NativeStat {
210 identity: FileIdentity::Windows {
211 volume: id.VolumeSerialNumber,
212 id: id.FileId.Identifier,
213 creation: basic.CreationTime,
214 },
215 size: file.metadata()?.len(),
216 modified_ns: unix_ns(basic.LastWriteTime),
217 changed_ns: unix_ns(basic.ChangeTime),
218 mode: basic.FileAttributes,
219 reuse_supported: true,
220 })
221}
222
223pub fn now_ns() -> u128 {
227 u128::from(
228 SystemTime::now()
229 .duration_since(UNIX_EPOCH)
230 .unwrap_or_default()
231 .as_secs(),
232 ) * 1_000_000_000
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn stat_evidence_discards_identity_change_and_racy_observations() {
241 let root = tempfile::tempdir().unwrap();
242 let file = root.path().join("file.rs");
243 fs::write(&file, b"one").unwrap();
244 let stat = NativeStat::read(&file).unwrap();
245 let observed = u128::try_from(stat.modified_ns).unwrap();
246 assert!(!stat.reusable(&stat, observed));
247 assert!(stat.reusable(&stat, observed + 1));
248 let mut changed = stat.clone();
249 changed.reuse_supported = false;
250 assert!(!changed.reusable(&changed, observed + 1));
251 changed = stat.clone();
252 changed.changed_ns += 1;
253 assert!(!stat.reusable(&changed, observed + 1));
254 changed = stat.clone();
255 changed.identity = FileIdentity::Windows {
256 volume: 42,
257 id: [3; 16],
258 creation: 0,
259 };
260 assert!(!stat.reusable(&changed, observed + 1));
261 }
262}