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