1
#![cfg_attr(docsrs, feature(doc_auto_cfg, 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
#![warn(clippy::cognitive_complexity)]
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_duration_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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
45

            
46
use std::path::Path;
47

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

            
76
impl LockFileGuard {
77
    /// Try to construct a new [`LockFileGuard`] representing a lock we hold on
78
    /// the file `path`.
79
    ///
80
    /// Blocks until we can get the lock.
81
4
    pub fn lock<P>(path: P) -> Result<Self, fslock::Error>
82
4
    where
83
4
        P: AsRef<Path>,
84
4
    {
85
4
        let path = path.as_ref();
86
        loop {
87
4
            let mut lockfile = fslock::LockFile::open(path)?;
88
4
            lockfile.lock()?;
89

            
90
4
            if os::lockfile_has_path(&lockfile, path)? {
91
4
                return Ok(Self { locked: lockfile });
92
            }
93
        }
94
4
    }
95

            
96
    /// Try to construct a new [`LockFileGuard`] representing a lock we hold on
97
    /// the file `path`.
98
    ///
99
    /// Does not block; returns Ok(None) if somebody else holds the lock.
100
643
    pub fn try_lock<P>(path: P) -> Result<Option<Self>, fslock::Error>
101
643
    where
102
643
        P: AsRef<Path>,
103
643
    {
104
643
        let path = path.as_ref();
105
643
        let mut lockfile = fslock::LockFile::open(path)?;
106
643
        if lockfile.try_lock()? && os::lockfile_has_path(&lockfile, path)? {
107
641
            return Ok(Some(Self { locked: lockfile }));
108
2
        }
109
2
        Ok(None)
110
643
    }
111

            
112
    /// Try to delete the lock file that we hold.
113
    ///
114
    /// The provided `path` must be the same as was passed to `lock`.
115
76
    pub fn delete_lock_file<P>(self, path: P) -> Result<(), std::io::Error>
116
76
    where
117
76
        P: AsRef<Path>,
118
76
    {
119
76
        let path = path.as_ref();
120
76
        if os::lockfile_has_path(&self.locked, path)? {
121
76
            std::fs::remove_file(path)
122
        } else {
123
            Err(std::io::Error::other(MismatchedPathError {}))
124
        }
125
76
    }
126
}
127

            
128
/// An error that we return when the path given to `delete_lock_file` does not
129
/// match the file we have.
130
///
131
/// Since we wrap this in an `io::Error`, it doesn't need to be public or fancy.
132
#[derive(thiserror::Error, Debug, Clone)]
133
#[error("Called delete_lock_file with a mismatched path.")]
134
struct MismatchedPathError {}
135

            
136
// Note: This requires AsFd and AsHandle implementations for `LockFile`.
137
//  See https://github.com/brunoczim/fslock/pull/15
138
// This is why we are using fslock-arti-fork in place of fslock.
139

            
140
/// Platform module for locking protocol on Unix.
141
///
142
/// ### Locking protocol on Unix
143
///
144
/// The lock is held by an open-file iff:
145
///
146
///  * that open-file holds an `flock` `LOCK_EX` lock; and
147
///  * the directory entry for `path` refers to the same file as the open-file
148
///
149
/// `path` may only refer to a plain file, or `ENOENT`.
150
/// If `path` refers to a file,
151
/// only the lockholder may cause it to no longer refer to that file.
152
///
153
/// In principle the open-file might be shared with subprocesses.
154
/// Even a naive program can safely and correctly inherit and hold the lock,
155
/// since the lockholder only needs to not close an fd.
156
/// However uncontrolled leaking of the fd into other processes is undesirable,
157
/// as it might cause delays or even deadlocks, if those processes' inheritors live too long.
158
/// In our Rust implementation we don't support sharing the held lock
159
/// with subprocesses or different process images (ie across exec);
160
/// we use `O_CLOEXEC`.
161
///
162
/// #### Locking algorithm
163
///
164
///  1. open the file with `O_CREAT|O_RDWR`
165
///  2. `flock LOCK_EX`
166
///  3. `fstat` the open-file and `lstat` the path
167
///  4. If the inode and device numbers don't match,
168
///     close the fd and go back to the start.
169
///  5. Now we hold the lock.
170
///
171
/// Proof sketch:
172
///
173
/// If we get to point 5, we see that at point 3, we had the lock.
174
/// No-one else could cause the conditions to become false
175
/// in the meantime:
176
/// no-one else ~~can~~ may make `path` refer to a different file
177
/// since they don't hold the lock.
178
/// And, no-one else can `flock` it since the kernel prevents
179
/// a conflicting lock.
180
/// So at step 5 we must still hold the lock.
181
///
182
/// #### Unlocking algorithm
183
///
184
///  1. Close the fd.
185
///  2. Now we no longer hold the lock and others can acquire it.
186
///
187
/// This drops the open-file and
188
/// leaves the lock available for another caller.
189
///
190
/// #### Deletion algorithm
191
///
192
///  0. The lock must already be held
193
///  1. `unlink` the file
194
///  2. close the fd
195
///  3. Now we no longer hold the lock and others can acquire it.
196
///
197
/// Step 1 atomically falsifies the lock-holding condition.
198
/// We are allowed to perform it because we hold the lock.
199
///
200
/// Concurrent lockers might open the old file,
201
/// which we are about to delete.
202
/// They will acquire their `flock` (locking step 2)
203
/// after we close (deletion step 2)
204
/// and then see that they have a stale file.
205
#[cfg(unix)]
206
mod os {
207
    use std::{fs::File, os::fd::AsFd, os::unix::fs::MetadataExt as _, path::Path};
208

            
209
    /// Return true if `lf` currently exists with the given `path`, and false otherwise.
210
5572
    pub(crate) fn lockfile_has_path(lf: &fslock::LockFile, path: &Path) -> std::io::Result<bool> {
211
5572
        let m1 = std::fs::metadata(path)?;
212
        // TODO: This does an unnecessary dup().
213
5572
        let f_dup = File::from(lf.as_fd().try_clone_to_owned()?);
214
5572
        let m2 = f_dup.metadata()?;
215

            
216
5572
        Ok(m1.ino() == m2.ino() && m1.dev() == m2.dev())
217
5572
    }
218
}
219

            
220
/// Platform module for locking protocol on Windows.
221
///
222
/// The argument for correctness on Windows proceeds as for Unix, but with a
223
/// higher degree of uncertainty, since we are not sufficient Windows experts to
224
/// determine if our assumptions hold.
225
///
226
/// Here we assume as follows:
227
/// * When `fslock` calls `CreateFileW`, it gets a `HANDLE` to an open file.
228
///   As we use them, the `HANDLE` behaves
229
///   similarly to the "fd" in the Unix argument above,
230
///   and the open file behaves similarly to the "open-file".
231
///   * We assume that any differences that exist in their behavior do not
232
///     affect our correctness above.
233
/// * When `fslock` calls `LockFileEx`, and it completes successfully,
234
///   we now have a lock on the file.
235
///   Only one lock can exist on a file at a time.
236
/// * When we compare members of `handle.metadata()` and `path.metadata()`,
237
///   the comparison will return equal if ~~and only if~~
238
///   the two files are truly the same.
239
///   * We rely on the property that a file cannot change its file_index while it is
240
///     open.
241
/// * Deleting the lock file will actually work, since `fslock` opened it with
242
///   FILE_SHARE_DELETE.
243
/// * When we delete the lock file, possibly-asynchronous ("deferred") deletion
244
///   definitely won't mean that the OS kernel violates our rule that no-one but the lockholder
245
///   is allowed to delete the file.
246
/// * The above is true even if someone with read
247
///   access to the file - eg the human user - opens it without the FILE_SHARE options.
248
/// * The same is true even if there is a virus scanner.
249
/// * The same is true even on a remote filesystem.
250
/// * If someone with read access to the file - eg the human user - opens it for reading
251
///   without FILE_SHARE options, the algorithm will still work and not fail
252
///   with a file sharing violation io error.
253
///   (Or, every program the user might use to randomly peer at files in arti's
254
///   state directory, including the equivalents of `grep -R` and backup programs,
255
///   will use suitable FILE_SHARE options.)
256
///   (If this assumption is false, the consequence is not data loss;
257
///   rather, arti would fall over.  So that would be tolerable if we don't
258
///   know how to do better, or if doing better is hard.)
259
#[cfg(windows)]
260
mod os {
261
    use std::{fs::File, mem::MaybeUninit, os::windows::io::AsRawHandle, path::Path};
262
    use winapi::um::fileapi::{GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION as Info};
263

            
264
    /// Return true if `lf` currently exists with the given `path`, and false otherwise.
265
    pub(crate) fn lockfile_has_path(lf: &fslock::LockFile, path: &Path) -> std::io::Result<bool> {
266
        let mut m1: MaybeUninit<Info> = MaybeUninit::uninit();
267
        let mut m2: MaybeUninit<Info> = MaybeUninit::uninit();
268

            
269
        let f2 = File::open(path)?;
270

            
271
        let (i1, i2) = unsafe {
272
            if GetFileInformationByHandle(lf.as_raw_handle() as _, m1.as_mut_ptr()) == 0 {
273
                return Err(std::io::Error::last_os_error());
274
            }
275
            if GetFileInformationByHandle(f2.as_raw_handle() as _, m2.as_mut_ptr()) == 0 {
276
                return Err(std::io::Error::last_os_error());
277
            }
278
            (m1.assume_init(), m2.assume_init())
279
        };
280

            
281
        // This comparison is about the best we can do on Windows,
282
        // though there are caveats.
283
        //
284
        // See Raymond Chen's writeup at
285
        //   https://devblogs.microsoft.com/oldnewthing/20220128-00/?p=106201
286
        // and also see BurntSushi's caveats at
287
        //   https://github.com/BurntSushi/same-file/blob/master/src/win.rs
288
        Ok(i1.nFileIndexHigh == i2.nFileIndexHigh
289
            && i1.nFileIndexLow == i2.nFileIndexLow
290
            && i1.dwVolumeSerialNumber == i2.dwVolumeSerialNumber)
291
    }
292
}
293

            
294
#[cfg(test)]
295
mod tests {
296
    // @@ begin test lint list maintained by maint/add_warning @@
297
    #![allow(clippy::bool_assert_comparison)]
298
    #![allow(clippy::clone_on_copy)]
299
    #![allow(clippy::dbg_macro)]
300
    #![allow(clippy::mixed_attributes_style)]
301
    #![allow(clippy::print_stderr)]
302
    #![allow(clippy::print_stdout)]
303
    #![allow(clippy::single_char_pattern)]
304
    #![allow(clippy::unwrap_used)]
305
    #![allow(clippy::unchecked_duration_subtraction)]
306
    #![allow(clippy::useless_vec)]
307
    #![allow(clippy::needless_pass_by_value)]
308
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
309

            
310
    use crate::LockFileGuard;
311
    use test_temp_dir::test_temp_dir;
312

            
313
    #[test]
314
    fn keep_lock_file_after_drop() {
315
        test_temp_dir!().used_by(|dir| {
316
            let file = dir.join("file");
317
            let flock_guard = LockFileGuard::lock(&file).unwrap();
318
            assert!(file.try_exists().unwrap());
319
            drop(flock_guard);
320
            assert!(file.try_exists().unwrap());
321
        });
322
    }
323

            
324
    #[test]
325
    fn delete_lock_file_if_requested() {
326
        test_temp_dir!().used_by(|dir| {
327
            let file = dir.join("file");
328
            let flock_guard = LockFileGuard::lock(&file).unwrap();
329
            assert!(file.try_exists().unwrap());
330
            assert!(flock_guard.delete_lock_file(&file).is_ok());
331
            assert!(!file.try_exists().unwrap());
332
        });
333
    }
334
}