artifactize_foundation/platform/files/
unix.rs1use 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
23pub fn canonicalize(path: &Path) -> io::Result<PathBuf> {
25 fs::canonicalize(path)
26}
27
28pub 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
38pub(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
58pub 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
66pub 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
74pub 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
86pub fn open_entry(directory: &File, name: &EntryName) -> io::Result<File> {
88 Ok(openat(
90 directory,
91 &name.0,
92 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
93 Mode::empty(),
94 )?
95 .into())
96}
97
98pub 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
109pub 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 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#[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
187pub fn entry_kind(directory: &File, name: &OsStr) -> io::Result<FileKind> {
189 let name = EntryName::new(name).ok_or(io::ErrorKind::InvalidInput)?;
190 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#[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#[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 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#[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#[cfg(not(any(target_os = "linux", target_os = "macos")))]
252pub fn case_sensitive(_directory: &File) -> io::Result<bool> {
253 Ok(false)
254}