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
5#[derive(Debug)]
6pub enum OpenRegularError {
7    Io(io::Error),
8    Symlink,
9    NotRegularFile,
10}
11impl std::fmt::Display for OpenRegularError {
12    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
13        match self {
14            Self::Io(error) => write!(f, "input open failed: {error}"),
15            Self::Symlink => f.write_str("input leaf is a symlink or reparse point"),
16            Self::NotRegularFile => f.write_str("input handle is not a regular file"),
17        }
18    }
19}
20impl std::error::Error for OpenRegularError {
21    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
22        match self {
23            Self::Io(error) => Some(error),
24            _ => None,
25        }
26    }
27}
28impl From<io::Error> for OpenRegularError {
29    fn from(error: io::Error) -> Self {
30        Self::Io(error)
31    }
32}
33
34/// Open a regular input without following its leaf. Parent directories remain
35/// the caller's responsibility. Nonblocking open prevents a FIFO substitution
36/// from hanging before the descriptor's type can be checked.
37#[cfg(unix)]
38pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
39    use std::os::unix::fs::OpenOptionsExt;
40    let file = std::fs::OpenOptions::new()
41        .read(true)
42        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
43        .open(path)
44        .map_err(|error| {
45            if error.raw_os_error() == Some(libc::ELOOP) {
46                OpenRegularError::Symlink
47            } else {
48                OpenRegularError::Io(error)
49            }
50        })?;
51    // File::metadata uses fstat on this descriptor, not a fresh path lookup.
52    if !file.metadata()?.is_file() {
53        return Err(OpenRegularError::NotRegularFile);
54    }
55    Ok(file)
56}
57
58/// Open an absolute regular file without following a symlink in any component.
59/// Directory descriptors anchor each lookup even if an ancestor is renamed.
60#[cfg(unix)]
61pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
62    open_nofollow_all(path, false)
63}
64
65/// Open an absolute directory without following symlinks in any component.
66pub fn open_directory_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
67    open_nofollow_all(path, true)
68}
69
70#[cfg(unix)]
71fn open_nofollow_all(
72    path: &std::path::Path,
73    want_directory: bool,
74) -> Result<File, OpenRegularError> {
75    use rustix::fs::{open, openat, Mode, OFlags};
76    use std::path::Component;
77    if !path.is_absolute() {
78        return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
79    }
80    let mut directory = open(
81        "/",
82        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
83        Mode::empty(),
84    )
85    .map_err(io::Error::from)?;
86    let parts = path
87        .components()
88        .filter(|part| !matches!(part, Component::RootDir | Component::CurDir))
89        .collect::<Vec<_>>();
90    for (index, part) in parts.iter().enumerate() {
91        let name = part.as_os_str();
92        let leaf = index + 1 == parts.len();
93        let flags = OFlags::RDONLY
94            | OFlags::CLOEXEC
95            | OFlags::NOFOLLOW
96            | OFlags::NONBLOCK
97            | if leaf && !want_directory {
98                OFlags::empty()
99            } else {
100                OFlags::DIRECTORY
101            };
102        directory = openat(&directory, name, flags, Mode::empty()).map_err(|error| {
103            if error == rustix::io::Errno::LOOP {
104                OpenRegularError::Symlink
105            } else {
106                OpenRegularError::Io(error.into())
107            }
108        })?;
109    }
110    let file = File::from(directory);
111    if if want_directory {
112        !file.metadata()?.is_dir()
113    } else {
114        !file.metadata()?.is_file()
115    } {
116        return Err(OpenRegularError::NotRegularFile);
117    }
118    Ok(file)
119}
120
121/// Pin each Windows directory against rename while rejecting symlinks and
122/// junctions (reparse points). Holding all ancestors until the leaf is open
123/// prevents another process from replacing a checked directory with a redirect.
124#[cfg(windows)]
125#[allow(unsafe_code)]
126pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
127    open_nofollow_all(path, false)
128}
129
130#[cfg(windows)]
131#[allow(unsafe_code)]
132fn open_nofollow_all(
133    path: &std::path::Path,
134    want_directory: bool,
135) -> Result<File, OpenRegularError> {
136    use std::{
137        os::windows::{fs::OpenOptionsExt, io::AsRawHandle},
138        path::Component,
139    };
140    use windows_sys::Win32::Storage::FileSystem::{
141        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
142        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
143    };
144    if !path.is_absolute() {
145        return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
146    }
147    let mut prefix = std::path::PathBuf::new();
148    let mut ancestors = Vec::new();
149    for part in path.components() {
150        match part {
151            Component::CurDir => continue,
152            _ => prefix.push(part),
153        }
154        if !prefix.is_absolute() {
155            continue;
156        }
157        let file = std::fs::OpenOptions::new()
158            .read(true)
159            .share_mode(1)
160            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
161            .open(&prefix)?;
162        let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
163        // SAFETY: file owns the queried handle and information is writable.
164        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
165            return Err(io::Error::last_os_error().into());
166        }
167        if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
168            return Err(OpenRegularError::Symlink);
169        }
170        ancestors.push(file);
171    }
172    let file = ancestors.pop().ok_or(OpenRegularError::NotRegularFile)?;
173    if if want_directory {
174        !file.metadata()?.is_dir()
175    } else {
176        !file.metadata()?.is_file()
177    } {
178        return Err(OpenRegularError::NotRegularFile);
179    }
180    Ok(file)
181}
182
183/// Windows equivalent of the regular-input opener. Reparse-point and type
184/// checks use the opened handle, never a second lookup through the pathname.
185#[cfg(windows)]
186#[allow(unsafe_code)]
187pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
188    use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
189    use windows_sys::Win32::Storage::FileSystem::{
190        GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION,
191        FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
192        FILE_FLAG_OPEN_REPARSE_POINT, FILE_TYPE_DISK,
193    };
194    let file = std::fs::OpenOptions::new()
195        .read(true)
196        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
197        .open(path)?;
198    // SAFETY: file owns the live handle for the entire query.
199    if unsafe { GetFileType(file.as_raw_handle()) } != FILE_TYPE_DISK {
200        return Err(OpenRegularError::NotRegularFile);
201    }
202    let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
203    // SAFETY: file owns the handle; information is a correctly sized writable
204    // output buffer and both remain live throughout the synchronous query.
205    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
206        return Err(io::Error::last_os_error().into());
207    }
208    if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
209        return Err(OpenRegularError::Symlink);
210    }
211    if information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
212        return Err(OpenRegularError::NotRegularFile);
213    }
214    Ok(file)
215}
216
217#[cfg(test)]
218#[path = "regular_open_tests.rs"]
219mod open_tests;
220
221#[cfg(unix)]
222pub type RetainedFileIdentity = crate::FileIdentity;
223#[cfg(windows)]
224pub type RetainedFileIdentity = crate::WindowsFileIdentity;
225
226/// Identify an already-open file, without resolving its mutable pathname again.
227/// Unix identities contain device and inode; Windows identities contain the
228/// volume serial and all sixteen file-id bytes. Content hashes remain separate.
229#[cfg(unix)]
230pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
231    use std::os::unix::fs::MetadataExt;
232    let metadata = file.metadata()?;
233    Ok(RetainedFileIdentity {
234        device: metadata.dev(),
235        inode: metadata.ino(),
236    })
237}
238
239/// The published registry's Windows identity uses the legacy 64-bit file index,
240/// not FILE_ID_INFO's 128-bit identifier; neither is a padded form of the other.
241#[cfg(windows)]
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct WindowsFileIndexIdentity {
244    pub volume_serial: u32,
245    pub file_index: u64,
246}
247
248/// Read the legacy 64-bit file index and volume serial from the exact handle.
249/// Registries publish this identity; FILE_ID_INFO's 128-bit identifier is a
250/// different representation and cannot safely be inferred by padding this one.
251#[cfg(windows)]
252#[allow(unsafe_code)]
253pub fn retained_file_index(file: &File) -> io::Result<WindowsFileIndexIdentity> {
254    use std::os::windows::io::AsRawHandle;
255    use windows_sys::Win32::Storage::FileSystem::{
256        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
257    };
258    let mut info: BY_HANDLE_FILE_INFORMATION = Default::default();
259    // SAFETY: file owns the live handle and info is a writable, correctly sized buffer.
260    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
261        return Err(io::Error::last_os_error());
262    }
263    Ok(WindowsFileIndexIdentity {
264        volume_serial: info.dwVolumeSerialNumber,
265        file_index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
266    })
267}
268
269/// Identify an already-open file using the complete Windows file-object id.
270#[cfg(windows)]
271#[allow(unsafe_code)]
272pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
273    use std::{mem::size_of, os::windows::io::AsRawHandle};
274    use windows_sys::Win32::Storage::FileSystem::{
275        FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO,
276    };
277    let mut info: FILE_ID_INFO = Default::default();
278    // SAFETY: file owns a live handle; the writable buffer has the FileIdInfo
279    // layout and size, and neither the handle nor the buffer escapes this call.
280    if unsafe {
281        GetFileInformationByHandleEx(
282            file.as_raw_handle(),
283            FileIdInfo,
284            (&mut info as *mut FILE_ID_INFO).cast(),
285            size_of::<FILE_ID_INFO>() as u32,
286        )
287    } == 0
288    {
289        return Err(io::Error::last_os_error());
290    }
291    Ok(RetainedFileIdentity {
292        volume_serial_number: info.VolumeSerialNumber,
293        file_id: info.FileId.Identifier,
294    })
295}
296
297#[cfg(all(test, any(unix, windows)))]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn retained_directory_open_checks_type_and_identity() {
303        let dir = cortexkit_test_support::ScratchDir::new("retained-directory");
304        let opened = open_directory_nofollow_all(&dir).unwrap();
305        assert!(opened.metadata().unwrap().is_dir());
306        assert_eq!(
307            retained_file_identity(&opened).unwrap(),
308            retained_file_identity(&open_directory_nofollow_all(&dir).unwrap()).unwrap()
309        );
310        let path = dir.join("file");
311        std::fs::write(&path, b"file").unwrap();
312        assert!(open_directory_nofollow_all(&path).is_err());
313        assert!(open_directory_nofollow_all(std::path::Path::new("relative")).is_err());
314    }
315
316    #[cfg(unix)]
317    #[test]
318    fn retained_directory_open_refuses_symlink_ancestors_and_leaf() {
319        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-symlink");
320        std::fs::create_dir_all(dir.join("real/child")).unwrap();
321        std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
322        assert!(open_directory_nofollow_all(&dir.join("link")).is_err());
323        assert!(open_directory_nofollow_all(&dir.join("link/child")).is_err());
324    }
325
326    #[test]
327    fn retained_file_identity_hard_links_share_identity_but_copies_do_not() {
328        let root = cortexkit_test_support::ScratchDir::new("subc-retained-file");
329        let first = root.join("first");
330        let link = root.join("link");
331        let copy = root.join("copy");
332        std::fs::write(&first, b"same bytes").unwrap();
333        std::fs::hard_link(&first, &link).unwrap();
334        std::fs::copy(&first, &copy).unwrap();
335        let id = |path| retained_file_identity(&File::open(path).unwrap()).unwrap();
336        assert_eq!(id(&first), id(&link));
337        assert_ne!(id(&first), id(&copy));
338    }
339}