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
use crate::SystemTimeSpec;
use io_lifetimes::AsFilelike;
use std::path::Path;
use std::time::SystemTime;
use std::{fs, io};
#[cfg(not(windows))]
use {
    rustix::{
        fs::{cwd, futimens, utimensat, AtFlags, Timestamps},
        fs::{UTIME_NOW, UTIME_OMIT},
        time::Timespec,
    },
    std::convert::TryInto,
};
#[cfg(windows)]
use {
    std::{
        os::windows::{fs::OpenOptionsExt, io::AsRawHandle},
        ptr,
        time::Duration,
    },
    windows_sys::Win32::Foundation::{ERROR_NOT_SUPPORTED, FILETIME, HANDLE},
    windows_sys::Win32::Storage::FileSystem::{
        SetFileTime, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
    },
};

/// Set the last access timestamp of a file or other filesystem object.
#[inline]
pub fn set_atime<P: AsRef<Path>>(path: P, atime: SystemTimeSpec) -> io::Result<()> {
    set_times(path, Some(atime), None)
}

/// Set the last modification timestamp of a file or other filesystem object.
#[inline]
pub fn set_mtime<P: AsRef<Path>>(path: P, mtime: SystemTimeSpec) -> io::Result<()> {
    set_times(path, None, Some(mtime))
}

/// Set the last access and last modification timestamps of a file or other
/// filesystem object.
#[inline]
pub fn set_times<P: AsRef<Path>>(
    path: P,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let path = path.as_ref();
    _set_times(path, atime, mtime)
}

#[cfg(not(windows))]
fn _set_times(
    path: &Path,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let times = Timestamps {
        last_access: to_timespec(atime)?,
        last_modification: to_timespec(mtime)?,
    };
    Ok(utimensat(cwd(), path, &times, AtFlags::empty())?)
}

#[cfg(windows)]
fn _set_times(
    path: &Path,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let custom_flags = FILE_FLAG_BACKUP_SEMANTICS;

    match fs::OpenOptions::new()
        .write(true)
        .custom_flags(custom_flags)
        .open(path)
    {
        Ok(file) => return _set_file_times(&file, atime, mtime),
        Err(err) => match err.kind() {
            io::ErrorKind::PermissionDenied => (),
            _ => return Err(err),
        },
    }

    match fs::OpenOptions::new()
        .read(true)
        .custom_flags(custom_flags)
        .open(path)
    {
        Ok(file) => return _set_file_times(&file, atime, mtime),
        Err(err) => match err.kind() {
            io::ErrorKind::PermissionDenied => (),
            _ => return Err(err),
        },
    }

    Err(io::Error::from_raw_os_error(ERROR_NOT_SUPPORTED as i32))
}

/// Like `set_times`, but never follows symlinks.
#[inline]
pub fn set_symlink_times<P: AsRef<Path>>(
    path: P,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let path = path.as_ref();
    _set_symlink_times(path, atime, mtime)
}

/// Like `set_times`, but never follows symlinks.
#[cfg(not(windows))]
fn _set_symlink_times(
    path: &Path,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let times = Timestamps {
        last_access: to_timespec(atime)?,
        last_modification: to_timespec(mtime)?,
    };
    Ok(utimensat(cwd(), path, &times, AtFlags::SYMLINK_NOFOLLOW)?)
}

/// Like `set_times`, but never follows symlinks.
#[cfg(windows)]
fn _set_symlink_times(
    path: &Path,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let custom_flags = FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT;

    match fs::OpenOptions::new()
        .write(true)
        .custom_flags(custom_flags)
        .open(path)
    {
        Ok(file) => return _set_file_times(&file, atime, mtime),
        Err(err) => match err.kind() {
            io::ErrorKind::PermissionDenied => (),
            _ => return Err(err),
        },
    }

    match fs::OpenOptions::new()
        .read(true)
        .custom_flags(custom_flags)
        .open(path)
    {
        Ok(file) => return _set_file_times(&file, atime, mtime),
        Err(err) => match err.kind() {
            io::ErrorKind::PermissionDenied => (),
            _ => return Err(err),
        },
    }

    Err(io::Error::from_raw_os_error(ERROR_NOT_SUPPORTED as i32))
}

/// An extension trait for `std::fs::File`, `cap_std::fs::File`, and similar
/// types.
pub trait SetTimes {
    /// Set the last access and last modification timestamps of an open file
    /// handle.
    ///
    /// This corresponds to [`filetime::set_file_handle_times`].
    ///
    /// [`filetime::set_file_handle_times`]: https://docs.rs/filetime/latest/filetime/fn.set_file_handle_times.html
    fn set_times(
        &self,
        atime: Option<SystemTimeSpec>,
        mtime: Option<SystemTimeSpec>,
    ) -> io::Result<()>;
}

impl<T: AsFilelike> SetTimes for T {
    #[inline]
    fn set_times(
        &self,
        atime: Option<SystemTimeSpec>,
        mtime: Option<SystemTimeSpec>,
    ) -> io::Result<()> {
        _set_file_times(&self.as_filelike_view::<fs::File>(), atime, mtime)
    }
}

#[cfg(not(windows))]
fn _set_file_times(
    file: &fs::File,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let times = Timestamps {
        last_access: to_timespec(atime)?,
        last_modification: to_timespec(mtime)?,
    };
    Ok(futimens(file, &times)?)
}

#[cfg(not(windows))]
#[allow(clippy::useless_conversion)]
pub(crate) fn to_timespec(ft: Option<SystemTimeSpec>) -> io::Result<Timespec> {
    Ok(match ft {
        None => Timespec {
            tv_sec: 0,
            tv_nsec: UTIME_OMIT.into(),
        },
        Some(SystemTimeSpec::SymbolicNow) => Timespec {
            tv_sec: 0,
            tv_nsec: UTIME_NOW.into(),
        },
        Some(SystemTimeSpec::Absolute(ft)) => {
            let duration = ft.duration_since(SystemTime::UNIX_EPOCH).unwrap();
            let nanoseconds = duration.subsec_nanos();
            assert_ne!(i64::from(nanoseconds), i64::from(UTIME_OMIT));
            assert_ne!(i64::from(nanoseconds), i64::from(UTIME_NOW));
            Timespec {
                tv_sec: duration
                    .as_secs()
                    .try_into()
                    .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?,
                tv_nsec: nanoseconds.try_into().unwrap(),
            }
        }
    })
}

#[cfg(windows)]
fn _set_file_times(
    file: &fs::File,
    atime: Option<SystemTimeSpec>,
    mtime: Option<SystemTimeSpec>,
) -> io::Result<()> {
    let mut now = None;

    let atime = match atime {
        None => None,
        Some(SystemTimeSpec::SymbolicNow) => {
            let right_now = SystemTime::now();
            now = Some(right_now);
            Some(right_now)
        }
        Some(SystemTimeSpec::Absolute(time)) => Some(time),
    };
    let mtime = match mtime {
        None => None,
        Some(SystemTimeSpec::SymbolicNow) => {
            if let Some(prev_now) = now {
                Some(prev_now)
            } else {
                Some(SystemTime::now())
            }
        }
        Some(SystemTimeSpec::Absolute(time)) => Some(time),
    };

    let atime = atime.map(to_filetime).transpose()?;
    let mtime = mtime.map(to_filetime).transpose()?;
    if unsafe {
        SetFileTime(
            file.as_raw_handle() as HANDLE,
            ptr::null(),
            atime.as_ref().map(|r| r as *const _).unwrap_or(ptr::null()),
            mtime.as_ref().map(|r| r as *const _).unwrap_or(ptr::null()),
        )
    } != 0
    {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

#[cfg(windows)]
fn to_filetime(ft: SystemTime) -> io::Result<FILETIME> {
    // To convert a `SystemTime` to absolute seconds and nanoseconds, we need
    // a reference point. The `UNIX_EPOCH` is the only reference point provided
    // by the standard library. But we know that Windows' time stamps are
    // relative to January 1, 1601 so adjust by the difference between that and
    // the Unix epoch.
    let epoch = SystemTime::UNIX_EPOCH - Duration::from_secs(11644473600);
    let ft = ft
        .duration_since(epoch)
        .map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;

    let intervals = ft.as_secs() * (1_000_000_000 / 100) + u64::from(ft.subsec_nanos() / 100);

    // On Windows, a zero time is silently ignored, so issue an error instead.
    if intervals == 0 {
        return Err(io::Error::from_raw_os_error(ERROR_NOT_SUPPORTED as i32));
    }

    Ok(FILETIME {
        dwLowDateTime: intervals as u32,
        dwHighDateTime: (intervals >> 32) as u32,
    })
}