| 1 | use std::{ |
| 2 | ffi::c_int, |
| 3 | fs::File, |
| 4 | io::Result, |
| 5 | os::fd::{AsRawFd, RawFd}, |
| 6 | }; |
| 7 | |
| 8 | use crate::cutils::cerr; |
| 9 | |
| 10 | pub(crate) struct FileLock { |
| 11 | fd: RawFd, |
| 12 | } |
| 13 | |
| 14 | impl FileLock { |
| 15 | /// Get an exclusive lock on the file, waits if there is currently a lock |
| 16 | /// on the file if `nonblocking` is true. |
| 17 | pub(crate) fn exclusive(file: &File, nonblocking: bool) -> Result<Self> { |
| 18 | let fd = file.as_raw_fd(); |
| 19 | flock(fd, LockOp::LockExclusive, nonblocking)?; |
| 20 | Ok(Self { fd }) |
| 21 | } |
| 22 | |
| 23 | /// Release the lock on the file. |
| 24 | pub(crate) fn unlock(self) -> Result<()> { |
| 25 | flock(self.fd, LockOp::Unlock, false) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | impl Drop for FileLock { |
| 30 | fn drop(&mut self) { |
| 31 | flock(self.fd, LockOp::Unlock, false).ok(); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[derive(Clone, Copy, Debug)] |
| 36 | enum LockOp { |
| 37 | LockExclusive, |
| 38 | Unlock, |
| 39 | } |
| 40 | |
| 41 | impl LockOp { |
| 42 | fn as_flock_operation(self) -> c_int { |
| 43 | match self { |
| 44 | LockOp::LockExclusive => libc::LOCK_EX, |
| 45 | LockOp::Unlock => libc::LOCK_UN, |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | fn flock(fd: RawFd, action: LockOp, nonblocking: bool) -> Result<()> { |
| 51 | let mut operation = action.as_flock_operation(); |
| 52 | if nonblocking { |
| 53 | operation |= libc::LOCK_NB; |
| 54 | } |
| 55 | |
| 56 | // SAFETY: even if `fd` would not be a valid file descriptor, that would merely |
| 57 | // result in an error condition, not UB |
| 58 | cerr(unsafe { libc::flock(fd, operation) })?; |
| 59 | Ok(()) |
| 60 | } |
| 61 | |
| 62 | #[cfg(test)] |
| 63 | mod tests { |
| 64 | use crate::system::tests::tempfile; |
| 65 | |
| 66 | use super::*; |
| 67 | |
| 68 | #[test] |
| 69 | fn test_locking_of_tmp_file() { |
| 70 | let f = tempfile().unwrap(); |
| 71 | |
| 72 | FileLock::exclusive(&f, false).unwrap().unlock().unwrap(); |
| 73 | } |
| 74 | } |