|
| 1 | +//! Raw directory iteration using Linux's getdents syscall |
| 2 | +
|
| 3 | +use crate::errno::Errno; |
| 4 | +use crate::file_type::FileType; |
| 5 | +use std::cmp::max; |
| 6 | +use std::ffi::CStr; |
| 7 | +use std::mem::MaybeUninit; |
| 8 | +use std::os::unix::io::AsFd; |
| 9 | +use std::{mem, slice}; |
| 10 | + |
| 11 | +/// A directory iterator implemented with getdents. |
| 12 | +/// |
| 13 | +/// This implementation: |
| 14 | +/// - Excludes deleted inodes (with ID 0). |
| 15 | +/// - Does not handle growing the buffer. If this functionality is necessary, |
| 16 | +/// you'll need to drop the current iterator, resize the buffer, and then |
| 17 | +/// re-create the iterator. The iterator is guaranteed to continue where it |
| 18 | +/// left off provided the file descriptor isn't changed. See the example in |
| 19 | +/// [`RawDir::new`]. |
| 20 | +#[derive(Debug)] |
| 21 | +pub struct RawDir<'buf, Fd: AsFd> { |
| 22 | + fd: Fd, |
| 23 | + buf: &'buf mut [MaybeUninit<u8>], |
| 24 | + initialized: usize, |
| 25 | + offset: usize, |
| 26 | +} |
| 27 | + |
| 28 | +impl<'buf, Fd: AsFd> RawDir<'buf, Fd> { |
| 29 | + /// Create a new iterator from the given file descriptor and buffer. |
| 30 | + /// |
| 31 | + /// # Examples |
| 32 | + /// |
| 33 | + /// ``` |
| 34 | + /// # use std::mem::MaybeUninit; |
| 35 | + /// # use std::os::unix::io::{AsFd, FromRawFd, OwnedFd}; |
| 36 | + /// # use nix::dents::RawDir; |
| 37 | + /// # use nix::errno::Errno; |
| 38 | + /// # use nix::fcntl::{OFlag, open, openat}; |
| 39 | + /// # use nix::sys::stat::Mode; |
| 40 | + /// |
| 41 | + /// let fd = open(".", OFlag::O_RDONLY | OFlag::O_DIRECTORY, Mode::empty()).unwrap(); |
| 42 | + /// let fd = unsafe { OwnedFd::from_raw_fd(fd) }; |
| 43 | + /// |
| 44 | + /// let mut buf = [MaybeUninit::uninit(); 2048]; |
| 45 | + /// |
| 46 | + /// for entry in RawDir::new(fd, &mut buf) { |
| 47 | + /// let entry = entry.unwrap(); |
| 48 | + /// dbg!(&entry); |
| 49 | + /// } |
| 50 | + /// ``` |
| 51 | + /// |
| 52 | + /// Contrived example that demonstrates reading entries with arbitrarily large file paths: |
| 53 | + /// |
| 54 | + /// ``` |
| 55 | + /// # use std::cmp::max; |
| 56 | + /// # use std::mem::MaybeUninit; |
| 57 | + /// # use std::os::unix::io::{AsFd, FromRawFd, OwnedFd}; |
| 58 | + /// # use nix::dents::RawDir; |
| 59 | + /// # use nix::errno::Errno; |
| 60 | + /// # use nix::fcntl::{OFlag, open, openat}; |
| 61 | + /// # use nix::sys::stat::Mode; |
| 62 | + /// |
| 63 | + /// let fd = open(".", OFlag::O_RDONLY | OFlag::O_DIRECTORY, Mode::empty()).unwrap(); |
| 64 | + /// let fd = unsafe { OwnedFd::from_raw_fd(fd) }; |
| 65 | + /// |
| 66 | + /// // DO NOT DO THIS. Use `Vec::with_capacity` to at least start the buffer |
| 67 | + /// // off with *some* space. |
| 68 | + /// let mut buf = Vec::new(); |
| 69 | + /// |
| 70 | + /// 'read: loop { |
| 71 | + /// 'resize: { |
| 72 | + /// for entry in RawDir::new(&fd, buf.spare_capacity_mut()) { |
| 73 | + /// let entry = match entry { |
| 74 | + /// Err(Errno::EINVAL) => break 'resize, |
| 75 | + /// r => r.unwrap(), |
| 76 | + /// }; |
| 77 | + /// dbg!(&entry); |
| 78 | + /// } |
| 79 | + /// break 'read; |
| 80 | + /// } |
| 81 | + /// |
| 82 | + /// let new_capacity = max(buf.capacity() * 2, 1); |
| 83 | + /// buf.reserve(new_capacity); |
| 84 | + /// } |
| 85 | + /// ``` |
| 86 | + /// |
| 87 | + /// Note that this is horribly inefficient as we'll most likely end up doing ~1 syscall per file. |
| 88 | + pub fn new(fd: Fd, buf: &'buf mut [MaybeUninit<u8>]) -> Self { |
| 89 | + Self { |
| 90 | + fd, |
| 91 | + buf, |
| 92 | + initialized: 0, |
| 93 | + offset: 0, |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +/// A raw directory entry, similar to `std::fs::DirEntry`. |
| 99 | +/// |
| 100 | +/// Note that unlike the std version, this may represent the `.` or `..` entries. |
| 101 | +#[derive(Debug)] |
| 102 | +#[allow(missing_docs)] |
| 103 | +pub struct RawDirEntry<'a> { |
| 104 | + pub inode_number: u64, |
| 105 | + pub file_type: FileType, |
| 106 | + pub name: &'a CStr, |
| 107 | +} |
| 108 | + |
| 109 | +#[repr(C, packed)] |
| 110 | +struct dirent64 { |
| 111 | + d_ino: libc::ino64_t, |
| 112 | + d_off: libc::off64_t, |
| 113 | + d_reclen: libc::c_ushort, |
| 114 | + d_type: libc::c_uchar, |
| 115 | +} |
| 116 | + |
| 117 | +impl<'buf, Fd: AsFd> Iterator for RawDir<'buf, Fd> { |
| 118 | + type Item = Result<RawDirEntry<'buf>, Errno>; |
| 119 | + |
| 120 | + fn next(&mut self) -> Option<Self::Item> { |
| 121 | + loop { |
| 122 | + if self.offset < self.initialized { |
| 123 | + let dirent_ptr = |
| 124 | + &self.buf[self.offset] as *const MaybeUninit<u8>; |
| 125 | + // Trust the kernel to use proper alignment |
| 126 | + #[allow(clippy::cast_ptr_alignment)] |
| 127 | + let dirent = unsafe { &*dirent_ptr.cast::<dirent64>() }; |
| 128 | + |
| 129 | + self.offset += dirent.d_reclen as usize; |
| 130 | + if dirent.d_ino == 0 { |
| 131 | + continue; |
| 132 | + } |
| 133 | + |
| 134 | + return Some(Ok(RawDirEntry { |
| 135 | + inode_number: dirent.d_ino, |
| 136 | + file_type: FileType::from(dirent.d_type), |
| 137 | + name: unsafe { |
| 138 | + let name_start = |
| 139 | + dirent_ptr.add(mem::size_of::<dirent64>()); |
| 140 | + let mut name_end = { |
| 141 | + // Find the last aligned byte of the file name so we can |
| 142 | + // start searching for NUL bytes. If we started searching |
| 143 | + // from the back, we would run into garbage left over from |
| 144 | + // previous iterations. |
| 145 | + // TODO use .map_addr() once strict_provenance is stable |
| 146 | + let addr = max( |
| 147 | + name_start as usize, |
| 148 | + dirent_ptr.add(dirent.d_reclen as usize - 1) |
| 149 | + as usize |
| 150 | + & !(mem::size_of::<usize>() - 1), |
| 151 | + ); |
| 152 | + addr as *const u8 |
| 153 | + }; |
| 154 | + |
| 155 | + while *name_end != 0 { |
| 156 | + name_end = name_end.add(1); |
| 157 | + } |
| 158 | + |
| 159 | + CStr::from_bytes_with_nul_unchecked( |
| 160 | + slice::from_raw_parts( |
| 161 | + name_start.cast::<u8>(), |
| 162 | + // Add 1 for the NUL byte |
| 163 | + // TODO use .addr() once strict_provenance is stable |
| 164 | + name_end as usize - name_start as usize + 1, |
| 165 | + ), |
| 166 | + ) |
| 167 | + }, |
| 168 | + })); |
| 169 | + } |
| 170 | + self.initialized = 0; |
| 171 | + self.offset = 0; |
| 172 | + |
| 173 | + match unsafe { |
| 174 | + Errno::result(libc::syscall( |
| 175 | + libc::SYS_getdents64, |
| 176 | + self.fd.as_fd(), |
| 177 | + self.buf.as_mut_ptr(), |
| 178 | + self.buf.len(), |
| 179 | + )) |
| 180 | + } { |
| 181 | + Ok(bytes_read) if bytes_read == 0 => return None, |
| 182 | + Ok(bytes_read) => self.initialized = bytes_read as usize, |
| 183 | + Err(e) => return Some(Err(e)), |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | +} |
0 commit comments