Skip to main content

sys_lib/
host.rs

1//! The machine and its environment.
2//!
3//! ```
4//! use sys_lib as sys;
5//!
6//! println!("running on {}", sys::host::name()?);
7//! # Ok::<(), sys_lib::Error>(())
8//! ```
9
10use core::time::Duration;
11use std::{sync::OnceLock, time::SystemTime};
12
13use crate::{Result, os::keep, parse, sys::HardwareFacts};
14
15/// The host name. A live reading on Unix: DHCP and `hostnamectl` change it
16/// while processes run. On Windows a new name takes effect only at restart, so
17/// it is read once. A name that is not UTF-8 is converted lossily, and one
18/// longer than 255 bytes is truncated (E-95).
19///
20/// The host name is an identifying value: keep it out of output that leaves
21/// the machine unless that is intended.
22///
23/// # Errors
24///
25/// `NotFound` or `PermissionDenied` when a sandbox hides it; `Os` when the
26/// system call fails.
27pub fn name() -> Result<String> {
28    crate::sys::host_name()
29}
30
31/// The time since the machine booted, including time suspended: monotonic.
32///
33/// ```
34/// println!("up {:?}", sys_lib::host::uptime()?);
35/// # Ok::<(), sys_lib::Error>(())
36/// ```
37///
38/// # Errors
39///
40/// `Os` when the clock cannot be read.
41pub fn uptime() -> Result<Duration> {
42    crate::sys::uptime()
43}
44
45/// When the machine booted: stable when the wall clock steps.
46///
47/// # Errors
48///
49/// `NotFound` when the boot time is hidden; `Malformed`; `Os`.
50pub fn boot_time() -> Result<SystemTime> {
51    crate::sys::boot_time()
52}
53
54/// How many processes and threads the machine runs. Totals only: no process
55/// is listed or inspected.
56#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
57#[non_exhaustive]
58pub struct Processes {
59    /// Processes. Inside a container, the container's process namespace.
60    pub total: u64,
61    /// Threads, when reported.
62    pub threads: Option<u64>,
63    /// Runnable right now, when reported (Linux).
64    pub running: Option<u64>,
65}
66
67/// How many processes and threads the machine runs.
68///
69/// ```
70/// let p = sys_lib::host::processes()?;
71/// println!("{} processes, {:?} threads", p.total, p.threads);
72/// # Ok::<(), sys_lib::Error>(())
73/// ```
74///
75/// # Errors
76///
77/// `TooLarge` past 4 million processes (Linux); `NotFound`; `Os`.
78pub fn processes() -> Result<Processes> {
79    crate::sys::processes()
80}
81
82/// How many files are open across the machine.
83#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
84#[non_exhaustive]
85pub struct OpenFiles {
86    /// Open now (Windows: handles).
87    pub open: Option<u64>,
88    /// The system-wide maximum (Windows has none).
89    pub max: Option<u64>,
90}
91
92/// How many files are open across the machine, and the maximum.
93///
94/// # Errors
95///
96/// `NotFound`; `Malformed`; `Os`.
97pub fn open_files() -> Result<OpenFiles> {
98    crate::sys::host_open_files()
99}
100
101/// The time zone: its name and the offset now.
102#[derive(Clone, Debug, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct TimeZone {
105    /// "Europe/London".
106    pub iana: Option<String>,
107    /// "GMT Standard Time".
108    pub windows: Option<String>,
109    /// East of UTC, now, including daylight saving.
110    pub utc_offset_seconds: i32,
111    /// "BST".
112    pub abbreviation: Option<String>,
113}
114
115/// The time zone: the zone **name** and the current offset, not zone arithmetic
116/// (that is a calendar crate's job). `TZ` is used only when it is a valid name;
117/// it is never opened as a path (T4). When `/etc/localtime` is a copy rather
118/// than a link, the name comes from `/etc/timezone` or is `None`: zone files are
119/// not compared to guess (E-92).
120///
121/// The time zone is an identifying value: keep it out of output that leaves
122/// the machine unless that is intended.
123///
124/// ```
125/// let tz = sys_lib::host::timezone()?;
126/// println!("zone {:?}, offset {} s", tz.iana, tz.utc_offset_seconds);
127/// # Ok::<(), sys_lib::Error>(())
128/// ```
129///
130/// # Errors
131///
132/// `Os` when the offset cannot be read.
133pub fn timezone() -> Result<TimeZone> {
134    crate::sys::timezone()
135}
136
137/// The user's locale.
138#[derive(Clone, Copy, PartialEq, Eq, Debug)]
139#[non_exhaustive]
140pub struct Locale {
141    /// The BCP 47 tag: "en-US".
142    pub tag: &'static str,
143    /// As the system spells it: "en_US.UTF-8".
144    pub raw: &'static str,
145}
146
147/// The locale, from the environment at the first call. `None` for `C`,
148/// `POSIX`, and `C.UTF-8`, which express no preference (E-94).
149#[must_use]
150pub fn locale() -> Option<&'static Locale> {
151    static FACT: OnceLock<Option<Locale>> = OnceLock::new();
152    FACT.get_or_init(|| {
153        let (tag, raw) = crate::sys::locale()?;
154        Some(Locale {
155            tag: keep(tag),
156            raw: keep(raw),
157        })
158    })
159    .as_ref()
160}
161
162/// `LC_ALL`, `LC_MESSAGES`, then `LANG`: the first that is set decides, as
163/// POSIX has it. For the Unix backends.
164#[allow(dead_code)] // unused on Windows and targets without a backend
165pub(crate) fn posix_locale() -> Option<(String, String)> {
166    let raw = ["LC_ALL", "LC_MESSAGES", "LANG"]
167        .iter()
168        .find_map(|k| std::env::var(k).ok().filter(|v| !v.is_empty()))?;
169    let tag = parse::locale::tag(&raw)?;
170    Some((tag, raw))
171}
172
173/// The hardware model.
174#[derive(Clone, Copy, PartialEq, Eq, Debug)]
175#[non_exhaustive]
176pub struct Model {
177    /// The maker.
178    pub vendor: Option<&'static str>,
179    /// "ThinkPad X1 Carbon Gen 11", "Raspberry Pi 5", "Mac14,9".
180    pub name: &'static str,
181    /// The family.
182    pub family: Option<&'static str>,
183}
184
185/// What kind of firmware the machine boots.
186#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
187#[non_exhaustive]
188pub enum FirmwareKind {
189    /// UEFI.
190    Uefi,
191    /// Legacy BIOS.
192    Bios,
193    /// Not known.
194    Unknown,
195}
196
197/// The machine's firmware. Inside a VM this describes the virtual firmware,
198/// which is correct for the process.
199#[derive(Clone, Copy, PartialEq, Eq, Debug)]
200#[non_exhaustive]
201pub struct Firmware {
202    /// What kind it is.
203    pub kind: FirmwareKind,
204    /// "American Megatrends International, LLC.", "Apple Inc."
205    pub vendor: Option<&'static str>,
206    /// "1.40", "11881.41.5".
207    pub version: Option<&'static str>,
208    /// "2025-03-14".
209    pub date: Option<&'static str>,
210}
211
212/// The main board. Serial numbers are never part of this answer.
213#[derive(Clone, Copy, PartialEq, Eq, Debug)]
214#[non_exhaustive]
215pub struct Board {
216    /// The maker.
217    pub vendor: Option<&'static str>,
218    /// The product name.
219    pub name: Option<&'static str>,
220    /// The version.
221    pub version: Option<&'static str>,
222}
223
224struct Hardware {
225    model: Option<Model>,
226    firmware: Option<Firmware>,
227    board: Option<Board>,
228}
229
230fn hardware() -> &'static Hardware {
231    static FACTS: OnceLock<Hardware> = OnceLock::new();
232    FACTS.get_or_init(|| keep_hardware(crate::sys::hardware()))
233}
234
235fn keep_hardware(f: HardwareFacts) -> Hardware {
236    let opt = |s: Option<String>| s.map(keep);
237    let model = f.model_name.map(|name| Model {
238        vendor: opt(f.model_vendor),
239        name: keep(name),
240        family: opt(f.model_family),
241    });
242    let known = f.firmware_kind.is_some()
243        || f.firmware_vendor.is_some()
244        || f.firmware_version.is_some()
245        || f.firmware_date.is_some();
246    let firmware = known.then(|| Firmware {
247        kind: f.firmware_kind.unwrap_or(FirmwareKind::Unknown),
248        vendor: opt(f.firmware_vendor),
249        version: opt(f.firmware_version),
250        date: opt(f.firmware_date),
251    });
252    let board = (f.board_vendor.is_some() || f.board_name.is_some() || f.board_version.is_some())
253        .then(|| Board {
254            vendor: opt(f.board_vendor),
255            name: opt(f.board_name),
256            version: opt(f.board_version),
257        });
258    Hardware {
259        model,
260        firmware,
261        board,
262    }
263}
264
265/// The hardware model, from DMI, SMBIOS, the device tree, or `hw.model` on
266/// macOS ("Mac14,9"; no marketing-name table is shipped). Cached.
267#[must_use]
268pub fn model() -> Option<&'static Model> {
269    hardware().model.as_ref()
270}
271
272/// The firmware. Placeholder strings are `None`. Cached.
273#[must_use]
274pub fn firmware() -> Option<&'static Firmware> {
275    hardware().firmware.as_ref()
276}
277
278/// The main board. Placeholder strings are `None`. Cached.
279#[must_use]
280pub fn board() -> Option<&'static Board> {
281    hardware().board.as_ref()
282}
283
284/// Whether the system clock is kept in sync.
285#[derive(Clone, Copy, PartialEq, Eq, Debug)]
286#[non_exhaustive]
287pub struct ClockSync {
288    /// The kernel believes the clock is disciplined.
289    pub synchronized: bool,
290    /// The kernel's error bound.
291    pub max_error: Option<Duration>,
292    /// The kernel's estimate.
293    pub estimated_error: Option<Duration>,
294}
295
296/// Whether the system clock is kept in sync (NTP, chrony, PTP), which leases,
297/// distributed locks, and hybrid logical clocks depend on. `None` where the OS
298/// has no unprivileged answer. Reading time itself stays in clock-lib.
299///
300/// ```
301/// if let Some(c) = sys_lib::host::clock_sync()? {
302///     println!("synchronized: {}", c.synchronized);
303/// }
304/// # Ok::<(), sys_lib::Error>(())
305/// ```
306///
307/// # Errors
308///
309/// `Os` when the call fails.
310pub fn clock_sync() -> Result<Option<ClockSync>> {
311    crate::sys::clock_sync()
312}
313
314/// A login session.
315#[derive(Clone, Debug, PartialEq, Eq)]
316#[non_exhaustive]
317pub struct Session {
318    /// The user.
319    pub user: String,
320    /// The terminal.
321    pub terminal: Option<String>,
322    /// Whether it is remote. The remote address is not returned.
323    pub remote: bool,
324    /// When it started.
325    pub since: Option<SystemTime>,
326}
327
328/// Who is logged in. User names are personal data: keep them out of output that
329/// leaves the machine.
330///
331/// # Errors
332///
333/// `Unsupported` where the OS has no session list; `Os` when the call fails.
334pub fn sessions() -> Result<Vec<Session>> {
335    crate::sys::sessions()
336}
337
338#[cfg(test)]
339mod tests {
340    #[test]
341    fn test_host_counts_and_clocks_live() {
342        let up = super::uptime().unwrap();
343        assert!(up.as_secs() > 0);
344        let boot = super::boot_time().unwrap();
345        assert!(boot < std::time::SystemTime::now());
346        let p = super::processes().unwrap();
347        assert!(p.total >= 1);
348        if let Some(t) = p.threads {
349            assert!(t >= p.total);
350        }
351        let f = super::open_files().unwrap();
352        if let (Some(open), Some(max)) = (f.open, f.max) {
353            assert!(open <= max);
354        }
355    }
356
357    #[test]
358    fn test_host_name_is_not_empty() {
359        let name = super::name().unwrap();
360        assert!(!name.is_empty() && name.len() <= 255);
361    }
362}