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
//! # FdLock
//!
//! `FdLock` is a Rust crate that provides functionality for file locking using `flock` or `fcntl` operations.
//!
//! This crate defines a trait `FdLock` that extends the `AsRawFd` trait,
//! allowing file locks to be placed on file descriptors. It supports both
//! shared and exclusive locks, as well as unlocking operations.
//!
//! ## Examples
//!
//! Placing a shared lock on a file:
//!
//! ```no_run
//! use filelock_rs::FdLock;
//! use std::fs::File;
//!
//! let file = File::open("data.txt").expect("Failed to open file");
//! let lock_result = file.lock_shared();
//!
//! match lock_result {
//!     Ok(()) => {
//!         println!("Shared lock placed on the file");
//!         // Perform operations with the locked file
//!     }
//!     Err(error) => {
//!         eprintln!("Failed to place a shared lock: {}", error);
//!     }
//! }
//! ```
//!
//! Placing an exclusive lock on a file:
//!
//! ```rust
//! use filelock_rs::FdLock;
//! use std::fs::File;
//!
//! let file = File::create("data.txt").expect("Failed to create file");
//! let lock_result = file.lock_exclusive();
//!
//! match lock_result {
//!     Ok(()) => {
//!         println!("Exclusive lock placed on the file");
//!         // Perform operations with the locked file
//!     }
//!     Err(error) => {
//!         eprintln!("Failed to place an exclusive lock: {}", error);
//!     }
//! }
//! ```
//!
//! ## Cleanup
//!
//! The `FdLock` trait is implemented for the `std::fs::File` type. When the `FdLock` methods are
//! used on a `File` instance, the locks are automatically released when they go out of scope.
//!
//! ## Notes
//!
//! - The behavior of file locking may differ depending on the operating system.
//! - The crate uses the `libc` and `io::Result` types from the standard library.
//! - If the file lock operation fails, an `io::Error` is returned.
pub mod pid;
use std::io;
use std::os::fd::AsRawFd;
/// FdLock Operation type.
pub type Operation = libc::c_int;
/// Place a shared lock. More than one process may hold a shared lock for a given file at a given time.
#[allow(dead_code)]
const LOCK_SH: Operation = libc::LOCK_SH;
/// Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time.
#[allow(dead_code)]
const LOCK_EX: Operation = libc::LOCK_EX;
/// Remove an existing lock held by this process.
#[allow(dead_code)]
const LOCK_UN: Operation = libc::LOCK_UN;
/// The `FdLock` trait extends the `AsRawFd` trait, allowing
/// file locks to be placed on file descriptors.
pub trait FdLock: AsRawFd {
    /// Places a file lock on the associated file descriptor using the `flock` operation.
    ///
    /// # Arguments
    ///
    /// * `operation`: The type of lock to place on the file.
    ///
    /// # Errors
    ///
    /// If the lock operation fails, an `io::Error` is returned.
    ///
    #[cfg(not(target_os = "solaris"))]
    fn flock(&self, operation: Operation) -> io::Result<()> {
        let ret = unsafe { libc::flock(self.as_raw_fd(), operation) };
        if ret < 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }
    /// Places a file lock on the associated file descriptor using the `flock` operation.
    ///
    /// # Arguments
    ///
    /// * `operation`: The type of lock to place on the file.
    ///
    /// # Errors
    ///
    /// If the lock operation fails, an `io::Error` is returned.
    ///
    #[cfg(target_os = "solaris")]
    fn flock(&self, operation: Operation) -> io::Result<()> {
        // Solaris lacks flock(), so try to emulate using fcntl()
        let mut flock = libc::flock {
            l_type: 0,
            l_whence: 0,
            l_start: 0,
            l_len: 0,
            l_sysid: 0,
            l_pid: 0,
            l_pad: [0, 0, 0, 0],
        };
        flock.l_type = if operation & LOCK_UN != 0 {
            LOCK_UN
        } else if operation & LOCK_EX != 0 {
            libc::F_WRLCK
        } else if operation & LOCK_SH != 0 {
            libc::F_RDLCK
        } else {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!("unexpected flock() operation"),
            ));
        };
        let mut cmd = libc::F_SETLKW;
        if (flag & libc::LOCK_NB) != 0 {
            cmd = libc::F_SETLK;
        }
        let ret = unsafe { libc::fcntl(file.as_raw_fd(), cmd, &flock) };
        if ret < 0 {
            Err(Error::last_os_error())
        } else {
            Ok(())
        }
    }
    /// Places a shared lock on the file.
    ///
    /// This method uses the `LOCK_SH` operation to place a shared lock on the associated file descriptor.
    ///
    /// # Errors
    ///
    /// If the lock operation fails, an `io::Error` is returned.
    ///
    fn lock_shared(&self) -> io::Result<()> {
        self.flock(libc::LOCK_SH)
    }
    /// Places an exclusive lock on the file.
    ///
    /// This method uses the `LOCK_EX` operation to place an exclusive lock on the associated file descriptor.
    ///
    /// # Errors
    ///
    /// If the lock operation fails, an `io::Error` is returned.
    ///
    fn lock_exclusive(&self) -> io::Result<()> {
        self.flock(libc::LOCK_EX)
    }
    /// Tries to place a shared lock on the file.
    ///
    /// This method uses the `LOCK_SH | LOCK_NB` operations to try placing a shared lock on the associated file descriptor.
    ///
    /// # Errors
    ///
    /// If the lock operation fails or the lock is not immediately available, an `io::Error` is returned.
    ///
    fn try_lock_shared(&self) -> io::Result<()> {
        self.flock(libc::LOCK_SH | libc::LOCK_NB)
    }
    /// Tries to place an exclusive lock on the file.
    ///
    /// This method uses the `LOCK_EX | LOCK_NB` operations to try placing an exclusive lock on the associated file descriptor.
    ///
    /// # Errors
    ///
    /// If the lock operation fails or the lock is not immediately available, an `io::Error` is returned.
    ///
    fn try_lock_exclusive(&self) -> io::Result<()> {
        self.flock(libc::LOCK_EX | libc::LOCK_NB)
    }
    /// Unlocks the file.
    ///
    /// This method removes the lock held by the current process on the associated file descriptor.
    /// It uses the `LOCK_UN` operation to unlock the file.
    ///
    /// # Errors
    ///
    /// If the unlock operation fails, an `io::Error` is returned.
    ///
    fn unlock(&self) -> io::Result<()> {
        self.flock(libc::LOCK_UN)
    }
}
impl FdLock for std::fs::File {}