Skip to main content

std/sys/fs/unix/
dir.rs

1use libc::{c_int, mkdirat, renameat, unlinkat};
2
3cfg_select! {
4    not(any(
5        all(target_os = "linux", not(target_env = "musl")),
6        target_os = "l4re",
7        target_os = "android",
8        target_os = "hurd",
9    )) => {
10        use libc::{open as open64, openat as openat64};
11    }
12    _ => {
13        use libc::{open64, openat64};
14    }
15}
16
17use crate::ffi::CStr;
18use crate::os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd};
19#[cfg(target_family = "unix")]
20use crate::os::unix::io::{AsRawFd, FromRawFd};
21#[cfg(target_os = "wasi")]
22use crate::os::wasi::io::{AsRawFd, FromRawFd};
23use crate::path::Path;
24use crate::sys::fd::FileDesc;
25use crate::sys::fs::OpenOptions;
26use crate::sys::fs::unix::{File, FileAttr, debug_path_fd};
27use crate::sys::helpers::run_path_with_cstr;
28use crate::sys::{AsInner, FromInner, IntoInner, cvt, cvt_r};
29use crate::{fmt, fs, io};
30
31const TRAVERSE_DIRECTORY: i32 =
32    cfg_select! {
33        any(target_os = "freebsd", target_os = "aix") => libc::O_EXEC,
34        any(target_os = "linux", target_os = "android", target_os = "l4re") => libc::O_PATH,
35        target_os = "illumos" => libc::O_SEARCH,
36        _ => libc::O_RDONLY,
37    };
38
39pub struct Dir(OwnedFd);
40
41impl Dir {
42    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<Self> {
43        run_path_with_cstr(path, &|path| Self::open_with_c(path, opts))
44    }
45
46    pub fn open_for_traversal(path: &Path) -> io::Result<Self> {
47        run_path_with_cstr(path, &|path| Self::open_traversal_c(path))
48    }
49
50    pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
51        run_path_with_cstr(path.as_ref(), &|path| self.open_file_c(path, opts, 0))
52            .map(FileDesc::from_inner)
53            .map(File)
54    }
55
56    pub fn metadata(&self) -> io::Result<FileAttr> {
57        // Reuse the implementation for files, which should work for all FDs.
58        let fd = self.0.as_raw_fd();
59        let f = core::mem::ManuallyDrop::new(File(
60            // SAFETY: we borrowed `self` so the FD will not be closed while this function runs.
61            unsafe { FileDesc::from_raw_fd(fd) },
62        ));
63        f.file_attr()
64    }
65
66    pub fn remove_file(&self, path: &Path) -> io::Result<()> {
67        run_path_with_cstr(path, &|path| self.remove_c(path, false))
68    }
69
70    pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
71        run_path_with_cstr(from, &|from| {
72            run_path_with_cstr(to, &|to| self.rename_c(from, to_dir, to))
73        })
74    }
75
76    pub fn open_dir(&self, path: &Path, opts: &OpenOptions) -> io::Result<Self> {
77        run_path_with_cstr(path, &|path| self.open_file_c(path, opts, libc::O_DIRECTORY)).map(Self)
78    }
79
80    pub fn create_dir(&self, path: &Path) -> io::Result<()> {
81        run_path_with_cstr(path.as_ref(), &|path| self.create_dir_c(path))
82    }
83
84    pub fn remove_dir(&self, path: &Path) -> io::Result<()> {
85        run_path_with_cstr(path, &|path| self.remove_c(path, true))
86    }
87
88    fn open_with_c(path: &CStr, opts: &OpenOptions) -> io::Result<Self> {
89        let flags = libc::O_CLOEXEC
90            | libc::O_DIRECTORY
91            | opts.get_access_mode()?
92            | opts.get_creation_mode()?
93            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
94        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
95        Ok(Self(unsafe { OwnedFd::from_raw_fd(fd) }))
96    }
97
98    fn open_traversal_c(path: &CStr) -> io::Result<Self> {
99        let flags = libc::O_CLOEXEC | libc::O_DIRECTORY | TRAVERSE_DIRECTORY;
100        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, 0) })?;
101        Ok(Self(unsafe { OwnedFd::from_raw_fd(fd) }))
102    }
103
104    fn open_file_c(
105        &self,
106        path: &CStr,
107        opts: &OpenOptions,
108        extra_flags: c_int,
109    ) -> io::Result<OwnedFd> {
110        let flags = libc::O_CLOEXEC
111            | opts.get_access_mode()?
112            | opts.get_creation_mode()?
113            | (opts.custom_flags as c_int & !libc::O_ACCMODE)
114            | extra_flags;
115        let fd = cvt_r(|| unsafe {
116            openat64(self.0.as_raw_fd(), path.as_ptr(), flags, opts.mode as c_int)
117        })?;
118        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
119    }
120
121    fn remove_c(&self, path: &CStr, remove_dir: bool) -> io::Result<()> {
122        cvt(unsafe {
123            unlinkat(
124                self.0.as_raw_fd(),
125                path.as_ptr(),
126                if remove_dir { libc::AT_REMOVEDIR } else { 0 },
127            )
128        })
129        .map(|_| ())
130    }
131
132    fn rename_c(&self, from: &CStr, to_dir: &Self, to: &CStr) -> io::Result<()> {
133        cvt(unsafe {
134            renameat(self.0.as_raw_fd(), from.as_ptr(), to_dir.0.as_raw_fd(), to.as_ptr())
135        })
136        .map(|_| ())
137    }
138
139    fn create_dir_c(&self, path: &CStr) -> io::Result<()> {
140        cvt(unsafe { mkdirat(self.0.as_raw_fd(), path.as_ptr(), 0o777) }).map(|_| ())
141    }
142}
143
144impl fmt::Debug for Dir {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        let fd = self.0.as_raw_fd();
147        let mut b = debug_path_fd(fd, f, "Dir");
148        b.finish()
149    }
150}
151
152#[unstable(feature = "dirfd", issue = "120426")]
153impl AsRawFd for fs::Dir {
154    fn as_raw_fd(&self) -> RawFd {
155        self.as_inner().0.as_raw_fd()
156    }
157}
158
159#[unstable(feature = "dirfd", issue = "120426")]
160impl IntoRawFd for fs::Dir {
161    fn into_raw_fd(self) -> RawFd {
162        self.into_inner().0.into_raw_fd()
163    }
164}
165
166#[unstable(feature = "dirfd", issue = "120426")]
167impl FromRawFd for fs::Dir {
168    unsafe fn from_raw_fd(fd: RawFd) -> Self {
169        Self::from_inner(Dir(unsafe { FromRawFd::from_raw_fd(fd) }))
170    }
171}
172
173#[unstable(feature = "dirfd", issue = "120426")]
174impl AsFd for fs::Dir {
175    fn as_fd(&self) -> BorrowedFd<'_> {
176        self.as_inner().0.as_fd()
177    }
178}
179
180#[unstable(feature = "dirfd", issue = "120426")]
181impl From<fs::Dir> for OwnedFd {
182    fn from(value: fs::Dir) -> Self {
183        value.into_inner().0
184    }
185}
186
187#[unstable(feature = "dirfd", issue = "120426")]
188impl From<OwnedFd> for fs::Dir {
189    fn from(value: OwnedFd) -> Self {
190        Self::from_inner(Dir(value))
191    }
192}