Skip to main content

sys_lib/process/
mod.rs

1//! This process: its id, the user it runs as, whether it is elevated, and the
2//! process guard every long-running service starts with.
3//!
4//! sys-lib does not list or inspect other processes.
5//!
6//! ```
7//! use sys_lib as sys;
8//!
9//! println!("pid {} as {}", sys::process::id(), sys::process::user()?.name);
10//! if sys::process::is_elevated()? {
11//!     println!("running as root or an elevated Administrator");
12//! }
13//! # Ok::<(), sys_lib::Error>(())
14//! ```
15
16#[cfg(feature = "guard")]
17mod guard;
18mod launch;
19mod usage;
20
21pub(crate) use launch::LaunchFacts;
22pub use launch::{Launch, Launcher, is_interactive, is_service, launch};
23pub use usage::{
24    CpuSampler, CpuTime, InfoOptions, Limits, ProcessInfo, ProcessIo, ProcessMemory, ProcessUsage,
25    cpu_time, info, info_with, io, limits, memory, memory_detail, open_files, parent_id,
26    peak_memory, started_at, threads,
27};
28
29#[cfg(feature = "guard")]
30#[cfg_attr(docsrs, doc(cfg(feature = "guard")))]
31pub use guard::{Guard, GuardBuilder, GuardReport, GuardWarning, guard};
32
33use crate::Result;
34
35/// This process's id.
36#[must_use]
37pub fn id() -> u32 {
38    std::process::id()
39}
40
41/// A user account.
42#[derive(Clone, Debug, PartialEq, Eq)]
43#[non_exhaustive]
44pub struct User {
45    /// The account name.
46    pub name: String,
47    /// The numeric user id (Unix); `None` on Windows, where accounts are SIDs.
48    pub id: Option<u32>,
49    /// Root, or an Administrator with an elevated token.
50    pub is_admin: bool,
51}
52
53/// The effective user this process runs as now.
54///
55/// On Linux and macOS the name comes from the system's user database (NSS),
56/// which can read `/etc/passwd` or, with directory-service users, wait on the
57/// network: keep it off hot paths. A user id without an entry gives its number
58/// as the name.
59///
60/// # Errors
61///
62/// `Os` when the user cannot be looked up.
63pub fn user() -> Result<User> {
64    crate::sys::user()
65}
66
67/// Whether this process runs as root, or with an elevated Administrator token.
68///
69/// This is a check, not a control: privilege drops belong to shield-sec, which
70/// calls this afterwards to verify.
71///
72/// ```
73/// if sys_lib::process::is_elevated()? {
74///     // refuse to serve requests until privileges are dropped
75/// }
76/// # Ok::<(), sys_lib::Error>(())
77/// ```
78///
79/// # Errors
80///
81/// `Os` when the token cannot be queried (Windows).
82pub fn is_elevated() -> Result<bool> {
83    crate::sys::is_elevated()
84}
85
86/// A resource limit: soft and hard values, `None` meaning unlimited or not
87/// applicable.
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
89#[non_exhaustive]
90pub struct Limit {
91    /// The limit in force.
92    pub soft: Option<u64>,
93    /// The ceiling the soft limit may be raised to without privileges.
94    pub hard: Option<u64>,
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn test_process_id_matches_std() {
103        assert_eq!(id(), std::process::id());
104    }
105
106    #[test]
107    fn test_process_user_has_a_name() {
108        let u = user().unwrap();
109        assert!(!u.name.is_empty());
110        assert_eq!(u.is_admin, is_elevated().unwrap());
111        if cfg!(unix) {
112            assert!(u.id.is_some());
113        }
114    }
115}