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
use std::fs;
use std::io;
use std::os::unix::prelude::*;

use crate::{AsPath, Dir, LookupFlags};

/// A struct that can be used to open files within a directory.
///
/// This is directly analogous to `std::fs::OpenOptions`, except that it only looks up files within
/// a specific `Dir`.
///
/// An `OpenOptions` struct can be created with [`Dir::open_file()`].
///
/// [`Dir::open_file()`]: ./struct.Dir.html#method.open_file
#[derive(Clone, Debug)]
pub struct OpenOptions<'a> {
    dir: &'a Dir,
    read: bool,
    write: bool,
    create: bool,
    create_new: bool,
    append: bool,
    truncate: bool,
    custom_flags: libc::c_int,
    mode: libc::mode_t,
    lookup_flags: LookupFlags,
}

impl<'a> OpenOptions<'a> {
    #[inline]
    pub(crate) fn beneath(dir: &'a Dir) -> Self {
        Self {
            dir,
            read: false,
            write: false,
            create: false,
            create_new: false,
            append: false,
            truncate: false,
            custom_flags: 0,
            mode: 0o666,
            lookup_flags: LookupFlags::empty(),
        }
    }

    /// Enable the option for read access.
    #[inline]
    pub fn read(&mut self, read: bool) -> &mut Self {
        self.read = read;
        self
    }

    /// Enable the option for write access.
    #[inline]
    pub fn write(&mut self, write: bool) -> &mut Self {
        self.write = write;
        self
    }

    /// Create the a new file if it does not exist.
    #[inline]
    pub fn create(&mut self, create: bool) -> &mut Self {
        self.create = create;
        self
    }

    /// Create a new file, failing if it already exists.
    ///
    /// This is atomic. Enabling it causes [`.create()`] and [`.truncate()`] to be ignored.
    ///
    /// [`.create()`]: #method.create
    /// [`.truncate()`]: #method.truncate
    #[inline]
    pub fn create_new(&mut self, create_new: bool) -> &mut Self {
        self.create_new = create_new;
        self
    }

    /// Enable append mode.
    #[inline]
    pub fn append(&mut self, append: bool) -> &mut Self {
        self.append = append;
        self
    }

    /// If the file already exists, truncate it while opening.
    #[inline]
    pub fn truncate(&mut self, truncate: bool) -> &mut Self {
        self.truncate = truncate;
        self
    }

    /// Set the mode with which the file will be opened (e.g `0o777`).
    ///
    /// The OS will mask out the system umask value.
    #[inline]
    pub fn mode(&mut self, mode: u32) -> &mut Self {
        self.mode = mode as libc::mode_t;
        self
    }

    /// Pass custom flags when opening the file.
    ///
    /// Like `std::fs::OpenOptions`, `O_ACCMODE` is masked out from the given flags.
    #[inline]
    pub fn custom_flags(&mut self, flags: libc::c_int) -> &mut Self {
        self.custom_flags = flags;
        self
    }

    /// Set the "lookup flags" used when opening the file.
    ///
    /// See [`LookupFlags`] for more information. (By default, none of the "lookup flags" are
    /// enabled.)
    ///
    /// [`LookupFlags`]: ./struct.LookupFlags.html
    pub fn lookup_flags(&mut self, lookup_flags: LookupFlags) -> &mut Self {
        self.lookup_flags = lookup_flags;
        self
    }

    fn flags(&self) -> io::Result<libc::c_int> {
        let mut flags = self.custom_flags & !libc::O_ACCMODE;

        if self.write || self.append {
            if self.read {
                flags |= libc::O_RDWR;
            } else {
                flags |= libc::O_WRONLY;
            }

            if self.create_new {
                flags |= libc::O_CREAT | libc::O_EXCL;
            } else {
                if self.create {
                    flags |= libc::O_CREAT;
                }

                if self.truncate {
                    flags |= libc::O_TRUNC;
                }
            }

            if self.append {
                flags |= libc::O_APPEND;
            }
        } else if self.read {
            flags |= libc::O_RDONLY;

            if self.create_new || self.create || self.truncate {
                return Err(io::Error::from_raw_os_error(libc::EINVAL));
            }
        } else {
            return Err(io::Error::from_raw_os_error(libc::EINVAL));
        }

        Ok(flags)
    }

    /// Open the file at `path` with the options specified by `path`.
    #[inline]
    pub fn open<P: AsPath>(&self, path: P) -> io::Result<fs::File> {
        crate::open_beneath(
            self.dir.as_raw_fd(),
            path,
            self.flags()?,
            self.mode,
            self.lookup_flags,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_flags() {
        let dir = Dir::open("/").unwrap();
        let opts = dir.open_file();

        assert_eq!(opts.clone().read(true).flags().unwrap(), libc::O_RDONLY);
        assert_eq!(opts.clone().write(true).flags().unwrap(), libc::O_WRONLY);
        assert_eq!(
            opts.clone().read(true).write(true).flags().unwrap(),
            libc::O_RDWR
        );

        assert_eq!(
            opts.clone().append(true).flags().unwrap(),
            libc::O_WRONLY | libc::O_APPEND
        );
        assert_eq!(
            opts.clone().read(true).append(true).flags().unwrap(),
            libc::O_RDWR | libc::O_APPEND
        );

        assert_eq!(
            opts.clone().write(true).create_new(true).flags().unwrap(),
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL
        );
        assert_eq!(
            opts.clone()
                .read(true)
                .write(true)
                .create_new(true)
                .flags()
                .unwrap(),
            libc::O_RDWR | libc::O_CREAT | libc::O_EXCL
        );

        assert_eq!(
            opts.clone().write(true).create(true).flags().unwrap(),
            libc::O_WRONLY | libc::O_CREAT
        );

        assert_eq!(
            opts.clone().write(true).truncate(true).flags().unwrap(),
            libc::O_WRONLY | libc::O_TRUNC
        );

        assert_eq!(
            opts.clone()
                .write(true)
                .create(true)
                .truncate(true)
                .flags()
                .unwrap(),
            libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC
        );

        assert_eq!(
            opts.clone().flags().unwrap_err().raw_os_error(),
            Some(libc::EINVAL)
        );

        assert_eq!(
            opts.clone()
                .read(true)
                .create(true)
                .flags()
                .unwrap_err()
                .raw_os_error(),
            Some(libc::EINVAL)
        );
        assert_eq!(
            opts.clone()
                .read(true)
                .create_new(true)
                .flags()
                .unwrap_err()
                .raw_os_error(),
            Some(libc::EINVAL)
        );
        assert_eq!(
            opts.clone()
                .read(true)
                .truncate(true)
                .flags()
                .unwrap_err()
                .raw_os_error(),
            Some(libc::EINVAL)
        );
    }

    #[test]
    fn test_custom_flags() {
        let dir = Dir::open("/").unwrap();
        let opts = dir.open_file();

        assert_eq!(
            opts.clone()
                .read(true)
                .custom_flags(libc::O_NOFOLLOW)
                .flags()
                .unwrap(),
            libc::O_RDONLY | libc::O_NOFOLLOW
        );
    }
}