Skip to content

Commit 0572ce2

Browse files
committed
Merge main into chore/craft-update-6e03f65
2 parents ecc3a58 + fd0b914 commit 0572ce2

21 files changed

Lines changed: 2168 additions & 188 deletions

‎crates/catalog/src/lib.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ pub mod lock;
2626
#[cfg(not(target_arch = "wasm32"))]
2727
mod log_writer;
2828
pub mod model;
29+
pub mod opened_folder;
2930
pub mod query;
3031
pub mod rules;
3132
pub mod safe_file;
@@ -44,6 +45,7 @@ use lightcraft_develop::DevelopSettings;
4445
pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of};
4546
pub use lock::{LibraryLock, LockError, LockOwner};
4647
pub use model::*;
48+
pub use opened_folder::OpenedFolder;
4749
pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64};
4850
pub use rules::{Match, Rule, RuleSet};
4951
use serde::{Deserialize, Serialize};
@@ -1543,6 +1545,8 @@ mod tests_lock;
15431545
#[cfg(all(test, not(target_arch = "wasm32")))]
15441546
mod tests_log_thread;
15451547
#[cfg(test)]
1548+
mod tests_opened_folder;
1549+
#[cfg(test)]
15461550
mod tests_repair;
15471551
#[cfg(test)]
15481552
mod tests_rule_order;

‎crates/catalog/src/lock.rs‎

Lines changed: 87 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,26 @@
1818
//! descriptor frees the lock whatever copies a child still holds.
1919
//! - Who holds it (process id, computer, program, version) is written to `catalog.lock.owner`, for
2020
//! the error message. Only dropping the [`LibraryLock`] removes it, so a program that ends with
21-
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). It's a separate
22-
//! file because a Windows lock also blocks reading the locked file. It's only a hint: it may be
23-
//! missing or left over from a crash.
21+
//! `std::process::exit` releases the lock first (`Session::release_library_lock`). Dropping
22+
//! removes only the note this lock wrote itself, with the bytes it wrote, and only while the
23+
//! path still leads to the folder it locked (a folder that holds exactly that note is it, whatever
24+
//! its numbers say: [`OpenedFolder::vouch`]): a note in another folder (a share mounted over the
25+
//! library's folder), or one another process wrote over ours, belongs to whoever has that library
26+
//! open (issue #3240). It's a separate file because a Windows lock also blocks reading the
27+
//! locked file. It's only a hint: it may be missing or left over from a crash. The note holds a
28+
//! value no other lock's note has ([`LockOwner::token`]), so no two folders hold the same note.
2429
//! - File systems without lock support (some network shares): the library opens unlocked, with a
2530
//! warning — refusing it would lock the user out of their own library. Locks over SMB/NFS are
2631
//! advisory and depend on the server; the owner file is then the only hint.
2732
//! - Browser storage (OPFS) has no file locks: see the web host for its own guard.
2833
2934
use std::fs::{File, OpenOptions, TryLockError};
35+
use std::hash::{BuildHasher, Hasher, RandomState};
3036
use std::io::{self, Write};
3137
use std::path::{Path, PathBuf};
38+
use std::sync::atomic::{AtomicU64, Ordering};
39+
40+
use crate::opened_folder::OpenedFolder;
3241

3342
/// The lock file in the library directory.
3443
pub const LOCK: &str = "catalog.lock";
@@ -47,6 +56,10 @@ pub struct LockOwner {
4756
pub version: String,
4857
/// When it opened the library (seconds since 1970).
4958
pub since: u64,
59+
/// This lock's alone, also among those one process takes in the same second: the note is what
60+
/// tells the folder that was locked from every other ([`OpenedFolder::vouch`], issue #3240), so
61+
/// no two may be the same. A count of locks mixed with a random key. Not a secret.
62+
pub token: String,
5063
}
5164

5265
impl LockOwner {
@@ -58,6 +71,7 @@ impl LockOwner {
5871
program: program.to_string(),
5972
version: env!("CARGO_PKG_VERSION").to_string(),
6073
since: web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0),
74+
token: lock_token(),
6175
}
6276
}
6377

@@ -82,6 +96,14 @@ fn host_name() -> String {
8296
env.or_else(|| std::fs::read_to_string("/etc/hostname").ok()).map(|h| h.trim().to_string()).filter(|h| !h.is_empty()).unwrap_or_default()
8397
}
8498

99+
/// A value no other lock's note has ([`LockOwner::token`]).
100+
fn lock_token() -> String {
101+
static LOCKS: AtomicU64 = AtomicU64::new(0);
102+
let mut h = RandomState::new().build_hasher();
103+
h.write_u64(LOCKS.fetch_add(1, Ordering::Relaxed));
104+
format!("{:016x}", h.finish())
105+
}
106+
85107
#[derive(Debug, thiserror::Error)]
86108
pub enum LockError {
87109
/// Another process has the library open.
@@ -97,14 +119,20 @@ pub struct LibraryLock {
97119
/// `None` when the file system can't lock (the library is open unlocked).
98120
file: Option<File>,
99121
held: bool,
122+
/// The folder `dir` named when the lock was taken: the lock file and the owner note are in it
123+
/// (`None`: it couldn't be looked at).
124+
folder: Option<OpenedFolder>,
125+
/// The owner note as this lock wrote it (`None`: it wrote none).
126+
note: Option<Vec<u8>>,
100127
}
101128

102129
impl LibraryLock {
103130
/// Lock `dir` (which must exist) for this process. Fails only when another process holds it.
104131
pub fn acquire(dir: &Path, program: &str) -> Result<LibraryLock, LockError> {
132+
let folder = OpenedFolder::at(dir).ok();
105133
let unlocked = |why: io::Error| {
106134
log::warn!("library {}: can't lock {LOCK} ({why}); opening it without protection against a second program", dir.display());
107-
LibraryLock { dir: dir.to_path_buf(), file: None, held: false }
135+
LibraryLock { dir: dir.to_path_buf(), file: None, held: false, folder: folder.clone(), note: None }
108136
};
109137
let file = match OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join(LOCK)) {
110138
Ok(f) => f,
@@ -118,15 +146,20 @@ impl LibraryLock {
118146
}
119147
Err(TryLockError::Error(e)) => return Ok(unlocked(e)),
120148
}
121-
// A new file in place of whatever is at the name: a link planted there in a library folder
122-
// someone else prepared is removed, never written through (as for the staging files, #1502).
123-
let owner = LockOwner::this_process(program);
124-
if let Ok(json) = serde_json::to_vec_pretty(&owner)
125-
&& let Err(e) = crate::store::create_staging(&dir.join(OWNER)).and_then(|mut f| f.write_all(&json))
126-
{
127-
log::warn!("library {}: can't write {OWNER}: {e}", dir.display());
128-
}
129-
Ok(LibraryLock { dir: dir.to_path_buf(), file: Some(file), held: true })
149+
let note = serde_json::to_vec_pretty(&LockOwner::this_process(program)).ok().and_then(|json| match write_note(dir, folder.as_ref(), &json) {
150+
Ok(()) => {
151+
// from now on the folder that holds this note is the locked one, whatever its numbers say
152+
if let Some(folder) = &folder {
153+
folder.vouch(&json);
154+
}
155+
Some(json)
156+
}
157+
Err(e) => {
158+
log::warn!("library {}: can't write {OWNER}: {e}", dir.display());
159+
None
160+
}
161+
});
162+
Ok(LibraryLock { dir: dir.to_path_buf(), file: Some(file), held: true, folder, note })
130163
}
131164

132165
/// The OS lock is held (`false`: the file system can't lock; opened unprotected).
@@ -138,24 +171,59 @@ impl LibraryLock {
138171
&self.dir
139172
}
140173

174+
/// The folder the lock was taken in, as `dir` named it then (`None`: it couldn't be looked at).
175+
pub fn folder(&self) -> Option<&OpenedFolder> {
176+
self.folder.as_ref()
177+
}
178+
179+
/// The owner note this lock wrote (`None`: it wrote none, so no folder is told by it).
180+
pub fn note(&self) -> Option<&[u8]> {
181+
self.note.as_deref()
182+
}
183+
141184
/// Another descriptor on the locked file: what a process spawned by another thread holds
142185
/// between fork and exec (a `dup` refers to the same open file description). Tests only (the
143186
/// test that uses it is Unix-only: `flock` semantics).
144187
#[cfg(all(test, unix))]
145188
pub(crate) fn descriptor_copy(&self) -> Option<File> {
146189
self.file.as_ref().and_then(|f| f.try_clone().ok())
147190
}
191+
192+
/// Remove the owner note if it is this lock's: the path still leads to the folder the lock was
193+
/// taken in (or to one that holds this very note), and the note has the bytes this lock wrote
194+
/// there (issue #3240).
195+
fn remove_own_note(&self) {
196+
let Some(ours) = &self.note else { return };
197+
if self.folder.as_ref().is_some_and(|f| f.check().is_err()) {
198+
return;
199+
}
200+
let path = self.dir.join(OWNER);
201+
if crate::opened_folder::holds_exactly(&path, ours) {
202+
let _ = std::fs::remove_file(&path);
203+
}
204+
}
205+
}
206+
207+
/// Write the owner note into `dir`: a new file in place of whatever is at the name (a link planted
208+
/// there in a library folder someone else prepared is removed, never written through, as for the
209+
/// staging files, #1502), and only while `dir` still leads to the folder the lock file was opened in.
210+
fn write_note(dir: &Path, folder: Option<&OpenedFolder>, json: &[u8]) -> io::Result<()> {
211+
if let Some(folder) = folder {
212+
folder.check()?;
213+
}
214+
crate::store::create_staging(&dir.join(OWNER))?.write_all(json)
148215
}
149216

150217
impl Drop for LibraryLock {
151-
/// Remove the owner note while still holding the lock (so it can't delete the next holder's),
152-
/// then release the lock explicitly. Closing the handle isn't enough on Unix: `flock` lasts
153-
/// while any copy of the descriptor is open, and a process another thread is spawning holds a
154-
/// copy of every descriptor until it execs (issue #680). If the unlock fails the handle still
155-
/// closes right after, which releases the lock once every copy is gone, as before.
218+
/// Remove the owner note, if it is ours, while still holding the lock (so it can't delete the
219+
/// next holder's), then release the lock explicitly. Closing the handle isn't enough on Unix:
220+
/// `flock` lasts while any copy of the descriptor is open, and a process another thread is
221+
/// spawning holds a copy of every descriptor until it execs (issue #680). If the unlock fails
222+
/// the handle still closes right after, which releases the lock once every copy is gone, as
223+
/// before.
156224
fn drop(&mut self) {
157225
if self.held {
158-
let _ = std::fs::remove_file(self.dir.join(OWNER));
226+
self.remove_own_note();
159227
if let Some(f) = &self.file
160228
&& let Err(e) = f.unlock()
161229
{

0 commit comments

Comments
 (0)