Skip to main content

artifactize_tools/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    options
31        .custom_flags((OFlags::NOFOLLOW | OFlags::NONBLOCK).bits() as i32)
32        .open(path)
33}
34
35/// Open for reading without blocking on a FIFO, so its type can be checked first.
36pub fn open_nonblocking(path: &Path) -> io::Result<File> {
37    OpenOptions::new()
38        .read(true)
39        .custom_flags(OFlags::NONBLOCK.bits() as i32)
40        .open(path)
41}
42
43/// Open a directory by path, such as the root a scoped walk starts from.
44pub fn open_directory(path: &Path) -> io::Result<File> {
45    File::open(path)
46}
47
48/// One path component, ready for `openat`.
49pub struct EntryName(CString);
50
51impl EntryName {
52    pub fn new(name: &OsStr) -> Option<Self> {
53        let bytes = name.as_bytes();
54        (!bytes.is_empty() && !matches!(bytes, b"." | b"..") && !bytes.contains(&b'/'))
55            .then(|| CString::new(bytes).ok().map(Self))
56            .flatten()
57    }
58}
59
60/// Open one entry of a pinned directory read-only, without following a symlink.
61pub fn open_entry(directory: &File, name: &EntryName) -> io::Result<File> {
62    // NONBLOCK avoids waiting on a FIFO before its type can be rejected.
63    Ok(openat(
64        directory,
65        &name.0,
66        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
67        Mode::empty(),
68    )?
69    .into())
70}
71
72/// Whether `open_entry` failed because the entry is a symlink: `O_NOFOLLOW` reports `ELOOP`
73/// on Linux and macOS, and `EMLINK` on FreeBSD and DragonFly.
74pub fn is_link_refusal(error: &io::Error) -> bool {
75    let link = if cfg!(any(target_os = "freebsd", target_os = "dragonfly")) {
76        Errno::MLINK
77    } else {
78        Errno::LOOP
79    };
80    error.raw_os_error() == Some(link.raw_os_error())
81}
82
83/// The entries of a pinned directory, listed through its descriptor rather than a path
84/// that could have been replaced by a link.
85pub fn read_dir(directory: &File) -> io::Result<impl Iterator<Item = io::Result<DirEntry<'_>>>> {
86    Ok(ReadDir {
87        stream: open_scan(directory)?,
88        directory,
89        state: Scan::Reading,
90    })
91}
92
93fn open_scan(directory: &File) -> io::Result<Dir> {
94    // Open a new description, not dup: directory offsets must be independent across scans.
95    let fd = openat(
96        directory,
97        c".",
98        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
99        Mode::empty(),
100    )?;
101    Ok(Dir::new(fd)?)
102}
103
104/// A failed or exhausted stream never reads the directory again.
105#[derive(Clone, Copy, PartialEq, Eq)]
106enum Scan {
107    Reading,
108    Done,
109}
110
111struct ReadDir<'a> {
112    stream: Dir,
113    directory: &'a File,
114    state: Scan,
115}
116
117impl<'a> Iterator for ReadDir<'a> {
118    type Item = io::Result<DirEntry<'a>>;
119
120    fn next(&mut self) -> Option<Self::Item> {
121        while self.state == Scan::Reading {
122            let entry = match self.stream.next() {
123                Some(Ok(entry)) => entry,
124                Some(Err(error)) => {
125                    self.state = Scan::Done;
126                    return Some(Err(error.into()));
127                }
128                None => {
129                    self.state = Scan::Done;
130                    return None;
131                }
132            };
133            let name = entry.file_name().to_bytes();
134            if name == b"." || name == b".." {
135                continue;
136            }
137            return Some(Ok(DirEntry {
138                directory: self.directory,
139                name: OsStr::from_bytes(name).to_owned(),
140            }));
141        }
142        None
143    }
144}
145
146pub struct DirEntry<'a> {
147    directory: &'a File,
148    name: OsString,
149}
150
151impl DirEntry<'_> {
152    pub fn file_name(&self) -> OsString {
153        self.name.clone()
154    }
155
156    pub fn file_type(&self) -> io::Result<FileKind> {
157        entry_kind(self.directory, &self.name)
158    }
159}
160
161/// The type of one entry of a pinned directory, without following it.
162pub fn entry_kind(directory: &File, name: &OsStr) -> io::Result<FileKind> {
163    let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
164    // Inspect the entry itself, never its target.
165    let stat = statat(directory, &name.0, AtFlags::SYMLINK_NOFOLLOW)?;
166    Ok(match FileType::from_raw_mode(stat.st_mode) {
167        FileType::RegularFile => FileKind::File,
168        FileType::Directory => FileKind::Directory,
169        FileType::Symlink => FileKind::Symlink,
170        _ => FileKind::Other,
171    })
172}
173
174/// Verify the spelling the filesystem enumerates and that it names the opened file.
175/// The descriptor path is not enough: case-folded filesystems can cache lookup spellings.
176#[cfg(not(target_os = "macos"))]
177pub fn exact_name(directory: &File, file: &File, name: &OsStr) -> io::Result<bool> {
178    let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
179    let scan = open_scan(directory)?;
180    for entry in scan {
181        if entry?.file_name() == name.0.as_c_str() {
182            let opened = rustix::fs::fstat(file)?;
183            let listed = statat(directory, &name.0, AtFlags::SYMLINK_NOFOLLOW)?;
184            return Ok((listed.st_dev, listed.st_ino) == (opened.st_dev, opened.st_ino));
185        }
186    }
187    Ok(false)
188}
189
190pub fn verified_path(_file: &File, root: &Path, names: &[&OsStr]) -> io::Result<PathBuf> {
191    let mut path = root.to_owned();
192    path.extend(names);
193    Ok(path)
194}
195
196/// Other callers use this volume hint only where the host exposes a case-policy query.
197#[cfg(not(target_os = "macos"))]
198pub fn case_sensitive(_directory: &File) -> io::Result<bool> {
199    Ok(true)
200}