cap_primitives/rustix/linux/fs/stat_impl.rs
1//! Linux has an `O_PATH` flag which allows opening a file without necessary
2//! having read or write access to it; we can use that with `openat2` and
3//! `fstat` to perform a fast sandboxed `stat`.
4
5use super::file_metadata::file_metadata;
6use crate::fs::{manually, open_beneath, FollowSymlinks, Metadata, OpenOptions};
7use rustix::fs::OFlags;
8use std::path::Path;
9use std::{fs, io};
10
11/// Use `openat2` with `O_PATH` and `fstat`. If that's not available, fallback
12/// to `manually::stat`.
13pub(crate) fn stat_impl(
14 start: &fs::File,
15 path: &Path,
16 follow: FollowSymlinks,
17) -> io::Result<Metadata> {
18 use crate::fs::{stat_unchecked, OpenOptionsExt};
19 use std::path::Component;
20
21 // Optimization: if path has exactly one component and it's not ".." or
22 // anything non-normal and we're not following symlinks we can go straight
23 // to `stat_unchecked`, which is faster than doing an open with a separate
24 // `fstat`.
25 if follow == FollowSymlinks::No {
26 let mut components = path.components();
27 if let Some(Component::Normal(component)) = components.next() {
28 if components.next().is_none() {
29 return stat_unchecked(start, component.as_ref(), FollowSymlinks::No);
30 }
31 }
32 }
33
34 // Open the path with `O_PATH`. Use `read(true)` even though we don't need
35 // `read` permissions, because Rust's libstd requires an access mode, and
36 // Linux ignores `O_RDONLY` with `O_PATH`.
37 let result = open_beneath(
38 start,
39 path,
40 OpenOptions::new()
41 .read(true)
42 .follow(follow)
43 .custom_flags(OFlags::PATH.bits() as i32),
44 );
45
46 // If that worked, call `fstat`.
47 match result {
48 Ok(file) => file_metadata(&file),
49 Err(err) => match rustix::io::Errno::from_io_error(&err) {
50 // `ENOSYS` from `open_beneath` means `openat2` is unavailable
51 // and we should use a fallback.
52 Some(rustix::io::Errno::NOSYS) => manually::stat(start, path, follow),
53 _ => Err(err),
54 },
55 }
56}