sys-lib 0.7.0

System facts for Rust services: OS, CPU, memory, disks, network, host, this process, virtualization, power, and device identity, container-aware by default, plus build info, instance info, and a process guard. No subprocesses, no third-party dependencies by default.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! The process guard: make sure this is the only copy running, make every
//! file it creates private by default, and make sure it will not run out of
//! file descriptors under load. One call, secure defaults, and a refusal with
//! an actionable error when a requirement cannot be met.

use std::{
    fmt,
    fs::{self, File, OpenOptions},
    io::{self, Read},
    path::{Path, PathBuf},
};

use super::Limit;
use crate::{Error, Result, parse::pid_file, sys};

/// The default umask: owner read and write, group read, others nothing.
const DEFAULT_UMASK: u32 = 0o027;
/// The default soft open-file limit the guard raises to.
const DEFAULT_OPEN_FILES_TARGET: u64 = 65_536;
/// The default minimum hard open-file limit; below it the guard refuses to start.
const DEFAULT_OPEN_FILES_MINIMUM: u64 = 1_024;

/// Starts the process guard with secure defaults: a single-instance lock in
/// the default lock directory for `name`, `umask(0o027)`, and the soft
/// open-file limit raised to 65 536 (at least 1 024 required). Call it before
/// any file is opened and before threads start, and keep the [`Guard`] for the
/// life of the process.
///
/// The default lock directory depends only on the user the process runs as,
/// never on environment variables, so a copy started by a service manager and
/// one started from a shell find the same lock (D-106):
///
/// | Platform | root | other users |
/// |---|---|---|
/// | Linux | `/run/<name>` | `<home>/.local/state/<name>/run` |
/// | macOS | `/var/run/<name>` | `<home>/Library/Application Support/<name>/run` |
/// | FreeBSD | `/var/run/<name>` | `<home>/.local/state/<name>/run` |
/// | Windows | the user's local application data folder, `<name>\run` | the same |
///
/// `<home>` is the home directory in the account database, not `$HOME`. The
/// lock is per user: copies running as different users do not exclude each
/// other. A program guarding shared data (a database) passes its data
/// directory with [`GuardBuilder::lock_dir`], so every copy that could touch
/// the data finds the same lock.
///
/// ```no_run
/// use sys_lib as sys;
///
/// let guard = sys::process::guard("site")?;      // before any file is opened
/// println!("lock {:?}", guard.lock_file());
/// // ... run; the lock is held while `guard` lives.
/// # Ok::<(), sys_lib::Error>(())
/// ```
///
/// # Errors
///
/// [`Error::AlreadyRunning`] when another copy holds the lock,
/// [`Error::RunDirUnavailable`] when the lock directory cannot be created or
/// trusted (or, for a user other than root, the account has no home
/// directory), [`Error::OpenFilesTooLow`] when the hard open-file limit is
/// below the minimum, and [`Error::InvalidInput`] for an invalid name.
pub fn guard(name: &str) -> Result<Guard> {
    Guard::builder(name).build()
}

/// The running guard. Dropping it closes the lock file, which releases the
/// lock; the lock file itself is never deleted (deleting it would let two
/// copies run, see the plan's guard section).
///
/// The lock belongs to the file, not to its path. On Windows the file cannot
/// be deleted or renamed while the guard holds it. On Unix it can (a temporary
/// file cleaner, an operator's `rm`), and a copy started afterwards would
/// create a new lock file and run; [`Guard::is_held`] tells a long-running
/// service when that has happened.
#[must_use = "dropping the guard releases the single-instance lock"]
pub struct Guard {
    // Held for its lock.
    lock: Option<File>,
    report: GuardReport,
}

impl Guard {
    /// A builder for options other than the defaults.
    ///
    /// ```no_run
    /// use sys_lib::process::Guard;
    ///
    /// // A database locks beside its data, so two copies under different users
    /// // or run directories still exclude each other.
    /// let guard = Guard::builder("myapp")
    ///     .lock_dir("/var/lib/myapp")
    ///     .open_files_target(1_048_576)
    ///     .open_files_minimum(65_536)
    ///     .build()?;
    /// # Ok::<(), sys_lib::Error>(())
    /// ```
    pub fn builder(name: &str) -> GuardBuilder {
        GuardBuilder {
            name: name.to_owned(),
            lock_dir: None,
            lock: true,
            allow_network_lock: false,
            umask: Some(DEFAULT_UMASK),
            open_files_target: DEFAULT_OPEN_FILES_TARGET,
            open_files_minimum: DEFAULT_OPEN_FILES_MINIMUM,
        }
    }

    /// What the guard did.
    #[must_use]
    pub fn report(&self) -> &GuardReport {
        &self.report
    }

    /// The lock file, when a lock was taken.
    #[must_use]
    pub fn lock_file(&self) -> Option<&Path> {
        self.report.lock_file.as_deref()
    }

    /// Whether the lock file at its path is still the one this guard locked.
    /// False when the file was deleted or replaced since (only possible on
    /// Unix), so another copy could now start, or when no lock was taken.
    /// A service that runs for long can check it periodically and stop.
    ///
    /// ```no_run
    /// use sys_lib as sys;
    ///
    /// let guard = sys::process::guard("site")?;
    /// // ... later, on a timer:
    /// if !guard.is_held() {
    ///     eprintln!("the lock file was removed; stopping so only one copy runs");
    /// }
    /// # Ok::<(), sys_lib::Error>(())
    /// ```
    #[must_use]
    pub fn is_held(&self) -> bool {
        match (&self.lock, &self.report.lock_file) {
            (Some(file), Some(path)) => same_file(file, path),
            _ => false,
        }
    }
}

impl fmt::Debug for Guard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Guard")
            .field("report", &self.report)
            .finish()
    }
}

/// Options for [`Guard`].
#[derive(Clone, Debug)]
pub struct GuardBuilder {
    name: String,
    lock_dir: Option<PathBuf>,
    lock: bool,
    allow_network_lock: bool,
    umask: Option<u32>,
    open_files_target: u64,
    open_files_minimum: u64,
}

impl GuardBuilder {
    /// The directory for the lock and pid files. The default depends only on
    /// the user (see [`guard`]); a database should pass its data directory.
    /// Created owner-only (0700) on Unix when missing; on Windows it inherits
    /// its parent's permissions, so choose a parent other users cannot write
    /// to (not `C:\ProgramData` itself).
    #[must_use]
    pub fn lock_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.lock_dir = Some(dir.into());
        self
    }

    /// Whether to take the single-instance lock (default true). Pass false when
    /// a supervisor holds it, as tower does across hand-off restarts.
    #[must_use]
    pub fn lock(mut self, on: bool) -> Self {
        self.lock = on;
        self
    }

    /// Accept a lock directory on a network filesystem (`nfs`, `cifs`, WSL's
    /// `9p`), whose locks may not hold across machines (default false).
    #[must_use]
    pub fn allow_network_lock(mut self, on: bool) -> Self {
        self.allow_network_lock = on;
        self
    }

    /// The umask to set (default `0o027`). Unix only; ignored on Windows.
    #[must_use]
    pub fn umask(mut self, mask: u32) -> Self {
        self.umask = Some(mask & 0o777);
        self
    }

    /// Leave the umask as it is.
    #[must_use]
    pub fn keep_umask(mut self) -> Self {
        self.umask = None;
        self
    }

    /// The soft open-file limit to raise to (default 65 536), capped at the
    /// hard limit and, on macOS, at `kern.maxfilesperproc`.
    #[must_use]
    pub fn open_files_target(mut self, n: u64) -> Self {
        self.open_files_target = n;
        self
    }

    /// The hard open-file limit below which the guard refuses to start
    /// (default 1 024).
    #[must_use]
    pub fn open_files_minimum(mut self, n: u64) -> Self {
        self.open_files_minimum = n;
        self
    }

    /// Starts the guard. See [`guard`] for the errors.
    pub fn build(self) -> Result<Guard> {
        validate_name(&self.name)?;
        let mut warnings = Vec::new();

        // Plan the open-file limit first, so a refusal changes nothing (E-67).
        let files_before = sys::open_files_limit()?;
        let raise_to = plan_open_files(
            files_before,
            self.open_files_target,
            self.open_files_minimum,
            sys::open_files_ceiling(),
        )?;

        let (lock, lock_file, lock_filesystem) = if self.lock {
            let dir = match &self.lock_dir {
                Some(d) => {
                    create_owner_only(d)?;
                    d.clone()
                }
                None => default_dir(&self.name)?,
            };
            check_dir(&dir)?;
            let fs_kind = sys::filesystem(&dir);
            if let Some(kind) = fs_kind.filter(|k| k.network) {
                if !self.allow_network_lock {
                    return Err(unavailable(
                        &dir,
                        io::ErrorKind::Unsupported,
                        &format!(
                            "it is on a {} filesystem, where locks may not hold across machines; use a local \
                             directory, or allow_network_lock(true)",
                            kind.name
                        ),
                    ));
                }
                warnings.push(GuardWarning::NetworkLockAllowed {
                    filesystem: kind.name,
                });
            }
            let lock_path = dir.join(format!("{}.lock", self.name));
            let pid_path = dir.join(format!("{}.pid", self.name));
            let file = lock_file(&dir, &lock_path, &pid_path)?;
            path_lib::write_atomic(&pid_path, format!("{}\n", std::process::id())).map_err(
                |e| {
                    unavailable(
                        &dir,
                        io::ErrorKind::Other,
                        &format!("the pid file cannot be written: {e}"),
                    )
                },
            )?;
            (Some(file), Some(lock_path), fs_kind.map(|k| k.name))
        } else {
            warnings.push(GuardWarning::LockDisabled);
            (None, None, None)
        };

        let files_after = match raise_to {
            Some(n) => {
                sys::set_open_files_soft(n)?;
                sys::open_files_limit()?
            }
            None => files_before,
        };

        let (umask_before, umask_after) = match self.umask {
            Some(mask) => {
                let before = sys::swap_umask(mask);
                (before, before.map(|_| mask))
            }
            None => {
                // Reading the umask means setting it; set it straight back.
                let current = sys::swap_umask(0o077);
                if let Some(c) = current {
                    sys::swap_umask(c);
                }
                (current, current)
            }
        };

        // The race is the umask's, so the warning is Unix-only. Windows has no
        // umask, and every Windows process starts with the loader's worker
        // threads, so a count there would warn on every start.
        #[cfg(unix)]
        if let Some(threads) = sys::thread_count().filter(|&n| n > 1) {
            warnings.push(GuardWarning::ThreadsAlreadyRunning { threads });
        }

        Ok(Guard {
            lock,
            report: GuardReport {
                lock_file,
                lock_filesystem,
                umask_before,
                umask_after,
                open_files_before: files_before,
                open_files_after: files_after,
                warnings,
            },
        })
    }
}

/// What the guard did.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct GuardReport {
    /// The lock file, when a lock was taken.
    pub lock_file: Option<PathBuf>,
    /// The lock directory's filesystem: "ext4", "apfs", "NTFS", ...
    pub lock_filesystem: Option<&'static str>,
    /// The umask before the guard (Unix; `None` on Windows).
    pub umask_before: Option<u32>,
    /// The umask after the guard (Unix; `None` on Windows).
    pub umask_after: Option<u32>,
    /// The open-file limit before the guard (`None` values: unlimited or not applicable).
    pub open_files_before: Limit,
    /// The open-file limit after the guard.
    pub open_files_after: Limit,
    /// Conditions worth logging that did not stop the guard.
    pub warnings: Vec<GuardWarning>,
}

/// A condition the guard reports without refusing to start.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GuardWarning {
    /// Other threads were running when the umask changed; files they created
    /// meanwhile may have the old permissions. Call the guard before starting
    /// threads. Unix only: Windows has no umask.
    ThreadsAlreadyRunning {
        /// The thread count, this one included.
        threads: usize,
    },
    /// The lock directory is on a filesystem whose locks may not hold across
    /// machines, accepted because `allow_network_lock(true)` was set.
    NetworkLockAllowed {
        /// The filesystem.
        filesystem: &'static str,
    },
    /// `lock(false)`: no single-instance lock was taken.
    LockDisabled,
}

/// 1 to 64 ASCII letters, digits, `-`, `_`, `.`, not starting with `.` (threat T4).
fn validate_name(name: &str) -> Result<()> {
    let ok = !name.is_empty()
        && name.len() <= 64
        && !name.starts_with('.')
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
    if ok {
        Ok(())
    } else {
        Err(Error::InvalidInput {
            what: "process guard name",
            reason: "use 1 to 64 ASCII letters, digits, '-', '_', or '.', not starting with '.'",
        })
    }
}

/// The soft limit to raise to, if any. Refuses when the hard limit (or the
/// platform ceiling) is below the minimum (E-66, E-67).
fn plan_open_files(
    before: Limit,
    target: u64,
    minimum: u64,
    ceiling: Option<u64>,
) -> Result<Option<u64>> {
    if before.soft.is_none() && before.hard.is_none() {
        return Ok(None); // Not applicable (Windows) or unlimited.
    }
    let hard = before.hard.unwrap_or(u64::MAX);
    let usable = hard.min(ceiling.unwrap_or(u64::MAX));
    if usable < minimum {
        return Err(Error::OpenFilesTooLow {
            have: usable,
            need: minimum,
        });
    }
    let want = target.max(minimum).min(usable);
    Ok((before.soft.unwrap_or(u64::MAX) < want).then_some(want))
}

fn unavailable(dir: &Path, kind: io::ErrorKind, reason: &str) -> Error {
    Error::RunDirUnavailable {
        path: dir.to_path_buf(),
        source: io::Error::new(kind, reason.to_owned()),
    }
}

/// Opens and locks the lock file, then checks that the locked file is still
/// the one at the path: a file deleted or replaced between the open and the
/// lock would hold a lock no other copy can see. Bounded retries.
fn lock_file(dir: &Path, lock_path: &Path, pid_path: &Path) -> Result<File> {
    for _ in 0..LOCK_ATTEMPTS {
        let file = open_lock_file(dir, lock_path)?;
        match file.try_lock() {
            Ok(()) => {}
            Err(fs::TryLockError::WouldBlock) => {
                return Err(Error::AlreadyRunning {
                    pid: read_pid(pid_path),
                    lock_file: lock_path.to_path_buf(),
                });
            }
            Err(fs::TryLockError::Error(e)) => {
                return Err(Error::Io {
                    what: "the process guard's lock",
                    source: e,
                });
            }
        }
        if same_file(&file, lock_path) {
            return Ok(file);
        }
    }
    Err(unavailable(
        dir,
        io::ErrorKind::Interrupted,
        "the lock file keeps being replaced while it is locked; find what removes it",
    ))
}

/// How many times [`lock_file`] opens and locks before giving up.
const LOCK_ATTEMPTS: usize = 3;

/// Whether `path` names the open `file`.
fn same_file(file: &File, path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        match (file.metadata(), fs::symlink_metadata(path)) {
            (Ok(a), Ok(b)) => (a.dev(), a.ino()) == (b.dev(), b.ino()),
            _ => false,
        }
    }
    #[cfg(not(unix))]
    {
        // Opened without delete sharing, so the file cannot be deleted or
        // renamed while it is open; the path only has to exist.
        let _ = file;
        fs::symlink_metadata(path).is_ok()
    }
}

/// The default lock directory, from the user alone (D-106).
#[cfg(unix)]
fn default_dir(name: &str) -> Result<PathBuf> {
    let Some(uid) = sys::effective_uid() else {
        return runtime_dir(name);
    };
    let dir = if uid == 0 {
        system_run_dir().join(name)
    } else {
        let home = sys::home_dir(uid).ok_or_else(|| {
            unavailable(
                Path::new(name),
                io::ErrorKind::NotFound,
                &format!(
                    "user {uid} has no home directory in the account database for the default lock;                      pass lock_dir"
                ),
            )
        })?;
        user_run_dir(&home, name)
    };
    create_owner_only(&dir)?;
    Ok(dir)
}

#[cfg(not(unix))]
fn default_dir(name: &str) -> Result<PathBuf> {
    // The known-folder path, which does not follow environment variables.
    runtime_dir(name)
}

/// The system run directory for root.
#[cfg(unix)]
fn system_run_dir() -> &'static Path {
    if cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/run").is_dir() {
        Path::new("/run")
    } else {
        Path::new("/var/run")
    }
}

/// The per-user run directory under `home`.
#[cfg(unix)]
fn user_run_dir(home: &Path, name: &str) -> PathBuf {
    if cfg!(any(target_os = "macos", target_os = "ios")) {
        home.join("Library/Application Support")
            .join(name)
            .join("run")
    } else {
        home.join(".local/state").join(name).join("run")
    }
}

fn runtime_dir(name: &str) -> Result<PathBuf> {
    let app = path_lib::App::new(name)
        .map_err(|e| unavailable(Path::new(name), io::ErrorKind::InvalidInput, &e.to_string()))?;
    let dir = app.dir(path_lib::Kind::Runtime).to_path_buf();
    app.ensure(path_lib::Kind::Runtime).map_err(|e| {
        unavailable(
            &dir,
            io::ErrorKind::Other,
            &format!("it cannot be created: {e}"),
        )
    })?;
    Ok(dir)
}

fn create_owner_only(dir: &Path) -> Result<()> {
    if fs::symlink_metadata(dir).is_ok() {
        return Ok(());
    }
    let mut builder = fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt;
        builder.mode(0o700);
    }
    builder
        .create(dir)
        .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be created: {e}")))
}

/// The lock directory must be a real, owner-only directory (threat T9).
fn check_dir(dir: &Path) -> Result<()> {
    let meta = fs::symlink_metadata(dir)
        .map_err(|e| unavailable(dir, e.kind(), &format!("it cannot be read: {e}")))?;
    if meta.file_type().is_symlink() {
        return Err(unavailable(
            dir,
            io::ErrorKind::InvalidInput,
            "it is a symbolic link; use the real directory",
        ));
    }
    if !meta.is_dir() {
        return Err(unavailable(
            dir,
            io::ErrorKind::InvalidInput,
            "it is not a directory",
        ));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if meta.mode() & 0o022 != 0 {
            return Err(unavailable(
                dir,
                io::ErrorKind::PermissionDenied,
                "other users can write to it and could replace the lock file; chmod 700 it, or use another directory",
            ));
        }
        if sys::effective_uid().is_some_and(|uid| uid != meta.uid()) {
            return Err(unavailable(
                dir,
                io::ErrorKind::PermissionDenied,
                "it belongs to another user; use a directory this user owns",
            ));
        }
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        if meta.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Err(unavailable(
                dir,
                io::ErrorKind::InvalidInput,
                "it is a junction or link; use the real directory",
            ));
        }
    }
    Ok(())
}

/// Opens the lock file without following a link at its path (threat T9).
fn open_lock_file(dir: &Path, path: &Path) -> Result<File> {
    if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
        return Err(unavailable(
            dir,
            io::ErrorKind::InvalidInput,
            "the lock file is a symbolic link; remove it",
        ));
    }
    let mut options = OpenOptions::new();
    options.read(true).write(true).create(true).truncate(false);
    sys::lock_open_options(&mut options);
    let file = options.open(path).map_err(|e| {
        unavailable(
            dir,
            e.kind(),
            &format!("the lock file cannot be opened: {e}"),
        )
    })?;
    let opened = file
        .metadata()
        .map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
    let at_path =
        fs::symlink_metadata(path).map_err(|e| unavailable(dir, e.kind(), &e.to_string()))?;
    if !opened.is_file() || at_path.file_type().is_symlink() {
        return Err(unavailable(
            dir,
            io::ErrorKind::InvalidInput,
            "the lock file is not a regular file; remove it",
        ));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        // The file opened must be the one at the path (no swap in between) and ours.
        if (opened.dev(), opened.ino()) != (at_path.dev(), at_path.ino()) {
            return Err(unavailable(
                dir,
                io::ErrorKind::InvalidInput,
                "the lock file changed while it was opened",
            ));
        }
        if sys::effective_uid().is_some_and(|uid| uid != opened.uid()) {
            return Err(unavailable(
                dir,
                io::ErrorKind::PermissionDenied,
                "the lock file belongs to another user; remove it",
            ));
        }
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        if opened.file_attributes() & sys::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Err(unavailable(
                dir,
                io::ErrorKind::InvalidInput,
                "the lock file is a link; remove it",
            ));
        }
    }
    Ok(file)
}

/// The other copy's pid from its pid file, read strictly (at most 128 bytes).
fn read_pid(path: &Path) -> Option<u32> {
    let mut data = Vec::with_capacity(pid_file::MAX_BYTES + 1);
    File::open(path)
        .ok()?
        .take(pid_file::MAX_BYTES as u64 + 1)
        .read_to_end(&mut data)
        .ok()?;
    pid_file::parse(&data)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn temp_dir(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("sys-lib-guard-{tag}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        dir
    }

    #[test]
    fn test_guard_name_validation() {
        for good in ["site", "my-app", "a.b_c", "x"] {
            assert!(validate_name(good).is_ok(), "{good}");
        }
        for bad in [
            "",
            ".hidden",
            "a/b",
            "a\\b",
            "..",
            "sp ace",
            "naïve",
            &"x".repeat(65),
        ] {
            assert!(
                matches!(validate_name(bad), Err(Error::InvalidInput { .. })),
                "{bad:?}"
            );
        }
    }

    #[test]
    fn test_guard_open_files_plan() {
        let limit = |soft, hard| Limit { soft, hard };
        // Raise to the target, capped at the hard limit.
        assert_eq!(
            plan_open_files(limit(Some(1024), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
            Some(65_536)
        );
        assert_eq!(
            plan_open_files(limit(Some(1024), Some(4096)), 65_536, 1_024, None).unwrap(),
            Some(4096)
        );
        // Already high enough: unchanged.
        assert_eq!(
            plan_open_files(limit(Some(100_000), Some(1_048_576)), 65_536, 1_024, None).unwrap(),
            None
        );
        // E-66: an unlimited hard limit is capped at the platform ceiling.
        assert_eq!(
            plan_open_files(limit(Some(256), None), 65_536, 1_024, Some(24_576)).unwrap(),
            Some(24_576)
        );
        // E-67: a hard limit below the minimum refuses, naming both.
        let e = plan_open_files(limit(Some(256), Some(512)), 65_536, 1_024, None).unwrap_err();
        assert!(matches!(
            e,
            Error::OpenFilesTooLow {
                have: 512,
                need: 1_024
            }
        ));
        // Windows: not applicable.
        assert_eq!(
            plan_open_files(limit(None, None), 65_536, 1_024, None).unwrap(),
            None
        );
    }

    #[test]
    fn test_guard_locks_and_a_second_guard_is_refused() {
        let dir = temp_dir("second");
        let first = Guard::builder("guard-test")
            .lock_dir(&dir)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build()
            .unwrap();
        let lock = first.lock_file().unwrap().to_path_buf();
        assert!(lock.ends_with("guard-test.lock"));
        assert_eq!(
            read_pid(&dir.join("guard-test.pid")),
            Some(std::process::id())
        );
        let second = Guard::builder("guard-test")
            .lock_dir(&dir)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build();
        match second {
            Err(Error::AlreadyRunning { pid, lock_file }) => {
                assert_eq!(pid, Some(std::process::id()));
                assert_eq!(lock_file, lock);
            }
            other => panic!("expected AlreadyRunning, got {other:?}"),
        }
        drop(first);
        // The lock is released; the lock file is never deleted.
        assert!(lock.exists());
        let again = Guard::builder("guard-test")
            .lock_dir(&dir)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build();
        assert!(again.is_ok());
        drop(again);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_guard_is_held_until_the_lock_file_is_replaced() {
        // A lock file deleted while held: the guard notices, and a later copy
        // gets a new lock (Unix); Windows refuses the delete instead.
        let dir = temp_dir("held");
        let g = Guard::builder("held")
            .lock_dir(&dir)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build()
            .unwrap();
        assert!(g.is_held());
        let lock = g.lock_file().unwrap().to_path_buf();
        let removed = fs::remove_file(&lock);
        if cfg!(windows) {
            assert!(removed.is_err(), "a held lock file was deleted");
            assert!(g.is_held());
        } else {
            removed.unwrap();
            assert!(!g.is_held());
            fs::write(&lock, b"").unwrap();
            assert!(!g.is_held(), "a new file at the path is not the locked one");
        }
        drop(g);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_guard_without_lock_is_not_held() {
        let g = Guard::builder("unheld")
            .lock(false)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build()
            .unwrap();
        assert!(!g.is_held());
    }

    #[cfg(unix)]
    #[test]
    fn test_guard_default_dir_ignores_the_environment() {
        // D-106: the default comes from the uid and the account database.
        let uid = sys::effective_uid().unwrap();
        if uid == 0 {
            assert!(system_run_dir().is_dir());
            return;
        }
        let Some(home) = sys::home_dir(uid) else {
            return;
        };
        let dir = user_run_dir(&home, "probe");
        assert!(dir.starts_with(&home));
        assert!(dir.ends_with("probe/run"));
        let dir = user_run_dir(Path::new("/h"), "site");
        if cfg!(target_os = "macos") {
            assert_eq!(dir, Path::new("/h/Library/Application Support/site/run"));
        } else {
            assert_eq!(dir, Path::new("/h/.local/state/site/run"));
        }
    }

    #[test]
    fn test_guard_lock_false_takes_no_lock() {
        let g = Guard::builder("nolock")
            .lock(false)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build()
            .unwrap();
        assert_eq!(g.lock_file(), None);
        assert!(g.report().warnings.contains(&GuardWarning::LockDisabled));
    }

    #[test]
    fn test_guard_refuses_a_file_as_lock_dir() {
        let dir = temp_dir("file");
        fs::create_dir_all(dir.parent().unwrap()).unwrap();
        fs::write(&dir, b"x").unwrap();
        let e = Guard::builder("g")
            .lock_dir(&dir)
            .keep_umask()
            .build()
            .unwrap_err();
        assert!(matches!(e, Error::RunDirUnavailable { .. }), "{e:?}");
        let _ = fs::remove_file(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn test_guard_lock_path_is_symlink_refuses() {
        // E-64, T9: a symlink planted at the lock path.
        let dir = temp_dir("symlink");
        create_owner_only(&dir).unwrap();
        let target = dir.join("elsewhere");
        fs::write(&target, b"").unwrap();
        std::os::unix::fs::symlink(&target, dir.join("g.lock")).unwrap();
        let e = Guard::builder("g")
            .lock_dir(&dir)
            .keep_umask()
            .build()
            .unwrap_err();
        assert!(e.to_string().contains("symbolic link"), "{e}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn test_guard_world_writable_dir_refuses() {
        // E-64, T9: a directory other users can write to.
        use std::os::unix::fs::PermissionsExt;
        let dir = temp_dir("writable");
        create_owner_only(&dir).unwrap();
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o777)).unwrap();
        let e = Guard::builder("g")
            .lock_dir(&dir)
            .keep_umask()
            .build()
            .unwrap_err();
        assert!(e.to_string().contains("other users can write"), "{e}");
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn test_guard_symlinked_dir_refuses() {
        let dir = temp_dir("dirlink");
        let real = temp_dir("dirlink-real");
        create_owner_only(&real).unwrap();
        std::os::unix::fs::symlink(&real, &dir).unwrap();
        let e = Guard::builder("g")
            .lock_dir(&dir)
            .keep_umask()
            .build()
            .unwrap_err();
        assert!(e.to_string().contains("symbolic link"), "{e}");
        let _ = fs::remove_file(&dir);
        let _ = fs::remove_dir_all(&real);
    }

    #[test]
    fn test_guard_stale_pid_file_is_replaced() {
        // E-63: a pid file left by a crashed run while the lock is free.
        let dir = temp_dir("stale");
        create_owner_only(&dir).unwrap();
        fs::write(dir.join("g.pid"), b"999999\n").unwrap();
        let g = Guard::builder("g")
            .lock_dir(&dir)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build()
            .unwrap();
        assert_eq!(read_pid(&dir.join("g.pid")), Some(std::process::id()));
        drop(g);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_guard_report_with_threads_warns() {
        // E-65, T10: the test harness runs tests on threads, so on Unix a warning
        // is expected wherever the platform can count them; never on Windows.
        let g = Guard::builder("threads")
            .lock(false)
            .keep_umask()
            .open_files_target(0)
            .open_files_minimum(0)
            .build()
            .unwrap();
        let warned = g
            .report()
            .warnings
            .iter()
            .any(|w| matches!(w, GuardWarning::ThreadsAlreadyRunning { .. }));
        if cfg!(unix) {
            assert_eq!(warned, sys::thread_count().is_some_and(|n| n > 1));
        } else {
            assert!(!warned);
        }
        if cfg!(unix) {
            assert!(g.report().umask_before.is_some());
            assert_eq!(g.report().umask_before, g.report().umask_after);
        } else {
            assert_eq!(g.report().umask_before, None);
        }
    }
}