Struct cap_primitives::fs::Metadata

source ·
pub struct Metadata { /* private fields */ }
Expand description

Metadata information about a file.

This corresponds to std::fs::Metadata.

We need to define our own version because the libstd `Metadata` doesn't have a public constructor that we can use.

Implementations§

Constructs a new instance of Self from the given std::fs::File.

Examples found in repository?
src/rustix/fs/read_dir_inner.rs (line 83)
82
83
84
    pub(super) fn self_metadata(&self) -> io::Result<Metadata> {
        Metadata::from_file(&self.as_file_view())
    }
More examples
Hide additional examples
src/rustix/fs/is_root_dir.rs (line 5)
4
5
6
pub(crate) fn is_root_dir(dir: &fs::File, parent_iter: &ReadDir) -> io::Result<bool> {
    Ok(Metadata::from_file(dir)?.is_same_file(&parent_iter.inner.self_metadata()?))
}
src/rustix/fs/is_same_file.rs (line 7)
6
7
8
9
10
pub(crate) fn is_same_file(a: &fs::File, b: &fs::File) -> io::Result<bool> {
    let a_metadata = Metadata::from_file(a)?;
    let b_metadata = Metadata::from_file(b)?;
    is_same_file_metadata(&a_metadata, &b_metadata)
}
src/rustix/fs/remove_open_dir_by_searching.rs (line 9)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
pub(crate) fn remove_open_dir_by_searching(dir: fs::File) -> io::Result<()> {
    let metadata = Metadata::from_file(&dir)?;
    let mut iter = read_dir_unchecked(&dir, Component::ParentDir.as_ref(), FollowSymlinks::No)?;
    while let Some(child) = iter.next() {
        let child = child?;
        if child.is_same_file(&metadata)? {
            return child.remove_dir();
        }
    }

    // We didn't find the directory among its parent's children. Check for the
    // root directory and handle it specially -- removal will probably fail, so
    // we'll get the appropriate error code.
    if is_root_dir(&dir, &iter)? {
        fs::remove_dir(Component::RootDir.as_os_str())
    } else {
        Err(errors::no_such_file_or_directory())
    }
}
src/rustix/linux/fs/file_metadata.rs (line 15)
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
pub(super) fn file_metadata(file: &fs::File) -> io::Result<Metadata> {
    // Record whether we've seen an `EBADF` from an `fstat` on an `O_PATH`
    // file descriptor, meaning we're on a Linux that doesn't support it.
    static FSTAT_PATH_BADF: AtomicBool = AtomicBool::new(false);

    if !FSTAT_PATH_BADF.load(Relaxed) {
        match Metadata::from_file(file) {
            Ok(metadata) => return Ok(metadata),
            Err(err) => match rustix::io::Errno::from_io_error(&err) {
                // Before Linux 3.6, `fstat` with `O_PATH` returned `EBADF`.
                Some(rustix::io::Errno::BADF) => FSTAT_PATH_BADF.store(true, Relaxed),
                _ => return Err(err),
            },
        }
    }

    // If `fstat` with `O_PATH` isn't supported, use `statat` with `AT_EMPTY_PATH`.
    Ok(statat(file, "", AtFlags::EMPTY_PATH).map(MetadataExt::from_rustix)?)
}
src/fs/manually/open.rs (line 525)
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
pub(crate) fn stat(start: &fs::File, path: &Path, follow: FollowSymlinks) -> io::Result<Metadata> {
    // POSIX returns `ENOENT` on an empty path. TODO: On Windows, we should
    // be compatible with what Windows does instead.
    if path.as_os_str().is_empty() {
        return Err(errors::no_such_file_or_directory());
    }

    let mut options = OpenOptions::new();
    options.follow(follow);
    let mut symlink_count = 0;
    let mut ctx = Context::new(MaybeOwnedFile::borrowed(start), path, &options, None);
    assert!(!ctx.dir_precluded);

    while let Some(c) = ctx.components.pop() {
        match c {
            CowComponent::PrefixOrRootDir => return Err(errors::escape_attempt()),
            CowComponent::CurDir => ctx.cur_dir()?,
            CowComponent::ParentDir => ctx.parent_dir()?,
            CowComponent::Normal(one) => {
                if ctx.components.is_empty() {
                    // If this is the last component, do a non-following
                    // `stat_unchecked` on it.
                    let stat = stat_unchecked(&ctx.base, one.as_ref(), FollowSymlinks::No)?;

                    // If we weren't asked to follow symlinks, or it wasn't a
                    // symlink, we're done.
                    if options.follow == FollowSymlinks::No || !stat.file_type().is_symlink() {
                        if stat.is_dir() {
                            if ctx.dir_precluded {
                                return Err(errors::is_directory());
                            }
                        } else if ctx.dir_required {
                            return Err(errors::is_not_directory());
                        }
                        return Ok(stat);
                    }

                    // On Windows, symlinks know whether they are a file or
                    // directory.
                    #[cfg(windows)]
                    if stat.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
                        ctx.dir_required = true;
                    } else {
                        ctx.dir_precluded = true;
                    }

                    // If it was a symlink and we're asked to follow symlinks,
                    // dereference it.
                    ctx.symlink(&one, &mut symlink_count)?
                } else {
                    // Otherwise open the path component normally.
                    ctx.normal(&one, &options, &mut symlink_count)?
                }
            }
        }
    }

    // If the path ended in `.` (explicit or implied) or `..`, we may have
    // opened the directory with eg. `O_PATH` on Linux, or we may have skipped
    // checking for search access to `.`, so re-check it.
    if ctx.follow_with_dot {
        if ctx.dir_precluded {
            return Err(errors::is_directory());
        }

        ctx.check_dot_access()?;
    }

    // If the path ended in `.` or `..`, we already have it open, so just do
    // `.metadata()` on it.
    Metadata::from_file(&*ctx.base)
}

Constructs a new instance of Self from the given std::fs::Metadata.

As with the comments in std::fs::Metadata::volume_serial_number and nearby functions, some fields of the resulting metadata will be None.

Returns the file type for this metadata.

This corresponds to std::fs::Metadata::file_type.

Examples found in repository?
src/rustix/fs/remove_dir_all_impl.rs (line 12)
8
9
10
11
12
13
14
15
16
17
18
19
pub(crate) fn remove_dir_all_impl(start: &fs::File, path: &Path) -> io::Result<()> {
    // Code adapted from `remove_dir_all` in Rust's
    // library/std/src/sys_common/fs.rs at revision
    // 108e90ca78f052c0c1c49c42a22c85620be19712.
    let filetype = stat(start, path, FollowSymlinks::No)?.file_type();
    if filetype.is_symlink() {
        remove_file(start, path)
    } else {
        remove_dir_all_recursive(read_dir_nofollow(start, path)?)?;
        remove_dir(start, path)
    }
}
More examples
Hide additional examples
src/rustix/fs/open_unchecked.rs (line 49)
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
pub(crate) fn open_unchecked(
    start: &fs::File,
    path: &Path,
    options: &OpenOptions,
) -> Result<fs::File, OpenUncheckedError> {
    let oflags = compute_oflags(options).map_err(OpenUncheckedError::Other)?;

    #[allow(clippy::useless_conversion)]
    #[cfg(not(target_os = "wasi"))]
    let mode = Mode::from_bits_truncate(options.ext.mode as _);
    #[cfg(target_os = "wasi")]
    let mode = Mode::empty();

    let err = match openat(start, path, oflags, mode) {
        Ok(file) => {
            return Ok(fs::File::from(file));
        }
        Err(err) => err,
    };
    match err {
        // `ELOOP` is the POSIX standard and most widely used error code to
        // indicate that a symlink was found when `O_NOFOLLOW` was set.
        #[cfg(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd")))]
        io::Errno::LOOP => Err(OpenUncheckedError::Symlink(err.into(), ())),

        // FreeBSD and similar (but not Darwin) use `EMLINK`.
        #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
        io::Errno::MLINK => Err(OpenUncheckedError::Symlink(err.into(), ())),

        // NetBSD uses `EFTYPE`.
        #[cfg(any(target_os = "netbsd"))]
        io::Errno::FTYPE => Err(OpenUncheckedError::Symlink(err.into(), ())),

        io::Errno::NOENT => Err(OpenUncheckedError::NotFound(err.into())),
        io::Errno::NOTDIR => {
            if options.dir_required
                && stat_unchecked(start, path, options.follow)
                    .map(|m| m.file_type().is_symlink())
                    .unwrap_or(false)
            {
                Err(OpenUncheckedError::Symlink(err.into(), ()))
            } else {
                Err(OpenUncheckedError::NotFound(err.into()))
            }
        }
        _ => Err(OpenUncheckedError::Other(err.into())),
    }
}
src/fs/manually/open.rs (line 481)
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
pub(crate) fn stat(start: &fs::File, path: &Path, follow: FollowSymlinks) -> io::Result<Metadata> {
    // POSIX returns `ENOENT` on an empty path. TODO: On Windows, we should
    // be compatible with what Windows does instead.
    if path.as_os_str().is_empty() {
        return Err(errors::no_such_file_or_directory());
    }

    let mut options = OpenOptions::new();
    options.follow(follow);
    let mut symlink_count = 0;
    let mut ctx = Context::new(MaybeOwnedFile::borrowed(start), path, &options, None);
    assert!(!ctx.dir_precluded);

    while let Some(c) = ctx.components.pop() {
        match c {
            CowComponent::PrefixOrRootDir => return Err(errors::escape_attempt()),
            CowComponent::CurDir => ctx.cur_dir()?,
            CowComponent::ParentDir => ctx.parent_dir()?,
            CowComponent::Normal(one) => {
                if ctx.components.is_empty() {
                    // If this is the last component, do a non-following
                    // `stat_unchecked` on it.
                    let stat = stat_unchecked(&ctx.base, one.as_ref(), FollowSymlinks::No)?;

                    // If we weren't asked to follow symlinks, or it wasn't a
                    // symlink, we're done.
                    if options.follow == FollowSymlinks::No || !stat.file_type().is_symlink() {
                        if stat.is_dir() {
                            if ctx.dir_precluded {
                                return Err(errors::is_directory());
                            }
                        } else if ctx.dir_required {
                            return Err(errors::is_not_directory());
                        }
                        return Ok(stat);
                    }

                    // On Windows, symlinks know whether they are a file or
                    // directory.
                    #[cfg(windows)]
                    if stat.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
                        ctx.dir_required = true;
                    } else {
                        ctx.dir_precluded = true;
                    }

                    // If it was a symlink and we're asked to follow symlinks,
                    // dereference it.
                    ctx.symlink(&one, &mut symlink_count)?
                } else {
                    // Otherwise open the path component normally.
                    ctx.normal(&one, &options, &mut symlink_count)?
                }
            }
        }
    }

    // If the path ended in `.` (explicit or implied) or `..`, we may have
    // opened the directory with eg. `O_PATH` on Linux, or we may have skipped
    // checking for search access to `.`, so re-check it.
    if ctx.follow_with_dot {
        if ctx.dir_precluded {
            return Err(errors::is_directory());
        }

        ctx.check_dot_access()?;
    }

    // If the path ended in `.` or `..`, we already have it open, so just do
    // `.metadata()` on it.
    Metadata::from_file(&*ctx.base)
}

Returns true if this metadata is for a directory.

This corresponds to std::fs::Metadata::is_dir.

Examples found in repository?
src/fs/manually/open.rs (line 482)
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
pub(crate) fn stat(start: &fs::File, path: &Path, follow: FollowSymlinks) -> io::Result<Metadata> {
    // POSIX returns `ENOENT` on an empty path. TODO: On Windows, we should
    // be compatible with what Windows does instead.
    if path.as_os_str().is_empty() {
        return Err(errors::no_such_file_or_directory());
    }

    let mut options = OpenOptions::new();
    options.follow(follow);
    let mut symlink_count = 0;
    let mut ctx = Context::new(MaybeOwnedFile::borrowed(start), path, &options, None);
    assert!(!ctx.dir_precluded);

    while let Some(c) = ctx.components.pop() {
        match c {
            CowComponent::PrefixOrRootDir => return Err(errors::escape_attempt()),
            CowComponent::CurDir => ctx.cur_dir()?,
            CowComponent::ParentDir => ctx.parent_dir()?,
            CowComponent::Normal(one) => {
                if ctx.components.is_empty() {
                    // If this is the last component, do a non-following
                    // `stat_unchecked` on it.
                    let stat = stat_unchecked(&ctx.base, one.as_ref(), FollowSymlinks::No)?;

                    // If we weren't asked to follow symlinks, or it wasn't a
                    // symlink, we're done.
                    if options.follow == FollowSymlinks::No || !stat.file_type().is_symlink() {
                        if stat.is_dir() {
                            if ctx.dir_precluded {
                                return Err(errors::is_directory());
                            }
                        } else if ctx.dir_required {
                            return Err(errors::is_not_directory());
                        }
                        return Ok(stat);
                    }

                    // On Windows, symlinks know whether they are a file or
                    // directory.
                    #[cfg(windows)]
                    if stat.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
                        ctx.dir_required = true;
                    } else {
                        ctx.dir_precluded = true;
                    }

                    // If it was a symlink and we're asked to follow symlinks,
                    // dereference it.
                    ctx.symlink(&one, &mut symlink_count)?
                } else {
                    // Otherwise open the path component normally.
                    ctx.normal(&one, &options, &mut symlink_count)?
                }
            }
        }
    }

    // If the path ended in `.` (explicit or implied) or `..`, we may have
    // opened the directory with eg. `O_PATH` on Linux, or we may have skipped
    // checking for search access to `.`, so re-check it.
    if ctx.follow_with_dot {
        if ctx.dir_precluded {
            return Err(errors::is_directory());
        }

        ctx.check_dot_access()?;
    }

    // If the path ended in `.` or `..`, we already have it open, so just do
    // `.metadata()` on it.
    Metadata::from_file(&*ctx.base)
}

Returns true if this metadata is for a regular file.

This corresponds to std::fs::Metadata::is_file.

Returns true if this metadata is for a symbolic link.

This corresponds to std::fs::Metadata::is_symlink.

Returns the size of the file, in bytes, this metadata is for.

This corresponds to std::fs::Metadata::len.

Returns the permissions of the file this metadata is for.

This corresponds to std::fs::Metadata::permissions.

Returns the last modification time listed in this metadata.

This corresponds to std::fs::Metadata::modified.

Returns the last access time of this metadata.

This corresponds to std::fs::Metadata::accessed.

Returns the creation time listed in this metadata.

This corresponds to std::fs::Metadata::created.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the ID of the device containing the file. Read more
Returns the inode number. Read more
Returns the rights applied to this file. Read more
Returns the number of hard links pointing to this file. Read more
Returns the user ID of the owner of this file. Read more
Returns the group ID of the owner of this file. Read more
Returns the device ID of this file (if it is a special one). Read more
Returns the total size of this file in bytes. Read more
Returns the last access time of the file, in seconds since Unix Epoch. Read more
Returns the last access time of the file, in nanoseconds since atime. Read more
Returns the last modification time of the file, in seconds since Unix Epoch. Read more
Returns the last modification time of the file, in nanoseconds since mtime. Read more
Returns the last status change time of the file, in seconds since Unix Epoch. Read more
Returns the last status change time of the file, in nanoseconds since ctime. Read more
Returns the block size for filesystem I/O. Read more
Returns the number of blocks allocated to the file, in 512-byte units. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.