| 1 |
//! List directory contents |
| 2 |
|
| 3 |
use crate::errno::Errno; |
| 4 |
use crate::fcntl::{self, OFlag}; |
| 5 |
use crate::sys; |
| 6 |
use crate::{NixPath, Result}; |
| 7 |
use cfg_if::cfg_if; |
| 8 |
use std::ffi; |
| 9 |
use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; |
| 10 |
use std::ptr; |
| 11 |
|
| 12 |
#[cfg(target_os = "linux")] |
| 13 |
use libc::{dirent64 as dirent, readdir64_r as readdir_r}; |
| 14 |
|
| 15 |
#[cfg(not(target_os = "linux"))] |
| 16 |
use libc::{dirent, readdir_r}; |
| 17 |
|
| 18 |
/// An open directory. |
| 19 |
/// |
| 20 |
/// This is a lower-level interface than [`std::fs::ReadDir`]. Notable differences: |
| 21 |
/// * can be opened from a file descriptor (as returned by [`openat`][openat], |
| 22 |
/// perhaps before knowing if the path represents a file or directory). |
| 23 |
/// * implements [`AsFd`][AsFd], so it can be passed to [`fstat`][fstat], |
| 24 |
/// [`openat`][openat], etc. The file descriptor continues to be owned by the |
| 25 |
/// `Dir`, so callers must not keep a `RawFd` after the `Dir` is dropped. |
| 26 |
/// * can be iterated through multiple times without closing and reopening the file |
| 27 |
/// descriptor. Each iteration rewinds when finished. |
| 28 |
/// * returns entries for `.` (current directory) and `..` (parent directory). |
| 29 |
/// * returns entries' names as a [`CStr`][cstr] (no allocation or conversion beyond whatever libc |
| 30 |
/// does). |
| 31 |
/// |
| 32 |
/// [AsFd]: std::os::fd::AsFd |
| 33 |
/// [fstat]: crate::sys::stat::fstat |
| 34 |
/// [openat]: crate::fcntl::openat |
| 35 |
/// [cstr]: std::ffi::CStr |
| 36 |
/// |
| 37 |
/// # Examples |
| 38 |
/// |
| 39 |
/// Traverse the current directory, and print entries' names: |
| 40 |
/// |
| 41 |
/// ``` |
| 42 |
/// use nix::dir::Dir; |
| 43 |
/// use nix::fcntl::OFlag; |
| 44 |
/// use nix::sys::stat::Mode; |
| 45 |
/// |
| 46 |
/// let mut cwd = Dir::open(".", OFlag::O_RDONLY | OFlag::O_CLOEXEC, Mode::empty()).unwrap(); |
| 47 |
/// for res_entry in cwd.iter() { |
| 48 |
/// let entry = res_entry.unwrap(); |
| 49 |
/// println!("File name: {}", entry.file_name().to_string_lossy()); |
| 50 |
/// } |
| 51 |
/// ``` |
| 52 |
#[derive(Debug, Eq, Hash, PartialEq)] |
| 53 |
pub struct Dir(ptr::NonNull<libc::DIR>); |
| 54 |
|
| 55 |
impl Dir { |
| 56 |
/// Opens the given path as with `fcntl::open`. |
| 57 |
pub fn open<P: ?Sized + NixPath>( |
| 58 |
path: &P, |
| 59 |
oflag: OFlag, |
| 60 |
mode: sys::stat::Mode, |
| 61 |
) -> Result<Self> { |
| 62 |
let fd = fcntl::open(path, oflag, mode)?; |
| 63 |
Dir::from_fd(fd) |
| 64 |
} |
| 65 |
|
| 66 |
/// Opens the given path as with `fcntl::openat`. |
| 67 |
pub fn openat<Fd: std::os::fd::AsFd, P: ?Sized + NixPath>( |
| 68 |
dirfd: Fd, |
| 69 |
path: &P, |
| 70 |
oflag: OFlag, |
| 71 |
mode: sys::stat::Mode, |
| 72 |
) -> Result<Self> { |
| 73 |
let fd = fcntl::openat(dirfd, path, oflag, mode)?; |
| 74 |
Dir::from_fd(fd) |
| 75 |
} |
| 76 |
|
| 77 |
/// Converts from a descriptor-based object, closing the descriptor on success or failure. |
| 78 |
/// |
| 79 |
/// # Safety |
| 80 |
/// |
| 81 |
/// It is only safe if `fd` is an owned file descriptor. |
| 82 |
#[inline] |
| 83 |
#[deprecated( |
| 84 |
since = "0.30.0", |
| 85 |
note = "Deprecate this since it is not I/O-safe, use from_fd instead." |
| 86 |
)] |
| 87 |
pub unsafe fn from<F: IntoRawFd>(fd: F) -> Result<Self> { |
| 88 |
use std::os::fd::FromRawFd; |
| 89 |
use std::os::fd::OwnedFd; |
| 90 |
|
| 91 |
// SAFETY: |
| 92 |
// |
| 93 |
// This is indeed unsafe is `fd` it not an owned fd. |
| 94 |
let owned_fd = unsafe { OwnedFd::from_raw_fd(fd.into_raw_fd()) }; |
| 95 |
Dir::from_fd(owned_fd) |
| 96 |
} |
| 97 |
|
| 98 |
/// Converts from a file descriptor, closing it on failure. |
| 99 |
/// |
| 100 |
/// # Examples |
| 101 |
/// |
| 102 |
/// `ENOTDIR` would be returned if `fd` does not refer to a directory: |
| 103 |
/// |
| 104 |
/// ```should_panic |
| 105 |
/// use std::os::fd::OwnedFd; |
| 106 |
/// use nix::dir::Dir; |
| 107 |
/// |
| 108 |
/// let temp_file = tempfile::tempfile().unwrap(); |
| 109 |
/// let temp_file_fd: OwnedFd = temp_file.into(); |
| 110 |
/// let never = Dir::from_fd(temp_file_fd).unwrap(); |
| 111 |
/// ``` |
| 112 |
#[doc(alias("fdopendir"))] |
| 113 |
pub fn from_fd(fd: std::os::fd::OwnedFd) -> Result<Self> { |
| 114 |
// take the ownership as the constructed `Dir` is now the owner |
| 115 |
let raw_fd = fd.into_raw_fd(); |
| 116 |
let d = ptr::NonNull::new(unsafe { libc::fdopendir(raw_fd) }) |
| 117 |
.ok_or(Errno::last())?; |
| 118 |
Ok(Dir(d)) |
| 119 |
} |
| 120 |
|
| 121 |
/// Returns an iterator of `Result<Entry>` which rewinds when finished. |
| 122 |
pub fn iter(&mut self) -> Iter { |
| 123 |
Iter(self) |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
// `Dir` is not `Sync`. With the current implementation, it could be, but according to |
| 128 |
// https://www.gnu.org/software/libc/manual/html_node/Reading_002fClosing-Directory.html, |
| 129 |
// future versions of POSIX are likely to obsolete `readdir_r` and specify that it's unsafe to |
| 130 |
// call `readdir` simultaneously from multiple threads. |
| 131 |
// |
| 132 |
// `Dir` is safe to pass from one thread to another, as it's not reference-counted. |
| 133 |
unsafe impl Send for Dir {} |
| 134 |
|
| 135 |
impl std::os::fd::AsFd for Dir { |
| 136 |
fn as_fd(&self) -> std::os::fd::BorrowedFd { |
| 137 |
let raw_fd = self.as_raw_fd(); |
| 138 |
|
| 139 |
// SAFETY: |
| 140 |
// |
| 141 |
// `raw_fd` should be open and valid for the lifetime of the returned |
| 142 |
// `BorrowedFd` as it is extracted from `&self`. |
| 143 |
unsafe { std::os::fd::BorrowedFd::borrow_raw(raw_fd) } |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
impl AsRawFd for Dir { |
| 148 |
fn as_raw_fd(&self) -> RawFd { |
| 149 |
unsafe { libc::dirfd(self.0.as_ptr()) } |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
impl Drop for Dir { |
| 154 |
fn drop(&mut self) { |
| 155 |
let e = Errno::result(unsafe { libc::closedir(self.0.as_ptr()) }); |
| 156 |
if !std::thread::panicking() && e == Err(Errno::EBADF) { |
| 157 |
panic!("Closing an invalid file descriptor!"); |
| 158 |
}; |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
// The pass by mut is technically needless only because the inner NonNull is |
| 163 |
// Copy. But philosophically we're mutating the Dir, so we pass by mut. |
| 164 |
#[allow(clippy::needless_pass_by_ref_mut)] |
| 165 |
fn next(dir: &mut Dir) -> Option<Result<Entry>> { |
| 166 |
unsafe { |
| 167 |
// Note: POSIX specifies that portable applications should dynamically allocate a |
| 168 |
// buffer with room for a `d_name` field of size `pathconf(..., _PC_NAME_MAX)` plus 1 |
| 169 |
// for the NUL byte. It doesn't look like the std library does this; it just uses |
| 170 |
// fixed-sized buffers (and libc's dirent seems to be sized so this is appropriate). |
| 171 |
// Probably fine here too then. |
| 172 |
let mut ent = std::mem::MaybeUninit::<dirent>::uninit(); |
| 173 |
let mut result = ptr::null_mut(); |
| 174 |
if let Err(e) = Errno::result(readdir_r( |
| 175 |
dir.0.as_ptr(), |
| 176 |
ent.as_mut_ptr(), |
| 177 |
&mut result, |
| 178 |
)) { |
| 179 |
return Some(Err(e)); |
| 180 |
} |
| 181 |
if result.is_null() { |
| 182 |
return None; |
| 183 |
} |
| 184 |
assert_eq!(result, ent.as_mut_ptr()); |
| 185 |
Some(Ok(Entry(ent.assume_init()))) |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
/// Return type of [`Dir::iter`]. |
| 190 |
#[derive(Debug, Eq, Hash, PartialEq)] |
| 191 |
pub struct Iter<'d>(&'d mut Dir); |
| 192 |
|
| 193 |
impl Iterator for Iter<'_> { |
| 194 |
type Item = Result<Entry>; |
| 195 |
|
| 196 |
fn next(&mut self) -> Option<Self::Item> { |
| 197 |
next(self.0) |
| 198 |
} |
| 199 |
} |
| 200 |
|
| 201 |
impl Drop for Iter<'_> { |
| 202 |
fn drop(&mut self) { |
| 203 |
unsafe { libc::rewinddir((self.0).0.as_ptr()) } |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
/// The return type of [Dir::into_iter] |
| 208 |
#[derive(Debug, Eq, Hash, PartialEq)] |
| 209 |
pub struct OwningIter(Dir); |
| 210 |
|
| 211 |
impl Iterator for OwningIter { |
| 212 |
type Item = Result<Entry>; |
| 213 |
|
| 214 |
fn next(&mut self) -> Option<Self::Item> { |
| 215 |
next(&mut self.0) |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
/// The file descriptor continues to be owned by the `OwningIter`, |
| 220 |
/// so callers must not keep a `RawFd` after the `OwningIter` is dropped. |
| 221 |
impl AsRawFd for OwningIter { |
| 222 |
fn as_raw_fd(&self) -> RawFd { |
| 223 |
self.0.as_raw_fd() |
| 224 |
} |
| 225 |
} |
| 226 |
|
| 227 |
impl IntoIterator for Dir { |
| 228 |
type Item = Result<Entry>; |
| 229 |
type IntoIter = OwningIter; |
| 230 |
|
| 231 |
/// Creates a owning iterator, that is, one that takes ownership of the |
| 232 |
/// `Dir`. The `Dir` cannot be used after calling this. This can be useful |
| 233 |
/// when you have a function that both creates a `Dir` instance and returns |
| 234 |
/// an `Iterator`. |
| 235 |
/// |
| 236 |
/// Example: |
| 237 |
/// |
| 238 |
/// ``` |
| 239 |
/// use nix::{dir::Dir, fcntl::OFlag, sys::stat::Mode}; |
| 240 |
/// use std::{iter::Iterator, string::String}; |
| 241 |
/// |
| 242 |
/// fn ls_upper(dirname: &str) -> impl Iterator<Item=String> { |
| 243 |
/// let d = Dir::open(dirname, OFlag::O_DIRECTORY, Mode::S_IXUSR).unwrap(); |
| 244 |
/// d.into_iter().map(|x| x.unwrap().file_name().as_ref().to_string_lossy().to_ascii_uppercase()) |
| 245 |
/// } |
| 246 |
/// ``` |
| 247 |
fn into_iter(self) -> Self::IntoIter { |
| 248 |
OwningIter(self) |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
/// A directory entry, similar to `std::fs::DirEntry`. |
| 253 |
/// |
| 254 |
/// Note that unlike the std version, this may represent the `.` or `..` entries. |
| 255 |
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] |
| 256 |
#[repr(transparent)] |
| 257 |
pub struct Entry(dirent); |
| 258 |
|
| 259 |
/// Type of file referenced by a directory entry |
| 260 |
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] |
| 261 |
pub enum Type { |
| 262 |
/// FIFO (Named pipe) |
| 263 |
Fifo, |
| 264 |
/// Character device |
| 265 |
CharacterDevice, |
| 266 |
/// Directory |
| 267 |
Directory, |
| 268 |
/// Block device |
| 269 |
BlockDevice, |
| 270 |
/// Regular file |
| 271 |
File, |
| 272 |
/// Symbolic link |
| 273 |
Symlink, |
| 274 |
/// Unix-domain socket |
| 275 |
Socket, |
| 276 |
} |
| 277 |
|
| 278 |
impl Entry { |
| 279 |
/// Returns the inode number (`d_ino`) of the underlying `dirent`. |
| 280 |
#[allow(clippy::useless_conversion)] // Not useless on all OSes |
| 281 |
// The cast is not unnecessary on all platforms. |
| 282 |
#[allow(clippy::unnecessary_cast)] |
| 283 |
pub fn ino(&self) -> u64 { |
| 284 |
cfg_if! { |
| 285 |
if #[cfg(any(target_os = "aix", |
| 286 |
target_os = "emscripten", |
| 287 |
target_os = "fuchsia", |
| 288 |
target_os = "haiku", |
| 289 |
target_os = "hurd", |
| 290 |
target_os = "cygwin", |
| 291 |
solarish, |
| 292 |
linux_android, |
| 293 |
apple_targets))] { |
| 294 |
self.0.d_ino as u64 |
| 295 |
} else { |
| 296 |
u64::from(self.0.d_fileno) |
| 297 |
} |
| 298 |
} |
| 299 |
} |
| 300 |
|
| 301 |
/// Returns the bare file name of this directory entry without any other leading path component. |
| 302 |
pub fn file_name(&self) -> &ffi::CStr { |
| 303 |
unsafe { ffi::CStr::from_ptr(self.0.d_name.as_ptr()) } |
| 304 |
} |
| 305 |
|
| 306 |
/// Returns the type of this directory entry, if known. |
| 307 |
/// |
| 308 |
/// See platform `readdir(3)` or `dirent(5)` manpage for when the file type is known; |
| 309 |
/// notably, some Linux filesystems don't implement this. The caller should use `stat` or |
| 310 |
/// `fstat` if this returns `None`. |
| 311 |
pub fn file_type(&self) -> Option<Type> { |
| 312 |
#[cfg(not(any(solarish, target_os = "aix", target_os = "haiku")))] |
| 313 |
match self.0.d_type { |
| 314 |
libc::DT_FIFO => Some(Type::Fifo), |
| 315 |
libc::DT_CHR => Some(Type::CharacterDevice), |
| 316 |
libc::DT_DIR => Some(Type::Directory), |
| 317 |
libc::DT_BLK => Some(Type::BlockDevice), |
| 318 |
libc::DT_REG => Some(Type::File), |
| 319 |
libc::DT_LNK => Some(Type::Symlink), |
| 320 |
libc::DT_SOCK => Some(Type::Socket), |
| 321 |
/* libc::DT_UNKNOWN | */ _ => None, |
| 322 |
} |
| 323 |
|
| 324 |
// illumos, Solaris, and Haiku systems do not have the d_type member at all: |
| 325 |
#[cfg(any(solarish, target_os = "aix", target_os = "haiku"))] |
| 326 |
None |
| 327 |
} |
| 328 |
} |