cap_primitives/rustix/linux/fs/
set_times_impl.rs

1//! This module consists of helper types and functions for dealing
2//! with setting the file times specific to Linux.
3
4use super::procfs::set_times_through_proc_self_fd;
5use crate::fs::{open, OpenOptions, SystemTimeSpec};
6use std::path::Path;
7use std::{fs, io};
8
9pub(crate) fn set_times_impl(
10    start: &fs::File,
11    path: &Path,
12    atime: Option<SystemTimeSpec>,
13    mtime: Option<SystemTimeSpec>,
14) -> io::Result<()> {
15    // Try `futimens` with a normal handle. Normal handles need some kind of
16    // access, so first try write.
17    match open(start, path, OpenOptions::new().write(true)) {
18        Ok(file) => {
19            return fs_set_times::SetTimes::set_times(
20                &file,
21                atime.map(SystemTimeSpec::into_std),
22                mtime.map(SystemTimeSpec::into_std),
23            )
24        }
25        Err(err) => match rustix::io::Errno::from_io_error(&err) {
26            Some(rustix::io::Errno::ACCESS) | Some(rustix::io::Errno::ISDIR) => (),
27            _ => return Err(err),
28        },
29    }
30
31    // Next try read.
32    match open(start, path, OpenOptions::new().read(true)) {
33        Ok(file) => {
34            return fs_set_times::SetTimes::set_times(
35                &file,
36                atime.map(SystemTimeSpec::into_std),
37                mtime.map(SystemTimeSpec::into_std),
38            )
39        }
40        Err(err) => match rustix::io::Errno::from_io_error(&err) {
41            Some(rustix::io::Errno::ACCESS) => (),
42            _ => return Err(err),
43        },
44    }
45
46    // If neither of those worked, turn to `/proc`.
47    set_times_through_proc_self_fd(start, path, atime, mtime)
48}