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