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
use bitflags::bitflags;
#[cfg(not(any(windows, target_os = "redox")))]
use posish::fs::{getfl, setfl, OFlags};
use std::io;
use unsafe_io::AsUnsafeFile;
#[cfg(windows)]
use {
    cap_fs_ext::{OpenOptions, Reopen},
    std::os::windows::fs::OpenOptionsExt,
    std::os::windows::io::AsRawHandle,
    unsafe_io::FromUnsafeFile,
    winapi::um::winbase::FILE_FLAG_WRITE_THROUGH,
    winx::file::{AccessMode, FileModeInformation},
};

/// Extension trait that can indicate various I/O flags.
pub trait GetSetFdFlags {
    /// Query the "status" flags for the `self` file descriptor.
    fn get_fd_flags(&self) -> io::Result<FdFlags>;

    /// Set the "status" flags for the `self` file descriptor. On some
    /// platforms, this may close the file descriptor and produce a new
    /// one.
    fn set_fd_flags(&mut self, flags: FdFlags) -> io::Result<()>;
}

bitflags! {
    /// Flag definitions for use with `SetFlags::set_flags`.
    pub struct FdFlags: u32 {
        /// Writes always write to the end of the file.
        const APPEND = 0x01;

        /// Write I/O operations on the file descriptor shall complete as
        /// defined by synchronized I/O *data* integrity completion.
        const DSYNC = 0x02;

        /// I/O operations return `io::ErrorKind::WouldBlock`.
        const NONBLOCK = 0x04;

        /// Read I/O operations on the file descriptor shall complete at the
        /// same level of integrity as specified by the `DSYNC` and `SYNC` flags.
        const RSYNC = 0x08;

        /// Write I/O operations on the file descriptor shall complete as
        /// defined by synchronized I/O *file* integrity completion.
        const SYNC = 0x10;
    }
}

#[cfg(not(windows))]
impl<T: AsUnsafeFile> GetSetFdFlags for T {
    fn get_fd_flags(&self) -> io::Result<FdFlags> {
        let mut fd_flags = FdFlags::empty();
        let flags = getfl(self)?;

        fd_flags.set(FdFlags::APPEND, flags.contains(OFlags::APPEND));
        fd_flags.set(FdFlags::DSYNC, flags.contains(OFlags::DSYNC));
        fd_flags.set(FdFlags::NONBLOCK, flags.contains(OFlags::NONBLOCK));
        #[cfg(any(
            target_os = "ios",
            target_os = "macos",
            target_os = "freebsd",
            target_os = "fuchsia"
        ))]
        {
            fd_flags.set(FdFlags::SYNC, flags.contains(OFlags::SYNC));
        }
        #[cfg(not(any(
            target_os = "ios",
            target_os = "macos",
            target_os = "freebsd",
            target_os = "fuchsia"
        )))]
        {
            fd_flags.set(FdFlags::RSYNC, flags.contains(OFlags::RSYNC));
            fd_flags.set(FdFlags::SYNC, flags.contains(OFlags::SYNC));
        }

        Ok(fd_flags)
    }

    fn set_fd_flags(&mut self, fd_flags: FdFlags) -> io::Result<()> {
        let mut flags = OFlags::empty();
        flags.set(OFlags::APPEND, fd_flags.contains(FdFlags::APPEND));
        flags.set(OFlags::NONBLOCK, fd_flags.contains(FdFlags::NONBLOCK));

        // Linux, FreeBSD, and others silently ignore these flags in `F_SETFL`.
        if fd_flags.intersects(FdFlags::DSYNC | FdFlags::SYNC | FdFlags::RSYNC) {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "setting fd_flags SYNC, DSYNC, and RSYNC is not supported",
            ));
        }

        setfl(self, flags)
    }
}

#[cfg(windows)]
impl<T: AsUnsafeFile + FromUnsafeFile> GetSetFdFlags for T {
    fn get_fd_flags(&self) -> io::Result<FdFlags> {
        let mut fd_flags = FdFlags::empty();
        let handle = self.as_unsafe_file().as_raw_handle();
        let access_mode = winx::file::query_access_information(handle)?;
        let mode = winx::file::query_mode_information(handle)?;

        // `FILE_APPEND_DATA` with `FILE_WRITE_DATA` means append-mode.
        if access_mode.contains(AccessMode::FILE_APPEND_DATA)
            && !access_mode.contains(AccessMode::FILE_WRITE_DATA)
        {
            fd_flags |= FdFlags::APPEND;
        }

        if mode.contains(FileModeInformation::FILE_WRITE_THROUGH) {
            // Only report `SYNC`. This is technically the only one of the
            // `O_?SYNC` flags Windows supports.
            fd_flags |= FdFlags::SYNC;
        }

        Ok(fd_flags)
    }

    fn set_fd_flags(&mut self, fd_flags: FdFlags) -> io::Result<()> {
        let mut flags = 0;

        if fd_flags.contains(FdFlags::SYNC)
            || fd_flags.contains(FdFlags::DSYNC)
            || fd_flags.contains(FdFlags::RSYNC)
        {
            flags |= FILE_FLAG_WRITE_THROUGH;
        }

        if fd_flags.contains(FdFlags::NONBLOCK) {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Non-blocking I/O is not yet supported on Windows",
            ));
        }

        let handle = self.as_unsafe_file().as_raw_handle();
        let access_mode = winx::file::query_access_information(handle)?;
        let new_access_mode = file_access_mode_from_fd_flags(
            fd_flags,
            access_mode.contains(AccessMode::FILE_READ_DATA),
            access_mode.contains(AccessMode::FILE_WRITE_DATA)
                | access_mode.contains(AccessMode::FILE_APPEND_DATA),
        );
        let mut options = OpenOptions::new();
        options.access_mode(new_access_mode.bits());
        options.custom_flags(flags);
        let reopened = self.as_file_view().reopen(&options)?;
        *self = T::from_filelike(reopened);
        Ok(())
    }
}

#[cfg(windows)]
fn file_access_mode_from_fd_flags(fd_flags: FdFlags, read: bool, write: bool) -> AccessMode {
    let mut access_mode = AccessMode::READ_CONTROL;

    // We always need `FILE_WRITE_ATTRIBUTES` so that we can set attributes
    // such as filetimes, etc.
    access_mode.insert(AccessMode::FILE_WRITE_ATTRIBUTES);

    // Note that `GENERIC_READ` and `GENERIC_WRITE` cannot be used to properly
    // support append-only mode. The file-specific flags `FILE_GENERIC_READ`
    // and `FILE_GENERIC_WRITE` are used here instead. These flags have the
    // same semantic meaning for file objects, but allow removal of specific
    // permissions (see below).
    if read {
        access_mode.insert(AccessMode::FILE_GENERIC_READ);
    }
    if write {
        access_mode.insert(AccessMode::FILE_GENERIC_WRITE);
    }

    // For append, grant the handle FILE_APPEND_DATA access but *not*
    // `FILE_WRITE_DATA`. This makes the handle "append only". Changes to the
    // file pointer will be ignored (like POSIX's `O_APPEND` behavior).
    if fd_flags.contains(FdFlags::APPEND) {
        access_mode.insert(AccessMode::FILE_APPEND_DATA);
        access_mode.remove(AccessMode::FILE_WRITE_DATA);
    }

    access_mode
}