Skip to content

Commit 430190c

Browse files
committed
fix(systemd_logind): use kernel btime for boot time and clarify fallback logic
1 parent 0ebb7e6 commit 430190c

2 files changed

Lines changed: 82 additions & 30 deletions

File tree

‎src/uucore/src/lib/features/systemd_logind.rs‎

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
//!
1010
//! This module provides systemd-logind based implementation for reading
1111
//! login records as an alternative to traditional utmp/utmpx files.
12-
//! On Linux, this is tried before traditional utmp files. If systemd-logind is
13-
//! unavailable, callers fall back to the traditional implementation.
12+
//! On Linux, this is used when the traditional utmp file is unavailable or
13+
//! empty. If systemd-logind is unavailable, callers fall back to the traditional
14+
//! implementation.
1415
1516
use std::ffi::CStr;
1617
use std::mem::MaybeUninit;
@@ -101,7 +102,7 @@ mod login {
101102
use super::ffi;
102103
use std::ffi::{CStr, CString};
103104
use std::ptr;
104-
use std::time::SystemTime;
105+
use std::time::{SystemTime, UNIX_EPOCH};
105106

106107
/// Get all active sessions
107108
pub fn get_sessions(
@@ -325,25 +326,20 @@ mod login {
325326
Ok(Some(seat_string))
326327
}
327328

328-
/// Get system boot time using systemd random-seed file fallback
329-
///
330-
/// TODO: This replicates GNU coreutils' fallback behavior for compatibility.
331-
/// GNU coreutils uses the mtime of /var/lib/systemd/random-seed as a heuristic for boot time
332-
/// when utmp is unavailable, rather than querying systemd's authoritative KernelTimestamp.
333-
/// This creates inconsistency: `uptime -s` shows the actual kernel boot time
334-
/// while `who -b` shows ~1 minute later when systemd services start.
335-
///
336-
/// Ideally, both should use the same source (KernelTimestamp) for semantic consistency.
337-
/// Consider proposing to GNU coreutils to use systemd's KernelTimestamp property instead.
338-
pub fn get_boot_time() -> Result<SystemTime, Box<dyn std::error::Error>> {
339-
use std::fs;
340-
341-
let metadata = fs::metadata("/var/lib/systemd/random-seed")
342-
.map_err(|e| format!("Failed to read /var/lib/systemd/random-seed: {e}"))?;
329+
pub(super) fn boot_time_from_proc_stat(contents: &str) -> Option<SystemTime> {
330+
contents.lines().find_map(|line| {
331+
line.strip_prefix("btime ")
332+
.and_then(|seconds| seconds.parse::<u64>().ok())
333+
.map(|seconds| UNIX_EPOCH + std::time::Duration::from_secs(seconds))
334+
})
335+
}
343336

344-
metadata
345-
.modified()
346-
.map_err(|e| format!("Failed to get modification time: {e}").into())
337+
/// Get the system boot time using the kernel's `/proc/stat` value.
338+
pub fn get_boot_time() -> Result<SystemTime, Box<dyn std::error::Error>> {
339+
let proc_stat = std::fs::read_to_string("/proc/stat")
340+
.map_err(|e| format!("Failed to read /proc/stat: {e}"))?;
341+
boot_time_from_proc_stat(&proc_stat)
342+
.ok_or_else(|| "Failed to find btime in /proc/stat".into())
347343
}
348344
}
349345

@@ -735,6 +731,19 @@ impl Iterator for SystemdUtmpxIter {
735731
mod tests {
736732
use super::*;
737733

734+
#[test]
735+
fn test_boot_time_from_proc_stat() {
736+
let boot_time = login::boot_time_from_proc_stat(
737+
"cpu 1 2 3 4 5 6 7 8 9 10\nbtime 1234567890\nprocesses 42\n",
738+
);
739+
740+
assert_eq!(
741+
boot_time,
742+
Some(UNIX_EPOCH + std::time::Duration::from_secs(1_234_567_890))
743+
);
744+
assert!(login::boot_time_from_proc_stat("cpu 1 2 3\n").is_none());
745+
}
746+
738747
#[test]
739748
fn test_empty_iterator() {
740749
let mut iter = SystemdUtmpxIter::empty();

‎src/uucore/src/lib/features/utmpx.rs‎

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ pub extern crate time;
3636
use std::ffi::CString;
3737
use std::io::Result as IOResult;
3838
use std::marker::PhantomData;
39+
#[cfg(target_os = "linux")]
40+
use std::mem::size_of;
3941
use std::os::unix::ffi::OsStrExt;
4042
use std::path::Path;
4143
use std::ptr;
@@ -327,16 +329,25 @@ impl Utmpx {
327329
/// This will use the default location, or the path [`Utmpx::iter_all_records_from`]
328330
/// was most recently called with.
329331
///
330-
/// On Linux, this will try systemd-logind first and fall back to traditional
331-
/// utmp files if systemd-logind is unavailable.
332+
/// On Linux, this will use a populated traditional utmp file when available.
333+
/// If the default utmp file is missing or empty, it will try systemd-logind
334+
/// and fall back to traditional utmp if systemd-logind is unavailable.
332335
///
333336
/// Only one instance of [`UtmpxIter`] may be active at a time. This
334337
/// function will block as long as one is still active. Beware!
335338
pub fn iter_all_records() -> UtmpxIter {
336339
#[cfg(target_os = "linux")]
337340
{
338-
// Prefer systemd-logind on Linux.
339-
UtmpxIter::new_systemd_with_fallback_path(None)
341+
if traditional_utmp_is_usable(Path::new(DEFAULT_FILE)) {
342+
let iter = UtmpxIter::new();
343+
unsafe {
344+
#[cfg_attr(target_env = "musl", allow(deprecated))]
345+
setutxent();
346+
}
347+
iter
348+
} else {
349+
UtmpxIter::new_systemd_with_fallback_path(None)
350+
}
340351
}
341352

342353
#[cfg(not(target_os = "linux"))]
@@ -359,15 +370,17 @@ impl Utmpx {
359370
///
360371
/// This function affects subsequent calls to [`Utmpx::iter_all_records`].
361372
///
362-
/// On Linux, if the path matches the default utmp file, this will try
363-
/// systemd-logind first and fall back to that file if it is unavailable.
373+
/// On Linux, if the path matches the default utmp file and that file is
374+
/// missing or empty, this will try systemd-logind first and fall back to
375+
/// that file if systemd-logind is unavailable.
364376
///
365377
/// The same caveats as for [`Utmpx::iter_all_records`] apply.
366378
pub fn iter_all_records_from<P: AsRef<Path>>(path: P) -> UtmpxIter {
367379
#[cfg(target_os = "linux")]
368380
{
369-
// Prefer systemd-logind for the default utmp file on Linux.
370-
if path.as_ref() == Path::new(DEFAULT_FILE) {
381+
if path.as_ref() == Path::new(DEFAULT_FILE)
382+
&& !traditional_utmp_is_usable(path.as_ref())
383+
{
371384
return UtmpxIter::new_systemd_with_fallback_path(Some(path.as_ref()));
372385
}
373386
}
@@ -401,6 +414,24 @@ impl Utmpx {
401414
// ordinary race conditions are also very much possible.
402415
static LOCK: Mutex<()> = Mutex::new(());
403416

417+
#[cfg(target_os = "linux")]
418+
fn traditional_utmp_is_usable(path: &Path) -> bool {
419+
#[cfg(target_env = "musl")]
420+
{
421+
let _ = path;
422+
false
423+
}
424+
425+
#[cfg(not(target_env = "musl"))]
426+
{
427+
std::fs::metadata(path).is_ok_and(|metadata| {
428+
metadata.is_file()
429+
&& metadata.len() >= size_of::<utmpx>() as u64
430+
&& std::fs::File::open(path).is_ok()
431+
})
432+
}
433+
}
434+
404435
/// Iterator of login records
405436
pub struct UtmpxIter {
406437
#[allow(dead_code)]
@@ -477,7 +508,7 @@ mod tests {
477508
use super::*;
478509
use std::fs::{File, remove_file};
479510
use std::io::Write;
480-
use std::mem::{size_of, zeroed};
511+
use std::mem::zeroed;
481512

482513
fn write_utmpx_record(path: &Path, user: &str) {
483514
// SAFETY: A zero-filled utmpx value is valid, and the initialized value is
@@ -527,6 +558,18 @@ mod tests {
527558
remove_file(custom_path).unwrap();
528559
remove_file(fallback_path).unwrap();
529560
}
561+
562+
#[test]
563+
fn traditional_utmp_requires_at_least_one_record() {
564+
let directory = tempfile::tempdir().unwrap();
565+
let path = directory.path().join("utmp");
566+
567+
File::create(&path).unwrap();
568+
assert!(!traditional_utmp_is_usable(&path));
569+
570+
write_utmpx_record(&path, "user");
571+
assert!(traditional_utmp_is_usable(&path));
572+
}
530573
}
531574

532575
/// Wrapper type that can hold either traditional utmpx records or systemd records

0 commit comments

Comments
 (0)