Skip to main content

system_interface/fs/
fd_flags.rs

1use bitflags::bitflags;
2use io_lifetimes::{AsFilelike, FromFilelike};
3#[cfg(not(any(windows, target_os = "redox")))]
4use rustix::fs::{fcntl_getfl, fcntl_setfl, OFlags};
5#[cfg(not(windows))]
6use std::marker::PhantomData;
7use std::{fs, io};
8#[cfg(windows)]
9use {
10    cap_fs_ext::{OpenOptions, Reopen},
11    cap_std::fs::OpenOptionsExt,
12    io_lifetimes::AsHandle,
13    windows_sys::Win32::Storage::FileSystem::FILE_FLAG_WRITE_THROUGH,
14    winx::file::{AccessMode, FileModeInformation},
15};
16
17/// An opaque representation of the state needed to perform a `set_fd_flags`
18/// operation.
19#[cfg(windows)]
20pub struct SetFdFlags<T> {
21    reopened: T,
22}
23
24/// An opaque representation of the state needed to perform a `set_fd_flags`
25/// operation.
26#[cfg(not(windows))]
27pub struct SetFdFlags<T> {
28    flags: OFlags,
29    _phantom: PhantomData<T>,
30}
31
32/// Extension trait that can indicate various I/O flags.
33pub trait GetSetFdFlags {
34    /// Query the "status" flags for the `self` file descriptor.
35    fn get_fd_flags(&self) -> io::Result<FdFlags>
36    where
37        Self: AsFilelike;
38
39    /// Create a new `SetFdFlags` value for use with `set_fd_flags`.
40    ///
41    /// Some platforms lack the ability to dynamically set the flags and
42    /// implement `set_fd_flags` by closing and re-opening the resource and
43    /// splitting it into two steps like this simplifies the lifetimes.
44    fn new_set_fd_flags(&self, flags: FdFlags) -> io::Result<SetFdFlags<Self>>
45    where
46        Self: AsFilelike + FromFilelike + Sized;
47
48    /// Set the "status" flags for the `self` file descriptor.
49    ///
50    /// This requires a `SetFdFlags` obtained from `new_set_fd_flags`.
51    fn set_fd_flags(&mut self, set_fd_flags: SetFdFlags<Self>) -> io::Result<()>
52    where
53        Self: AsFilelike + Sized;
54}
55
56bitflags! {
57    /// Flag definitions for use with `SetFlags::set_flags`.
58    pub struct FdFlags: u32 {
59        /// Writes always write to the end of the file.
60        const APPEND = 0x01;
61
62        /// Write I/O operations on the file descriptor shall complete as
63        /// defined by synchronized I/O *data* integrity completion.
64        const DSYNC = 0x02;
65
66        /// I/O operations return `io::ErrorKind::WouldBlock`.
67        const NONBLOCK = 0x04;
68
69        /// Read I/O operations on the file descriptor shall complete at the
70        /// same level of integrity as specified by the `DSYNC` and `SYNC` flags.
71        const RSYNC = 0x08;
72
73        /// Write I/O operations on the file descriptor shall complete as
74        /// defined by synchronized I/O *file* integrity completion.
75        const SYNC = 0x10;
76    }
77}
78
79#[cfg(not(windows))]
80impl<T> GetSetFdFlags for T {
81    fn get_fd_flags(&self) -> io::Result<FdFlags>
82    where
83        Self: AsFilelike,
84    {
85        let mut fd_flags = FdFlags::empty();
86        let flags = fcntl_getfl(self)?;
87
88        fd_flags.set(FdFlags::APPEND, flags.contains(OFlags::APPEND));
89        #[cfg(not(target_os = "freebsd"))]
90        fd_flags.set(FdFlags::DSYNC, flags.contains(OFlags::DSYNC));
91        fd_flags.set(FdFlags::NONBLOCK, flags.contains(OFlags::NONBLOCK));
92        #[cfg(any(target_vendor = "apple", target_os = "freebsd", target_os = "fuchsia"))]
93        {
94            fd_flags.set(FdFlags::SYNC, flags.contains(OFlags::SYNC));
95        }
96        #[cfg(not(any(target_vendor = "apple", target_os = "freebsd", target_os = "fuchsia")))]
97        {
98            fd_flags.set(FdFlags::RSYNC, flags.contains(OFlags::RSYNC));
99            fd_flags.set(FdFlags::SYNC, flags.contains(OFlags::SYNC));
100        }
101
102        Ok(fd_flags)
103    }
104
105    fn new_set_fd_flags(&self, fd_flags: FdFlags) -> io::Result<SetFdFlags<Self>>
106    where
107        Self: AsFilelike,
108    {
109        let mut flags = OFlags::empty();
110        flags.set(OFlags::APPEND, fd_flags.contains(FdFlags::APPEND));
111        flags.set(OFlags::NONBLOCK, fd_flags.contains(FdFlags::NONBLOCK));
112
113        // Linux, FreeBSD, and others silently ignore these flags in `F_SETFL`.
114        if fd_flags.intersects(FdFlags::DSYNC | FdFlags::SYNC | FdFlags::RSYNC) {
115            return Err(io::Error::new(
116                io::ErrorKind::Other,
117                "setting fd_flags SYNC, DSYNC, and RSYNC is not supported",
118            ));
119        }
120
121        Ok(SetFdFlags {
122            flags,
123            _phantom: PhantomData,
124        })
125    }
126
127    fn set_fd_flags(&mut self, set_fd_flags: SetFdFlags<Self>) -> io::Result<()>
128    where
129        Self: AsFilelike + Sized,
130    {
131        Ok(fcntl_setfl(
132            &*self.as_filelike_view::<fs::File>(),
133            set_fd_flags.flags,
134        )?)
135    }
136}
137
138#[cfg(windows)]
139impl<T> GetSetFdFlags for T {
140    fn get_fd_flags(&self) -> io::Result<FdFlags>
141    where
142        Self: AsFilelike,
143    {
144        let mut fd_flags = FdFlags::empty();
145        let handle = self.as_filelike();
146        let access_mode = winx::file::query_access_information(handle)?;
147        let mode = winx::file::query_mode_information(handle)?;
148
149        // `FILE_APPEND_DATA` with `FILE_WRITE_DATA` means append-mode.
150        if access_mode.contains(AccessMode::FILE_APPEND_DATA)
151            && !access_mode.contains(AccessMode::FILE_WRITE_DATA)
152        {
153            fd_flags |= FdFlags::APPEND;
154        }
155
156        if mode.contains(FileModeInformation::FILE_WRITE_THROUGH) {
157            // Only report `DSYNC`. This is technically the only one of the
158            // `O_?SYNC` flags Windows supports.
159            fd_flags |= FdFlags::DSYNC;
160        }
161
162        Ok(fd_flags)
163    }
164
165    fn new_set_fd_flags(&self, fd_flags: FdFlags) -> io::Result<SetFdFlags<Self>>
166    where
167        Self: AsFilelike + FromFilelike,
168    {
169        let mut flags = 0;
170
171        if fd_flags.contains(FdFlags::SYNC) || fd_flags.contains(FdFlags::DSYNC) {
172            flags |= FILE_FLAG_WRITE_THROUGH;
173        }
174
175        let file = self.as_filelike_view::<fs::File>();
176        let access_mode = winx::file::query_access_information(file.as_handle())?;
177        let new_access_mode = file_access_mode_from_fd_flags(
178            fd_flags,
179            access_mode.contains(AccessMode::FILE_READ_DATA),
180            access_mode.contains(AccessMode::FILE_WRITE_DATA)
181                | access_mode.contains(AccessMode::FILE_APPEND_DATA),
182        );
183        let mut options = OpenOptions::new();
184        options.access_mode(new_access_mode.bits());
185        options.custom_flags(flags);
186        let reopened = Self::from_into_filelike(file.reopen(&options)?);
187        Ok(SetFdFlags { reopened })
188    }
189
190    fn set_fd_flags(&mut self, set_fd_flags: SetFdFlags<Self>) -> io::Result<()>
191    where
192        Self: AsFilelike,
193    {
194        *self = set_fd_flags.reopened;
195        Ok(())
196    }
197}
198
199#[cfg(windows)]
200fn file_access_mode_from_fd_flags(fd_flags: FdFlags, read: bool, write: bool) -> AccessMode {
201    let mut access_mode = AccessMode::READ_CONTROL;
202
203    // We always need `FILE_WRITE_ATTRIBUTES` so that we can set attributes
204    // such as filetimes, etc.
205    access_mode.insert(AccessMode::FILE_WRITE_ATTRIBUTES);
206
207    // Note that `GENERIC_READ` and `GENERIC_WRITE` cannot be used to properly
208    // support append-only mode. The file-specific flags `FILE_GENERIC_READ`
209    // and `FILE_GENERIC_WRITE` are used here instead. These flags have the
210    // same semantic meaning for file objects, but allow removal of specific
211    // permissions (see below).
212    if read {
213        access_mode.insert(AccessMode::FILE_GENERIC_READ);
214    }
215    if write {
216        access_mode.insert(AccessMode::FILE_GENERIC_WRITE);
217    }
218
219    // For append, grant the handle FILE_APPEND_DATA access but *not*
220    // `FILE_WRITE_DATA`. This makes the handle "append only". Changes to the
221    // file pointer will be ignored (like POSIX's `O_APPEND` behavior).
222    if fd_flags.contains(FdFlags::APPEND) {
223        access_mode.insert(AccessMode::FILE_APPEND_DATA);
224        access_mode.remove(AccessMode::FILE_WRITE_DATA);
225    }
226
227    access_mode
228}