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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
#![cfg_attr(not(feature = "std"), no_std)]
//! API to use files as a lock. Supports non-std crates by disabling feature
//! `std`.
//!
//! # Types
//! Currently, only one type is provided: [`LockFile`]. It does not destroy the
//! file after closed and behaviour on locking different file handles owned by
//! the same process is different between Unix and Windows. # Example:
//!
//! # Example
//! ```
//! use fslock::LockFile;
//! fn main() -> Result<(), fslock::Error> {
//!
//! let mut file = LockFile::open("mylock.test")?;
//! file.lock()?;
//! do_stuff();
//! file.unlock()?;
//!
//! Ok(())
//! }
//! # fn do_stuff() {
//! # // doing stuff here.
//! # }
//! ```
#[cfg(unix)]
mod unix;
#[cfg(unix)]
use crate::unix as sys;
#[cfg(all(unix, feature = "multilock"))]
mod unix_fileid;
#[cfg(all(unix, feature = "multilock"))]
use unix_fileid as fileid;
#[cfg(not(all(unix, feature = "multilock")))]
mod nil_fileid;
#[cfg(not(all(unix, feature = "multilock")))]
use nil_fileid as fileid;
/// Enumeration used to declare whether FsLock instances opened with the same
/// file, by the same process, are exclusive.
#[derive(Debug, Copy, Clone)]
#[non_exhaustive]
enum Exclusivity {
/// Treat any two file descriptors to the same file as having
/// separate locks.
///
/// This option requires allocation internally, and is not
/// available on Unix when building without the `std` feature.
#[cfg(any(not(unix), feature = "multilock"))]
PerFileDesc,
/// Os-dependent behavior.
OsDependent,
}
#[cfg(windows)]
mod windows;
#[cfg(windows)]
use crate::windows as sys;
pub use crate::sys::{Error, OsStr, OsString};
#[cfg(feature = "std")]
use std::{
ffi,
path::{Path, PathBuf},
};
use core::{fmt, ops::Deref};
impl Clone for OsString {
fn clone(&self) -> Self {
self.to_os_str()
.and_then(|str| str.into_os_string())
.expect("Allocation error")
}
}
impl fmt::Debug for OsString {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{:?}", self.as_ref())
}
}
impl fmt::Display for OsString {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.as_ref())
}
}
impl Deref for OsString {
type Target = OsStr;
fn deref(&self) -> &OsStr {
self.as_ref()
}
}
/// Either borrowed or owned allocation of an OS-native string.
#[derive(Debug)]
pub enum EitherOsStr<'str> {
/// Borrowed allocation.
Borrowed(&'str OsStr),
/// Owned allocation.
Owned(OsString),
}
impl<'str> AsRef<OsStr> for EitherOsStr<'str> {
fn as_ref(&self) -> &OsStr {
match self {
Self::Borrowed(str) => str,
Self::Owned(string) => string.as_ref(),
}
}
}
impl<'str> Deref for EitherOsStr<'str> {
type Target = OsStr;
fn deref(&self) -> &OsStr {
self.as_ref()
}
}
/// Conversion of anything into an owned OS-native string. If allocation fails,
/// an error shall be returned.
pub trait IntoOsString {
/// Converts with possible allocation error.
fn into_os_string(self) -> Result<OsString, Error>;
}
impl IntoOsString for OsString {
fn into_os_string(self) -> Result<OsString, Error> {
Ok(self)
}
}
impl<'str> IntoOsString for EitherOsStr<'str> {
fn into_os_string(self) -> Result<OsString, Error> {
match self {
Self::Borrowed(str) => str.into_os_string(),
Self::Owned(string) => Ok(string),
}
}
}
#[cfg(feature = "std")]
impl<'str> IntoOsString for &'str ffi::OsStr {
fn into_os_string(self) -> Result<OsString, Error> {
self.to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl IntoOsString for PathBuf {
fn into_os_string(self) -> Result<OsString, Error> {
(*self).into_os_string()
}
}
#[cfg(feature = "std")]
impl<'str> IntoOsString for &'str Path {
fn into_os_string(self) -> Result<OsString, Error> {
AsRef::<ffi::OsStr>::as_ref(self).to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl IntoOsString for ffi::OsString {
fn into_os_string(self) -> Result<OsString, Error> {
(*self).into_os_string()
}
}
impl<'str> IntoOsString for &'str str {
fn into_os_string(self) -> Result<OsString, Error> {
self.to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl IntoOsString for String {
fn into_os_string(self) -> Result<OsString, Error> {
self.to_os_str()?.into_os_string()
}
}
#[cfg(feature = "std")]
impl ToOsStr for String {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
(**self).to_os_str()
}
}
/// Conversion of anything to an either borrowed or owned OS-native string. If
/// allocation fails, an error shall be returned.
pub trait ToOsStr {
/// Converts with possible allocation error.
fn to_os_str(&self) -> Result<EitherOsStr, Error>;
}
impl<'str> ToOsStr for EitherOsStr<'str> {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
Ok(match self {
EitherOsStr::Owned(string) => {
EitherOsStr::Owned(string.to_os_str()?.into_os_string()?)
},
EitherOsStr::Borrowed(str) => EitherOsStr::Borrowed(str),
})
}
}
impl ToOsStr for OsStr {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
Ok(EitherOsStr::Borrowed(self))
}
}
impl ToOsStr for OsString {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
Ok(EitherOsStr::Borrowed(self.as_ref()))
}
}
#[cfg(feature = "std")]
impl ToOsStr for ffi::OsString {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
(**self).to_os_str()
}
}
#[cfg(feature = "std")]
impl ToOsStr for PathBuf {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
(**self).to_os_str()
}
}
#[cfg(feature = "std")]
impl ToOsStr for Path {
fn to_os_str(&self) -> Result<EitherOsStr, Error> {
AsRef::<ffi::OsStr>::as_ref(self).to_os_str()
}
}
#[derive(Debug)]
/// A handle to a file that is lockable. Does not delete the file.
///
/// # Multiple Handles/Descriptors To The Same File
///
/// The underlying file locking code behaves differently on Windows
/// and Unix when the same process tries to lock the same file via two
/// different LockFiles. See [`LockFile::open()`] for more
/// information. You can work around this OS dependency by using
/// [`LockFile::open_excl()`].
///
/// # Example
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// file.lock()?;
/// do_stuff();
/// file.unlock()?;
///
/// # Ok(())
/// # }
/// # fn do_stuff() {
/// # // doing stuff here.
/// # }
/// ```
pub struct LockFile {
locked: bool,
id: fileid::FileId,
desc: sys::FileDesc,
}
impl LockFile {
/// Opens a file for locking. Exclusive here means the lock is exclusive to
/// a file descriptor/handle on all platforms, instead of Unix's behaviour
/// of locking for the whole process. Do not confuse "exclusive" with the
/// terminology of Linux's and BSD's flock system call.
///
/// On Unix, if the path is nul-terminated (ends with 0), no extra
/// allocation will be made.
///
/// # Panics
/// Panics if the path contains a nul-byte in a place other than the end.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open_excl("mylock.test")?;
///
/// # Ok(())
/// # }
/// ```
///
/// # Example with multiple locks.
///
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut lock1 = LockFile::open_excl("mylock.test")?;
/// let mut lock2 = LockFile::open_excl("mylock.test")?;
///
/// lock1.lock()?;
/// // We're holding the lock via lock1: locking via lock2 will fail.
/// assert_eq!(lock2.try_lock()?, false);
/// # Ok(())
/// # }
/// ```
///
/// # Panicking Example
///
/// ```should_panic
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("my\0lock")?;
///
/// # Ok(())
/// # }
/// ```
///
/// # Availability
///
/// This function is only available on Unix when the `multilock`
/// feature is enabled.
#[cfg(any(not(unix), feature = "multilock"))]
pub fn open_excl<P>(path: &P) -> Result<Self, Error>
where
P: ToOsStr + ?Sized,
{
Self::open_internal(path, Exclusivity::PerFileDesc)
}
/// Opens a file for locking, with OS-dependent locking behavior. On Unix,
/// if the path is nul-terminated (ends with 0), no extra
/// allocation will be made.
///
/// # Multiple Handles/Descriptors to the same file.
///
/// This function replicates the underlying OS behavior from file
/// locking, which gives different results on Windows and Unix
/// when the same process tries to lock the same file more than
/// once.
///
/// Windows treats each _handle_ to a file as having its own lock,
/// whereas Unix treats all descriptors for a file as sharing a
/// lock for the whole process. This means that on Windows you may
/// open a file, lock it, open it again, and when you try to lock the
/// second handle, it will block until the first lock is
/// released. Meanwhile, Unix will check whether your process already
/// owns the look, see that you already locked the file, and simply
/// return as you already have the lock! It will only block if there
/// is a _different_ process holding the lock. Also, unlocking one
/// file descriptor on unix will unlock the file for the whole
/// process.
///
/// For consistent behavior across operating systems, you can
/// either make sure that the same file is never locked more than
/// once by the same process, or you can use the
/// [`LockFile::open_excl()`] call instead (which requires
/// `multilock` and `std` on Unix).
///
/// # Compatibility
///
/// The lock files returned by this method can exhibit
/// OS-dependent behavior: See "Multiple Handles/Descriptors To
/// The Same File" in the documentation for [`LockFile`].
///
/// # Panics
/// Panics if the path contains a nul-byte in a place other than the end.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
///
/// # Ok(())
/// # }
/// ```
///
/// # Panicking Example
///
/// ```should_panic
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("my\0lock")?;
///
/// # Ok(())
/// # }
/// ```
pub fn open<P>(path: &P) -> Result<Self, Error>
where
P: ToOsStr + ?Sized,
{
Self::open_internal(path, Exclusivity::OsDependent)
}
/// Implementation helper for open_excl and open.
fn open_internal<P>(path: &P, ex: Exclusivity) -> Result<Self, Error>
where
P: ToOsStr + ?Sized,
{
let path = path.to_os_str()?;
let desc = sys::open(path.as_ref())?;
let id = fileid::FileId::get_id(desc, ex)?;
Ok(Self { locked: false, id, desc })
}
/// Locks this file. Blocks while it is not possible to lock (i.e. someone
/// else already owns a lock. After locked, if no attempt to unlock is made,
/// it will be automatically unlocked on the file handle drop.
///
/// # Panics
/// Panics if this handle already owns the file.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// file.lock()?;
/// do_stuff();
/// file.unlock()?;
///
/// # Ok(())
/// # }
/// # fn do_stuff() {
/// # // doing stuff here.
/// # }
/// ```
///
/// # Panicking Example
///
/// ```should_panic
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// file.lock()?;
/// file.lock()?;
///
/// # Ok(())
/// # }
/// ```
pub fn lock(&mut self) -> Result<(), Error> {
if self.locked {
panic!("Cannot lock if already owning a lock");
}
self.id.take_lock();
// We got the fileid lock; now try to lock the file.
if let Err(error) = sys::lock(self.desc) {
self.id.release_lock();
return Err(error);
}
self.locked = true;
Ok(())
}
/// Locks this file. Does NOT block if it is not possible to lock (i.e.
/// someone else already owns a lock. After locked, if no attempt to
/// unlock is made, it will be automatically unlocked on the file handle
/// drop.
///
/// # Panics
/// Panics if this handle already owns the file.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// if file.try_lock()? {
/// do_stuff();
/// file.unlock()?;
/// }
///
/// # Ok(())
/// # }
/// # fn do_stuff() {
/// # // doing stuff here.
/// # }
/// ```
///
/// # Panicking Example
///
/// ```should_panic
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// file.lock()?;
/// file.try_lock()?;
///
/// # Ok(())
/// # }
/// ```
pub fn try_lock(&mut self) -> Result<bool, Error> {
if self.locked {
panic!("Cannot lock if already owning a lock");
}
if self.id.try_take_lock() {
// We got the fileid lock; now try to lock the file.
let lock_result = sys::try_lock(self.desc);
match lock_result {
Ok(true) => self.locked = true,
_ => self.id.release_lock(),
}
lock_result
} else {
Ok(false)
}
}
/// Returns whether this file handle owns the lock.
///
/// # Example
/// ```
/// use fslock::LockFile;
/// # fn main() -> Result<(), fslock::Error> {
///
/// let mut file = LockFile::open("mylock.test")?;
/// do_stuff_with_lock(&mut file);
/// if !file.owns_lock() {
/// file.lock()?;
/// do_stuff();
/// file.unlock()?;
/// }
///
/// # Ok(())
/// # }
/// # fn do_stuff_with_lock(_lock: &mut LockFile) {
/// # // doing stuff here.
/// # }
/// # fn do_stuff() {
/// # // doing stuff here.
/// # }
/// ```
pub fn owns_lock(&self) -> bool {
self.locked
}
/// Unlocks this file. This file handle must own the file lock. If not
/// called manually, it is automatically called on `drop`.
///
/// # Panics
/// Panics if this handle does not own the file.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// file.lock()?;
/// do_stuff();
/// file.unlock()?;
///
/// # Ok(())
/// # }
/// # fn do_stuff() {
/// # // doing stuff here.
/// # }
/// ```
///
/// # Panicking Example
///
/// ```should_panic
/// # fn main() -> Result<(), fslock::Error> {
/// use fslock::LockFile;
///
/// let mut file = LockFile::open("mylock.test")?;
/// file.unlock()?;
///
/// # Ok(())
/// # }
/// ```
pub fn unlock(&mut self) -> Result<(), Error> {
if !self.locked {
panic!("Attempted to unlock already locked lockfile");
}
self.locked = false;
sys::unlock(self.desc)?;
self.id.release_lock();
Ok(())
}
}
impl Drop for LockFile {
fn drop(&mut self) {
if self.locked {
let _ = sys::unlock(self.desc);
self.id.release_lock();
self.locked = false;
}
sys::close(self.desc);
}
}
// Safe because:
// 1. We never actually access the contents of the pointer that represents the
// Windows Handle.
//
// 2. We require a mutable reference to actually mutate the file
// system.
#[cfg(windows)]
unsafe impl Send for LockFile {}
#[cfg(windows)]
unsafe impl Sync for LockFile {}
#[cfg(test)]
mod test {
#[cfg(all(feature = "std", any(not(unix), feature = "multilock")))]
#[test]
fn exclusive_lock_cases() -> Result<(), crate::Error> {
let mut f1 = crate::LockFile::open_excl("lock2.test")?;
let mut f2 = crate::LockFile::open_excl("lock2.test")?;
// f1 will get the lock; f2 can't.
assert!(f1.try_lock()?);
assert!(!f2.try_lock()?);
// have f2 wait for f1.
let thr = std::thread::spawn(move || {
f2.lock().unwrap();
f2
});
// Sleep here a little, so that the other thread has time to
// block on the fd-lock.
std::thread::sleep(std::time::Duration::from_millis(100));
drop(f1); // Causes f1 to unlock.
let f2 = thr.join().unwrap();
assert!(f2.owns_lock());
Ok(())
}
}