Skip to main content

subc_os/
retained_file.rs

1//! File-object identity taken from the same handle that supplied captured bytes.
2
3use std::{fs::File, io};
4#[cfg(windows)]
5use windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION;
6
7#[derive(Debug)]
8pub enum OpenRegularError {
9    Io(io::Error),
10    Symlink,
11    NotRegularFile,
12}
13impl std::fmt::Display for OpenRegularError {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        match self {
16            Self::Io(error) => write!(f, "input open failed: {error}"),
17            Self::Symlink => f.write_str("input leaf is a symlink or reparse point"),
18            Self::NotRegularFile => f.write_str("input handle is not a regular file"),
19        }
20    }
21}
22impl std::error::Error for OpenRegularError {
23    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
24        match self {
25            Self::Io(error) => Some(error),
26            _ => None,
27        }
28    }
29}
30impl From<io::Error> for OpenRegularError {
31    fn from(error: io::Error) -> Self {
32        Self::Io(error)
33    }
34}
35
36/// Open a regular input without following its leaf. Parent directories remain
37/// the caller's responsibility. Nonblocking open prevents a FIFO substitution
38/// from hanging before the descriptor's type can be checked.
39#[cfg(unix)]
40pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
41    use std::os::unix::fs::OpenOptionsExt;
42    let file = std::fs::OpenOptions::new()
43        .read(true)
44        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
45        .open(path)
46        .map_err(|error| {
47            if error.raw_os_error() == Some(libc::ELOOP) {
48                OpenRegularError::Symlink
49            } else {
50                OpenRegularError::Io(error)
51            }
52        })?;
53    // File::metadata uses fstat on this descriptor, not a fresh path lookup.
54    if !file.metadata()?.is_file() {
55        return Err(OpenRegularError::NotRegularFile);
56    }
57    Ok(file)
58}
59
60/// Open an absolute regular file without following a symlink in any component.
61/// Directory descriptors anchor each lookup even if an ancestor is renamed.
62#[cfg(unix)]
63pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
64    open_nofollow_all(path, false)
65}
66
67/// Open an absolute directory without following symlinks in any component.
68pub fn open_directory_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
69    open_nofollow_all(path, true)
70}
71
72#[cfg(unix)]
73fn open_nofollow_all(
74    path: &std::path::Path,
75    want_directory: bool,
76) -> Result<File, OpenRegularError> {
77    use rustix::fs::{open, openat, statat, AtFlags, FileType, Mode, OFlags};
78    use std::path::Component;
79    if !path.is_absolute() {
80        return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
81    }
82    let mut directory = open(
83        "/",
84        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
85        Mode::empty(),
86    )
87    .map_err(io::Error::from)?;
88    let parts = path
89        .components()
90        .filter(|part| !matches!(part, Component::RootDir | Component::CurDir))
91        .collect::<Vec<_>>();
92    for (index, part) in parts.iter().enumerate() {
93        let name = part.as_os_str();
94        let leaf = index + 1 == parts.len();
95        let flags = OFlags::RDONLY
96            | OFlags::CLOEXEC
97            | OFlags::NOFOLLOW
98            | OFlags::NONBLOCK
99            | if leaf && !want_directory {
100                OFlags::empty()
101            } else {
102                OFlags::DIRECTORY
103            };
104        directory = openat(&directory, name, flags, Mode::empty()).map_err(|error| {
105            if error == rustix::io::Errno::LOOP
106                || (error == rustix::io::Errno::NOTDIR
107                    && statat(&directory, name, AtFlags::SYMLINK_NOFOLLOW).is_ok_and(|stat| {
108                        FileType::from_raw_mode(stat.st_mode) == FileType::Symlink
109                    }))
110            {
111                OpenRegularError::Symlink
112            } else if error == rustix::io::Errno::NOTDIR {
113                OpenRegularError::NotRegularFile
114            } else {
115                OpenRegularError::Io(error.into())
116            }
117        })?;
118    }
119    let file = File::from(directory);
120    if if want_directory {
121        !file.metadata()?.is_dir()
122    } else {
123        !file.metadata()?.is_file()
124    } {
125        return Err(OpenRegularError::NotRegularFile);
126    }
127    Ok(file)
128}
129
130/// Pin each Windows directory against rename while rejecting symlinks and
131/// junctions (reparse points). Holding all ancestors until the leaf is open
132/// prevents another process from replacing a checked directory with a redirect.
133#[cfg(windows)]
134#[allow(unsafe_code)]
135pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
136    open_nofollow_all(path, false)
137}
138
139#[cfg(windows)]
140#[allow(unsafe_code)]
141fn open_nofollow_all(
142    path: &std::path::Path,
143    want_directory: bool,
144) -> Result<File, OpenRegularError> {
145    use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
146    use windows_sys::Win32::Storage::FileSystem::{
147        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
148        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,
149        FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE,
150    };
151    if !path.is_absolute() {
152        return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
153    }
154    let mut ancestors = Vec::new();
155    // Use slices of the original path. Rebuilding it with PathBuf::push can
156    // lose the root separator on verbatim drive paths such as \\?\C:\.
157    let prefixes: Vec<_> = path
158        .ancestors()
159        .take_while(|prefix| prefix.is_absolute())
160        .collect();
161    for prefix in prefixes.into_iter().rev() {
162        // Directory writers need not exclude traversal. Still deny delete
163        // sharing to pin each checked name, and leave regular leaves read-only.
164        let mut options = std::fs::OpenOptions::new();
165        if want_directory || prefix != path {
166            options
167                .access_mode(FILE_READ_ATTRIBUTES | FILE_TRAVERSE)
168                .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
169        } else {
170            options.read(true).share_mode(FILE_SHARE_READ);
171        }
172        let file = options
173            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
174            .open(prefix)?;
175        let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
176        // SAFETY: file owns the queried handle and information is writable.
177        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
178            return Err(io::Error::last_os_error().into());
179        }
180        if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
181            return Err(OpenRegularError::Symlink);
182        }
183        ancestors.push(file);
184    }
185    let file = ancestors.pop().ok_or(OpenRegularError::NotRegularFile)?;
186    if if want_directory {
187        !file.metadata()?.is_dir()
188    } else {
189        !file.metadata()?.is_file()
190    } {
191        return Err(OpenRegularError::NotRegularFile);
192    }
193    Ok(file)
194}
195
196/// Windows equivalent of the regular-input opener. Reparse-point and type
197/// checks use the opened handle, never a second lookup through the pathname.
198#[cfg(windows)]
199#[allow(unsafe_code)]
200pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
201    use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
202    use windows_sys::Win32::Storage::FileSystem::{
203        GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION,
204        FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
205        FILE_FLAG_OPEN_REPARSE_POINT, FILE_TYPE_DISK,
206    };
207    let file = std::fs::OpenOptions::new()
208        .read(true)
209        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
210        .open(path)?;
211    // SAFETY: file owns the live handle for the entire query.
212    if unsafe { GetFileType(file.as_raw_handle()) } != FILE_TYPE_DISK {
213        return Err(OpenRegularError::NotRegularFile);
214    }
215    let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
216    // SAFETY: file owns the handle; information is a correctly sized writable
217    // output buffer and both remain live throughout the synchronous query.
218    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
219        return Err(io::Error::last_os_error().into());
220    }
221    if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
222        return Err(OpenRegularError::Symlink);
223    }
224    if information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
225        return Err(OpenRegularError::NotRegularFile);
226    }
227    Ok(file)
228}
229
230#[cfg(test)]
231#[path = "regular_open_tests.rs"]
232mod open_tests;
233
234#[cfg(unix)]
235pub type RetainedFileIdentity = crate::FileIdentity;
236#[cfg(windows)]
237pub type RetainedFileIdentity = crate::WindowsFileIdentity;
238
239/// Identify an already-open file, without resolving its mutable pathname again.
240/// Unix identities contain device and inode; Windows identities contain the
241/// volume serial and all sixteen file-id bytes. Content hashes remain separate.
242#[cfg(unix)]
243pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
244    use std::os::unix::fs::MetadataExt;
245    let metadata = file.metadata()?;
246    Ok(RetainedFileIdentity {
247        device: metadata.dev(),
248        inode: metadata.ino(),
249    })
250}
251
252/// The published registry's Windows identity uses the legacy 64-bit file index,
253/// not FILE_ID_INFO's 128-bit identifier; neither is a padded form of the other.
254#[cfg(windows)]
255#[derive(Clone, Debug, PartialEq, Eq)]
256pub struct WindowsFileIndexIdentity {
257    pub volume_serial: u32,
258    pub file_index: u64,
259}
260
261/// A snapshot of Windows file information from an open handle.
262#[cfg(windows)]
263pub struct WindowsFileInformation(BY_HANDLE_FILE_INFORMATION);
264
265#[cfg(windows)]
266impl WindowsFileInformation {
267    /// The number of hard links reported for the file when queried.
268    pub fn link_count(&self) -> u32 {
269        self.0.nNumberOfLinks
270    }
271
272    pub(crate) fn attributes(&self) -> u32 {
273        self.0.dwFileAttributes
274    }
275}
276
277/// Query information about the opened object without resolving its path again.
278/// This does not validate the file type or check for reparse points.
279#[cfg(windows)]
280#[allow(unsafe_code)]
281pub fn retained_file_information(file: &File) -> io::Result<WindowsFileInformation> {
282    use std::os::windows::io::AsRawHandle;
283    use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandle;
284    let mut info = BY_HANDLE_FILE_INFORMATION::default();
285    // SAFETY: file owns the live handle and info is a writable, correctly sized buffer.
286    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
287        return Err(io::Error::last_os_error());
288    }
289    Ok(WindowsFileInformation(info))
290}
291
292/// Read the legacy 64-bit file index and volume serial from the exact handle.
293/// Registries publish this identity; FILE_ID_INFO's 128-bit identifier is a
294/// different representation and cannot safely be inferred by padding this one.
295#[cfg(windows)]
296pub fn retained_file_index(file: &File) -> io::Result<WindowsFileIndexIdentity> {
297    let info = retained_file_information(file)?.0;
298    Ok(WindowsFileIndexIdentity {
299        volume_serial: info.dwVolumeSerialNumber,
300        file_index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
301    })
302}
303
304/// Identify an already-open file using the complete Windows file-object id.
305#[cfg(windows)]
306#[allow(unsafe_code)]
307pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
308    use std::{mem::size_of, os::windows::io::AsRawHandle};
309    use windows_sys::Win32::Storage::FileSystem::{
310        FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO,
311    };
312    let mut info: FILE_ID_INFO = Default::default();
313    // SAFETY: file owns a live handle; the writable buffer has the FileIdInfo
314    // layout and size, and neither the handle nor the buffer escapes this call.
315    if unsafe {
316        GetFileInformationByHandleEx(
317            file.as_raw_handle(),
318            FileIdInfo,
319            (&mut info as *mut FILE_ID_INFO).cast(),
320            size_of::<FILE_ID_INFO>() as u32,
321        )
322    } == 0
323    {
324        return Err(io::Error::last_os_error());
325    }
326    Ok(RetainedFileIdentity {
327        volume_serial_number: info.VolumeSerialNumber,
328        file_id: info.FileId.Identifier,
329    })
330}
331
332#[cfg(all(test, any(unix, windows)))]
333mod tests {
334    use super::*;
335
336    #[cfg(windows)]
337    #[test]
338    fn retained_file_information_reports_link_count_from_an_open_handle() {
339        let scratch = cortexkit_test_support::ScratchDir::new("retained-link-count");
340        let path = scratch.join("file");
341        std::fs::write(&path, b"content").unwrap();
342        let file = File::open(&path).unwrap();
343        assert_eq!(retained_file_information(&file).unwrap().link_count(), 1);
344
345        std::fs::hard_link(&path, scratch.join("second-link")).unwrap();
346        assert_eq!(retained_file_information(&file).unwrap().link_count(), 2);
347    }
348
349    #[test]
350    fn retained_directory_open_checks_type_and_identity() {
351        let dir = cortexkit_test_support::ScratchDir::new("retained-directory");
352        let opened = open_directory_nofollow_all(&dir).unwrap();
353        assert!(opened.metadata().unwrap().is_dir());
354        assert_eq!(
355            retained_file_identity(&opened).unwrap(),
356            retained_file_identity(&open_directory_nofollow_all(&dir).unwrap()).unwrap()
357        );
358        let path = dir.join("file");
359        std::fs::write(&path, b"file").unwrap();
360        assert!(open_directory_nofollow_all(&path).is_err());
361        assert!(open_directory_nofollow_all(std::path::Path::new("relative")).is_err());
362    }
363
364    #[cfg(unix)]
365    #[test]
366    fn retained_directory_open_refuses_symlink_ancestors_and_leaf() {
367        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-symlink");
368        std::fs::create_dir_all(dir.join("real/child")).unwrap();
369        std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
370        assert!(open_directory_nofollow_all(&dir.join("link")).is_err());
371        assert!(open_directory_nofollow_all(&dir.join("link/child")).is_err());
372    }
373
374    #[cfg(windows)]
375    #[test]
376    fn retained_directory_open_can_publish_under_a_canonical_windows_path() {
377        use std::{ffi::OsStr, io::Write};
378
379        let root = cortexkit_test_support::ScratchDir::new("retained-canonical-directory");
380        let canonical = std::fs::canonicalize(root.path()).unwrap();
381        let parent = open_directory_nofollow_all(&canonical).unwrap();
382        let mut file = crate::RetainedTempFile::create_for_publish(&parent).unwrap();
383        file.file_mut().write_all(b"published").unwrap();
384        file.publish(OsStr::new("published")).unwrap();
385        assert_eq!(std::fs::read(root.join("published")).unwrap(), b"published");
386    }
387
388    #[cfg(windows)]
389    #[test]
390    fn retained_directory_open_coexists_with_an_existing_directory_writer() {
391        use std::os::windows::fs::OpenOptionsExt;
392        use windows_sys::Win32::Storage::FileSystem::{FILE_ADD_FILE, FILE_FLAG_BACKUP_SEMANTICS};
393
394        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-writer");
395        let child = dir.join("child");
396        std::fs::create_dir(&child).unwrap();
397        // FILE_ADD_FILE requests the directory right corresponding to write
398        // data on a file, so an opener that denies write sharing conflicts.
399        let writer = std::fs::OpenOptions::new()
400            .access_mode(FILE_ADD_FILE)
401            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
402            .open(&dir)
403            .unwrap();
404
405        let parent = open_directory_nofollow_all(&dir).unwrap();
406        let reopened = open_directory_nofollow_all(&dir).unwrap();
407        assert_eq!(
408            retained_file_identity(&parent).unwrap(),
409            retained_file_identity(&reopened).unwrap()
410        );
411        assert!(open_directory_nofollow_all(&child)
412            .unwrap()
413            .metadata()
414            .unwrap()
415            .is_dir());
416        drop(writer);
417    }
418
419    #[cfg(windows)]
420    #[test]
421    fn retained_directory_open_still_blocks_rename_until_handle_closes() {
422        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-rename");
423        let child = dir.join("child");
424        let renamed = dir.join("renamed");
425        std::fs::create_dir(&child).unwrap();
426        let handle = open_directory_nofollow_all(&child).unwrap();
427
428        assert!(std::fs::rename(&child, &renamed).is_err());
429        assert!(!renamed.exists());
430        drop(handle);
431        std::fs::rename(&child, &renamed).unwrap();
432        assert!(renamed.is_dir());
433    }
434
435    #[test]
436    fn retained_file_identity_hard_links_share_identity_but_copies_do_not() {
437        let root = cortexkit_test_support::ScratchDir::new("subc-retained-file");
438        let first = root.join("first");
439        let link = root.join("link");
440        let copy = root.join("copy");
441        std::fs::write(&first, b"same bytes").unwrap();
442        std::fs::hard_link(&first, &link).unwrap();
443        std::fs::copy(&first, &copy).unwrap();
444        let id = |path| retained_file_identity(&File::open(path).unwrap()).unwrap();
445        assert_eq!(id(&first), id(&link));
446        assert_ne!(id(&first), id(&copy));
447    }
448}