1use std::{
7 fmt,
8 fs::{self, File, OpenOptions},
9 io::{self, Read},
10 path::{Path, PathBuf},
11};
12
13use super::Limit;
14use crate::{Error, Result, parse::pid_file, sys};
15
16const DEFAULT_UMASK: u32 = 0o027;
18const DEFAULT_OPEN_FILES_TARGET: u64 = 65_536;
20const DEFAULT_OPEN_FILES_MINIMUM: u64 = 1_024;
22
23pub fn guard(name: &str) -> Result<Guard> {
45 Guard::builder(name).build()
46}
47
48#[must_use = "dropping the guard releases the single-instance lock"]
52pub struct Guard {
53 _lock: Option<File>,
55 report: GuardReport,
56}
57
58impl Guard {
59 pub fn builder(name: &str) -> GuardBuilder {
74 GuardBuilder {
75 name: name.to_owned(),
76 lock_dir: None,
77 lock: true,
78 allow_network_lock: false,
79 umask: Some(DEFAULT_UMASK),
80 open_files_target: DEFAULT_OPEN_FILES_TARGET,
81 open_files_minimum: DEFAULT_OPEN_FILES_MINIMUM,
82 }
83 }
84
85 #[must_use]
87 pub fn report(&self) -> &GuardReport {
88 &self.report
89 }
90
91 #[must_use]
93 pub fn lock_file(&self) -> Option<&Path> {
94 self.report.lock_file.as_deref()
95 }
96}
97
98impl fmt::Debug for Guard {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 f.debug_struct("Guard")
101 .field("report", &self.report)
102 .finish()
103 }
104}
105
106#[derive(Clone, Debug)]
108pub struct GuardBuilder {
109 name: String,
110 lock_dir: Option<PathBuf>,
111 lock: bool,
112 allow_network_lock: bool,
113 umask: Option<u32>,
114 open_files_target: u64,
115 open_files_minimum: u64,
116}
117
118impl GuardBuilder {
119 #[must_use]
123 pub fn lock_dir(mut self, dir: impl Into<PathBuf>) -> Self {
124 self.lock_dir = Some(dir.into());
125 self
126 }
127
128 #[must_use]
131 pub fn lock(mut self, on: bool) -> Self {
132 self.lock = on;
133 self
134 }
135
136 #[must_use]
139 pub fn allow_network_lock(mut self, on: bool) -> Self {
140 self.allow_network_lock = on;
141 self
142 }
143
144 #[must_use]
146 pub fn umask(mut self, mask: u32) -> Self {
147 self.umask = Some(mask & 0o777);
148 self
149 }
150
151 #[must_use]
153 pub fn keep_umask(mut self) -> Self {
154 self.umask = None;
155 self
156 }
157
158 #[must_use]
161 pub fn open_files_target(mut self, n: u64) -> Self {
162 self.open_files_target = n;
163 self
164 }
165
166 #[must_use]
169 pub fn open_files_minimum(mut self, n: u64) -> Self {
170 self.open_files_minimum = n;
171 self
172 }
173
174 pub fn build(self) -> Result<Guard> {
176 validate_name(&self.name)?;
177 let mut warnings = Vec::new();
178
179 let files_before = sys::open_files_limit()?;
181 let raise_to = plan_open_files(
182 files_before,
183 self.open_files_target,
184 self.open_files_minimum,
185 sys::open_files_ceiling(),
186 )?;
187
188 let (lock, lock_file, lock_filesystem) = if self.lock {
189 let dir = match &self.lock_dir {
190 Some(d) => {
191 create_owner_only(d)?;
192 d.clone()
193 }
194 None => runtime_dir(&self.name)?,
195 };
196 check_dir(&dir)?;
197 let fs_kind = sys::filesystem(&dir);
198 if let Some(kind) = fs_kind.filter(|k| k.network) {
199 if !self.allow_network_lock {
200 return Err(unavailable(
201 &dir,
202 io::ErrorKind::Unsupported,
203 &format!(
204 "it is on a {} filesystem, where locks may not hold across machines; use a local \
205 directory, or allow_network_lock(true)",
206 kind.name
207 ),
208 ));
209 }
210 warnings.push(GuardWarning::NetworkLockAllowed {
211 filesystem: kind.name,
212 });
213 }
214 let lock_path = dir.join(format!("{}.lock", self.name));
215 let pid_path = dir.join(format!("{}.pid", self.name));
216 let file = open_lock_file(&dir, &lock_path)?;
217 match file.try_lock() {
218 Ok(()) => {}
219 Err(fs::TryLockError::WouldBlock) => {
220 return Err(Error::AlreadyRunning {
221 pid: read_pid(&pid_path),
222 lock_file: lock_path,
223 });
224 }
225 Err(fs::TryLockError::Error(e)) => {
226 return Err(Error::Io {
227 what: "the process guard's lock",
228 source: e,
229 });
230 }
231 }
232 path_lib::write_atomic(&pid_path, format!("{}\n", std::process::id())).map_err(
233 |e| {
234 unavailable(
235 &dir,
236 io::ErrorKind::Other,
237 &format!("the pid file cannot be written: {e}"),
238 )
239 },
240 )?;
241 (Some(file), Some(lock_path), fs_kind.map(|k| k.name))
242 } else {
243 warnings.push(GuardWarning::LockDisabled);
244 (None, None, None)
245 };
246
247 let files_after = match raise_to {
248 Some(n) => {
249 sys::set_open_files_soft(n)?;
250 sys::open_files_limit()?
251 }
252 None => files_before,
253 };
254
255 let (umask_before, umask_after) = match self.umask {
256 Some(mask) => {
257 let before = sys::swap_umask(mask);
258 (before, before.map(|_| mask))
259 }
260 None => {
261 let current = sys::swap_umask(0o077);
263 if let Some(c) = current {
264 sys::swap_umask(c);
265 }
266 (current, current)
267 }
268 };
269
270 #[cfg(unix)]
274 if let Some(threads) = sys::thread_count().filter(|&n| n > 1) {
275 warnings.push(GuardWarning::ThreadsAlreadyRunning { threads });
276 }
277
278 Ok(Guard {
279 _lock: lock,
280 report: GuardReport {
281 lock_file,
282 lock_filesystem,
283 umask_before,
284 umask_after,
285 open_files_before: files_before,
286 open_files_after: files_after,
287 warnings,
288 },
289 })
290 }
291}
292
293#[derive(Clone, Debug, PartialEq, Eq)]
295#[non_exhaustive]
296pub struct GuardReport {
297 pub lock_file: Option<PathBuf>,
299 pub lock_filesystem: Option<&'static str>,
301 pub umask_before: Option<u32>,
303 pub umask_after: Option<u32>,
305 pub open_files_before: Limit,
307 pub open_files_after: Limit,
309 pub warnings: Vec<GuardWarning>,
311}
312
313#[derive(Clone, Debug, PartialEq, Eq)]
315#[non_exhaustive]
316pub enum GuardWarning {
317 ThreadsAlreadyRunning {
321 threads: usize,
323 },
324 NetworkLockAllowed {
327 filesystem: &'static str,
329 },
330 LockDisabled,
332}
333
334fn validate_name(name: &str) -> Result<()> {
336 let ok = !name.is_empty()
337 && name.len() <= 64
338 && !name.starts_with('.')
339 && name
340 .bytes()
341 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
342 if ok {
343 Ok(())
344 } else {
345 Err(Error::InvalidInput {
346 what: "process guard name",
347 reason: "use 1 to 64 ASCII letters, digits, '-', '_', or '.', not starting with '.'",
348 })
349 }
350}
351
352fn plan_open_files(
355 before: Limit,
356 target: u64,
357 minimum: u64,
358 ceiling: Option<u64>,
359) -> Result<Option<u64>> {
360 if before.soft.is_none() && before.hard.is_none() {
361 return Ok(None); }
363 let hard = before.hard.unwrap_or(u64::MAX);
364 let usable = hard.min(ceiling.unwrap_or(u64::MAX));
365 if usable < minimum {
366 return Err(Error::OpenFilesTooLow {
367 have: usable,
368 need: minimum,
369 });
370 }
371 let want = target.max(minimum).min(usable);
372 Ok((before.soft.unwrap_or(u64::MAX) < want).then_some(want))
373}
374
375fn unavailable(dir: &Path, kind: io::ErrorKind, reason: &str) -> Error {
376 Error::RunDirUnavailable {
377 path: dir.to_path_buf(),
378 source: io::Error::new(kind, reason.to_owned()),
379 }
380}
381
382fn runtime_dir(name: &str) -> Result<PathBuf> {
383 let app = path_lib::App::new(name)
384 .map_err(|e| unavailable(Path::new(name), io::ErrorKind::InvalidInput, &e.to_string()))?;
385 let dir = app.dir(path_lib::Kind::Runtime).to_path_buf();
386 app.ensure(path_lib::Kind::Runtime).map_err(|e| {
387 unavailable(
388 &dir,
389 io::ErrorKind::Other,
390 &format!("it cannot be created: {e}"),
391 )
392 })?;
393 Ok(dir)
394}
395
396fn create_owner_only(dir: &Path) -> Result<()> {
397 if fs::symlink_metadata(dir).is_ok() {
398 return Ok(());
399 }
400 let mut builder = fs::DirBuilder::new();
401 builder.recursive(true);
402 #[cfg(unix)]
403 {
404 use std::os::unix::fs::DirBuilderExt;
405 builder.mode(0o700);
406 }
407 builder
408 .create(dir)
409 .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be created: {e}")))
410}
411
412fn check_dir(dir: &Path) -> Result<()> {
414 let meta = fs::symlink_metadata(dir)
415 .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be read: {e}")))?;
416 if meta.file_type().is_symlink() {
417 return Err(unavailable(
418 dir,
419 io::ErrorKind::InvalidInput,
420 "it is a symbolic link; use the real directory",
421 ));
422 }
423 if !meta.is_dir() {
424 return Err(unavailable(
425 dir,
426 io::ErrorKind::InvalidInput,
427 "it is not a directory",
428 ));
429 }
430 #[cfg(unix)]
431 {
432 use std::os::unix::fs::MetadataExt;
433 if meta.mode() & 0o022 != 0 {
434 return Err(unavailable(
435 dir,
436 io::ErrorKind::PermissionDenied,
437 "other users can write to it and could replace the lock file; chmod 700 it, or use another directory",
438 ));
439 }
440 if sys::effective_uid().is_some_and(|uid| uid != meta.uid()) {
441 return Err(unavailable(
442 dir,
443 io::ErrorKind::PermissionDenied,
444 "it belongs to another user; use a directory this user owns",
445 ));
446 }
447 }
448 #[cfg(windows)]
449 {
450 use std::os::windows::fs::MetadataExt;
451 if meta.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
452 return Err(unavailable(
453 dir,
454 io::ErrorKind::InvalidInput,
455 "it is a junction or link; use the real directory",
456 ));
457 }
458 }
459 Ok(())
460}
461
462fn open_lock_file(dir: &Path, path: &Path) -> Result<File> {
464 if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
465 return Err(unavailable(
466 dir,
467 io::ErrorKind::InvalidInput,
468 "the lock file is a symbolic link; remove it",
469 ));
470 }
471 let mut options = OpenOptions::new();
472 options.read(true).write(true).create(true).truncate(false);
473 sys::lock_open_options(&mut options);
474 let file = options.open(path).map_err(|e| {
475 unavailable(
476 dir,
477 e.kind(),
478 &format!("the lock file cannot be opened: {e}"),
479 )
480 })?;
481 let opened = file
482 .metadata()
483 .map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
484 let at_path =
485 fs::symlink_metadata(path).map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
486 if !opened.is_file() || at_path.file_type().is_symlink() {
487 return Err(unavailable(
488 dir,
489 io::ErrorKind::InvalidInput,
490 "the lock file is not a regular file; remove it",
491 ));
492 }
493 #[cfg(unix)]
494 {
495 use std::os::unix::fs::MetadataExt;
496 if (opened.dev(), opened.ino()) != (at_path.dev(), at_path.ino()) {
498 return Err(unavailable(
499 dir,
500 io::ErrorKind::InvalidInput,
501 "the lock file changed while it was opened",
502 ));
503 }
504 if sys::effective_uid().is_some_and(|uid| uid != opened.uid()) {
505 return Err(unavailable(
506 dir,
507 io::ErrorKind::PermissionDenied,
508 "the lock file belongs to another user; remove it",
509 ));
510 }
511 }
512 #[cfg(windows)]
513 {
514 use std::os::windows::fs::MetadataExt;
515 if opened.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
516 return Err(unavailable(
517 dir,
518 io::ErrorKind::InvalidInput,
519 "the lock file is a link; remove it",
520 ));
521 }
522 }
523 Ok(file)
524}
525
526fn read_pid(path: &Path) -> Option<u32> {
528 let mut data = Vec::with_capacity(pid_file::MAX_BYTES + 1);
529 File::open(path)
530 .ok()?
531 .take(pid_file::MAX_BYTES as u64 + 1)
532 .read_to_end(&mut data)
533 .ok()?;
534 pid_file::parse(&data)
535}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540
541 fn temp_dir(tag: &str) -> PathBuf {
542 let dir = std::env::temp_dir().join(format!("sys-lib-guard-{tag}-{}", std::process::id()));
543 let _ = fs::remove_dir_all(&dir);
544 dir
545 }
546
547 #[test]
548 fn test_guard_name_validation() {
549 for good in ["site", "hive-db", "a.b_c", "x"] {
550 assert!(validate_name(good).is_ok(), "{good}");
551 }
552 for bad in [
553 "",
554 ".hidden",
555 "a/b",
556 "a\\b",
557 "..",
558 "sp ace",
559 "naïve",
560 &"x".repeat(65),
561 ] {
562 assert!(
563 matches!(validate_name(bad), Err(Error::InvalidInput { .. })),
564 "{bad:?}"
565 );
566 }
567 }
568
569 #[test]
570 fn test_guard_open_files_plan() {
571 let limit = |soft, hard| Limit { soft, hard };
572 assert_eq!(
574 plan_open_files(limit(Some(1024), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
575 Some(65_536)
576 );
577 assert_eq!(
578 plan_open_files(limit(Some(1024), Some(4096)), 65_536, 1_024, None).unwrap(),
579 Some(4096)
580 );
581 assert_eq!(
583 plan_open_files(limit(Some(100_000), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
584 None
585 );
586 assert_eq!(
588 plan_open_files(limit(Some(256), None), 65_536, 1_024, Some(24_576)).unwrap(),
589 Some(24_576)
590 );
591 let e = plan_open_files(limit(Some(256), Some(512)), 65_536, 1_024, None).unwrap_err();
593 assert!(matches!(
594 e,
595 Error::OpenFilesTooLow {
596 have: 512,
597 need: 1_024
598 }
599 ));
600 assert_eq!(
602 plan_open_files(limit(None, None), 65_536, 1_024, None).unwrap(),
603 None
604 );
605 }
606
607 #[test]
608 fn test_guard_locks_and_a_second_guard_is_refused() {
609 let dir = temp_dir("second");
610 let first = Guard::builder("guard-test")
611 .lock_dir(&dir)
612 .keep_umask()
613 .open_files_target(0)
614 .open_files_minimum(0)
615 .build()
616 .unwrap();
617 let lock = first.lock_file().unwrap().to_path_buf();
618 assert!(lock.ends_with("guard-test.lock"));
619 assert_eq!(
620 read_pid(&dir.join("guard-test.pid")),
621 Some(std::process::id())
622 );
623 let second = Guard::builder("guard-test")
624 .lock_dir(&dir)
625 .keep_umask()
626 .open_files_target(0)
627 .open_files_minimum(0)
628 .build();
629 match second {
630 Err(Error::AlreadyRunning { pid, lock_file }) => {
631 assert_eq!(pid, Some(std::process::id()));
632 assert_eq!(lock_file, lock);
633 }
634 other => panic!("expected AlreadyRunning, got {other:?}"),
635 }
636 drop(first);
637 assert!(lock.exists());
639 let again = Guard::builder("guard-test")
640 .lock_dir(&dir)
641 .keep_umask()
642 .open_files_target(0)
643 .open_files_minimum(0)
644 .build();
645 assert!(again.is_ok());
646 drop(again);
647 let _ = fs::remove_dir_all(&dir);
648 }
649
650 #[test]
651 fn test_guard_lock_false_takes_no_lock() {
652 let g = Guard::builder("nolock")
653 .lock(false)
654 .keep_umask()
655 .open_files_target(0)
656 .open_files_minimum(0)
657 .build()
658 .unwrap();
659 assert_eq!(g.lock_file(), None);
660 assert!(g.report().warnings.contains(&GuardWarning::LockDisabled));
661 }
662
663 #[test]
664 fn test_guard_refuses_a_file_as_lock_dir() {
665 let dir = temp_dir("file");
666 fs::create_dir_all(dir.parent().unwrap()).unwrap();
667 fs::write(&dir, b"x").unwrap();
668 let e = Guard::builder("g")
669 .lock_dir(&dir)
670 .keep_umask()
671 .build()
672 .unwrap_err();
673 assert!(matches!(e, Error::RunDirUnavailable { .. }), "{e:?}");
674 let _ = fs::remove_file(&dir);
675 }
676
677 #[cfg(unix)]
678 #[test]
679 fn test_guard_lock_path_is_symlink_refuses() {
680 let dir = temp_dir("symlink");
682 create_owner_only(&dir).unwrap();
683 let target = dir.join("elsewhere");
684 fs::write(&target, b"").unwrap();
685 std::os::unix::fs::symlink(&target, dir.join("g.lock")).unwrap();
686 let e = Guard::builder("g")
687 .lock_dir(&dir)
688 .keep_umask()
689 .build()
690 .unwrap_err();
691 assert!(e.to_string().contains("symbolic link"), "{e}");
692 let _ = fs::remove_dir_all(&dir);
693 }
694
695 #[cfg(unix)]
696 #[test]
697 fn test_guard_world_writable_dir_refuses() {
698 use std::os::unix::fs::PermissionsExt;
700 let dir = temp_dir("writable");
701 create_owner_only(&dir).unwrap();
702 fs::set_permissions(&dir, fs::Permissions::from_mode(0o777)).unwrap();
703 let e = Guard::builder("g")
704 .lock_dir(&dir)
705 .keep_umask()
706 .build()
707 .unwrap_err();
708 assert!(e.to_string().contains("other users can write"), "{e}");
709 fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
710 let _ = fs::remove_dir_all(&dir);
711 }
712
713 #[cfg(unix)]
714 #[test]
715 fn test_guard_symlinked_dir_refuses() {
716 let dir = temp_dir("dirlink");
717 let real = temp_dir("dirlink-real");
718 create_owner_only(&real).unwrap();
719 std::os::unix::fs::symlink(&real, &dir).unwrap();
720 let e = Guard::builder("g")
721 .lock_dir(&dir)
722 .keep_umask()
723 .build()
724 .unwrap_err();
725 assert!(e.to_string().contains("symbolic link"), "{e}");
726 let _ = fs::remove_file(&dir);
727 let _ = fs::remove_dir_all(&real);
728 }
729
730 #[test]
731 fn test_guard_stale_pid_file_is_replaced() {
732 let dir = temp_dir("stale");
734 create_owner_only(&dir).unwrap();
735 fs::write(dir.join("g.pid"), b"999999\n").unwrap();
736 let g = Guard::builder("g")
737 .lock_dir(&dir)
738 .keep_umask()
739 .open_files_target(0)
740 .open_files_minimum(0)
741 .build()
742 .unwrap();
743 assert_eq!(read_pid(&dir.join("g.pid")), Some(std::process::id()));
744 drop(g);
745 let _ = fs::remove_dir_all(&dir);
746 }
747
748 #[test]
749 fn test_guard_report_with_threads_warns() {
750 let g = Guard::builder("threads")
753 .lock(false)
754 .keep_umask()
755 .open_files_target(0)
756 .open_files_minimum(0)
757 .build()
758 .unwrap();
759 let warned = g
760 .report()
761 .warnings
762 .iter()
763 .any(|w| matches!(w, GuardWarning::ThreadsAlreadyRunning { .. }));
764 if cfg!(unix) {
765 assert_eq!(warned, sys::thread_count().is_some_and(|n| n > 1));
766 } else {
767 assert!(!warned);
768 }
769 if cfg!(unix) {
770 assert!(g.report().umask_before.is_some());
771 assert_eq!(g.report().umask_before, g.report().umask_after);
772 } else {
773 assert_eq!(g.report().umask_before, None);
774 }
775 }
776}