rustix 1.1.3

Safe Rust bindings to POSIX/Unix/Linux/Winsock-like syscalls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#[cfg(not(any(
    solarish,
    target_os = "aix",
    target_os = "haiku",
    target_os = "nto",
    target_os = "vita"
)))]
use super::types::FileType;
use crate::backend::c;
use crate::backend::conv::owned_fd;
use crate::fd::{AsFd, BorrowedFd, OwnedFd};
use crate::ffi::{CStr, CString};
use crate::fs::{fcntl_getfl, openat, Mode, OFlags};
#[cfg(not(target_os = "vita"))]
use crate::fs::{fstat, Stat};
#[cfg(not(any(
    solarish,
    target_os = "haiku",
    target_os = "horizon",
    target_os = "netbsd",
    target_os = "nto",
    target_os = "redox",
    target_os = "vita",
    target_os = "wasi",
)))]
use crate::fs::{fstatfs, StatFs};
#[cfg(not(any(solarish, target_os = "vita", target_os = "wasi")))]
use crate::fs::{fstatvfs, StatVfs};
use crate::io;
#[cfg(not(any(target_os = "fuchsia", target_os = "vita", target_os = "wasi")))]
#[cfg(feature = "process")]
use crate::process::fchdir;
use alloc::borrow::ToOwned as _;
#[cfg(not(any(linux_like, target_os = "hurd")))]
use c::readdir as libc_readdir;
#[cfg(any(linux_like, target_os = "hurd"))]
use c::readdir64 as libc_readdir;
use core::fmt;
use core::ptr::NonNull;
use libc_errno::{errno, set_errno, Errno};

/// `DIR*`
pub struct Dir {
    /// The `libc` `DIR` pointer.
    libc_dir: NonNull<c::DIR>,

    /// Have we seen any errors in this iteration?
    any_errors: bool,
}

impl Dir {
    /// Take ownership of `fd` and construct a `Dir` that reads entries from
    /// the given directory file descriptor.
    #[inline]
    pub fn new<Fd: Into<OwnedFd>>(fd: Fd) -> io::Result<Self> {
        Self::_new(fd.into())
    }

    #[inline]
    fn _new(fd: OwnedFd) -> io::Result<Self> {
        let raw = owned_fd(fd);
        unsafe {
            let libc_dir = c::fdopendir(raw);

            if let Some(libc_dir) = NonNull::new(libc_dir) {
                Ok(Self {
                    libc_dir,
                    any_errors: false,
                })
            } else {
                let err = io::Errno::last_os_error();
                let _ = c::close(raw);
                Err(err)
            }
        }
    }

    /// Returns the file descriptor associated with the directory stream.
    ///
    /// The file descriptor is used internally by the directory stream. As a result, it is useful
    /// only for functions which do not depend or alter the file position.
    ///
    /// # References
    ///
    ///   - [POSIX]
    ///
    /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/dirfd.html
    #[inline]
    #[doc(alias = "dirfd")]
    pub fn fd<'a>(&'a self) -> io::Result<BorrowedFd<'a>> {
        let raw_fd = unsafe { c::dirfd(self.libc_dir.as_ptr()) };
        if raw_fd < 0 {
            Err(io::Errno::last_os_error())
        } else {
            Ok(unsafe { BorrowedFd::borrow_raw(raw_fd) })
        }
    }

    /// Borrow `fd` and construct a `Dir` that reads entries from the given
    /// directory file descriptor.
    #[inline]
    pub fn read_from<Fd: AsFd>(fd: Fd) -> io::Result<Self> {
        Self::_read_from(fd.as_fd())
    }

    #[inline]
    #[allow(unused_mut)]
    fn _read_from(fd: BorrowedFd<'_>) -> io::Result<Self> {
        let mut any_errors = false;

        // Given an arbitrary `OwnedFd`, it's impossible to know whether the
        // user holds a `dup`'d copy which could continue to modify the
        // file description state, which would cause Undefined Behavior after
        // our call to `fdopendir`. To prevent this, we obtain an independent
        // `OwnedFd`.
        let flags = fcntl_getfl(fd)?;
        let fd_for_dir = match openat(fd, cstr!("."), flags | OFlags::CLOEXEC, Mode::empty()) {
            Ok(fd) => fd,
            #[cfg(not(target_os = "wasi"))]
            Err(io::Errno::NOENT) => {
                // If "." doesn't exist, it means the directory was removed.
                // We treat that as iterating through a directory with no
                // entries.
                any_errors = true;
                crate::io::dup(fd)?
            }
            Err(err) => return Err(err),
        };

        let raw = owned_fd(fd_for_dir);
        unsafe {
            let libc_dir = c::fdopendir(raw);

            if let Some(libc_dir) = NonNull::new(libc_dir) {
                Ok(Self {
                    libc_dir,
                    any_errors,
                })
            } else {
                let err = io::Errno::last_os_error();
                let _ = c::close(raw);
                Err(err)
            }
        }
    }

    /// `rewinddir(self)`
    #[inline]
    pub fn rewind(&mut self) {
        self.any_errors = false;
        unsafe { c::rewinddir(self.libc_dir.as_ptr()) }
    }

    /// `seekdir(self, offset)`
    ///
    /// This function is only available on 64-bit platforms because it's
    /// implemented using [`libc::seekdir`] which only supports offsets that
    /// fit in a `c_long`.
    ///
    /// [`libc::seekdir`]: https://docs.rs/libc/*/arm-unknown-linux-gnueabihf/libc/fn.seekdir.html
    #[cfg(target_pointer_width = "64")]
    #[cfg_attr(docsrs, doc(cfg(target_pointer_width = "64")))]
    #[doc(alias = "seekdir")]
    #[inline]
    pub fn seek(&mut self, offset: i64) -> io::Result<()> {
        self.any_errors = false;
        unsafe { c::seekdir(self.libc_dir.as_ptr(), offset) }
        Ok(())
    }

    /// `readdir(self)`, where `None` means the end of the directory.
    pub fn read(&mut self) -> Option<io::Result<DirEntry>> {
        // If we've seen errors, don't continue to try to read anything
        // further.
        if self.any_errors {
            return None;
        }

        set_errno(Errno(0));
        let dirent_ptr = unsafe { libc_readdir(self.libc_dir.as_ptr()) };
        if dirent_ptr.is_null() {
            let curr_errno = errno().0;
            if curr_errno == 0 {
                // We successfully reached the end of the stream.
                None
            } else {
                // `errno` is unknown or non-zero, so an error occurred.
                self.any_errors = true;
                Some(Err(io::Errno(curr_errno)))
            }
        } else {
            // We successfully read an entry.
            unsafe {
                let dirent = &*dirent_ptr;

                // We have our own copy of OpenBSD's dirent; check that the
                // layout minimally matches libc's.
                #[cfg(target_os = "openbsd")]
                check_dirent_layout(dirent);

                let result = DirEntry {
                    #[cfg(not(any(
                        solarish,
                        target_os = "aix",
                        target_os = "haiku",
                        target_os = "nto",
                        target_os = "vita"
                    )))]
                    d_type: dirent.d_type,

                    #[cfg(not(any(freebsdlike, netbsdlike, target_os = "vita")))]
                    d_ino: dirent.d_ino,

                    #[cfg(any(
                        linux_like,
                        solarish,
                        target_os = "fuchsia",
                        target_os = "hermit",
                        target_os = "openbsd",
                        target_os = "redox"
                    ))]
                    d_off: dirent.d_off,

                    #[cfg(any(freebsdlike, netbsdlike))]
                    d_fileno: dirent.d_fileno,

                    name: CStr::from_ptr(dirent.d_name.as_ptr().cast()).to_owned(),
                };

                Some(Ok(result))
            }
        }
    }

    /// `fstat(self)`
    #[cfg(not(any(target_os = "horizon", target_os = "vita")))]
    #[inline]
    pub fn stat(&self) -> io::Result<Stat> {
        fstat(unsafe { BorrowedFd::borrow_raw(c::dirfd(self.libc_dir.as_ptr())) })
    }

    /// `fstatfs(self)`
    #[cfg(not(any(
        solarish,
        target_os = "haiku",
        target_os = "horizon",
        target_os = "netbsd",
        target_os = "nto",
        target_os = "redox",
        target_os = "vita",
        target_os = "wasi",
    )))]
    #[inline]
    pub fn statfs(&self) -> io::Result<StatFs> {
        fstatfs(unsafe { BorrowedFd::borrow_raw(c::dirfd(self.libc_dir.as_ptr())) })
    }

    /// `fstatvfs(self)`
    #[cfg(not(any(
        solarish,
        target_os = "horizon",
        target_os = "vita",
        target_os = "wasi"
    )))]
    #[inline]
    pub fn statvfs(&self) -> io::Result<StatVfs> {
        fstatvfs(unsafe { BorrowedFd::borrow_raw(c::dirfd(self.libc_dir.as_ptr())) })
    }

    /// `fchdir(self)`
    #[cfg(feature = "process")]
    #[cfg(not(any(
        target_os = "fuchsia",
        target_os = "horizon",
        target_os = "vita",
        target_os = "wasi"
    )))]
    #[cfg_attr(docsrs, doc(cfg(feature = "process")))]
    #[inline]
    pub fn chdir(&self) -> io::Result<()> {
        fchdir(unsafe { BorrowedFd::borrow_raw(c::dirfd(self.libc_dir.as_ptr())) })
    }
}

/// `Dir` is `Send` and `Sync`, because even though it contains internal
/// state, all methods that modify the state require a `mut &self` and
/// can therefore not be called concurrently. Calling them from different
/// threads sequentially is fine.
unsafe impl Send for Dir {}
unsafe impl Sync for Dir {}

impl Drop for Dir {
    #[inline]
    fn drop(&mut self) {
        unsafe { c::closedir(self.libc_dir.as_ptr()) };
    }
}

impl Iterator for Dir {
    type Item = io::Result<DirEntry>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Self::read(self)
    }
}

impl fmt::Debug for Dir {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("Dir");
        #[cfg(not(any(target_os = "horizon", target_os = "vita")))]
        s.field("fd", unsafe { &c::dirfd(self.libc_dir.as_ptr()) });
        s.finish()
    }
}

/// `struct dirent`
#[derive(Debug)]
pub struct DirEntry {
    #[cfg(not(any(
        solarish,
        target_os = "aix",
        target_os = "haiku",
        target_os = "nto",
        target_os = "vita"
    )))]
    d_type: u8,

    #[cfg(not(any(freebsdlike, netbsdlike, target_os = "vita")))]
    d_ino: c::ino_t,

    #[cfg(any(freebsdlike, netbsdlike))]
    d_fileno: c::ino_t,

    name: CString,

    #[cfg(any(
        linux_like,
        solarish,
        target_os = "fuchsia",
        target_os = "hermit",
        target_os = "openbsd",
        target_os = "redox"
    ))]
    d_off: c::off_t,
}

impl DirEntry {
    /// Returns the file name of this directory entry.
    #[inline]
    pub fn file_name(&self) -> &CStr {
        &self.name
    }

    /// Returns the “offset” of this directory entry. This is not a true
    /// numerical offset but an opaque cookie that identifies a position in the
    /// given stream.
    #[cfg(any(
        linux_like,
        solarish,
        target_os = "fuchsia",
        target_os = "hermit",
        target_os = "openbsd",
        target_os = "redox"
    ))]
    #[inline]
    pub fn offset(&self) -> i64 {
        self.d_off as i64
    }

    /// Returns the type of this directory entry.
    #[cfg(not(any(
        solarish,
        target_os = "aix",
        target_os = "haiku",
        target_os = "nto",
        target_os = "vita"
    )))]
    #[inline]
    pub fn file_type(&self) -> FileType {
        FileType::from_dirent_d_type(self.d_type)
    }

    /// Return the inode number of this directory entry.
    #[cfg(not(any(freebsdlike, netbsdlike, target_os = "vita")))]
    #[inline]
    pub fn ino(&self) -> u64 {
        self.d_ino as u64
    }

    /// Return the inode number of this directory entry.
    #[cfg(any(freebsdlike, netbsdlike))]
    #[inline]
    pub fn ino(&self) -> u64 {
        #[allow(clippy::useless_conversion)]
        self.d_fileno.into()
    }
}

/// libc's OpenBSD `dirent` has a private field so we can't construct it
/// directly, so we declare it ourselves to make all fields accessible.
#[cfg(target_os = "openbsd")]
#[repr(C)]
#[derive(Debug)]
struct libc_dirent {
    d_fileno: c::ino_t,
    d_off: c::off_t,
    d_reclen: u16,
    d_type: u8,
    d_namlen: u8,
    __d_padding: [u8; 4],
    d_name: [c::c_char; 256],
}

/// We have our own copy of OpenBSD's dirent; check that the layout
/// minimally matches libc's.
#[cfg(target_os = "openbsd")]
fn check_dirent_layout(dirent: &c::dirent) {
    use crate::utils::as_ptr;

    // Check that the basic layouts match.
    #[cfg(test)]
    {
        assert_eq_size!(libc_dirent, c::dirent);
        assert_eq_size!(libc_dirent, c::dirent);
    }

    // Check that the field offsets match.
    assert_eq!(
        {
            let z = libc_dirent {
                d_fileno: 0_u64,
                d_off: 0_i64,
                d_reclen: 0_u16,
                d_type: 0_u8,
                d_namlen: 0_u8,
                __d_padding: [0_u8; 4],
                d_name: [0 as c::c_char; 256],
            };
            let base = as_ptr(&z) as usize;
            (
                (as_ptr(&z.d_fileno) as usize) - base,
                (as_ptr(&z.d_off) as usize) - base,
                (as_ptr(&z.d_reclen) as usize) - base,
                (as_ptr(&z.d_type) as usize) - base,
                (as_ptr(&z.d_namlen) as usize) - base,
                (as_ptr(&z.d_name) as usize) - base,
            )
        },
        {
            let z = dirent;
            let base = as_ptr(z) as usize;
            (
                (as_ptr(&z.d_fileno) as usize) - base,
                (as_ptr(&z.d_off) as usize) - base,
                (as_ptr(&z.d_reclen) as usize) - base,
                (as_ptr(&z.d_type) as usize) - base,
                (as_ptr(&z.d_namlen) as usize) - base,
                (as_ptr(&z.d_name) as usize) - base,
            )
        }
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dir_iterator_handles_io_errors() {
        // create a dir, keep the FD, then delete the dir
        let tmp = tempfile::tempdir().unwrap();
        let fd = crate::fs::openat(
            crate::fs::CWD,
            tmp.path(),
            crate::fs::OFlags::RDONLY | crate::fs::OFlags::CLOEXEC,
            crate::fs::Mode::empty(),
        )
        .unwrap();

        let file_fd = crate::fs::openat(
            &fd,
            tmp.path().join("test.txt"),
            crate::fs::OFlags::WRONLY | crate::fs::OFlags::CREATE,
            crate::fs::Mode::RWXU,
        )
        .unwrap();

        let mut dir = Dir::read_from(&fd).unwrap();

        // Reach inside the `Dir` and replace its directory with a file, which
        // will cause the subsequent `readdir` to fail.
        unsafe {
            let raw_fd = c::dirfd(dir.libc_dir.as_ptr());
            let mut owned_fd: crate::fd::OwnedFd = crate::fd::FromRawFd::from_raw_fd(raw_fd);
            crate::io::dup2(&file_fd, &mut owned_fd).unwrap();
            core::mem::forget(owned_fd);
        }

        // FreeBSD and macOS seem to read some directory entries before we call
        // `.next()`.
        #[cfg(any(apple, freebsdlike))]
        {
            dir.rewind();
        }

        assert!(matches!(dir.next(), Some(Err(_))));
        assert!(dir.next().is_none());
    }
}