1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
use std::{fs, path::Path};
52

            
53
/// A lock-file for which we hold the lock.
54
///
55
/// So long as this object exists, we hold the lock on this file.
56
/// When it is dropped, we will release the lock.
57
///
58
/// # Semantics
59
///
60
///  * Only one `LockFileGuard` can exist at one time
61
///    for any particular `path`.
62
///  * This applies across all tasks and threads in all programs;
63
///    other acquisitions of the lock in the same process are prevented.
64
///  * This applies across even separate machines, if `path` is on a shared filesystem.
65
///
66
/// # Restrictions
67
///
68
///  * **`path` must only be deleted (or renamed) via the APIs in this module**
69
///  * This restriction applies to all programs on the computer,
70
///    so for example automatic file cleaning with `find` and `rm` is forbidden.
71
///  * Cross-filesystem locking is broken on Linux before 2.6.12.
72
#[derive(Debug)]
73
pub struct LockFileGuard {
74
    /// A [`File`](fs::File) with its exclusive lock held.
75
    ///
76
    /// This `File` instance will remain locked for as long as this
77
    /// LockFileGuard exists.
78
    locked_file: fs::File,
79
}
80

            
81
impl LockFileGuard {
82
    /// Try to open `path` with options suitable for using it as a lockfile,
83
    /// creating it as necessary.
84
22979
    fn open<P>(path: P) -> Result<fs::File, std::io::Error>
85
22979
    where
86
22979
        P: AsRef<Path>,
87
    {
88
22979
        fs::OpenOptions::new()
89
22979
            .read(true)
90
22979
            .write(true)
91
22979
            .create(true)
92
22979
            .truncate(false)
93
22979
            .open(&path)
94
22979
    }
95

            
96
    /// Try to construct a new [`LockFileGuard`] representing a lock we hold on
97
    /// the file `path`.
98
    ///
99
    /// Blocks until we can get the lock.
100
6
    pub fn lock<P>(path: P) -> Result<Self, std::io::Error>
101
6
    where
102
6
        P: AsRef<Path>,
103
    {
104
6
        let path = path.as_ref();
105
        loop {
106
6
            let file = Self::open(path)?;
107
6
            do_lock(&file)?;
108

            
109
6
            if os::lockfile_has_path(&file, path)? {
110
6
                return Ok(Self { locked_file: file });
111
            }
112
        }
113
6
    }
114

            
115
    /// Try to construct a new [`LockFileGuard`] representing a lock we hold on
116
    /// the file `path`.
117
    ///
118
    /// Does not block; returns Ok(None) if somebody else holds the lock.
119
22973
    pub fn try_lock<P>(path: P) -> Result<Option<Self>, std::io::Error>
120
22973
    where
121
22973
        P: AsRef<Path>,
122
    {
123
22973
        let path = path.as_ref();
124
22973
        let file = Self::open(path)?;
125
22973
        match do_try_lock(&file) {
126
            Ok(()) => {
127
22969
                if os::lockfile_has_path(&file, path)? {
128
22969
                    Ok(Some(Self { locked_file: file }))
129
                } else {
130
                    Ok(None)
131
                }
132
            }
133
4
            Err(fs::TryLockError::WouldBlock) => Ok(None),
134
            Err(fs::TryLockError::Error(e)) => Err(e),
135
        }
136
22973
    }
137

            
138
    /// Try to delete the lock file that we hold.
139
    ///
140
    /// The provided `path` must be the same as was passed to `lock`.
141
76
    pub fn delete_lock_file<P>(self, path: P) -> Result<(), std::io::Error>
142
76
    where
143
76
        P: AsRef<Path>,
144
    {
145
76
        let path = path.as_ref();
146
76
        if os::lockfile_has_path(&self.locked_file, path)? {
147
76
            std::fs::remove_file(path)
148
        } else {
149
            Err(std::io::Error::other(MismatchedPathError {}))
150
        }
151
76
    }
152
}
153

            
154
impl Drop for LockFileGuard {
155
    // We pro-actively unlock the file rather than relying on drop of the File closing it.
156
    //
157
    // This is necessary on Unix because otherwise the following scenario is possible:
158
    //   0. The process has multiple threads
159
    //   1. Thread A executes fork (eg as part of spawn), and the child gets a copy of the fd,
160
    //   2. Thread B drops the `LockFileGuard` and calls close() on its copy of the fd
161
    //   3. Thread B tries to re-acquire the same lock with try_lock and fails
162
    //   4. Thread A closes the fd (via exec, or otherwise)
163
    // We want to prevent the error in step 3, which arises from a race which is possible
164
    // due to us violating the expected semantics of a guard (namely, that the lock is
165
    // synchronously released when the guard is dropped).
166
    #[allow(clippy::unnecessary_lazy_evaluations)] // we want to write the discarded error type
167
26704
    fn drop(&mut self) {
168
26704
        self.locked_file
169
26704
            .unlock()
170
            // Ignore errors from unlock.  There shouldn't be any, but if there are we
171
            // don't have anything sensible we could do with them.
172
26704
            .unwrap_or_else(|_: std::io::Error| ());
173
26704
    }
174
}
175

            
176
/// Try to lock `f`, blocking if need be.
177
///
178
/// On non-android, this just calls [`fs::File::lock`].
179
#[cfg(not(target_os = "android"))]
180
6
fn do_lock(f: &fs::File) -> std::io::Result<()> {
181
6
    f.lock()
182
6
}
183

            
184
/// Try to lock `f`, without blocking.
185
///
186
/// On non-android, this just calls [`fs::File::try_lock`].
187
#[cfg(not(target_os = "android"))]
188
27238
fn do_try_lock(f: &fs::File) -> Result<(), std::fs::TryLockError> {
189
27238
    f.try_lock()
190
27238
}
191

            
192
/// Try to lock `f`, blocking if need be.
193
///
194
/// On android, we need to use flock manually, since Rust (as of May 2026)
195
/// always returns "not implemented" for `lock()` and `try_lock()`.
196
///
197
/// See <https://github.com/rust-lang/rust/issues/148325>.
198
/// Apparently,
199
/// although there are filesystems (specifically FUSE filesystems)
200
/// where flock won't work, it will correctly report ENOSYS
201
/// on those filesystems.
202
//
203
// TODO MSRV ????: we can remove this once Rust supports file locking on Android
204
// at our MSRV.  As of May 2026, https://github.com/rust-lang/rust/pull/157038/
205
// seems like the likeliest MR for that, but it has not been merged.
206
#[cfg(target_os = "android")]
207
fn do_lock(f: &fs::File) -> std::io::Result<()> {
208
    use std::os::fd::AsRawFd;
209

            
210
    let fd = f.as_raw_fd();
211
    // SAFETY: Since `f` is a file, it has a valid fd.
212
    let success = unsafe { libc::flock(fd, libc::LOCK_EX) } == 0;
213

            
214
    if success {
215
        Ok(())
216
    } else {
217
        Err(std::io::Error::last_os_error())
218
    }
219
}
220

            
221
/// Try to lock `f`, without blocking.
222
///
223
/// On android, we need to use flock manually, since Rust (as of May 2026)
224
/// always returns "not implemented" for `lock()` and `try_lock()`.
225
///
226
/// See <https://github.com/rust-lang/rust/issues/148325>.
227
/// Apparently,
228
/// although there are filesystems (specifically FUSE filesystems)
229
/// where flock won't work, it will correctly report ENOSYS
230
/// on those filesystems.
231
//
232
// TODO MSRV ????: See 'TODO MSRV' on do_lock above.
233
#[cfg(target_os = "android")]
234
fn do_try_lock(f: &fs::File) -> Result<(), std::fs::TryLockError> {
235
    use std::os::fd::AsRawFd;
236

            
237
    let fd = f.as_raw_fd();
238
    // SAFETY: Since `f` is a file, it has a valid fd.
239
    let success = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) } == 0;
240

            
241
    if success {
242
        Ok(())
243
    } else {
244
        let err = std::io::Error::last_os_error();
245
        if err.kind() == std::io::ErrorKind::WouldBlock {
246
            Err(std::fs::TryLockError::WouldBlock)
247
        } else {
248
            Err(std::fs::TryLockError::Error(err))
249
        }
250
    }
251
}
252

            
253
/// An error that we return when the path given to `delete_lock_file` does not
254
/// match the file we have.
255
///
256
/// Since we wrap this in an `io::Error`, it doesn't need to be public or fancy.
257
#[derive(thiserror::Error, Debug, Clone)]
258
#[error("Called delete_lock_file with a mismatched path.")]
259
struct MismatchedPathError {}
260

            
261
/// Platform module for locking protocol on Unix.
262
///
263
/// ### Locking protocol on Unix
264
///
265
/// The lock is held by an open-file iff:
266
///
267
///  * that open-file holds an `flock` `LOCK_EX` lock; and
268
///  * the directory entry for `path` refers to the same file as the open-file
269
///
270
/// `path` may only refer to a plain file, or `ENOENT`.
271
/// If `path` refers to a file,
272
/// only the lockholder may cause it to no longer refer to that file.
273
///
274
/// In principle the open-file might be shared with subprocesses.
275
/// Even a naive program can safely and correctly inherit and hold the lock,
276
/// since the lockholder only needs to not close an fd.
277
/// However uncontrolled leaking of the fd into other processes is undesirable,
278
/// as it might cause delays or even deadlocks, if those processes' inheritors live too long.
279
/// In our Rust implementation we don't support sharing the held lock
280
/// with subprocesses or different process images (ie across exec);
281
/// we use `O_CLOEXEC`.
282
///
283
/// #### Locking algorithm
284
///
285
///  1. open the file with `O_CREAT|O_RDWR`
286
///  2. `flock LOCK_EX`
287
///  3. `fstat` the open-file and `lstat` the path
288
///  4. If the inode and device numbers don't match,
289
///     close the fd and go back to the start.
290
///  5. Now we hold the lock.
291
///
292
/// Proof sketch:
293
///
294
/// If we get to point 5, we see that at point 3, we had the lock.
295
/// No-one else could cause the conditions to become false
296
/// in the meantime:
297
/// no-one else ~~can~~ may make `path` refer to a different file
298
/// since they don't hold the lock.
299
/// And, no-one else can `flock` it since the kernel prevents
300
/// a conflicting lock.
301
/// So at step 5 we must still hold the lock.
302
///
303
/// #### Unlocking algorithm
304
///
305
///  1. Close the fd.
306
///  2. Now we no longer hold the lock and others can acquire it.
307
///
308
/// This drops the open-file and
309
/// leaves the lock available for another caller.
310
///
311
/// #### Deletion algorithm
312
///
313
///  0. The lock must already be held
314
///  1. `unlink` the file
315
///  2. close the fd
316
///  3. Now we no longer hold the lock and others can acquire it.
317
///
318
/// Step 1 atomically falsifies the lock-holding condition.
319
/// We are allowed to perform it because we hold the lock.
320
///
321
/// Concurrent lockers might open the old file,
322
/// which we are about to delete.
323
/// They will acquire their `flock` (locking step 2)
324
/// after we close (deletion step 2)
325
/// and then see that they have a stale file.
326
#[cfg(unix)]
327
mod os {
328
    use std::{fs::File, os::unix::fs::MetadataExt as _, path::Path};
329

            
330
    /// Return true if `lf` currently exists with the given `path`, and false otherwise.
331
29136
    pub(crate) fn lockfile_has_path(lf: &File, path: &Path) -> std::io::Result<bool> {
332
29136
        let m1 = std::fs::metadata(path)?;
333
29136
        let m2 = lf.metadata()?;
334

            
335
29136
        Ok(m1.ino() == m2.ino() && m1.dev() == m2.dev())
336
29136
    }
337
}
338

            
339
/// Platform module for locking protocol on Windows.
340
///
341
/// The argument for correctness on Windows proceeds as for Unix, but with a
342
/// higher degree of uncertainty, since we are not sufficient Windows experts to
343
/// determine if our assumptions hold.
344
///
345
/// Here we assume as follows:
346
/// * When `File::open` calls `CreateFileW`, it gets a `HANDLE` to an open file.
347
///   As we use them, the `HANDLE` behaves
348
///   similarly to the "fd" in the Unix argument above,
349
///   and the open file behaves similarly to the "open-file".
350
///   * We assume that any differences that exist in their behavior do not
351
///     affect our correctness above.
352
/// * When `File::lock` calls `LockFileEx`, and it completes successfully,
353
///   we now have a lock on the file.
354
///   Only one lock can exist on a file at a time.
355
/// * When we compare members of `handle.metadata()` and `path.metadata()`,
356
///   the comparison will return equal if ~~and only if~~
357
///   the two files are truly the same.
358
///   * We rely on the property that a file cannot change its file_index while it is
359
///     open.
360
/// * Deleting the lock file will actually work, since `File::open` opened it with
361
///   FILE_SHARE_DELETE.  (This is the default according to the documentation
362
///   for `OpenOptionsExt::share_mode`.)
363
/// * When we delete the lock file, possibly-asynchronous ("deferred") deletion
364
///   definitely won't mean that the OS kernel violates our rule that no-one but the lockholder
365
///   is allowed to delete the file.
366
/// * The above is true even if someone with read
367
///   access to the file - eg the human user - opens it without the FILE_SHARE options.
368
/// * The same is true even if there is a virus scanner.
369
/// * The same is true even on a remote filesystem.
370
/// * If someone with read access to the file - eg the human user - opens it for reading
371
///   without FILE_SHARE options, the algorithm will still work and not fail
372
///   with a file sharing violation io error.
373
///   (Or, every program the user might use to randomly peer at files in arti's
374
///   state directory, including the equivalents of `grep -R` and backup programs,
375
///   will use suitable FILE_SHARE options.)
376
///   (If this assumption is false, the consequence is not data loss;
377
///   rather, arti would fall over.  So that would be tolerable if we don't
378
///   know how to do better, or if doing better is hard.)
379
#[cfg(windows)]
380
mod os {
381
    use std::{fs::File, mem::MaybeUninit, os::windows::io::AsRawHandle, path::Path};
382
    use windows_sys::Win32::{
383
        Foundation::HANDLE,
384
        Storage::FileSystem::{FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx},
385
    };
386

            
387
    /// Use `GetFileInformationByHandleEx` to return a FILE_ID_INFO data for `f`.
388
    ///
389
    /// `GetFileInformationByHandleEx` is supported in Vista and later, so it
390
    /// should be fine here.  Unlike GetFileInformationByHandle, it gives
391
    /// 128-bit identifiers which are supposedly even more unique.
392
    fn get_id_info(f: &File) -> std::io::Result<FILE_ID_INFO> {
393
        let handle = f.as_raw_handle() as HANDLE;
394
        let mut info: MaybeUninit<FILE_ID_INFO> = MaybeUninit::uninit();
395
        let buffersize: u32 = std::mem::size_of::<FILE_ID_INFO>()
396
            .try_into()
397
            .expect("sizeof(FILE_ID_INFO) is ridiculously large");
398

            
399
        let info = unsafe {
400
            // SAFETY: Since `size` is the size of info, this will not write to
401
            // uninitialized memory.
402
            let rv = GetFileInformationByHandleEx(
403
                handle,
404
                FileIdInfo,
405
                info.as_mut_ptr() as _,
406
                buffersize,
407
            );
408

            
409
            if rv == 0 {
410
                return Err(std::io::Error::last_os_error());
411
            }
412

            
413
            // SAFETY: since rv was nonzero, this value is initialized.
414
            info.assume_init()
415
        };
416
        Ok(info)
417
    }
418

            
419
    /// Return true if `lf` currently exists with the given `path`, and false otherwise.
420
    pub(crate) fn lockfile_has_path(lf: &File, path: &Path) -> std::io::Result<bool> {
421
        let f2 = File::open(path)?;
422

            
423
        // Note: we would like to just use the MetadataExt methods for index and
424
        // volume serial number, but they are currently available only on
425
        // nightly: https://github.com/rust-lang/rust/issues/63010
426
        //
427
        // If they stabilize at our MSRV, _and_ the file ID is expanded to the
428
        // 128-bit version, we can use them here instead.
429

            
430
        let i1 = get_id_info(lf)?;
431
        let i2 = get_id_info(&f2)?;
432

            
433
        // This comparison is about the best we can do on Windows,
434
        // though there are caveats.
435
        //
436
        // See Raymond Chen's writeup at
437
        //   https://devblogs.microsoft.com/oldnewthing/20220128-00/?p=106201
438
        // and also see BurntSushi's caveats at
439
        //   https://github.com/BurntSushi/same-file/blob/master/src/win.rs
440
        Ok(i1.VolumeSerialNumber == i2.VolumeSerialNumber
441
            && i1.FileId.Identifier == i2.FileId.Identifier)
442
    }
443
}
444

            
445
/// Non-windows, non-unix implementation for lockfile_has_path.
446
///
447
/// For now, this implementation always reports an error.
448
/// It exists so that we can build (but not run) on wasm.
449
#[cfg(all(not(windows), not(unix)))]
450
mod os {
451
    use std::path::Path;
452

            
453
    /// Return true if `lf` currently exists with the given `path`, and false otherwise.
454
    pub(crate) fn lockfile_has_path(_lf: &std::fs::File, _path: &Path) -> std::io::Result<bool> {
455
        Err(std::io::Error::other(
456
            "fslock-guard does not support this operating system".to_string(),
457
        ))
458
    }
459
}
460

            
461
#[cfg(test)]
462
mod tests {
463
    // @@ begin test lint list maintained by maint/add_warning @@
464
    #![allow(clippy::bool_assert_comparison)]
465
    #![allow(clippy::clone_on_copy)]
466
    #![allow(clippy::dbg_macro)]
467
    #![allow(clippy::mixed_attributes_style)]
468
    #![allow(clippy::print_stderr)]
469
    #![allow(clippy::print_stdout)]
470
    #![allow(clippy::single_char_pattern)]
471
    #![allow(clippy::unwrap_used)]
472
    #![allow(clippy::unchecked_time_subtraction)]
473
    #![allow(clippy::useless_vec)]
474
    #![allow(clippy::needless_pass_by_value)]
475
    #![allow(clippy::string_slice)] // See arti#2571
476
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
477

            
478
    use crate::LockFileGuard;
479
    use std::sync::Arc;
480
    use std::thread;
481
    use test_temp_dir::test_temp_dir;
482

            
483
    #[test]
484
    fn keep_lock_file_after_drop() {
485
        test_temp_dir!().used_by(|dir| {
486
            let file = dir.join("file");
487
            let flock_guard = LockFileGuard::lock(&file).unwrap();
488
            assert!(file.try_exists().unwrap());
489
            drop(flock_guard);
490
            assert!(file.try_exists().unwrap());
491
        });
492
    }
493

            
494
    #[test]
495
    fn delete_lock_file_if_requested() {
496
        test_temp_dir!().used_by(|dir| {
497
            let file = dir.join("file");
498
            let flock_guard = LockFileGuard::lock(&file).unwrap();
499
            assert!(file.try_exists().unwrap());
500
            assert!(flock_guard.delete_lock_file(&file).is_ok());
501
            assert!(!file.try_exists().unwrap());
502
        });
503
    }
504

            
505
    #[test]
506
    fn tight_loop() {
507
        let tmp = Arc::new(test_temp_dir!());
508

            
509
        // We make several threads in case there are any cross-thread interactions
510
        // that we're not aware of.  There shouldn't be.
511
        let threads = (0..10)
512
            .map(|i| {
513
                let tmp = tmp.clone();
514
                thread::spawn(move || {
515
                    tmp.used_by(|dir| {
516
                        let file = dir.join(format!("{i}"));
517
                        for _ in 0..1000 {
518
                            // Test that the lock is immediately re-requirable after drop.
519
                            let lock: LockFileGuard =
520
                                LockFileGuard::try_lock(&file).unwrap().unwrap();
521
                            drop(lock);
522
                        }
523
                    });
524
                })
525
            })
526
            .collect::<Vec<_>>();
527

            
528
        for t in threads {
529
            t.join().unwrap_or_else(|e| std::panic::resume_unwind(e));
530
        }
531
    }
532

            
533
    #[test]
534
    #[cfg(unix)]
535
    fn fork_leak_fds() {
536
        use std::ffi::c_int;
537

            
538
        let tmp = test_temp_dir!();
539

            
540
        tmp.used_by(|tmp| {
541
            let file = tmp.join("lock");
542
            let lock = LockFileGuard::lock(&file).unwrap();
543

            
544
            let child = unsafe {
545
                // It would be nicer to do this with std's Command, but
546
                // we'd have to use the unsafe pre-exec hook for synchronisation
547
                // and anyway that runs after Command's impl has closed "unwanted" fds.
548
                match libc::fork() {
549
                    -1 => panic!("fork failed"),
550
                    0 => {
551
                        libc::usleep(10_000);
552
                        libc::_exit(0);
553
                    }
554
                    child => child,
555
                }
556
            };
557

            
558
            drop(lock);
559
            let _lock: LockFileGuard = LockFileGuard::try_lock(&file).unwrap().unwrap();
560

            
561
            unsafe {
562
                let mut status: c_int = 0;
563
                let got = libc::waitpid(child, (&mut status) as *mut _, 0);
564
                assert_eq!(got, child);
565
                assert_eq!(status, 0, "{status}");
566
            }
567
        });
568
    }
569
}