Skip to main content

sys_lib/process/
guard.rs

1//! The process guard: make sure this is the only copy running, make every
2//! file it creates private by default, and make sure it will not run out of
3//! file descriptors under load. One call, secure defaults, and a refusal with
4//! an actionable error when a requirement cannot be met.
5
6use 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
16/// The default umask: owner read and write, group read, others nothing.
17const DEFAULT_UMASK: u32 = 0o027;
18/// The default soft open-file limit the guard raises to.
19const DEFAULT_OPEN_FILES_TARGET: u64 = 65_536;
20/// The default minimum hard open-file limit; below it the guard refuses to start.
21const DEFAULT_OPEN_FILES_MINIMUM: u64 = 1_024;
22
23/// Starts the process guard with secure defaults: a single-instance lock in
24/// the default lock directory for `name`, `umask(0o027)`, and the soft
25/// open-file limit raised to 65 536 (at least 1 024 required). Call it before
26/// any file is opened and before threads start, and keep the [`Guard`] for the
27/// life of the process.
28///
29/// The default lock directory depends only on the user the process runs as,
30/// never on environment variables, so a copy started by a service manager and
31/// one started from a shell find the same lock (D-106):
32///
33/// | Platform | root | other users |
34/// |---|---|---|
35/// | Linux | `/run/<name>` | `<home>/.local/state/<name>/run` |
36/// | macOS | `/var/run/<name>` | `<home>/Library/Application Support/<name>/run` |
37/// | FreeBSD | `/var/run/<name>` | `<home>/.local/state/<name>/run` |
38/// | Windows | the user's local application data folder, `<name>\run` | the same |
39///
40/// `<home>` is the home directory in the account database, not `$HOME`. The
41/// lock is per user: copies running as different users do not exclude each
42/// other. A program guarding shared data (a database) passes its data
43/// directory with [`GuardBuilder::lock_dir`], so every copy that could touch
44/// the data finds the same lock.
45///
46/// ```no_run
47/// use sys_lib as sys;
48///
49/// let guard = sys::process::guard("site")?;      // before any file is opened
50/// println!("lock {:?}", guard.lock_file());
51/// // ... run; the lock is held while `guard` lives.
52/// # Ok::<(), sys_lib::Error>(())
53/// ```
54///
55/// # Errors
56///
57/// [`Error::AlreadyRunning`] when another copy holds the lock,
58/// [`Error::RunDirUnavailable`] when the lock directory cannot be created or
59/// trusted (or, for a user other than root, the account has no home
60/// directory), [`Error::OpenFilesTooLow`] when the hard open-file limit is
61/// below the minimum, and [`Error::InvalidInput`] for an invalid name.
62pub fn guard(name: &str) -> Result<Guard> {
63    Guard::builder(name).build()
64}
65
66/// The running guard. Dropping it closes the lock file, which releases the
67/// lock; the lock file itself is never deleted (deleting it would let two
68/// copies run, see the plan's guard section).
69///
70/// The lock belongs to the file, not to its path. On Windows the file cannot
71/// be deleted or renamed while the guard holds it. On Unix it can (a temporary
72/// file cleaner, an operator's `rm`), and a copy started afterwards would
73/// create a new lock file and run; [`Guard::is_held`] tells a long-running
74/// service when that has happened.
75#[must_use = "dropping the guard releases the single-instance lock"]
76pub struct Guard {
77    // Held for its lock.
78    lock: Option<File>,
79    report: GuardReport,
80}
81
82impl Guard {
83    /// A builder for options other than the defaults.
84    ///
85    /// ```no_run
86    /// use sys_lib::process::Guard;
87    ///
88    /// // A database locks beside its data, so two copies under different users
89    /// // or run directories still exclude each other.
90    /// let guard = Guard::builder("myapp")
91    ///     .lock_dir("/var/lib/myapp")
92    ///     .open_files_target(1_048_576)
93    ///     .open_files_minimum(65_536)
94    ///     .build()?;
95    /// # Ok::<(), sys_lib::Error>(())
96    /// ```
97    pub fn builder(name: &str) -> GuardBuilder {
98        GuardBuilder {
99            name: name.to_owned(),
100            lock_dir: None,
101            lock: true,
102            allow_network_lock: false,
103            umask: Some(DEFAULT_UMASK),
104            open_files_target: DEFAULT_OPEN_FILES_TARGET,
105            open_files_minimum: DEFAULT_OPEN_FILES_MINIMUM,
106        }
107    }
108
109    /// What the guard did.
110    #[must_use]
111    pub fn report(&self) -> &GuardReport {
112        &self.report
113    }
114
115    /// The lock file, when a lock was taken.
116    #[must_use]
117    pub fn lock_file(&self) -> Option<&Path> {
118        self.report.lock_file.as_deref()
119    }
120
121    /// Whether the lock file at its path is still the one this guard locked.
122    /// False when the file was deleted or replaced since (only possible on
123    /// Unix), so another copy could now start, or when no lock was taken.
124    /// A service that runs for long can check it periodically and stop.
125    ///
126    /// ```no_run
127    /// use sys_lib as sys;
128    ///
129    /// let guard = sys::process::guard("site")?;
130    /// // ... later, on a timer:
131    /// if !guard.is_held() {
132    ///     eprintln!("the lock file was removed; stopping so only one copy runs");
133    /// }
134    /// # Ok::<(), sys_lib::Error>(())
135    /// ```
136    #[must_use]
137    pub fn is_held(&self) -> bool {
138        match (&self.lock, &self.report.lock_file) {
139            (Some(file), Some(path)) => same_file(file, path),
140            _ => false,
141        }
142    }
143}
144
145impl fmt::Debug for Guard {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.debug_struct("Guard")
148            .field("report", &self.report)
149            .finish()
150    }
151}
152
153/// Options for [`Guard`].
154#[derive(Clone, Debug)]
155pub struct GuardBuilder {
156    name: String,
157    lock_dir: Option<PathBuf>,
158    lock: bool,
159    allow_network_lock: bool,
160    umask: Option<u32>,
161    open_files_target: u64,
162    open_files_minimum: u64,
163}
164
165impl GuardBuilder {
166    /// The directory for the lock and pid files. The default depends only on
167    /// the user (see [`guard`]); a database should pass its data directory.
168    /// Created owner-only (0700) on Unix when missing; on Windows it inherits
169    /// its parent's permissions, so choose a parent other users cannot write
170    /// to (not `C:\ProgramData` itself).
171    #[must_use]
172    pub fn lock_dir(mut self, dir: impl Into<PathBuf>) -> Self {
173        self.lock_dir = Some(dir.into());
174        self
175    }
176
177    /// Whether to take the single-instance lock (default true). Pass false when
178    /// a supervisor holds it, as tower does across hand-off restarts.
179    #[must_use]
180    pub fn lock(mut self, on: bool) -> Self {
181        self.lock = on;
182        self
183    }
184
185    /// Accept a lock directory on a network filesystem (`nfs`, `cifs`, WSL's
186    /// `9p`), whose locks may not hold across machines (default false).
187    #[must_use]
188    pub fn allow_network_lock(mut self, on: bool) -> Self {
189        self.allow_network_lock = on;
190        self
191    }
192
193    /// The umask to set (default `0o027`). Unix only; ignored on Windows.
194    #[must_use]
195    pub fn umask(mut self, mask: u32) -> Self {
196        self.umask = Some(mask & 0o777);
197        self
198    }
199
200    /// Leave the umask as it is.
201    #[must_use]
202    pub fn keep_umask(mut self) -> Self {
203        self.umask = None;
204        self
205    }
206
207    /// The soft open-file limit to raise to (default 65 536), capped at the
208    /// hard limit and, on macOS, at `kern.maxfilesperproc`.
209    #[must_use]
210    pub fn open_files_target(mut self, n: u64) -> Self {
211        self.open_files_target = n;
212        self
213    }
214
215    /// The hard open-file limit below which the guard refuses to start
216    /// (default 1 024).
217    #[must_use]
218    pub fn open_files_minimum(mut self, n: u64) -> Self {
219        self.open_files_minimum = n;
220        self
221    }
222
223    /// Starts the guard. See [`guard`] for the errors.
224    pub fn build(self) -> Result<Guard> {
225        validate_name(&self.name)?;
226        let mut warnings = Vec::new();
227
228        // Plan the open-file limit first, so a refusal changes nothing (E-67).
229        let files_before = sys::open_files_limit()?;
230        let raise_to = plan_open_files(
231            files_before,
232            self.open_files_target,
233            self.open_files_minimum,
234            sys::open_files_ceiling(),
235        )?;
236
237        let (lock, lock_file, lock_filesystem) = if self.lock {
238            let dir = match &self.lock_dir {
239                Some(d) => {
240                    create_owner_only(d)?;
241                    d.clone()
242                }
243                None => default_dir(&self.name)?,
244            };
245            check_dir(&dir)?;
246            let fs_kind = sys::filesystem(&dir);
247            if let Some(kind) = fs_kind.filter(|k| k.network) {
248                if !self.allow_network_lock {
249                    return Err(unavailable(
250                        &dir,
251                        io::ErrorKind::Unsupported,
252                        &format!(
253                            "it is on a {} filesystem, where locks may not hold across machines; use a local \
254                             directory, or allow_network_lock(true)",
255                            kind.name
256                        ),
257                    ));
258                }
259                warnings.push(GuardWarning::NetworkLockAllowed {
260                    filesystem: kind.name,
261                });
262            }
263            let lock_path = dir.join(format!("{}.lock", self.name));
264            let pid_path = dir.join(format!("{}.pid", self.name));
265            let file = lock_file(&dir, &lock_path, &pid_path)?;
266            path_lib::write_atomic(&pid_path, format!("{}\n", std::process::id())).map_err(
267                |e| {
268                    unavailable(
269                        &dir,
270                        io::ErrorKind::Other,
271                        &format!("the pid file cannot be written: {e}"),
272                    )
273                },
274            )?;
275            (Some(file), Some(lock_path), fs_kind.map(|k| k.name))
276        } else {
277            warnings.push(GuardWarning::LockDisabled);
278            (None, None, None)
279        };
280
281        let files_after = match raise_to {
282            Some(n) => {
283                sys::set_open_files_soft(n)?;
284                sys::open_files_limit()?
285            }
286            None => files_before,
287        };
288
289        let (umask_before, umask_after) = match self.umask {
290            Some(mask) => {
291                let before = sys::swap_umask(mask);
292                (before, before.map(|_| mask))
293            }
294            None => {
295                // Reading the umask means setting it; set it straight back.
296                let current = sys::swap_umask(0o077);
297                if let Some(c) = current {
298                    sys::swap_umask(c);
299                }
300                (current, current)
301            }
302        };
303
304        // The race is the umask's, so the warning is Unix-only. Windows has no
305        // umask, and every Windows process starts with the loader's worker
306        // threads, so a count there would warn on every start.
307        #[cfg(unix)]
308        if let Some(threads) = sys::thread_count().filter(|&n| n > 1) {
309            warnings.push(GuardWarning::ThreadsAlreadyRunning { threads });
310        }
311
312        Ok(Guard {
313            lock,
314            report: GuardReport {
315                lock_file,
316                lock_filesystem,
317                umask_before,
318                umask_after,
319                open_files_before: files_before,
320                open_files_after: files_after,
321                warnings,
322            },
323        })
324    }
325}
326
327/// What the guard did.
328#[derive(Clone, Debug, PartialEq, Eq)]
329#[non_exhaustive]
330pub struct GuardReport {
331    /// The lock file, when a lock was taken.
332    pub lock_file: Option<PathBuf>,
333    /// The lock directory's filesystem: "ext4", "apfs", "NTFS", ...
334    pub lock_filesystem: Option<&'static str>,
335    /// The umask before the guard (Unix; `None` on Windows).
336    pub umask_before: Option<u32>,
337    /// The umask after the guard (Unix; `None` on Windows).
338    pub umask_after: Option<u32>,
339    /// The open-file limit before the guard (`None` values: unlimited or not applicable).
340    pub open_files_before: Limit,
341    /// The open-file limit after the guard.
342    pub open_files_after: Limit,
343    /// Conditions worth logging that did not stop the guard.
344    pub warnings: Vec<GuardWarning>,
345}
346
347/// A condition the guard reports without refusing to start.
348#[derive(Clone, Debug, PartialEq, Eq)]
349#[non_exhaustive]
350pub enum GuardWarning {
351    /// Other threads were running when the umask changed; files they created
352    /// meanwhile may have the old permissions. Call the guard before starting
353    /// threads. Unix only: Windows has no umask.
354    ThreadsAlreadyRunning {
355        /// The thread count, this one included.
356        threads: usize,
357    },
358    /// The lock directory is on a filesystem whose locks may not hold across
359    /// machines, accepted because `allow_network_lock(true)` was set.
360    NetworkLockAllowed {
361        /// The filesystem.
362        filesystem: &'static str,
363    },
364    /// `lock(false)`: no single-instance lock was taken.
365    LockDisabled,
366}
367
368/// 1 to 64 ASCII letters, digits, `-`, `_`, `.`, not starting with `.` (threat T4).
369fn validate_name(name: &str) -> Result<()> {
370    let ok = !name.is_empty()
371        && name.len() <= 64
372        && !name.starts_with('.')
373        && name
374            .bytes()
375            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
376    if ok {
377        Ok(())
378    } else {
379        Err(Error::InvalidInput {
380            what: "process guard name",
381            reason: "use 1 to 64 ASCII letters, digits, '-', '_', or '.', not starting with '.'",
382        })
383    }
384}
385
386/// The soft limit to raise to, if any. Refuses when the hard limit (or the
387/// platform ceiling) is below the minimum (E-66, E-67).
388fn plan_open_files(
389    before: Limit,
390    target: u64,
391    minimum: u64,
392    ceiling: Option<u64>,
393) -> Result<Option<u64>> {
394    if before.soft.is_none() && before.hard.is_none() {
395        return Ok(None); // Not applicable (Windows) or unlimited.
396    }
397    let hard = before.hard.unwrap_or(u64::MAX);
398    let usable = hard.min(ceiling.unwrap_or(u64::MAX));
399    if usable < minimum {
400        return Err(Error::OpenFilesTooLow {
401            have: usable,
402            need: minimum,
403        });
404    }
405    let want = target.max(minimum).min(usable);
406    Ok((before.soft.unwrap_or(u64::MAX) < want).then_some(want))
407}
408
409fn unavailable(dir: &Path, kind: io::ErrorKind, reason: &str) -> Error {
410    Error::RunDirUnavailable {
411        path: dir.to_path_buf(),
412        source: io::Error::new(kind, reason.to_owned()),
413    }
414}
415
416/// Opens and locks the lock file, then checks that the locked file is still
417/// the one at the path: a file deleted or replaced between the open and the
418/// lock would hold a lock no other copy can see. Bounded retries.
419fn lock_file(dir: &Path, lock_path: &Path, pid_path: &Path) -> Result<File> {
420    for _ in 0..LOCK_ATTEMPTS {
421        let file = open_lock_file(dir, lock_path)?;
422        match file.try_lock() {
423            Ok(()) => {}
424            Err(fs::TryLockError::WouldBlock) => {
425                return Err(Error::AlreadyRunning {
426                    pid: read_pid(pid_path),
427                    lock_file: lock_path.to_path_buf(),
428                });
429            }
430            Err(fs::TryLockError::Error(e)) => {
431                return Err(Error::Io {
432                    what: "the process guard's lock",
433                    source: e,
434                });
435            }
436        }
437        if same_file(&file, lock_path) {
438            return Ok(file);
439        }
440    }
441    Err(unavailable(
442        dir,
443        io::ErrorKind::Interrupted,
444        "the lock file keeps being replaced while it is locked; find what removes it",
445    ))
446}
447
448/// How many times [`lock_file`] opens and locks before giving up.
449const LOCK_ATTEMPTS: usize = 3;
450
451/// Whether `path` names the open `file`.
452fn same_file(file: &File, path: &Path) -> bool {
453    #[cfg(unix)]
454    {
455        use std::os::unix::fs::MetadataExt;
456        match (file.metadata(), fs::symlink_metadata(path)) {
457            (Ok(a), Ok(b)) => (a.dev(), a.ino()) == (b.dev(), b.ino()),
458            _ => false,
459        }
460    }
461    #[cfg(not(unix))]
462    {
463        // Opened without delete sharing, so the file cannot be deleted or
464        // renamed while it is open; the path only has to exist.
465        let _ = file;
466        fs::symlink_metadata(path).is_ok()
467    }
468}
469
470/// The default lock directory, from the user alone (D-106).
471#[cfg(unix)]
472fn default_dir(name: &str) -> Result<PathBuf> {
473    let Some(uid) = sys::effective_uid() else {
474        return runtime_dir(name);
475    };
476    let dir = if uid == 0 {
477        system_run_dir().join(name)
478    } else {
479        let home = sys::home_dir(uid).ok_or_else(|| {
480            unavailable(
481                Path::new(name),
482                io::ErrorKind::NotFound,
483                &format!(
484                    "user {uid} has no home directory in the account database for the default lock;                      pass lock_dir"
485                ),
486            )
487        })?;
488        user_run_dir(&home, name)
489    };
490    create_owner_only(&dir)?;
491    Ok(dir)
492}
493
494#[cfg(not(unix))]
495fn default_dir(name: &str) -> Result<PathBuf> {
496    // The known-folder path, which does not follow environment variables.
497    runtime_dir(name)
498}
499
500/// The system run directory for root.
501#[cfg(unix)]
502fn system_run_dir() -> &'static Path {
503    if cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/run").is_dir() {
504        Path::new("/run")
505    } else {
506        Path::new("/var/run")
507    }
508}
509
510/// The per-user run directory under `home`.
511#[cfg(unix)]
512fn user_run_dir(home: &Path, name: &str) -> PathBuf {
513    if cfg!(any(target_os = "macos", target_os = "ios")) {
514        home.join("Library/Application Support")
515            .join(name)
516            .join("run")
517    } else {
518        home.join(".local/state").join(name).join("run")
519    }
520}
521
522fn runtime_dir(name: &str) -> Result<PathBuf> {
523    let app = path_lib::App::new(name)
524        .map_err(|e| unavailable(Path::new(name), io::ErrorKind::InvalidInput, &e.to_string()))?;
525    let dir = app.dir(path_lib::Kind::Runtime).to_path_buf();
526    app.ensure(path_lib::Kind::Runtime).map_err(|e| {
527        unavailable(
528            &dir,
529            io::ErrorKind::Other,
530            &format!("it cannot be created: {e}"),
531        )
532    })?;
533    Ok(dir)
534}
535
536fn create_owner_only(dir: &Path) -> Result<()> {
537    if fs::symlink_metadata(dir).is_ok() {
538        return Ok(());
539    }
540    let mut builder = fs::DirBuilder::new();
541    builder.recursive(true);
542    #[cfg(unix)]
543    {
544        use std::os::unix::fs::DirBuilderExt;
545        builder.mode(0o700);
546    }
547    builder
548        .create(dir)
549        .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be created: {e}")))
550}
551
552/// The lock directory must be a real, owner-only directory (threat T9).
553fn check_dir(dir: &Path) -> Result<()> {
554    let meta = fs::symlink_metadata(dir)
555        .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be read: {e}")))?;
556    if meta.file_type().is_symlink() {
557        return Err(unavailable(
558            dir,
559            io::ErrorKind::InvalidInput,
560            "it is a symbolic link; use the real directory",
561        ));
562    }
563    if !meta.is_dir() {
564        return Err(unavailable(
565            dir,
566            io::ErrorKind::InvalidInput,
567            "it is not a directory",
568        ));
569    }
570    #[cfg(unix)]
571    {
572        use std::os::unix::fs::MetadataExt;
573        if meta.mode() & 0o022 != 0 {
574            return Err(unavailable(
575                dir,
576                io::ErrorKind::PermissionDenied,
577                "other users can write to it and could replace the lock file; chmod 700 it, or use another directory",
578            ));
579        }
580        if sys::effective_uid().is_some_and(|uid| uid != meta.uid()) {
581            return Err(unavailable(
582                dir,
583                io::ErrorKind::PermissionDenied,
584                "it belongs to another user; use a directory this user owns",
585            ));
586        }
587    }
588    #[cfg(windows)]
589    {
590        use std::os::windows::fs::MetadataExt;
591        if meta.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
592            return Err(unavailable(
593                dir,
594                io::ErrorKind::InvalidInput,
595                "it is a junction or link; use the real directory",
596            ));
597        }
598    }
599    Ok(())
600}
601
602/// Opens the lock file without following a link at its path (threat T9).
603fn open_lock_file(dir: &Path, path: &Path) -> Result<File> {
604    if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
605        return Err(unavailable(
606            dir,
607            io::ErrorKind::InvalidInput,
608            "the lock file is a symbolic link; remove it",
609        ));
610    }
611    let mut options = OpenOptions::new();
612    options.read(true).write(true).create(true).truncate(false);
613    sys::lock_open_options(&mut options);
614    let file = options.open(path).map_err(|e| {
615        unavailable(
616            dir,
617            e.kind(),
618            &format!("the lock file cannot be opened: {e}"),
619        )
620    })?;
621    let opened = file
622        .metadata()
623        .map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
624    let at_path =
625        fs::symlink_metadata(path).map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
626    if !opened.is_file() || at_path.file_type().is_symlink() {
627        return Err(unavailable(
628            dir,
629            io::ErrorKind::InvalidInput,
630            "the lock file is not a regular file; remove it",
631        ));
632    }
633    #[cfg(unix)]
634    {
635        use std::os::unix::fs::MetadataExt;
636        // The file opened must be the one at the path (no swap in between) and ours.
637        if (opened.dev(), opened.ino()) != (at_path.dev(), at_path.ino()) {
638            return Err(unavailable(
639                dir,
640                io::ErrorKind::InvalidInput,
641                "the lock file changed while it was opened",
642            ));
643        }
644        if sys::effective_uid().is_some_and(|uid| uid != opened.uid()) {
645            return Err(unavailable(
646                dir,
647                io::ErrorKind::PermissionDenied,
648                "the lock file belongs to another user; remove it",
649            ));
650        }
651    }
652    #[cfg(windows)]
653    {
654        use std::os::windows::fs::MetadataExt;
655        if opened.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
656            return Err(unavailable(
657                dir,
658                io::ErrorKind::InvalidInput,
659                "the lock file is a link; remove it",
660            ));
661        }
662    }
663    Ok(file)
664}
665
666/// The other copy's pid from its pid file, read strictly (at most 128 bytes).
667fn read_pid(path: &Path) -> Option<u32> {
668    let mut data = Vec::with_capacity(pid_file::MAX_BYTES + 1);
669    File::open(path)
670        .ok()?
671        .take(pid_file::MAX_BYTES as u64 + 1)
672        .read_to_end(&mut data)
673        .ok()?;
674    pid_file::parse(&data)
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680
681    fn temp_dir(tag: &str) -> PathBuf {
682        let dir = std::env::temp_dir().join(format!("sys-lib-guard-{tag}-{}", std::process::id()));
683        let _ = fs::remove_dir_all(&dir);
684        dir
685    }
686
687    #[test]
688    fn test_guard_name_validation() {
689        for good in ["site", "my-app", "a.b_c", "x"] {
690            assert!(validate_name(good).is_ok(), "{good}");
691        }
692        for bad in [
693            "",
694            ".hidden",
695            "a/b",
696            "a\\b",
697            "..",
698            "sp ace",
699            "naïve",
700            &"x".repeat(65),
701        ] {
702            assert!(
703                matches!(validate_name(bad), Err(Error::InvalidInput { .. })),
704                "{bad:?}"
705            );
706        }
707    }
708
709    #[test]
710    fn test_guard_open_files_plan() {
711        let limit = |soft, hard| Limit { soft, hard };
712        // Raise to the target, capped at the hard limit.
713        assert_eq!(
714            plan_open_files(limit(Some(1024), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
715            Some(65_536)
716        );
717        assert_eq!(
718            plan_open_files(limit(Some(1024), Some(4096)), 65_536, 1_024, None).unwrap(),
719            Some(4096)
720        );
721        // Already high enough: unchanged.
722        assert_eq!(
723            plan_open_files(limit(Some(100_000), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
724            None
725        );
726        // E-66: an unlimited hard limit is capped at the platform ceiling.
727        assert_eq!(
728            plan_open_files(limit(Some(256), None), 65_536, 1_024, Some(24_576)).unwrap(),
729            Some(24_576)
730        );
731        // E-67: a hard limit below the minimum refuses, naming both.
732        let e = plan_open_files(limit(Some(256), Some(512)), 65_536, 1_024, None).unwrap_err();
733        assert!(matches!(
734            e,
735            Error::OpenFilesTooLow {
736                have: 512,
737                need: 1_024
738            }
739        ));
740        // Windows: not applicable.
741        assert_eq!(
742            plan_open_files(limit(None, None), 65_536, 1_024, None).unwrap(),
743            None
744        );
745    }
746
747    #[test]
748    fn test_guard_locks_and_a_second_guard_is_refused() {
749        let dir = temp_dir("second");
750        let first = Guard::builder("guard-test")
751            .lock_dir(&dir)
752            .keep_umask()
753            .open_files_target(0)
754            .open_files_minimum(0)
755            .build()
756            .unwrap();
757        let lock = first.lock_file().unwrap().to_path_buf();
758        assert!(lock.ends_with("guard-test.lock"));
759        assert_eq!(
760            read_pid(&dir.join("guard-test.pid")),
761            Some(std::process::id())
762        );
763        let second = Guard::builder("guard-test")
764            .lock_dir(&dir)
765            .keep_umask()
766            .open_files_target(0)
767            .open_files_minimum(0)
768            .build();
769        match second {
770            Err(Error::AlreadyRunning { pid, lock_file }) => {
771                assert_eq!(pid, Some(std::process::id()));
772                assert_eq!(lock_file, lock);
773            }
774            other => panic!("expected AlreadyRunning, got {other:?}"),
775        }
776        drop(first);
777        // The lock is released; the lock file is never deleted.
778        assert!(lock.exists());
779        let again = Guard::builder("guard-test")
780            .lock_dir(&dir)
781            .keep_umask()
782            .open_files_target(0)
783            .open_files_minimum(0)
784            .build();
785        assert!(again.is_ok());
786        drop(again);
787        let _ = fs::remove_dir_all(&dir);
788    }
789
790    #[test]
791    fn test_guard_is_held_until_the_lock_file_is_replaced() {
792        // A lock file deleted while held: the guard notices, and a later copy
793        // gets a new lock (Unix); Windows refuses the delete instead.
794        let dir = temp_dir("held");
795        let g = Guard::builder("held")
796            .lock_dir(&dir)
797            .keep_umask()
798            .open_files_target(0)
799            .open_files_minimum(0)
800            .build()
801            .unwrap();
802        assert!(g.is_held());
803        let lock = g.lock_file().unwrap().to_path_buf();
804        let removed = fs::remove_file(&lock);
805        if cfg!(windows) {
806            assert!(removed.is_err(), "a held lock file was deleted");
807            assert!(g.is_held());
808        } else {
809            removed.unwrap();
810            assert!(!g.is_held());
811            fs::write(&lock, b"").unwrap();
812            assert!(!g.is_held(), "a new file at the path is not the locked one");
813        }
814        drop(g);
815        let _ = fs::remove_dir_all(&dir);
816    }
817
818    #[test]
819    fn test_guard_without_lock_is_not_held() {
820        let g = Guard::builder("unheld")
821            .lock(false)
822            .keep_umask()
823            .open_files_target(0)
824            .open_files_minimum(0)
825            .build()
826            .unwrap();
827        assert!(!g.is_held());
828    }
829
830    #[cfg(unix)]
831    #[test]
832    fn test_guard_default_dir_ignores_the_environment() {
833        // D-106: the default comes from the uid and the account database.
834        let uid = sys::effective_uid().unwrap();
835        if uid == 0 {
836            assert!(system_run_dir().is_dir());
837            return;
838        }
839        let Some(home) = sys::home_dir(uid) else {
840            return;
841        };
842        let dir = user_run_dir(&home, "probe");
843        assert!(dir.starts_with(&home));
844        assert!(dir.ends_with("probe/run"));
845        let dir = user_run_dir(Path::new("/h"), "site");
846        if cfg!(target_os = "macos") {
847            assert_eq!(dir, Path::new("/h/Library/Application Support/site/run"));
848        } else {
849            assert_eq!(dir, Path::new("/h/.local/state/site/run"));
850        }
851    }
852
853    #[test]
854    fn test_guard_lock_false_takes_no_lock() {
855        let g = Guard::builder("nolock")
856            .lock(false)
857            .keep_umask()
858            .open_files_target(0)
859            .open_files_minimum(0)
860            .build()
861            .unwrap();
862        assert_eq!(g.lock_file(), None);
863        assert!(g.report().warnings.contains(&GuardWarning::LockDisabled));
864    }
865
866    #[test]
867    fn test_guard_refuses_a_file_as_lock_dir() {
868        let dir = temp_dir("file");
869        fs::create_dir_all(dir.parent().unwrap()).unwrap();
870        fs::write(&dir, b"x").unwrap();
871        let e = Guard::builder("g")
872            .lock_dir(&dir)
873            .keep_umask()
874            .build()
875            .unwrap_err();
876        assert!(matches!(e, Error::RunDirUnavailable { .. }), "{e:?}");
877        let _ = fs::remove_file(&dir);
878    }
879
880    #[cfg(unix)]
881    #[test]
882    fn test_guard_lock_path_is_symlink_refuses() {
883        // E-64, T9: a symlink planted at the lock path.
884        let dir = temp_dir("symlink");
885        create_owner_only(&dir).unwrap();
886        let target = dir.join("elsewhere");
887        fs::write(&target, b"").unwrap();
888        std::os::unix::fs::symlink(&target, dir.join("g.lock")).unwrap();
889        let e = Guard::builder("g")
890            .lock_dir(&dir)
891            .keep_umask()
892            .build()
893            .unwrap_err();
894        assert!(e.to_string().contains("symbolic link"), "{e}");
895        let _ = fs::remove_dir_all(&dir);
896    }
897
898    #[cfg(unix)]
899    #[test]
900    fn test_guard_world_writable_dir_refuses() {
901        // E-64, T9: a directory other users can write to.
902        use std::os::unix::fs::PermissionsExt;
903        let dir = temp_dir("writable");
904        create_owner_only(&dir).unwrap();
905        fs::set_permissions(&dir, fs::Permissions::from_mode(0o777)).unwrap();
906        let e = Guard::builder("g")
907            .lock_dir(&dir)
908            .keep_umask()
909            .build()
910            .unwrap_err();
911        assert!(e.to_string().contains("other users can write"), "{e}");
912        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
913        let _ = fs::remove_dir_all(&dir);
914    }
915
916    #[cfg(unix)]
917    #[test]
918    fn test_guard_symlinked_dir_refuses() {
919        let dir = temp_dir("dirlink");
920        let real = temp_dir("dirlink-real");
921        create_owner_only(&real).unwrap();
922        std::os::unix::fs::symlink(&real, &dir).unwrap();
923        let e = Guard::builder("g")
924            .lock_dir(&dir)
925            .keep_umask()
926            .build()
927            .unwrap_err();
928        assert!(e.to_string().contains("symbolic link"), "{e}");
929        let _ = fs::remove_file(&dir);
930        let _ = fs::remove_dir_all(&real);
931    }
932
933    #[test]
934    fn test_guard_stale_pid_file_is_replaced() {
935        // E-63: a pid file left by a crashed run while the lock is free.
936        let dir = temp_dir("stale");
937        create_owner_only(&dir).unwrap();
938        fs::write(dir.join("g.pid"), b"999999\n").unwrap();
939        let g = Guard::builder("g")
940            .lock_dir(&dir)
941            .keep_umask()
942            .open_files_target(0)
943            .open_files_minimum(0)
944            .build()
945            .unwrap();
946        assert_eq!(read_pid(&dir.join("g.pid")), Some(std::process::id()));
947        drop(g);
948        let _ = fs::remove_dir_all(&dir);
949    }
950
951    #[test]
952    fn test_guard_report_with_threads_warns() {
953        // E-65, T10: the test harness runs tests on threads, so on Unix a warning
954        // is expected wherever the platform can count them; never on Windows.
955        let g = Guard::builder("threads")
956            .lock(false)
957            .keep_umask()
958            .open_files_target(0)
959            .open_files_minimum(0)
960            .build()
961            .unwrap();
962        let warned = g
963            .report()
964            .warnings
965            .iter()
966            .any(|w| matches!(w, GuardWarning::ThreadsAlreadyRunning { .. }));
967        if cfg!(unix) {
968            assert_eq!(warned, sys::thread_count().is_some_and(|n| n > 1));
969        } else {
970            assert!(!warned);
971        }
972        if cfg!(unix) {
973            assert!(g.report().umask_before.is_some());
974            assert_eq!(g.report().umask_before, g.report().umask_after);
975        } else {
976            assert_eq!(g.report().umask_before, None);
977        }
978    }
979}