Skip to main content

artifactize_foundation/platform/files/
unix.rs

1//! Unix pinned opens and descriptor-based directory listings.
2
3use std::{
4    ffi::{CString, OsStr, OsString},
5    fs::{self, File, OpenOptions},
6    io,
7    os::unix::{ffi::OsStrExt, fs::OpenOptionsExt},
8    path::{Path, PathBuf},
9};
10
11use rustix::{
12    fs::{AtFlags, Dir, FileType, Mode, OFlags, openat, statat},
13    io::Errno,
14};
15
16use super::FileKind;
17
18#[cfg(target_os = "macos")]
19mod macos;
20#[cfg(target_os = "macos")]
21pub use macos::{case_sensitive, exact_name};
22
23/// The absolute path of an existing file with every link resolved.
24pub fn canonicalize(path: &Path) -> io::Result<PathBuf> {
25    fs::canonicalize(path)
26}
27
28/// Open without following a link in the last component or blocking on a FIFO.
29pub fn open_no_follow(options: &mut OpenOptions, path: &Path) -> io::Result<File> {
30    let (path, directory) = terminal_component(path);
31    let mut flags = OFlags::NOFOLLOW | OFlags::NONBLOCK;
32    if directory {
33        flags |= OFlags::DIRECTORY;
34    }
35    options.custom_flags(flags.bits() as i32).open(path)
36}
37
38/// Preserve the directory requirement of trailing separators and `/.`, but don't let
39/// them hide a final symlink from `O_NOFOLLOW` or `symlink_metadata`.
40pub(in crate::platform) fn terminal_component(path: &Path) -> (&Path, bool) {
41    let original = path.as_os_str().as_bytes();
42    let mut bytes = original;
43    while bytes.len() > 1 {
44        if let Some(prefix) = bytes.strip_suffix(b"/") {
45            bytes = prefix;
46        } else if let Some(prefix) = bytes.strip_suffix(b"/.") {
47            bytes = if prefix.is_empty() { b"/" } else { prefix };
48        } else {
49            break;
50        }
51    }
52    (
53        Path::new(OsStr::from_bytes(bytes)),
54        bytes.len() != original.len(),
55    )
56}
57
58/// Open for reading without blocking on a FIFO, so its type can be checked first.
59pub fn open_nonblocking(path: &Path) -> io::Result<File> {
60    OpenOptions::new()
61        .read(true)
62        .custom_flags(OFlags::NONBLOCK.bits() as i32)
63        .open(path)
64}
65
66/// Open a directory by path, such as the root a scoped walk starts from.
67pub fn open_directory(path: &Path) -> io::Result<File> {
68    OpenOptions::new()
69        .read(true)
70        .custom_flags(OFlags::DIRECTORY.bits() as i32)
71        .open(path)
72}
73
74/// One path component, ready for `openat`.
75pub struct EntryName(CString);
76
77impl EntryName {
78    pub fn new(name: &OsStr) -> Option<Self> {
79        let bytes = name.as_bytes();
80        (!bytes.is_empty() && !matches!(bytes, b"." | b"..") && !bytes.contains(&b'/'))
81            .then(|| CString::new(bytes).ok().map(Self))
82            .flatten()
83    }
84}
85
86/// Open one entry of a pinned directory read-only, without following a symlink.
87pub fn open_entry(directory: &File, name: &EntryName) -> io::Result<File> {
88    // NONBLOCK avoids waiting on a FIFO before its type can be rejected.
89    Ok(openat(
90        directory,
91        &name.0,
92        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
93        Mode::empty(),
94    )?
95    .into())
96}
97
98/// Whether `open_entry` failed because the entry is a symlink: `O_NOFOLLOW` reports `ELOOP`
99/// on Linux and macOS, and `EMLINK` on FreeBSD and DragonFly.
100pub fn is_link_refusal(error: &io::Error) -> bool {
101    let link = if cfg!(any(target_os = "freebsd", target_os = "dragonfly")) {
102        Errno::MLINK
103    } else {
104        Errno::LOOP
105    };
106    error.raw_os_error() == Some(link.raw_os_error())
107}
108
109/// The entries of a pinned directory, listed through its descriptor rather than a path
110/// that could have been replaced by a link.
111pub fn read_dir(directory: &File) -> io::Result<impl Iterator<Item = io::Result<DirEntry<'_>>>> {
112    Ok(ReadDir {
113        stream: open_scan(directory)?,
114        directory,
115        state: Scan::Reading,
116    })
117}
118
119fn open_scan(directory: &File) -> io::Result<Dir> {
120    // Open a new description, not dup: directory offsets must be independent across scans.
121    let fd = openat(
122        directory,
123        c".",
124        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
125        Mode::empty(),
126    )?;
127    Ok(Dir::new(fd)?)
128}
129
130/// A failed or exhausted stream never reads the directory again.
131#[derive(Clone, Copy, PartialEq, Eq)]
132enum Scan {
133    Reading,
134    Done,
135}
136
137struct ReadDir<'a> {
138    stream: Dir,
139    directory: &'a File,
140    state: Scan,
141}
142
143impl<'a> Iterator for ReadDir<'a> {
144    type Item = io::Result<DirEntry<'a>>;
145
146    fn next(&mut self) -> Option<Self::Item> {
147        while self.state == Scan::Reading {
148            let entry = match self.stream.next() {
149                Some(Ok(entry)) => entry,
150                Some(Err(error)) => {
151                    self.state = Scan::Done;
152                    return Some(Err(error.into()));
153                }
154                None => {
155                    self.state = Scan::Done;
156                    return None;
157                }
158            };
159            let name = entry.file_name().to_bytes();
160            if name == b"." || name == b".." {
161                continue;
162            }
163            return Some(Ok(DirEntry {
164                directory: self.directory,
165                name: OsStr::from_bytes(name).to_owned(),
166            }));
167        }
168        None
169    }
170}
171
172pub struct DirEntry<'a> {
173    directory: &'a File,
174    name: OsString,
175}
176
177impl DirEntry<'_> {
178    pub fn file_name(&self) -> OsString {
179        self.name.clone()
180    }
181
182    pub fn file_type(&self) -> io::Result<FileKind> {
183        entry_kind(self.directory, &self.name)
184    }
185}
186
187/// The type of one entry of a pinned directory, without following it.
188pub fn entry_kind(directory: &File, name: &OsStr) -> io::Result<FileKind> {
189    let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
190    // Inspect the entry itself, never its target.
191    let stat = statat(directory, &name.0, AtFlags::SYMLINK_NOFOLLOW)?;
192    Ok(match FileType::from_raw_mode(stat.st_mode) {
193        FileType::RegularFile => FileKind::File,
194        FileType::Directory => FileKind::Directory,
195        FileType::Symlink => FileKind::Symlink,
196        _ => FileKind::Other,
197    })
198}
199
200/// Verify the spelling the filesystem enumerates and that it names the opened file.
201/// The descriptor path is not enough: case-folded filesystems can cache lookup spellings.
202#[cfg(not(target_os = "macos"))]
203pub fn exact_name(directory: &File, file: &File, name: &OsStr) -> io::Result<bool> {
204    let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
205    let scan = open_scan(directory)?;
206    for entry in scan {
207        if entry?.file_name() == name.0.as_c_str() {
208            let opened = rustix::fs::fstat(file)?;
209            let listed = statat(directory, &name.0, AtFlags::SYMLINK_NOFOLLOW)?;
210            return Ok((listed.st_dev, listed.st_ino) == (opened.st_dev, opened.st_ino));
211        }
212    }
213    Ok(false)
214}
215
216pub fn verified_path(_file: &File, root: &Path, names: &[&OsStr]) -> io::Result<PathBuf> {
217    let mut path = root.to_owned();
218    path.extend(names);
219    Ok(path)
220}
221
222/// Test Linux's known filesystem policies without assuming unknown mounts are folded.
223#[cfg(target_os = "linux")]
224pub(in crate::platform) fn native_case_sensitive(
225    directory: &File,
226    filesystem: rustix::fs::FsWord,
227) -> Option<bool> {
228    match filesystem as u64 {
229        kind if kind == libc::EXT4_SUPER_MAGIC as u64 || kind == libc::F2FS_SUPER_MAGIC as u64 => {
230            // Linux FS_CASEFOLD_FL. Old filesystems sharing ext4's magic may not report flags.
231            const CASEFOLD: u32 = 0x4000_0000;
232            rustix::fs::ioctl_getflags(directory)
233                .ok()
234                .map(|flags| flags.bits() & CASEFOLD == 0)
235        }
236        kind if kind == libc::TMPFS_MAGIC as u64 || kind == libc::BTRFS_SUPER_MAGIC as u64 => {
237            Some(true)
238        }
239        _ => None,
240    }
241}
242
243/// Strict scoped lookup cannot assume an unknown mount distinguishes case variants.
244#[cfg(target_os = "linux")]
245pub fn case_sensitive(directory: &File) -> io::Result<bool> {
246    let volume = rustix::fs::fstatfs(directory)?;
247    Ok(native_case_sensitive(directory, volume.f_type).unwrap_or(false))
248}
249
250/// No portable Unix API can prove that a mount doesn't alias case variants.
251#[cfg(not(any(target_os = "linux", target_os = "macos")))]
252pub fn case_sensitive(_directory: &File) -> io::Result<bool> {
253    Ok(false)
254}