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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#![doc(html_root_url = "https://docs.rs/fcntl/0.1.0")]
//! Wrapper around [fcntl (2)](https://www.man7.org/linux/man-pages/man2/fcntl.2.html) and convenience methods to make
//! interacting with it easier. Currently only supports commands related to Advisory record locking.
//
//
// TODO: Instead of exposing `libc::flock` we should implement our own flock which implements
//     - `From<flock>`
//     - `Into<flock>`
//     - Methods from `FlockOperations` without the need for the extra trait
//     - Other common traits (`Eq`, `PartialEq`, `Ord`, `PartialOrd`, `Hash`, `Debug`, `Display`, `Default`)

use libc::{
    __errno_location,
    fcntl as libc_fcntl,
};
use std::{
    convert::TryInto,
    error::Error,
    fmt::{self, Display},
    os::unix::io::AsRawFd,
};

// re-exports
pub use libc::{
    c_int,
    c_short,
    flock,
};


/// Allowed types for the `arg` parameter for the `fcntl` syscall.
#[derive(Copy, Clone)]
pub enum FcntlArg {
    Flock(flock),
}


/// Allowed commands (`cmd` parameter) for the `fcntl` syscall.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FcntlCmd {
    /// F_SETLK,
    SetLock,
    /// F_SETLKW
    SetLockWait,
    /// F_GETLK
    GetLock,
}


/// Error type which functions of this crate will return.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FcntlError {
    /// The requested FcntlCmd is not yet handled by our implementation
    CommandNotImplemented(FcntlCmd),
    /// The syscall returned the respective error (which may be `None`, if the errno lookup fails)
    Errno(Option<c_int>),
    /// An `crate`-internal error occured. If you get this error variant, please report this as a bug!
    Internal,
    /// The enum variant of `arg` does not match the expected variant for the requested `cmd`. No operation was
    /// performed.
    InvalidArgForCmd,
}


/// Defines which types of lock can be set onto files.
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FcntlLockType {
    /// Wrapper for `F_RDLCK`
    Read,
    /// Wrapper for `F_WRLCK`
    Write,
}


/// This trait is used to define functions wich directly operate on `flock`.
/// ```rust
/// use libc::flock;
/// use fcntl::{FcntlLockType, FlockOperations};
///
/// let flock = flock::default().with_locktype(FcntlLockType::Write);
/// ```
pub trait FlockOperations {
    /// Since we don't have control over `libc::flock` we cannot `impl Default for libc::flock`
    fn default() -> Self;

    /// Sets `l_type` to the given value using the builder pattern. This is mostly intended for internal use. Where
    /// possible, it is recommended to use other methods which alter `l_type` (e.g. `with_locktype`).
    fn with_l_type(self, l_type: c_short) -> Self;

    /// Sets the lock type (`l_type`) to the appropriate value for the given `FcntlLockType`, using the builder pattern.
    fn with_locktype(self, locktype: FcntlLockType) -> Self;
}


/// Calls `fcntl` with the given `cmd` and `arg`. On success, the structure passed to the `arg` parameter is returned
/// as returned by the kernel.
/// **Note**: Where possible convenience wrappers (such as `is_file_locked`, `lock_file`, etc.) should be used as they
/// correctly interpret possible return values of the syscall.
///
/// Currently supported `cmd`s:
/// - `FcntlCmd::GetLock`
/// - `FcntlCmd::SetLock`
///
/// # Errors
///
/// In case of an error (syscall returned an error, invalid `arg` provided, `cmd` not supported, etc.) an appropriate
/// value is returned.
pub fn fcntl<'a, RF>(fd: &'a RF, cmd: FcntlCmd, arg: FcntlArg) -> Result<FcntlArg, FcntlError>
where RF: AsRawFd
{
    let fd = fd.as_raw_fd();
    // different commands require different types of `arg`
    match cmd {
        FcntlCmd::GetLock | FcntlCmd::SetLock /*| FcntlCmd::SetLockWait*/ => {
            match arg {
                FcntlArg::Flock(flock) => {
                    let mut flock = flock;
                    let rv = unsafe { libc_fcntl(fd, cmd.into(), &mut flock) };
                    if rv == 0 {
                        Ok(FcntlArg::Flock(flock))
                    } else {
                        let errno_ptr = unsafe { __errno_location() };
                        let errno = if errno_ptr.is_null() {
                            None
                        } else {
                            // *should* be safe here as we checked against NULL pointer..
                            Some(unsafe {*errno_ptr})
                        };
                        Err(FcntlError::Errno(errno))
                    }
                }
                _ => Err(FcntlError::InvalidArgForCmd),
            }
        }
        FcntlCmd::SetLockWait => Err(FcntlError::CommandNotImplemented(FcntlCmd::SetLockWait)),
    }
}


/// Checks whether the given file is locked.
///
/// The caller is responsible that `fd` was opened with the appropriate parameters, as stated by
/// [fcntl (2)](https://www.man7.org/linux/man-pages/man2/fcntl.2.html):
/// > In order to place a read lock, `fd` must be open for reading.  In order to place a write lock, `fd` must be open
/// for writing.  To place both types of lock, open a file read-write.
///
/// ```rust
/// use std::fs::OpenOptions;
/// use fcntl::is_file_locked;
/// # let file_name = "README.md";
///
/// let file = OpenOptions::new().read(true).open(file_name).unwrap();
/// match is_file_locked(&file, None) {
///     Ok(true) => println!("File is currently locked"),
///     Ok(false) => println!("File is not locked"),
///     Err(err) => println!("Error: {:?}", err),
/// }
/// ```
pub fn is_file_locked<'a, RF>(fd: &'a RF, flock: Option<flock>) -> Result<bool, FcntlError>
where RF: AsRawFd
{
    let arg = match flock {
        Some(flock) => FcntlArg::Flock(flock),
        None => FcntlArg::Flock(libc::flock::default())
    };

    match fcntl(fd, FcntlCmd::GetLock, arg) {
        Ok(FcntlArg::Flock(result)) => {
            // We need to convert from c_int into c_short. F_UNLCK is defined with value 2, so this should never panic.
            // To be extra safe, we have a test case for that ;)
            Ok(result.l_type != libc::F_UNLCK.try_into().unwrap())
        }
        Ok(_) => Err(FcntlError::Internal),
        Err(err) => Err(err),
    }
}


/// Locks the given file (using `FcntlCmd::SetLock`). If `flock` is `None` all parameters of the flock structure (
/// `l_whence`, `l_start`, `l_len`, `l_pid`) will be set to 0.  `locktype` controls the `l_type` parameter. When it is
/// `None`, `FcntlLockType::Read` is used. `flock.l_type` will be overwritten in all cases to avoid passing an invalid
/// parameter to the syscall.
///
/// The caller is responsible that `fd` was opened with the appropriate parameters, as stated by `fcntl 2`:
/// > In order to place a read lock, `fd` must be open for reading.  In order to place a write lock, `fd` must be open
/// for writing.  To place both types of lock, open a file read-write.
///
/// ```rust
/// use std::fs::OpenOptions;
/// use fcntl::{FcntlLockType, lock_file};
/// # let file_name = "README.md";
///
/// let file = OpenOptions::new().read(true).write(true).open(file_name).unwrap();
/// match lock_file(&file, None, Some(FcntlLockType::Write)) {
///     Ok(true) => println!("Lock acuired!"),
///     Ok(false) => println!("Could not acquire lock!"),
///     Err(err) => println!("Error: {:?}", err),
/// }
/// ```
pub fn lock_file<'a, RF>(fd: &'a RF, flock: Option<flock>, locktype: Option<FcntlLockType>) -> Result<bool, FcntlError>
where RF: AsRawFd
{
    let locktype = locktype.unwrap_or(FcntlLockType::Read);
    let arg = match flock {
        Some(flock) => FcntlArg::Flock(flock.with_locktype(locktype)),
        None => FcntlArg::Flock(libc::flock::default().with_locktype(locktype)),
    };

    match fcntl(fd, FcntlCmd::SetLock, arg) {
        // Locking was successful
        Ok(FcntlArg::Flock(_result)) => Ok(true),
        // This should not happen, unless we have a bug..
        Ok(_) => Err(FcntlError::Internal),
        // "If a conflicting lock is held by another process, this call returns -1 and sets errno to EACCES or EAGAIN."
        Err(FcntlError::Errno(Some(libc::EACCES))) | Err(FcntlError::Errno(Some(libc::EAGAIN))) => Ok(false),
        // Everything else is also an error
        Err(err) => Err(err),
    }
}


/// Releases the lock on the given file (using `FcntlCmd::SetLock`). If `flock` is `None` all parameters of the flock
/// structure (`l_whence`, `l_start`, `l_len`, `l_pid`) will be set to 0. `flock.l_type` will be set to `libc::F_UNLCK`
/// regardless of its original value.
///
/// ```rust
/// use std::fs::OpenOptions;
/// use fcntl::unlock_file;
/// # let file_name = "README.md";
///
/// let file = OpenOptions::new().read(true).open(file_name).unwrap();
/// match unlock_file(&file, None) {
///     Ok(true) => println!("Lock successfully released"),
///     Ok(false) => println!("Falied to release lock"),
///     Err(err) => println!("Error: {:?}", err),
/// }
/// ```
pub fn unlock_file<'a, RF>(fd: &'a RF, flock: Option<flock>) -> Result<bool, FcntlError>
where RF: AsRawFd
{

    let arg = match flock {
        // unrwap is safe here
        Some(flock) => FcntlArg::Flock(flock.with_l_type(libc::F_UNLCK.try_into().unwrap())),
            // unwrap is safe here
        None => FcntlArg::Flock(libc::flock::default().with_l_type(libc::F_UNLCK.try_into().unwrap(),)),
    };

    match fcntl(fd, FcntlCmd::SetLock, arg) {
        // Unlocking was successful
        Ok(FcntlArg::Flock(_result)) => Ok(true),
        // This should not happen, unless we have a bug..
        Ok(_) => Err(FcntlError::Internal),
        // "If a conflicting lock is held by another process, this call returns -1 and sets errno to EACCES or EAGAIN."
        //Err(FcntlError::Errno(Some(libc::EACCES))) | Err(FcntlError::Errno(Some(libc::EAGAIN))) => Ok(false),
        // Everything else is also an error
        Err(err) => Err(err),
    }
}


impl FlockOperations for flock {
    /// Sets all fields to 0.
    fn default() -> Self {
        flock {
            l_type: 0,
            l_whence: 0,
            l_start: 0,
            l_len: 0,
            l_pid: 0,
        }
    }

    fn with_l_type(mut self, l_type: c_short) -> Self {
        self.l_type = l_type;
        self
    }

    fn with_locktype(mut self, locktype: FcntlLockType) -> Self {
        self.l_type = locktype.into();
        self
    }
}


impl Display for FcntlError {
    fn fmt(&self, ff: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CommandNotImplemented(cmd) => write!(ff, "{:?} is not implemented for this operation", cmd),
            Self::Errno(Some(errno)) => write!(ff, "syscall returned unknown or unexpected value: {}", errno),
            Self::Errno(None) => write!(ff, "syscall returned error but we could not retrieve errno"),
            Self::Internal => write!(ff, "we encountered an internal error. Please report this as a bug (fcntl)!"),
            Self::InvalidArgForCmd => write!(ff, "the provided arg parameter is invalid for the requested cmd"),
        }
    }
}


impl Error for FcntlError {}


impl From<FcntlCmd> for c_int {
    fn from(cmd: FcntlCmd) -> c_int {
        match cmd {
            FcntlCmd::GetLock => libc::F_GETLK,
            FcntlCmd::SetLock => libc::F_SETLK,
            FcntlCmd::SetLockWait => libc::F_SETLKW,
        }
    }
}

impl From<FcntlLockType> for c_short {
    fn from(locktype: FcntlLockType) -> c_short {
        match locktype {
            // These should never panic as their values are hardcoded in the kernel with low enough values
            FcntlLockType::Read => libc::F_RDLCK.try_into().unwrap(),
            FcntlLockType::Write => libc::F_WRLCK.try_into().unwrap(),
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{OpenOptions, remove_file};

    const LOCK_FILE_NAME: &str = "./test-work-dir/lock-test";

    #[test]
    fn check_cmd_conversion() {
        let pairs = vec![
            (FcntlCmd::GetLock, libc::F_GETLK),
            (FcntlCmd::SetLock, libc::F_SETLK),
            (FcntlCmd::SetLockWait, libc::F_SETLKW),
        ];

        for (cmd, check) in pairs.into_iter() {
            assert_eq!(libc::c_int::from(cmd), check);
        }
    }

    #[test]
    fn ensure_conversions_dont_panic() {
        let _: libc::c_short = libc::F_UNLCK.try_into().unwrap();
    }

    #[test]
    fn check_file_locking_simple() {
        // nested so that `file` goes out of scope before we delete the file again
        let result = {
            let file = OpenOptions::new().write(true).create(true).open(LOCK_FILE_NAME).unwrap();
            is_file_locked(&file, None)
        };

        // cleanup
        let _ = remove_file(LOCK_FILE_NAME);

        // final assertion
        assert_eq!(result, Ok(false));
    }


    #[test]
    fn lock_file_simple() {
        // nested so that `file` goes out of scope before we delete the file again
        // create the file
        {
            let file = OpenOptions::new().write(true).create(true).open(LOCK_FILE_NAME).unwrap();
        }
        let file = OpenOptions::new().read(true).open(LOCK_FILE_NAME).unwrap();

        let result_is_file_locked_before = is_file_locked(&file, None);
        let result_lock_file_read = lock_file(&file, None, None);
        // We would need to test this with a separate process...
        //let result_is_file_locked_after = is_file_locked(&file, None);
        let result_unlock_after = unlock_file(&file, None);

        // cleanup
        let _ = remove_file(LOCK_FILE_NAME);

        // final assertions
        assert_eq!(result_is_file_locked_before, Ok(false), "Verify that file was unlocked");
        assert_eq!(result_lock_file_read, Ok(true), "Lock file");
        //assert_eq!(result_is_file_locked_after, Ok(true));
        assert_eq!(result_unlock_after, Ok(true), "Unlock file");
    }
}