ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//! OS and kernel information — kernel version, hostname, boot time, loaded modules.
//!
//! # Platform Support
//!
//! - **Linux**: Reads `/proc/version`, `/proc/uptime`, `/proc/modules`, `/proc/cmdline`, `uname`
//! - **Windows**: Uses WMI (`Win32_OperatingSystem`), `ver`, registry
//! - **macOS**: Uses `sw_vers`, `uname`, `sysctl`
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::os_info::OsInfoMonitor;
//!
//! let monitor = OsInfoMonitor::new().unwrap();
//! let info = monitor.info();
//! println!("OS: {} {} ({})", info.os_name, info.os_version, info.architecture);
//! println!("Kernel: {}", info.kernel_version);
//! println!("Hostname: {}", info.hostname);
//! match info.uptime_seconds {
//!     Some(s) => println!("Uptime: {s} seconds"),
//!     None => println!("Uptime: not read"),
//! }
//! println!("Loaded modules: {}", info.loaded_modules.len());
//! ```

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// Operating system family
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum OsFamily {
    Linux,
    Windows,
    MacOS,
    FreeBSD,
    Unknown,
}

/// Boot mode. `Unknown` is used when the firmware type was not read.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BootMode {
    UEFI,
    BIOS,
    Unknown,
}

/// Loaded kernel module / driver
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelModule {
    /// Module name
    pub name: String,
    /// Module size in bytes; `None` when the source does not report it
    pub size_bytes: Option<u64>,
    /// Number of instances (use count); `None` when the source does not report it
    pub instances: Option<u32>,
    /// Modules that depend on this one
    pub used_by: Vec<String>,
    /// Module state (e.g., "Live")
    pub state: String,
}

/// Comprehensive OS and kernel information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsInfo {
    /// OS family (Linux, Windows, macOS)
    pub os_family: OsFamily,
    /// OS name (e.g., "Ubuntu", "Windows 11", "macOS Sequoia")
    pub os_name: String,
    /// OS version string
    pub os_version: String,
    /// OS build number. Empty when the platform did not report one.
    pub os_build: String,
    /// Kernel version string (e.g., "6.8.0-51-generic")
    pub kernel_version: String,
    /// Full kernel version line
    pub kernel_full: String,
    /// CPU architecture (e.g., "x86_64", "aarch64")
    pub architecture: String,
    /// Hostname
    pub hostname: String,
    /// Domain name (if configured)
    pub domain: String,
    /// System uptime in seconds; `None` when the platform source could not be read
    pub uptime_seconds: Option<u64>,
    /// Boot time as Unix timestamp; `None` whenever `uptime_seconds` is `None`,
    /// because it is derived from the same source
    pub boot_timestamp: Option<u64>,
    /// Boot mode (UEFI or BIOS). `Unknown` when the platform did not report it.
    pub boot_mode: BootMode,
    /// Kernel command line (Linux)
    pub kernel_cmdline: String,
    /// Number of logged-in users; `None` when the count was not read (for
    /// example a failed `who` on Linux, or any platform without a reader).
    /// A real zero is `Some(0)`.
    pub user_count: Option<u32>,
    /// Loaded kernel modules
    pub loaded_modules: Vec<KernelModule>,
    /// Timezone string (e.g., "America/New_York")
    pub timezone: String,
    /// System locale
    pub locale: String,
    /// Whether this is a 64-bit OS
    pub is_64bit: bool,
    /// Whether Secure Boot is enabled. `None` when the state could not be read
    /// (no `mokutil` on Linux, an unreadable firmware variable on Windows, or
    /// no firmware query on macOS). It is never defaulted to `false`.
    pub secure_boot: Option<bool>,
}

/// Parse the output of `mokutil --sb-state`. Only the two explicit states are
/// readings; any other output is `None`.
#[cfg(any(target_os = "linux", test))]
fn parse_mokutil_sb_state(text: &str) -> Option<bool> {
    if text.contains("SecureBoot enabled") {
        Some(true)
    } else if text.contains("SecureBoot disabled") {
        Some(false)
    } else {
        None
    }
}

/// Parse the first field of `/proc/uptime` (seconds since boot, as a decimal).
#[cfg(any(target_os = "linux", test))]
fn parse_proc_uptime(text: &str) -> Option<u64> {
    let secs: f64 = text.split_whitespace().next()?.parse().ok()?;
    Some(secs as u64)
}

/// Parse the `btime` line of `/proc/stat` (boot time as a Unix timestamp).
#[cfg(any(target_os = "linux", test))]
fn parse_btime(text: &str) -> Option<u64> {
    text.lines()
        .find_map(|line| line.strip_prefix("btime "))
        .and_then(|rest| rest.trim().parse().ok())
}

/// Count the sessions in `who` output, one per line.
#[cfg(any(target_os = "linux", test))]
fn parse_who_count(text: &str) -> u32 {
    text.lines().count() as u32
}

/// Monitor for OS and kernel information
pub struct OsInfoMonitor {
    info: OsInfo,
}

impl OsInfoMonitor {
    /// Create a new OsInfoMonitor and gather system information.
    pub fn new() -> Result<Self, IronError> {
        let mut monitor = Self {
            info: OsInfo {
                os_family: OsFamily::Unknown,
                os_name: String::new(),
                os_version: String::new(),
                os_build: String::new(),
                kernel_version: String::new(),
                kernel_full: String::new(),
                architecture: String::new(),
                hostname: String::new(),
                domain: String::new(),
                uptime_seconds: None,
                boot_timestamp: None,
                boot_mode: BootMode::Unknown,
                kernel_cmdline: String::new(),
                user_count: None,
                loaded_modules: Vec::new(),
                timezone: String::new(),
                locale: String::new(),
                is_64bit: cfg!(target_pointer_width = "64"),
                // Unread until a platform reader sets it. Defaulting to `false`
                // reported Secure Boot as off on any run where the read failed.
                secure_boot: None,
            },
        };
        monitor.refresh()?;
        Ok(monitor)
    }

    /// Refresh information.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.info.loaded_modules.clear();

        #[cfg(target_os = "linux")]
        self.refresh_linux()?;

        #[cfg(target_os = "windows")]
        self.refresh_windows()?;

        #[cfg(target_os = "macos")]
        self.refresh_macos()?;

        // Common: hostname from std
        if self.info.hostname.is_empty() {
            if let Ok(output) = std::process::Command::new("hostname").output() {
                self.info.hostname = String::from_utf8(output.stdout)
                    .unwrap_or_default()
                    .trim()
                    .to_string();
            }
        }

        Ok(())
    }

    /// Get the gathered OS information.
    pub fn info(&self) -> &OsInfo {
        &self.info
    }

    /// Get loaded kernel modules.
    pub fn modules(&self) -> &[KernelModule] {
        &self.info.loaded_modules
    }

    /// Get the number of loaded modules.
    pub fn module_count(&self) -> usize {
        self.info.loaded_modules.len()
    }

    /// Find a specific module by name.
    pub fn find_module(&self, name: &str) -> Option<&KernelModule> {
        self.info.loaded_modules.iter().find(|m| m.name == name)
    }

    // ── Linux ──

    #[cfg(target_os = "linux")]
    fn refresh_linux(&mut self) -> Result<(), IronError> {
        self.info.os_family = OsFamily::Linux;

        // /etc/os-release. A distribution without one is unusual but legal, so
        // its absence leaves the name empty rather than failing; a file that
        // will not open is a failure.
        let os_release = match std::fs::read_to_string("/etc/os-release") {
            Ok(c) => Some(c),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                return Err(IronError::System(format!(
                    "cannot read /etc/os-release: {e}"
                )))
            }
        };
        if let Some(content) = os_release {
            for line in content.lines() {
                if let Some(val) = line.strip_prefix("PRETTY_NAME=") {
                    self.info.os_name = val.trim_matches('"').to_string();
                } else if let Some(val) = line.strip_prefix("VERSION_ID=") {
                    self.info.os_version = val.trim_matches('"').to_string();
                } else if let Some(val) = line.strip_prefix("BUILD_ID=") {
                    self.info.os_build = val.trim_matches('"').to_string();
                }
            }
        }

        // /proc/version
        if let Ok(content) = std::fs::read_to_string("/proc/version") {
            self.info.kernel_full = content.trim().to_string();
            // "Linux version 6.8.0-51-generic ..."
            if let Some(ver) = content.split_whitespace().nth(2) {
                self.info.kernel_version = ver.to_string();
            }
        }

        // Architecture via uname
        if let Ok(output) = std::process::Command::new("uname").arg("-m").output() {
            self.info.architecture = String::from_utf8(output.stdout)
                .unwrap_or_default()
                .trim()
                .to_string();
        }

        // Hostname
        if let Ok(content) = std::fs::read_to_string("/etc/hostname") {
            self.info.hostname = content.trim().to_string();
        }

        // Domain
        if let Ok(content) = std::fs::read_to_string("/proc/sys/kernel/domainname") {
            let d = content.trim();
            if d != "(none)" {
                self.info.domain = d.to_string();
            }
        }

        // Uptime. Left `None` when /proc/uptime is unreadable or unparsable; a
        // zero here would claim the machine booted this instant.
        self.info.uptime_seconds = std::fs::read_to_string("/proc/uptime")
            .ok()
            .and_then(|content| parse_proc_uptime(&content));

        // Boot timestamp from /proc/stat. Only meaningful alongside an uptime
        // reading, so it is cleared when the uptime was not read.
        self.info.boot_timestamp = None;
        if self.info.uptime_seconds.is_some() {
            self.info.boot_timestamp = std::fs::read_to_string("/proc/stat")
                .ok()
                .and_then(|content| parse_btime(&content));
        }

        // Boot mode
        self.info.boot_mode = if std::path::Path::new("/sys/firmware/efi").exists() {
            BootMode::UEFI
        } else {
            BootMode::BIOS
        };

        // Secure Boot. `mokutil --sb-state` prints "SecureBoot enabled" or
        // "SecureBoot disabled". Anything else (tool missing, or a firmware
        // that reports no Secure Boot support) leaves the state unknown. The
        // old code mapped every such case to `false`.
        self.info.secure_boot = None;
        if let Ok(output) = std::process::Command::new("mokutil")
            .arg("--sb-state")
            .output()
        {
            let text = String::from_utf8(output.stdout).unwrap_or_default();
            self.info.secure_boot = parse_mokutil_sb_state(&text);
        }

        // Kernel command line
        if let Ok(content) = std::fs::read_to_string("/proc/cmdline") {
            self.info.kernel_cmdline = content.trim().to_string();
        }

        // Logged-in users (who). One line per session. A failed `who` leaves the
        // count `None`; a successful run with no sessions is a real `Some(0)`.
        self.info.user_count = std::process::Command::new("who")
            .output()
            .ok()
            .filter(|output| output.status.success())
            .map(|output| parse_who_count(&String::from_utf8_lossy(&output.stdout)));

        // Loaded modules from /proc/modules
        if let Ok(content) = std::fs::read_to_string("/proc/modules") {
            for line in content.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 4 {
                    let name = parts[0].to_string();
                    let size_bytes = parts[1].parse().ok();
                    let instances = parts[2].parse().ok();
                    let used_by: Vec<String> = if parts[3] == "-" {
                        Vec::new()
                    } else {
                        parts[3]
                            .trim_end_matches(',')
                            .split(',')
                            .filter(|s| !s.is_empty())
                            .map(|s| s.to_string())
                            .collect()
                    };
                    let state = parts.get(4).unwrap_or(&"").to_string();

                    self.info.loaded_modules.push(KernelModule {
                        name,
                        size_bytes,
                        instances,
                        used_by,
                        state,
                    });
                }
            }
        }

        // Timezone
        if let Ok(tz) = std::fs::read_link("/etc/localtime") {
            let path = tz.to_string_lossy().to_string();
            if let Some(pos) = path.find("zoneinfo/") {
                self.info.timezone = path[pos + 9..].to_string();
            }
        }
        if self.info.timezone.is_empty() {
            if let Ok(content) = std::fs::read_to_string("/etc/timezone") {
                self.info.timezone = content.trim().to_string();
            }
        }

        // Locale
        if let Ok(val) = std::env::var("LANG") {
            self.info.locale = val;
        }
        Ok(())
    }

    // ── Windows ──

    #[cfg(target_os = "windows")]
    fn refresh_windows(&mut self) -> Result<(), IronError> {
        use crate::platform::windows as plat;

        self.info.os_family = OsFamily::Windows;

        // Every field below was previously read by spawning a subprocess — four
        // PowerShell invocations plus one `cmd /c ver`. That cost 3.2 s per refresh
        // and 10.8 s to construct the monitor, for data Windows publishes in the
        // registry and through plain Win32 calls. Two of those readings were also
        // wrong; see the boot-mode and Secure Boot notes below.
        const CURRENT_VERSION: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";

        // `None` when the build number was not read. Nothing below substitutes
        // 0 for it: "10.0.0" would be a made-up version string.
        let build: Option<u32> = plat::read_registry_string(CURRENT_VERSION, "CurrentBuildNumber")
            .and_then(|s| s.parse().ok());

        if let Some(product) = plat::read_registry_string(CURRENT_VERSION, "ProductName") {
            // `ProductName` still reads "Windows 10 ..." on Windows 11; Microsoft
            // never updated it, and the build number is the documented way to tell
            // the two apart. This is a correction from an authoritative field, not a
            // guess: 22000 is the first Windows 11 build. Without a build number the
            // product name is kept as the registry reports it.
            self.info.os_name = if build.is_some_and(|b| b >= 22000) {
                product.replace("Windows 10", "Windows 11")
            } else {
                product
            };
        }

        // Major/minor come from the registry as DWORDs on Windows 10 and later.
        // The version string needs the build too, so it is left empty without one.
        let major = plat::read_registry_u32(CURRENT_VERSION, "CurrentMajorVersionNumber");
        let minor = plat::read_registry_u32(CURRENT_VERSION, "CurrentMinorVersionNumber");
        if let (Some(major), Some(minor), Some(build)) = (major, minor, build) {
            self.info.os_version = format!("{major}.{minor}.{build}");
        }
        if let Some(build) = build {
            self.info.os_build = build.to_string();
        }

        // The kernel version includes the update revision, which is the part that
        // moves between patch Tuesdays and the reason `cmd /c ver` was being parsed.
        let ubr = plat::read_registry_u32(CURRENT_VERSION, "UBR");
        if !self.info.os_version.is_empty() {
            self.info.kernel_version = match ubr {
                Some(ubr) => format!("{}.{ubr}", self.info.os_version),
                None => self.info.os_version.clone(),
            };
            self.info.kernel_full =
                format!("Microsoft Windows [Version {}]", self.info.kernel_version);
        }

        if let Some(name) = windows_computer_name() {
            self.info.hostname = name;
        }

        let (arch, is_64bit) = windows_native_architecture();
        self.info.architecture = arch;
        self.info.is_64bit = is_64bit;

        // `GetTickCount64` is milliseconds since boot and does not advance across
        // sleep, matching what `LastBootUpTime` reported.
        let uptime_ms = unsafe { windows::Win32::System::SystemInformation::GetTickCount64() };
        let uptime = uptime_ms / 1000;
        self.info.uptime_seconds = Some(uptime);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        self.info.boot_timestamp = Some(now.saturating_sub(uptime));

        // Boot mode. The old reading spawned PowerShell to test `$env:firmware_type`,
        // which Windows does not set for a non-interactive child process — so it was
        // empty on every call and the result was decided by the fallback arm rather
        // than by the firmware.
        self.info.boot_mode = match plat::firmware_type() {
            Some(crate::boot_config::BootType::Uefi) => BootMode::UEFI,
            Some(crate::boot_config::BootType::Legacy) => BootMode::BIOS,
            _ => BootMode::Unknown,
        };

        // Secure Boot, from the `UEFISecureBootEnabled` value. An unreadable value is
        // `None`. The old code used `unwrap_or(false)`, which reported Secure Boot as
        // off whenever the read failed.
        self.info.secure_boot = plat::secure_boot_enabled();

        if let Some(tz) = windows_timezone_key() {
            self.info.timezone = tz;
        }
        if let Some(locale) = windows_user_locale() {
            self.info.locale = locale;
        }

        self.info.loaded_modules = windows_running_drivers();

        // `user_count` stays `None`. The candidate source was
        // `Win32_OperatingSystem.NumberOfUsers`, whose meaning as a logged-in count
        // was not verified here; counting sessions properly needs a WTS enumeration
        // this monitor does not otherwise do. Reporting a 0 would be a fabrication.
        self.info.user_count = None;
        Ok(())
    }

    // ── macOS ──

    #[cfg(target_os = "macos")]
    fn refresh_macos(&mut self) -> Result<(), IronError> {
        self.info.os_family = OsFamily::MacOS;

        // `sw_vers` ships with macOS and is how the OS names itself, so a
        // failure to run it is a failure rather than an absent optional tool.
        {
            let text = crate::core::command::capture("sw_vers", &[])?;
            for line in text.lines() {
                if let Some(val) = line.strip_prefix("ProductName:") {
                    self.info.os_name = val.trim().to_string();
                } else if let Some(val) = line.strip_prefix("ProductVersion:") {
                    self.info.os_version = val.trim().to_string();
                } else if let Some(val) = line.strip_prefix("BuildVersion:") {
                    self.info.os_build = val.trim().to_string();
                }
            }
        }

        // Kernel
        if let Ok(output) = std::process::Command::new("uname").arg("-r").output() {
            self.info.kernel_version = String::from_utf8(output.stdout)
                .unwrap_or_default()
                .trim()
                .to_string();
        }
        if let Ok(output) = std::process::Command::new("uname").arg("-v").output() {
            self.info.kernel_full = String::from_utf8(output.stdout)
                .unwrap_or_default()
                .trim()
                .to_string();
        }

        // Architecture
        if let Ok(output) = std::process::Command::new("uname").arg("-m").output() {
            self.info.architecture = String::from_utf8(output.stdout)
                .unwrap_or_default()
                .trim()
                .to_string();
        }

        // Hostname
        if let Ok(output) = std::process::Command::new("hostname").output() {
            self.info.hostname = String::from_utf8(output.stdout)
                .unwrap_or_default()
                .trim()
                .to_string();
        }

        // Uptime via sysctl
        if let Ok(output) = std::process::Command::new("sysctl")
            .args(["-n", "kern.boottime"])
            .output()
        {
            let text = String::from_utf8(output.stdout).unwrap_or_default();
            // "{ sec = 1234567890, usec = 0 } ..."
            if let Some(sec_str) = text
                .split("sec = ")
                .nth(1)
                .and_then(|s| s.split(',').next())
            {
                if let Ok(boot_sec) = sec_str.trim().parse::<u64>() {
                    self.info.boot_timestamp = Some(boot_sec);
                    let now = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_secs();
                    self.info.uptime_seconds = Some(now.saturating_sub(boot_sec));
                }
            }
        }

        // Boot mode. Not read here. The old code assigned UEFI to every Mac, but
        // Apple silicon Macs boot through iBoot rather than UEFI, and Intel Macs
        // use EFI, so no single value is true of the platform. Nothing cheap
        // distinguishes them, so the mode stays `Unknown`.
        self.info.boot_mode = BootMode::Unknown;

        // Secure Boot. The old code inferred it from the chip name ("Apple M" or
        // "Apple T2"). That is a guess from a product name, not a reading of the
        // firmware, so it is now `None`. Intel Macs without a T2 chip have no
        // Secure Boot at all, and the name cannot distinguish them.
        self.info.secure_boot = None;

        // Timezone
        if let Ok(tz) = std::fs::read_link("/etc/localtime") {
            let path = tz.to_string_lossy().to_string();
            if let Some(pos) = path.find("zoneinfo/") {
                self.info.timezone = path[pos + 9..].to_string();
            }
        }

        // Locale
        if let Ok(val) = std::env::var("LANG") {
            self.info.locale = val;
        }

        // Loaded kernel extensions
        if let Ok(output) = std::process::Command::new("kextstat").args(["-l"]).output() {
            let text = String::from_utf8(output.stdout).unwrap_or_default();
            for line in text.lines().skip(1) {
                // "  Index Refs Address ... Name (Version) <Linked Against>"
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 6 {
                    let name = parts[5].to_string();
                    let refs: Option<u32> = parts[1].parse().ok();
                    let size: Option<u64> =
                        u64::from_str_radix(parts[3].trim_start_matches("0x"), 16).ok();

                    self.info.loaded_modules.push(KernelModule {
                        name,
                        size_bytes: size,
                        instances: refs,
                        used_by: Vec::new(),
                        state: "Live".to_string(),
                    });
                }
            }
        }
        Ok(())
    }
}

impl Default for OsInfoMonitor {
    fn default() -> Self {
        Self::new().unwrap_or(Self {
            info: OsInfo {
                os_family: OsFamily::Unknown,
                os_name: String::new(),
                os_version: String::new(),
                os_build: String::new(),
                kernel_version: String::new(),
                kernel_full: String::new(),
                architecture: String::new(),
                hostname: String::new(),
                domain: String::new(),
                uptime_seconds: None,
                boot_timestamp: None,
                boot_mode: BootMode::Unknown,
                kernel_cmdline: String::new(),
                user_count: None,
                loaded_modules: Vec::new(),
                timezone: String::new(),
                locale: String::new(),
                is_64bit: cfg!(target_pointer_width = "64"),
                secure_boot: None,
            },
        })
    }
}

impl std::fmt::Display for OsFamily {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Linux => write!(f, "Linux"),
            Self::Windows => write!(f, "Windows"),
            Self::MacOS => write!(f, "macOS"),
            Self::FreeBSD => write!(f, "FreeBSD"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

impl std::fmt::Display for BootMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UEFI => write!(f, "UEFI"),
            Self::BIOS => write!(f, "BIOS"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

// ── Windows native readers ──
//
// These replace subprocess spawns. Each returns `None` rather than a placeholder
// when the platform does not answer, so callers keep the field's default instead of
// publishing a made-up value.

/// The machine's NetBIOS computer name.
#[cfg(target_os = "windows")]
fn windows_computer_name() -> Option<String> {
    use windows::Win32::System::SystemInformation::{ComputerNameNetBIOS, GetComputerNameExW};

    let mut len: u32 = 0;
    // First call reports the required length; it is expected to fail with
    // ERROR_MORE_DATA, so its status is deliberately not checked.
    let _ =
        unsafe { GetComputerNameExW(ComputerNameNetBIOS, windows::core::PWSTR::null(), &mut len) };
    if len == 0 {
        return None;
    }

    // The reported length excludes the terminating null, which the second call still
    // writes — so the buffer needs one more slot than `len` says.
    let mut buffer = vec![0u16; len as usize + 1];
    unsafe {
        GetComputerNameExW(
            ComputerNameNetBIOS,
            windows::core::PWSTR(buffer.as_mut_ptr()),
            &mut len,
        )
    }
    .ok()?;
    buffer.truncate(len as usize);

    let name = String::from_utf16_lossy(&buffer);
    let name = name.trim().to_string();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

/// The processor architecture the OS is running on, and whether it is 64-bit.
///
/// `GetNativeSystemInfo` reports the machine's architecture even when the caller is a
/// 32-bit process under WOW64, which `GetSystemInfo` does not.
#[cfg(target_os = "windows")]
fn windows_native_architecture() -> (String, bool) {
    use windows::Win32::System::SystemInformation::{GetNativeSystemInfo, SYSTEM_INFO};
    use windows::Win32::System::SystemInformation::{
        PROCESSOR_ARCHITECTURE_AMD64, PROCESSOR_ARCHITECTURE_ARM, PROCESSOR_ARCHITECTURE_ARM64,
        PROCESSOR_ARCHITECTURE_INTEL,
    };

    let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() };
    unsafe { GetNativeSystemInfo(&mut info) };

    let arch = unsafe { info.Anonymous.Anonymous.wProcessorArchitecture };
    match arch {
        PROCESSOR_ARCHITECTURE_AMD64 => ("x86_64".to_string(), true),
        PROCESSOR_ARCHITECTURE_ARM64 => ("aarch64".to_string(), true),
        PROCESSOR_ARCHITECTURE_ARM => ("arm".to_string(), false),
        PROCESSOR_ARCHITECTURE_INTEL => ("x86".to_string(), false),
        // Compiled-in target as a last resort: it is what this binary was built for,
        // which is at least a fact about the running process.
        _ => (
            std::env::consts::ARCH.to_string(),
            cfg!(target_pointer_width = "64"),
        ),
    }
}

/// The IANA-equivalent Windows time zone key (e.g. "Pacific Standard Time").
#[cfg(target_os = "windows")]
fn windows_timezone_key() -> Option<String> {
    use windows::Win32::System::Time::{
        GetDynamicTimeZoneInformation, DYNAMIC_TIME_ZONE_INFORMATION,
    };

    let mut tz = DYNAMIC_TIME_ZONE_INFORMATION::default();
    // Returns the daylight-saving state, not a status code; TIME_ZONE_ID_INVALID
    // (0xFFFFFFFF) is the failure value.
    if unsafe { GetDynamicTimeZoneInformation(&mut tz) } == u32::MAX {
        return None;
    }

    let key: String = String::from_utf16_lossy(&tz.TimeZoneKeyName)
        .trim_end_matches('\0')
        .trim()
        .to_string();
    if key.is_empty() {
        None
    } else {
        Some(key)
    }
}

/// The user's default locale name (e.g. "en-US").
#[cfg(target_os = "windows")]
fn windows_user_locale() -> Option<String> {
    use windows::Win32::Globalization::GetUserDefaultLocaleName;

    let mut buffer = [0u16; 85]; // LOCALE_NAME_MAX_LENGTH
    let len = unsafe { GetUserDefaultLocaleName(&mut buffer) };
    if len <= 1 {
        return None;
    }

    // The returned length includes the terminating null.
    Some(String::from_utf16_lossy(&buffer[..(len as usize - 1)]))
}

/// Currently running kernel-mode drivers, the Windows analogue of kernel modules.
///
/// Sourced from WMI over the existing COM connection rather than by spawning
/// PowerShell to emit JSON, which alone accounted for roughly a second per refresh.
#[cfg(target_os = "windows")]
fn windows_running_drivers() -> Vec<KernelModule> {
    let Ok(drivers) = crate::motherboard::get_running_drivers() else {
        return Vec::new();
    };

    drivers
        .into_iter()
        .map(|(name, state)| KernelModule {
            name,
            // Neither figure is exposed by `Win32_SystemDriver`.
            size_bytes: None,
            instances: None,
            used_by: Vec::new(),
            state,
        })
        .collect()
}

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

    /// Constructing the monitor either enumerates or says why it could not.
    ///
    /// See the identically-shaped tests in `camera`, `usb` and the rest: this
    /// asserted `is_ok()`, which was true by construction while `refresh` could
    /// not fail. A failure must carry a reason, because a reason is the whole
    /// difference between "this machine has none" and "nobody looked".
    #[test]
    fn test_os_info_creation() {
        match OsInfoMonitor::new() {
            Ok(_monitor) => {}
            Err(e) => {
                let why = e.to_string();
                assert!(
                    why.len() > 10,
                    "enumeration failed without saying why: {why:?}"
                );
            }
        }
    }

    #[test]
    fn test_os_info_default() {
        let monitor = OsInfoMonitor::default();
        let info = monitor.info();
        assert!(!info.hostname.is_empty() || info.os_family == OsFamily::Unknown);
    }

    #[test]
    fn test_os_info_has_data() {
        if let Ok(monitor) = OsInfoMonitor::new() {
            let info = monitor.info();
            // Should have at least an OS family detected
            assert_ne!(info.os_family, OsFamily::Unknown);
            // Should have kernel version
            assert!(!info.kernel_version.is_empty());
        }
    }

    #[test]
    fn proc_uptime_is_the_first_field_and_absent_when_malformed() {
        assert_eq!(parse_proc_uptime("123456.78 987654.32\n"), Some(123456));
        assert_eq!(parse_proc_uptime(""), None);
        assert_eq!(parse_proc_uptime("garbage"), None);
    }

    #[test]
    fn btime_is_read_from_proc_stat_and_absent_without_the_line() {
        let stat = "cpu  100 0 200 300 0 0 0 0 0 0\nbtime 1700000000\nprocesses 42\n";
        assert_eq!(parse_btime(stat), Some(1_700_000_000));
        assert_eq!(parse_btime("cpu  1 2 3\nprocesses 42\n"), None);
    }

    #[test]
    fn who_counts_sessions_and_an_empty_listing_is_zero() {
        let who = concat!(
            "alice tty2 2026-10-24 08:01 (:0)\n",
            "bob pts/0 2026-10-24 09:14 (10.0.0.5)\n"
        );
        assert_eq!(parse_who_count(who), 2);
        assert_eq!(parse_who_count(""), 0);
    }

    #[test]
    fn test_os_family_display() {
        assert_eq!(OsFamily::Linux.to_string(), "Linux");
        assert_eq!(OsFamily::Windows.to_string(), "Windows");
        assert_eq!(BootMode::UEFI.to_string(), "UEFI");
    }

    #[test]
    fn test_os_info_serialization() {
        let info = OsInfo {
            os_family: OsFamily::Linux,
            os_name: "Ubuntu 22.04".into(),
            os_version: "22.04".into(),
            os_build: "".into(),
            kernel_version: "6.8.0".into(),
            kernel_full: "Linux version 6.8.0".into(),
            architecture: "x86_64".into(),
            hostname: "myhost".into(),
            domain: "".into(),
            uptime_seconds: Some(3600),
            boot_timestamp: Some(1700000000),
            boot_mode: BootMode::UEFI,
            kernel_cmdline: "root=/dev/sda1".into(),
            user_count: Some(1),
            loaded_modules: Vec::new(),
            timezone: "America/New_York".into(),
            locale: "en_US.UTF-8".into(),
            is_64bit: true,
            secure_boot: Some(true),
        };
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("Ubuntu"));
        let _: OsInfo = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn mokutil_output_is_read_only_when_it_states_the_mode() {
        assert_eq!(parse_mokutil_sb_state("SecureBoot enabled\n"), Some(true));
        assert_eq!(parse_mokutil_sb_state("SecureBoot disabled\n"), Some(false));
        // Unsupported firmware, or any other output, is not a disabled state.
        assert_eq!(
            parse_mokutil_sb_state("This system doesn't support Secure Boot\n"),
            None
        );
        assert_eq!(parse_mokutil_sb_state(""), None);
    }

    #[test]
    fn test_kernel_module_serialization() {
        let module = KernelModule {
            name: "nvidia".into(),
            size_bytes: Some(1048576),
            instances: Some(1),
            used_by: vec!["nvidia_uvm".into()],
            state: "Live".into(),
        };
        let json = serde_json::to_string(&module).unwrap();
        assert!(json.contains("nvidia"));
        let _: KernelModule = serde_json::from_str(&json).unwrap();
    }
}