sys-lib 0.4.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, zero third-party dependencies.
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
//! Windows: kernel32, advapi32, iphlpapi, powrprof, and ntdll, called directly.

mod cpu;
mod disk;
mod ffi;
mod host;
mod mem;
mod net;
mod process;

pub(crate) use cpu::*;
pub(crate) use disk::*;
#[cfg(feature = "guard")]
pub(crate) use ffi::FILE_ATTRIBUTE_REPARSE_POINT;
pub(crate) use host::*;
pub(crate) use mem::*;
pub(crate) use net::*;
pub(crate) use process::*;
use std::{
    ffi::c_void,
    mem::{MaybeUninit, size_of},
    time::{Duration, SystemTime},
};
#[cfg(feature = "guard")]
use std::{fs::OpenOptions, path::Path};

use crate::{Error, Result, os::Source, process::User, sys::OsFacts};
#[cfg(feature = "guard")]
use crate::{process::Limit, sys::FsKind};

/// A UTF-16, NUL-terminated copy of `s`.
fn wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

/// `buf` up to its first NUL, as a lossy string.
fn from_wide(buf: &[u16]) -> String {
    let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
    String::from_utf16_lossy(&buf[..end])
}

fn last_error() -> i32 {
    std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
}

/// `Os` for a failed call, with the thread's last error.
fn os_error(what: &'static str, call: &'static str) -> Error {
    Error::Os {
        what,
        call,
        code: last_error(),
    }
}

/// `Unsupported` on this platform.
fn unsupported(what: &'static str) -> Error {
    Error::Unsupported {
        what,
        platform: crate::os::kind().name(),
    }
}

/// A count of 100 ns intervals (`FILETIME`, `LARGE_INTEGER` times) as a
/// `Duration`, without overflow.
fn hundred_ns(n: u64) -> Duration {
    Duration::new(n / 10_000_000, (n % 10_000_000) as u32 * 100)
}

/// A signed OS counter that is never negative in practice; a negative one
/// reads as zero.
fn non_negative(n: i64) -> u64 {
    u64::try_from(n).unwrap_or(0)
}

/// 100 ns intervals from 1601-01-01 to 1970-01-01.
const UNIX_EPOCH_FILETIME: u64 = 116_444_736_000_000_000;

/// A `FILETIME` value (100 ns since 1601) as a `SystemTime`.
fn filetime_to_system(ft: u64) -> Option<SystemTime> {
    if ft >= UNIX_EPOCH_FILETIME {
        SystemTime::UNIX_EPOCH.checked_add(hundred_ns(ft - UNIX_EPOCH_FILETIME))
    } else {
        SystemTime::UNIX_EPOCH.checked_sub(hundred_ns(UNIX_EPOCH_FILETIME - ft))
    }
}

/// An open registry key, closed on drop.
struct Key(ffi::Hkey);

impl Key {
    /// Opens `HKLM\<path>` for reading, in the 64-bit view (E-74).
    fn local_machine(path: &str) -> Option<Key> {
        let path = wide(path);
        let mut key: ffi::Hkey = std::ptr::null_mut();
        // SAFETY: `path` is NUL-terminated and `key` is a writable handle slot.
        let rc = unsafe {
            ffi::RegOpenKeyExW(
                ffi::HKEY_LOCAL_MACHINE,
                path.as_ptr(),
                0,
                ffi::KEY_QUERY_VALUE | ffi::KEY_WOW64_64KEY,
                &raw mut key,
            )
        };
        (rc == 0).then_some(Key(key))
    }

    /// A `REG_SZ` value, at most 1 KiB of UTF-16.
    fn string(&self, name: &str) -> Option<String> {
        let name = wide(name);
        let mut buf = [0u16; 512];
        let mut kind = 0u32;
        let mut len = (buf.len() * 2) as u32;
        // SAFETY: `name` is NUL-terminated; `buf` is `len` writable bytes.
        let rc = unsafe {
            ffi::RegQueryValueExW(
                self.0,
                name.as_ptr(),
                std::ptr::null_mut(),
                &raw mut kind,
                buf.as_mut_ptr().cast::<u8>(),
                &raw mut len,
            )
        };
        if rc != 0 || kind != ffi::REG_SZ {
            return None;
        }
        let units = (len as usize / 2).min(buf.len());
        let text = from_wide(&buf[..units]).trim().to_owned();
        (!text.is_empty()).then_some(text)
    }

    /// A `REG_DWORD` value.
    fn dword(&self, name: &str) -> Option<u32> {
        let name = wide(name);
        let mut value = 0u32;
        let mut kind = 0u32;
        let mut len = 4u32;
        // SAFETY: `name` is NUL-terminated; `value` is 4 writable bytes.
        let rc = unsafe {
            ffi::RegQueryValueExW(
                self.0,
                name.as_ptr(),
                std::ptr::null_mut(),
                &raw mut kind,
                (&raw mut value).cast::<u8>(),
                &raw mut len,
            )
        };
        (rc == 0 && kind == ffi::REG_DWORD && len == 4).then_some(value)
    }
}

impl Drop for Key {
    fn drop(&mut self) {
        // SAFETY: the key was opened by RegOpenKeyExW and is closed once.
        unsafe { ffi::RegCloseKey(self.0) };
    }
}

/// A handle closed on drop.
struct Owned(ffi::Handle);

impl Drop for Owned {
    fn drop(&mut self) {
        // SAFETY: the handle is valid and owned here; it is closed once.
        unsafe { ffi::CloseHandle(self.0) };
    }
}

/// Critical-error dialogs ("insert a disk in drive E:") are off for this
/// thread while a value lives, and the previous mode comes back on drop
/// (threat T8). Every volume call runs under one.
struct NoDialogs(Option<u32>);

impl NoDialogs {
    fn new() -> NoDialogs {
        let mut previous = 0u32;
        // SAFETY: `previous` is a writable local.
        let ok = unsafe { ffi::SetThreadErrorMode(ffi::SEM_FAILCRITICALERRORS, &raw mut previous) };
        NoDialogs((ok != 0).then_some(previous))
    }
}

impl Drop for NoDialogs {
    fn drop(&mut self) {
        if let Some(previous) = self.0 {
            // SAFETY: restores the mode saved by `new`; the old-mode output is
            // optional.
            unsafe { ffi::SetThreadErrorMode(previous, std::ptr::null_mut()) };
        }
    }
}

/// `GlobalMemoryStatusEx`.
fn memory_status() -> Result<ffi::MemoryStatusEx> {
    let mut status = ffi::MemoryStatusEx {
        length: size_of::<ffi::MemoryStatusEx>() as u32,
        ..ffi::MemoryStatusEx::default()
    };
    // SAFETY: `status` is a MEMORYSTATUSEX with its length set.
    let ok = unsafe { ffi::GlobalMemoryStatusEx(&raw mut status) };
    if ok == 0 {
        return Err(os_error("memory", "GlobalMemoryStatusEx"));
    }
    Ok(status)
}

/// `GetPerformanceInfo`: system-wide commit, cache, and object counts. It
/// counts handles across every process, so only the readings that need those
/// values call it.
fn performance_info(what: &'static str) -> Result<ffi::PerformanceInformation> {
    let mut info = ffi::PerformanceInformation::default();
    let size = size_of::<ffi::PerformanceInformation>() as u32;
    info.cb = size;
    // SAFETY: `info` is a PERFORMANCE_INFORMATION of the size passed.
    let ok = unsafe { ffi::K32GetPerformanceInfo(&raw mut info, size) };
    if ok == 0 {
        return Err(os_error(what, "GetPerformanceInfo"));
    }
    Ok(info)
}

/// The limits of the job object this process is in, or `None` outside a job.
/// A nested job reports its own limits: the query answers for the immediate
/// job, not the effective minimum over the enclosing ones.
fn job_limits() -> Option<ffi::JobObjectExtendedLimitInformation> {
    let mut info = ffi::JobObjectExtendedLimitInformation::default();
    // SAFETY: a null job means the job of this process; `info` is the buffer
    // for the extended-limit class, of the size passed.
    let ok = unsafe {
        ffi::QueryInformationJobObject(
            std::ptr::null_mut(),
            ffi::JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
            (&raw mut info).cast::<c_void>(),
            size_of::<ffi::JobObjectExtendedLimitInformation>() as u32,
            std::ptr::null_mut(),
        )
    };
    (ok != 0).then_some(info)
}

pub(crate) fn os() -> OsFacts {
    let info = MaybeUninit::<ffi::OsVersionInfoExW>::zeroed();
    // SAFETY: `info` is zeroed, so every field is valid before the call.
    let mut info = unsafe { info.assume_init() };
    info.os_version_info_size = size_of::<ffi::OsVersionInfoExW>() as u32;
    // SAFETY: `info` is a valid OSVERSIONINFOEXW with its size set.
    let status = unsafe { ffi::RtlGetVersion(&raw mut info) };
    let (major, minor, build, product) = if status >= 0 {
        (
            info.major_version,
            info.minor_version,
            info.build_number,
            info.product_type,
        )
    } else {
        (0, 0, 0, 0)
    };
    let key = Key::local_machine(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
    let ubr = key.as_ref().and_then(|k| k.dword("UBR"));
    let product_name = key.as_ref().and_then(|k| k.string("ProductName"));
    let version = (major > 0).then(|| match ubr {
        Some(u) => format!("{major}.{minor}.{build}.{u}"),
        None => format!("{major}.{minor}.{build}"),
    });
    OsFacts {
        name: windows_name(major, minor, build, product, product_name.as_deref()),
        kernel: version.clone().unwrap_or_default(),
        version,
        distro: "Windows".to_owned(),
        distro_id: "windows".to_owned(),
        release: None,
        name_source: Source::Registry,
    }
}

/// "Windows 11 Pro", "Windows Server 2022 Datacenter". The registry's
/// `ProductName` still says "Windows 10" on Windows 11 (E-49), so the build
/// number decides the product; the edition comes from `ProductName`.
fn windows_name(
    major: u32,
    minor: u32,
    build: u32,
    product: u8,
    product_name: Option<&str>,
) -> String {
    let workstation = product == ffi::VER_NT_WORKSTATION || product == 0;
    match product_name {
        Some(n) if workstation && major == 10 && build >= 22_000 => {
            n.replacen("Windows 10", "Windows 11", 1)
        }
        Some(n) => n.to_owned(),
        None if !workstation => match build {
            14_393 => "Windows Server 2016".to_owned(),
            17_763 => "Windows Server 2019".to_owned(),
            20_348 => "Windows Server 2022".to_owned(),
            26_100 => "Windows Server 2025".to_owned(),
            _ => "Windows Server".to_owned(),
        },
        None => match (major, minor) {
            (10, _) if build >= 22_000 => "Windows 11".to_owned(),
            (10, _) => "Windows 10".to_owned(),
            (6, 3) => "Windows 8.1".to_owned(),
            (6, 2) => "Windows 8".to_owned(),
            (6, 1) => "Windows 7".to_owned(),
            _ => "Windows".to_owned(),
        },
    }
}

pub(crate) fn host_name() -> Result<String> {
    let mut len = 0u32;
    // SAFETY: a null buffer with size 0 asks for the size needed.
    unsafe {
        ffi::GetComputerNameExW(
            ffi::COMPUTER_NAME_DNS_HOSTNAME,
            std::ptr::null_mut(),
            &raw mut len,
        )
    };
    let mut buf = vec![0u16; (len as usize).clamp(1, 1024)];
    let mut size = buf.len() as u32;
    // SAFETY: `buf` has `size` writable UTF-16 units.
    let ok = unsafe {
        ffi::GetComputerNameExW(
            ffi::COMPUTER_NAME_DNS_HOSTNAME,
            buf.as_mut_ptr(),
            &raw mut size,
        )
    };
    if ok == 0 {
        return Err(os_error("host name", "GetComputerNameExW"));
    }
    let name = from_wide(&buf[..(size as usize).min(buf.len())]);
    Ok(crate::parse::lossy(name.as_bytes(), 255))
}

pub(crate) fn user() -> Result<User> {
    let mut buf = [0u16; 257];
    let mut size = buf.len() as u32;
    // SAFETY: `buf` has `size` writable UTF-16 units (UNLEN + 1).
    let ok = unsafe { ffi::GetUserNameW(buf.as_mut_ptr(), &raw mut size) };
    if ok == 0 {
        return Err(os_error("user name", "GetUserNameW"));
    }
    Ok(User {
        name: from_wide(&buf),
        id: None,
        is_admin: is_elevated()?,
    })
}

pub(crate) fn is_elevated() -> Result<bool> {
    let mut token: ffi::Handle = std::ptr::null_mut();
    // SAFETY: the pseudo-handle of this process is always valid; `token` is writable.
    let ok = unsafe {
        ffi::OpenProcessToken(ffi::GetCurrentProcess(), ffi::TOKEN_QUERY, &raw mut token)
    };
    if ok == 0 {
        return Err(os_error("elevation", "OpenProcessToken"));
    }
    let token = Owned(token);
    let mut elevation = ffi::TokenElevation {
        token_is_elevated: 0,
    };
    let mut returned = 0u32;
    // SAFETY: `elevation` is the TOKEN_ELEVATION buffer of the size passed.
    let ok = unsafe {
        ffi::GetTokenInformation(
            token.0,
            ffi::TOKEN_ELEVATION_CLASS,
            (&raw mut elevation).cast::<c_void>(),
            size_of::<ffi::TokenElevation>() as u32,
            &raw mut returned,
        )
    };
    if ok == 0 {
        return Err(os_error("elevation", "GetTokenInformation"));
    }
    Ok(elevation.token_is_elevated != 0)
}

// ---------------------------------------------------------------------------
// The process guard's needs
// ---------------------------------------------------------------------------

/// Windows has no umask.
#[cfg(feature = "guard")]
pub(crate) fn swap_umask(_mask: u32) -> Option<u32> {
    None
}

/// Not applicable: no per-process descriptor count limits sockets or files.
#[cfg(feature = "guard")]
pub(crate) fn open_files_limit() -> Result<Limit> {
    Ok(Limit::default())
}

#[cfg(feature = "guard")]
pub(crate) fn set_open_files_soft(_n: u64) -> Result<()> {
    Ok(())
}

#[cfg(feature = "guard")]
pub(crate) fn open_files_ceiling() -> Option<u64> {
    None
}

#[cfg(feature = "guard")]
pub(crate) fn lock_open_options(options: &mut OpenOptions) {
    use std::os::windows::fs::OpenOptionsExt;
    options.custom_flags(ffi::FILE_FLAG_OPEN_REPARSE_POINT);
}

#[cfg(feature = "guard")]
pub(crate) fn filesystem(path: &Path) -> Option<FsKind> {
    use std::os::windows::ffi::OsStrExt;
    let path: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let _quiet = NoDialogs::new();
    let mut root = [0u16; 1024];
    // SAFETY: `path` is NUL-terminated; `root` has its length in units.
    let ok =
        unsafe { ffi::GetVolumePathNameW(path.as_ptr(), root.as_mut_ptr(), root.len() as u32) };
    if ok == 0 {
        return None;
    }
    // SAFETY: `root` is the NUL-terminated volume path just written.
    let network = unsafe { ffi::GetDriveTypeW(root.as_ptr()) } == ffi::DRIVE_REMOTE;
    let mut fs_name = [0u16; 64];
    // SAFETY: `root` is NUL-terminated; only the file-system-name buffer is
    // requested, with its length in units.
    let ok = unsafe {
        ffi::GetVolumeInformationW(
            root.as_ptr(),
            std::ptr::null_mut(),
            0,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            fs_name.as_mut_ptr(),
            fs_name.len() as u32,
        )
    };
    let name = if ok == 0 {
        "other"
    } else {
        match from_wide(&fs_name).as_str() {
            "NTFS" => "NTFS",
            "ReFS" => "ReFS",
            "FAT32" => "FAT32",
            "FAT" => "FAT",
            "exFAT" => "exFAT",
            "CSVFS" => "CSVFS",
            _ => "other",
        }
    };
    Some(FsKind { name, network })
}

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

    #[test]
    fn test_sys_windows_names_from_build_and_registry() {
        assert_eq!(
            windows_name(10, 0, 26_200, 1, Some("Windows 10 Pro")),
            "Windows 11 Pro"
        );
        assert_eq!(
            windows_name(10, 0, 19_045, 1, Some("Windows 10 Pro")),
            "Windows 10 Pro"
        );
        assert_eq!(
            windows_name(10, 0, 20_348, 3, Some("Windows Server 2022 Datacenter")),
            "Windows Server 2022 Datacenter"
        );
        assert_eq!(windows_name(10, 0, 17_763, 3, None), "Windows Server 2019");
        assert_eq!(windows_name(10, 0, 22_631, 1, None), "Windows 11");
        assert_eq!(windows_name(6, 1, 7601, 1, None), "Windows 7");
        assert_eq!(windows_name(0, 0, 0, 0, None), "Windows");
    }

    #[test]
    fn test_sys_windows_time_conversions_exact() {
        assert_eq!(hundred_ns(0), Duration::ZERO);
        assert_eq!(hundred_ns(15), Duration::from_nanos(1_500));
        assert_eq!(hundred_ns(10_000_000), Duration::from_secs(1));
        assert_eq!(
            hundred_ns(u64::MAX),
            Duration::new(u64::MAX / 10_000_000, 955_161_500)
        );
        assert_eq!(non_negative(-1), 0);
        assert_eq!(non_negative(7), 7);
        assert_eq!(
            filetime_to_system(UNIX_EPOCH_FILETIME),
            Some(SystemTime::UNIX_EPOCH)
        );
        assert_eq!(
            filetime_to_system(UNIX_EPOCH_FILETIME + 10_000_000),
            Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1))
        );
        assert!(filetime_to_system(0).is_some_and(|t| t < SystemTime::UNIX_EPOCH));
    }

    #[test]
    fn test_sys_windows_live_identity() {
        assert!(os().version.is_some());
        assert!(!host_name().unwrap().is_empty());
        assert!(memory_status().unwrap().total_phys > 0);
    }
}