1#[cfg(unix)]
4use std::ffi::{CString, OsStr};
5#[cfg(unix)]
6use std::io::{Read as _, Write as _};
7#[cfg(unix)]
8use std::os::fd::AsFd;
9#[cfg(unix)]
10use std::os::unix::ffi::OsStrExt;
11#[cfg(unix)]
12use std::os::unix::fs::{FileExt as _, MetadataExt};
13#[cfg(unix)]
14use std::path::PathBuf;
15
16#[cfg(unix)]
18#[derive(Debug)]
19pub struct DaemonStoreGuard {
20 pub(super) parent_dir: std::fs::File,
23 pub(super) _sidecar: std::fs::File,
24 pub(super) database: PathBuf,
25 claimed_identity: Option<(u64, u64)>,
26 pub(super) _bound_database: Option<std::fs::File>,
27}
28
29#[cfg(unix)]
30impl Drop for DaemonStoreGuard {
31 fn drop(&mut self) {
32 if let Err(error) = self._sidecar.unlock() {
35 tracing::warn!(
36 database = %self.database.display(),
37 %error,
38 "cannot release daemon store lock"
39 );
40 }
41 }
42}
43
44#[cfg(not(unix))]
46#[derive(Debug)]
47pub struct DaemonStoreGuard;
48
49#[cfg(unix)]
50pub(super) fn regular_store_identity(
51 database: &std::path::Path,
52) -> anyhow::Result<Option<(u64, u64)>> {
53 let metadata = match std::fs::symlink_metadata(database) {
54 Ok(metadata) => metadata,
55 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
56 Err(error) => {
57 anyhow::bail!(
58 "cannot inspect claimed database {}: {error}",
59 database.display()
60 )
61 }
62 };
63 anyhow::ensure!(
64 metadata.is_file(),
65 "claimed database {} is not a regular file",
66 database.display()
67 );
68 Ok(Some((metadata.dev(), metadata.ino())))
69}
70
71#[cfg(unix)]
73fn check_store_entry_name(name: &OsStr) -> std::io::Result<()> {
74 CString::new(name.as_bytes()).map_err(|_| {
75 std::io::Error::new(
76 std::io::ErrorKind::InvalidInput,
77 "store entry contains U+0000",
78 )
79 })?;
80 Ok(())
81}
82
83#[cfg(unix)]
85fn open_claimed_store_file(
86 parent: &std::fs::File,
87 name: &OsStr,
88 read_only: bool,
89) -> std::io::Result<std::fs::File> {
90 check_store_entry_name(name)?;
91 if read_only {
92 khive_fs::fd_relative::open_at(parent, name, false)
95 } else {
96 khive_fs::fd_relative::open_file_at(
97 parent.as_fd(),
98 name,
99 khive_fs::fd_relative::OpenFileOptions {
100 read_write: true,
101 create: khive_fs::fd_relative::Create::IfMissing,
102 nonblock: false,
103 mode: 0o600,
104 },
105 )
106 }
107}
108
109#[cfg(unix)]
116fn open_claimed_directory(path: &std::path::Path) -> std::io::Result<std::fs::File> {
117 use std::path::Component;
118
119 if !path.is_absolute() {
120 return Err(std::io::Error::new(
121 std::io::ErrorKind::InvalidInput,
122 "claimed store directory must be absolute",
123 ));
124 }
125 let mut directory = khive_fs::fd_relative::open_search_root()?;
126 let mut components = path.components().peekable();
127 while let Some(component) = components.next() {
128 match component {
129 Component::RootDir => {}
130 Component::Normal(name) => {
131 check_store_entry_name(name)?;
132 directory = if components.peek().is_some() {
133 khive_fs::fd_relative::open_search_dir_at(&directory, name)?
134 } else {
135 khive_fs::fd_relative::open_dir_at(&directory, name)?
136 };
137 }
138 _ => {
139 return Err(std::io::Error::new(
140 std::io::ErrorKind::InvalidInput,
141 "claimed store directory must be canonical",
142 ));
143 }
144 }
145 }
146 Ok(directory)
147}
148
149#[cfg(unix)]
153pub(super) fn ensure_claimed_parent_identity(
154 directory: &std::fs::File,
155 database: &std::path::Path,
156) -> anyhow::Result<()> {
157 let parent = database.parent().expect("claimed path has a parent");
158 let held = khive_fs::fd_relative::FileIdentity::of(directory)?;
159 let observed = std::fs::symlink_metadata(parent)?;
160 anyhow::ensure!(
161 observed.is_dir() && (held.dev, held.ino) == (observed.dev(), observed.ino()),
162 "claimed database {} parent directory changed since claim",
163 database.display()
164 );
165 Ok(())
166}
167
168#[cfg(unix)]
171fn regular_store_identity_at(
172 parent: &std::fs::File,
173 name: &OsStr,
174 database: &std::path::Path,
175) -> anyhow::Result<Option<(u64, u64)>> {
176 CString::new(name.as_bytes())
177 .map_err(|_| anyhow::anyhow!("database name {} contains U+0000", database.display()))?;
178 let stat = match khive_fs::fd_relative::stat_at(parent, name) {
179 Ok(stat) => stat,
180 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
181 Err(error) => anyhow::bail!(
182 "cannot inspect claimed database {}: {error}",
183 database.display()
184 ),
185 };
186 anyhow::ensure!(
187 stat.st_mode & libc::S_IFMT == libc::S_IFREG,
188 "claimed database {} is not a regular file",
189 database.display()
190 );
191 #[cfg(target_os = "linux")]
192 let device = stat.st_dev;
193 #[cfg(not(target_os = "linux"))]
194 let device = stat.st_dev as u64;
195 Ok(Some((device, stat.st_ino)))
196}
197
198#[cfg(all(test, unix))]
199thread_local! {
200 static STORE_BIND_RACE_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
201 const { std::cell::RefCell::new(None) };
202}
203
204#[cfg(all(test, unix))]
205pub(super) fn set_store_bind_race_hook(hook: impl FnOnce() + 'static) {
206 STORE_BIND_RACE_HOOK.with(|cell| *cell.borrow_mut() = Some(Box::new(hook)));
207}
208
209#[cfg(all(test, unix))]
210fn take_store_bind_race_hook() -> Option<Box<dyn FnOnce()>> {
211 STORE_BIND_RACE_HOOK.with(|cell| cell.borrow_mut().take())
212}
213
214#[cfg(unix)]
217fn bind_open_error(
218 error: &std::io::Error,
219 database: &std::path::Path,
220 read_only: bool,
221) -> anyhow::Error {
222 if !read_only
223 && error.kind() == std::io::ErrorKind::PermissionDenied
224 && std::fs::metadata(database).is_ok_and(|metadata| metadata.permissions().readonly())
225 {
226 return anyhow::anyhow!(
227 "claimed database {} has no filesystem write bits; declare `read_only = true` so \
228 backend topology and daemon config identity describe the snapshot-inspection mode \
229 explicitly",
230 database.display()
231 );
232 }
233 anyhow::anyhow!(
234 "cannot open claimed database {}: {error}",
235 database.display()
236 )
237}
238
239#[cfg(unix)]
244pub fn bind_daemon_store_files(
245 guards: &mut [DaemonStoreGuard],
246 read_only_paths: &[PathBuf],
247) -> anyhow::Result<()> {
248 for guard in guards {
249 let read_only = read_only_paths.contains(&guard.database);
250 ensure_claimed_parent_identity(&guard.parent_dir, &guard.database)?;
251 let filename = guard
252 .database
253 .file_name()
254 .expect("claimed path has a file name");
255 #[cfg(test)]
256 if let Some(hook) = take_store_bind_race_hook() {
257 hook();
258 }
259 let file = open_claimed_store_file(&guard.parent_dir, filename, read_only)
261 .map_err(|error| bind_open_error(&error, &guard.database, read_only))?;
262 let metadata = file.metadata()?;
263 anyhow::ensure!(
264 metadata.is_file(),
265 "claimed database {} is not a regular file",
266 guard.database.display()
267 );
268 let opened_identity = (metadata.dev(), metadata.ino());
269 if let Some(claimed_identity) = guard.claimed_identity {
270 anyhow::ensure!(
271 claimed_identity == opened_identity,
272 "claimed database {} changed inode between claim and open",
273 guard.database.display()
274 );
275 }
276 guard.claimed_identity = Some(opened_identity);
277 guard._bound_database = Some(file);
278 anyhow::ensure!(
279 regular_store_identity(&guard.database)? == Some(opened_identity),
280 "claimed database {} changed inode while binding its open file",
281 guard.database.display()
282 );
283 }
284 Ok(())
285}
286
287#[cfg(unix)]
292pub fn assert_daemon_store_identities(guards: &[DaemonStoreGuard]) -> anyhow::Result<()> {
293 for guard in guards {
294 ensure_claimed_parent_identity(&guard.parent_dir, &guard.database)?;
295 let bound = guard._bound_database.as_ref().ok_or_else(|| {
296 anyhow::anyhow!(
297 "claimed database {} was not bound",
298 guard.database.display()
299 )
300 })?;
301 let identity = khive_fs::fd_relative::FileIdentity::of(bound)?;
302 let bound_identity = (identity.dev, identity.ino);
303 let observed = regular_store_identity(&guard.database)?;
304 anyhow::ensure!(
305 observed == Some(bound_identity) && observed == guard.claimed_identity,
306 "claimed database {} changed inode after open (claimed {:?}, now {:?}); refusing daemon boot",
307 guard.database.display(),
308 guard.claimed_identity,
309 observed
310 );
311 }
312 Ok(())
313}
314
315#[cfg(not(unix))]
317pub fn assert_daemon_store_identities(_guards: &[DaemonStoreGuard]) -> anyhow::Result<()> {
318 Ok(())
319}
320
321#[cfg(unix)]
323pub(super) fn daemon_store_lock_path(database: &std::path::Path) -> anyhow::Result<PathBuf> {
324 let filename = database
325 .file_name()
326 .ok_or_else(|| anyhow::anyhow!("database path {} has no file name", database.display()))?;
327 let mut lock_name = std::ffi::OsString::from(".");
328 lock_name.push(filename);
329 lock_name.push(".khived.lock");
330 Ok(database.with_file_name(lock_name))
331}
332
333#[cfg(unix)]
335const STORE_LOCK_RECORD_MAX: u64 = 64;
336
337#[cfg(unix)]
340pub(super) fn store_lock_holder_pid(file: &mut std::fs::File) -> Option<u32> {
341 let mut holder_text = String::new();
342 file.take(STORE_LOCK_RECORD_MAX)
343 .read_to_string(&mut holder_text)
344 .ok()?;
345 holder_text.trim().parse::<u32>().ok()
346}
347
348#[cfg(unix)]
351fn has_lock_sidecar_name(filename: &OsStr) -> bool {
352 const SUFFIX: &[u8] = b".khived.lock";
353 let name = filename.as_bytes();
354 name.len() > SUFFIX.len() && name.starts_with(b".") && name.ends_with(SUFFIX)
355}
356
357#[cfg(unix)]
361fn ensure_sidecar_holds_only_a_lock_record(
362 file: &std::fs::File,
363 len: u64,
364 lock_path: &std::path::Path,
365 database: &std::path::Path,
366) -> anyhow::Result<()> {
367 const SQLITE_HEADER: &[u8; 16] = b"SQLite format 3\0";
368 let mut sqlite_header = false;
369 if len >= 16 {
370 let mut head = [0u8; 16];
371 file.read_exact_at(&mut head, 0).map_err(|error| {
372 anyhow::anyhow!(
373 "cannot read daemon store lock {}: {error}",
374 lock_path.display()
375 )
376 })?;
377 sqlite_header = head == *SQLITE_HEADER;
378 }
379 anyhow::ensure!(
380 len <= STORE_LOCK_RECORD_MAX && !sqlite_header,
381 "refusing daemon store claim: existing file at lock sidecar {} for database {} is not a \
382 daemon lock record (longer than {} bytes or a SQLite database); the file was left \
383 untouched",
384 lock_path.display(),
385 database.display(),
386 STORE_LOCK_RECORD_MAX
387 );
388 Ok(())
389}
390
391#[cfg(unix)]
394pub fn acquire_daemon_store_guards(
395 database_paths: impl IntoIterator<Item = PathBuf>,
396) -> anyhow::Result<Vec<DaemonStoreGuard>> {
397 claim_stores(&database_paths.into_iter().collect::<Vec<_>>(), &[])
398}
399
400#[cfg(unix)]
418pub fn claim_stores(
419 database_paths: &[PathBuf],
420 read_only_paths: &[PathBuf],
421) -> anyhow::Result<Vec<DaemonStoreGuard>> {
422 let mut database_paths = database_paths.to_vec();
423 database_paths.sort();
424 database_paths.dedup();
425 let lock_paths: Vec<PathBuf> = database_paths
426 .iter()
427 .map(|database| daemon_store_lock_path(database))
428 .collect::<anyhow::Result<_>>()?;
429 for (database, lock_path) in database_paths.iter().zip(&lock_paths) {
430 if database_paths.binary_search(lock_path).is_ok() {
431 anyhow::bail!(
432 "refusing daemon store claim: lock sidecar {} for database {} is itself a \
433 configured database; no store lock was opened",
434 lock_path.display(),
435 database.display()
436 );
437 }
438 }
439 for database in &database_paths {
440 if database.file_name().is_some_and(has_lock_sidecar_name) {
441 anyhow::bail!(
442 "refusing daemon store claim: database {} is named like a store lock sidecar \
443 (`.<name>.khived.lock`); no store lock was opened",
444 database.display()
445 );
446 }
447 if read_only_paths.contains(database) {
448 if let Some(parent) = database.parent() {
449 if let Err(error) = std::fs::metadata(parent) {
450 if error.kind() == std::io::ErrorKind::NotFound {
451 anyhow::bail!(
452 "refusing daemon store claim: parent directory {} of read-only \
453 database {} does not exist; nothing was created",
454 parent.display(),
455 database.display()
456 );
457 }
458 }
459 }
460 }
461 }
462 let mut configured_identities = Vec::new();
463 for database in &database_paths {
464 if let Some(identity) = regular_store_identity(database)? {
465 configured_identities.push((database.clone(), identity));
466 }
467 }
468 let mut guards = Vec::with_capacity(database_paths.len());
469
470 for (database, lock_path) in database_paths.into_iter().zip(lock_paths) {
471 let filename = database
472 .file_name()
473 .expect("store lock preflight required a database file name");
474 let parent = lock_path
475 .parent()
476 .ok_or_else(|| anyhow::anyhow!("store lock {} has no parent", lock_path.display()))?;
477 if !read_only_paths.contains(&database) {
478 std::fs::create_dir_all(parent).map_err(|error| {
479 anyhow::anyhow!(
480 "cannot create store lock directory {}: {error}",
481 parent.display()
482 )
483 })?;
484 }
485 let parent_dir = open_claimed_directory(parent).map_err(|error| {
486 anyhow::anyhow!(
487 "cannot open daemon store directory {} for {}: {error}",
488 parent.display(),
489 database.display()
490 )
491 })?;
492 ensure_claimed_parent_identity(&parent_dir, &database)?;
493 let mut file = open_claimed_store_file(
494 &parent_dir,
495 lock_path.file_name().expect("sidecar path has a file name"),
496 false,
497 )
498 .map_err(|error| {
499 anyhow::anyhow!(
500 "cannot open daemon store lock {} for {}: {error}",
501 lock_path.display(),
502 database.display()
503 )
504 })?;
505 let sidecar_metadata = file.metadata()?;
506 if !sidecar_metadata.is_file() {
507 anyhow::bail!(
508 "daemon store lock {} is not a regular file",
509 lock_path.display()
510 );
511 }
512 let sidecar_identity = (sidecar_metadata.dev(), sidecar_metadata.ino());
513 if let Some((matching_database, _)) = configured_identities
514 .iter()
515 .find(|(_, identity)| *identity == sidecar_identity)
516 {
517 anyhow::bail!(
518 "refusing daemon store claim: opened lock sidecar {} for database {} is the same \
519 file as configured database {}; no sidecar lock was acquired or truncated",
520 lock_path.display(),
521 database.display(),
522 matching_database.display()
523 );
524 }
525 anyhow::ensure!(
526 sidecar_metadata.nlink() <= 1,
527 "refusing daemon store claim: opened lock sidecar {} for database {} has {} hard \
528 links; no sidecar lock was acquired or truncated",
529 lock_path.display(),
530 database.display(),
531 sidecar_metadata.nlink()
532 );
533 ensure_sidecar_holds_only_a_lock_record(
534 &file,
535 sidecar_metadata.len(),
536 &lock_path,
537 &database,
538 )?;
539 match file.try_lock() {
540 Ok(()) => {}
541 Err(std::fs::TryLockError::WouldBlock) => {
542 let holder = store_lock_holder_pid(&mut file)
546 .map(|pid| format!("pid {pid}"))
547 .unwrap_or_else(|| "an unknown pid".to_string());
548 anyhow::bail!(
549 "refusing to start: khived is already running as {holder} for database {}; \
550 daemon store lock {} is held",
551 database.display(),
552 lock_path.display()
553 );
554 }
555 Err(std::fs::TryLockError::Error(error)) => {
556 anyhow::bail!(
557 "cannot acquire daemon store lock {} for {}: {error}",
558 lock_path.display(),
559 database.display()
560 );
561 }
562 }
563 file.set_len(0)?;
564 file.write_all(std::process::id().to_string().as_bytes())?;
565 file.sync_data()?;
566 let claimed_identity = regular_store_identity_at(&parent_dir, filename, &database)?;
567 guards.push(DaemonStoreGuard {
568 parent_dir,
569 _sidecar: file,
570 database,
571 claimed_identity,
572 _bound_database: None,
573 });
574 }
575 Ok(guards)
576}