From b8a5387f5aaf800a49b27be4628948cdee4d9b24 Mon Sep 17 00:00:00 2001 From: mattsu Date: Tue, 17 Nov 2026 17:36:12 +0900 Subject: [PATCH 1/2] utmpx: fall back to logind when default utmp is unavailable --- .github/workflows/CICD.yml | 34 +- .../workspace.wordlist.txt | 5 + Cargo.lock | 2 + Cargo.toml | 11 +- DEVELOPMENT.md | 25 + build.rs | 3 +- docs/src/platforms.md | 5 + src/uu/pinky/Cargo.toml | 5 +- src/uu/pinky/src/platform/unix.rs | 48 ++ src/uu/uptime/Cargo.toml | 10 +- src/uu/users/Cargo.toml | 5 +- src/uu/who/Cargo.toml | 6 +- src/uu/who/src/platform/unix.rs | 43 +- src/uucore/Cargo.toml | 4 +- src/uucore/src/lib/features.rs | 2 +- src/uucore/src/lib/features/systemd_logind.rs | 436 ++++++++++-------- .../src/lib/features/systemd_logind/tests.rs | 237 ++++++++++ src/uucore/src/lib/features/utmpx.rs | 206 ++++----- src/uucore/src/lib/features/utmpx/tests.rs | 78 ++++ src/uucore/src/lib/lib.rs | 2 +- src/uucore/tests/support/utmpx.rs | 23 + tests/by-util/test_who.rs | 228 +++++++++ util/test-logind.sh | 28 ++ 23 files changed, 1099 insertions(+), 347 deletions(-) create mode 100644 src/uucore/src/lib/features/systemd_logind/tests.rs create mode 100644 src/uucore/src/lib/features/utmpx/tests.rs create mode 100644 src/uucore/tests/support/utmpx.rs create mode 100755 util/test-logind.sh diff --git a/.github/workflows/CICD.yml b/.github/workflows/CICD.yml index a4d4d7e29a6..5a0613ba86c 100644 --- a/.github/workflows/CICD.yml +++ b/.github/workflows/CICD.yml @@ -42,6 +42,27 @@ jobs: persist-credentials: false - uses: EmbarkStudios/cargo-deny-action@v2 + logind: + name: Logind/${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-22.04, ubuntu-24.04] + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_MIN_SRV }} + - uses: Swatinem/rust-cache@v2 + - name: Compare with systemd commands + shell: bash + run: | + cargo test --locked --no-default-features --features test_logind --test tests --no-run --message-format=json > "$RUNNER_TEMP/logind-tests.json" + logind_test_binary=$(jq -r 'select(.reason == "compiler-artifact" and .target.name == "tests" and .executable != null) | .executable' "$RUNNER_TEMP/logind-tests.json") + bash util/test-logind.sh "$logind_test_binary" + style_deps: ## ToDO: [2021-11-10; rivy] 'Style/deps' needs more informative output and better integration of results into the GHA dashboard name: Style/deps @@ -233,7 +254,7 @@ jobs: cargo +stable fetch --locked --quiet --target $(rustc --print host-tuple) cargo +stable tree --no-dedupe --locked -e=no-dev --prefix=none ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} | grep -vE "$PWD" | sort --unique - name: Test - run: cargo nextest run --hide-progress-bar --profile ci ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} -p uucore -p coreutils + run: cargo nextest run --hide-progress-bar --profile ci ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} --features test_logind -p uucore -p coreutils env: RUSTFLAGS: "-Awarnings" RUST_BACKTRACE: "1" @@ -305,6 +326,9 @@ jobs: run: cargo nextest run --hide-progress-bar --profile ci --features ${{ matrix.job.features }} env: RUST_BACKTRACE: "1" + - name: Test utmpx with systemd-logind + if: runner.os == 'Linux' + run: cargo test -p uucore -p uu_who -p uu_pinky --lib --locked --features systemd-logind - name: Upload test results to Codecov if: ${{ !cancelled() }} uses: codecov/codecov-action@v7 @@ -557,9 +581,9 @@ jobs: esac case '${{ matrix.job.os }}' in ubuntu-*) - # selinux and systemd headers needed to build tests + # selinux headers needed to build tests sudo apt-get -y update - sudo apt-get -y install libselinux1-dev libsystemd-dev + sudo apt-get -y install libselinux1-dev # pinky is a tool to show logged-in users from utmp, and gecos fields from /etc/passwd. # In GitHub Action *nix VMs, no accounts log in, even the "runner" account that runs the commands, and "system boot" entry is missing. # The account also has empty gecos fields. @@ -796,10 +820,10 @@ jobs: ## Install/setup prerequisites case '${{ matrix.job.os }}' in ubuntu-latest) - # selinux and systemd headers needed to build tests + # selinux headers needed to build tests # acl: setfacl for coverage profile-trace dir default ACL (umask 0777 tests) sudo apt-get -y update - sudo apt-get -y install libselinux1-dev libsystemd-dev acl + sudo apt-get -y install libselinux1-dev acl # pinky is a tool to show logged-in users from utmp, and gecos fields from /etc/passwd. # In GitHub Action *nix VMs, no accounts log in, even the "runner" account that runs the commands, and "system boot" entry is missing. # The account also has empty gecos fields. diff --git a/.vscode/cspell.dictionaries/workspace.wordlist.txt b/.vscode/cspell.dictionaries/workspace.wordlist.txt index 78bb78c480f..7a9f3c0aa3b 100644 --- a/.vscode/cspell.dictionaries/workspace.wordlist.txt +++ b/.vscode/cspell.dictionaries/workspace.wordlist.txt @@ -1,6 +1,8 @@ # * cargo cdylib doctest +libloading +nocapture # * uutils project uutils @@ -11,6 +13,7 @@ ucmd uumain rlimit mkfifo +logind urandom uchild ello @@ -203,6 +206,8 @@ inode inodes isatty lchown +libsystemd +ohos pathlen setgid setgroups diff --git a/Cargo.lock b/Cargo.lock index 2ad3cfa9e89..242b8aba244 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4396,6 +4396,7 @@ dependencies = [ "jiff", "jiff-icu", "libc", + "libloading", "md-5", "memchr", "nix", @@ -4404,6 +4405,7 @@ dependencies = [ "openssl", "os_display", "procfs", + "rstest", "rustc-hash", "rustix", "selinux", diff --git a/Cargo.toml b/Cargo.toml index 91c9ec1b7ea..e57892a58d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -85,6 +85,7 @@ jiff = "0.2.18" jiff-icu = "0.2.2" jiff-tzdb = "0.1" libc = "0.2.191" +libloading = "0.8.9" lscolors = { version = "0.21.0", default-features = false, features = [ "gnu_legacy", ] } @@ -438,6 +439,8 @@ openssl = [ ] # "test_risky_names" == enable tests that create problematic file names (would make a network share inaccessible to Windows, breaks SVN on Mac OS, etc.) test_risky_names = [] +# Linux logind integration tests. +test_logind = ["who", "pinky", "users", "uptime"] # * only build `uudoc` when `--feature uudoc` is activated uudoc = [ "dep:clap_complete", @@ -461,14 +464,6 @@ feat_diagnostics = ["uucore/diagnostics"] ## Optional feature for stdbuf # "feat_external_libstdbuf" == use an external libstdbuf.so for stdbuf instead of embedding it feat_external_libstdbuf = ["stdbuf/feat_external_libstdbuf"] -# "feat_systemd_logind" == enable systemd_logind support for utmpx replacement -feat_systemd_logind = [ - "pinky/systemd_logind", - "uptime/systemd_logind", - "users/systemd_logind", - "uucore/systemd_logind", - "who/systemd_logind", -] # "feat_selinux" == enable support for SELinux Security Context (by using `--features feat_selinux`) # NOTE: # * The selinux(-sys) crate requires `libselinux` headers and shared library to be accessible in the C toolchain at compile time. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index bbe3ccaf6ed..cd8c40a4a9d 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -136,6 +136,31 @@ If you would prefer to test a select few utilities: cargo test --features "chmod mv tail" --no-default-features ``` +The logind record assembly and error tests run as `uucore` unit tests without a running +systemd instance or compiled shared-library fixtures: + +```shell +cargo test -p uucore --features 'utmpx systemd-logind' --lib +``` + +The comparison against real systemd commands requires Linux with systemd as +PID 1, an active systemd-logind/D-Bus service, and a PAM `login` stack including +pam_systemd. Enable the four utilities and build the integration test executable: + +```shell +cargo test --no-default-features --features test_logind --test tests --no-run +bash util/test-logind.sh /absolute/path/to/target/debug/deps/tests-HASH +``` + +Use the executable path printed by Cargo. This runs the otherwise ignored +`sessions_match_loginctl` test as a system service, using sudo when needed. +An empty utmp is mounted only inside that service's namespace. The test creates +a temporary PAM/TTY session with systemd-run, compares session metadata with +loginctl and the four utilities, then stops its session. The Logind CI jobs run +this comparison on Ubuntu 22.04 and 24.04 to cover older and newer sd-login APIs. +Older libraries cannot supply session timestamps or PIDs; the comparison checks +that the utilities show `?` for these fields. + If you also want to test the core utilities: ```shell diff --git a/build.rs b/build.rs index 923b2f44d1a..304557849c7 100644 --- a/build.rs +++ b/build.rs @@ -52,7 +52,8 @@ pub fn main() { } "default" | "macos" | "unix" | "windows" | "selinux" | "zip" | "clap_complete" | "clap_mangen" | "fluent_syntax" | "openssl" => continue, // common/standard feature names - "nightly" | "test_unimplemented" | "expensive_tests" | "test_risky_names" => { + "nightly" | "test_unimplemented" | "expensive_tests" | "test_risky_names" + | "test_logind" => { continue; } // crate-local custom features "uudoc" => continue, // is not a utility diff --git a/docs/src/platforms.md b/docs/src/platforms.md index 4ac6ab0a180..ed35cd7494e 100644 --- a/docs/src/platforms.md +++ b/docs/src/platforms.md @@ -45,3 +45,8 @@ Note that for some utilities, not all functionality is supported on each platform. This is documented per utility. {{ #include platform_table.md }} + +## Linux login records + +On Linux, `who`, `pinky`, `users`, and `uptime` prefer traditional login records +and try systemd-logind when the default file is empty or unavailable. diff --git a/src/uu/pinky/Cargo.toml b/src/uu/pinky/Cargo.toml index 515c65db03c..62932de2bf5 100644 --- a/src/uu/pinky/Cargo.toml +++ b/src/uu/pinky/Cargo.toml @@ -20,10 +20,7 @@ doctest = false [dependencies] clap = { workspace = true } fluent = { workspace = true } -uucore = { workspace = true, features = ["utmpx", "entries"] } - -[features] -systemd_logind = ["uucore/systemd_logind"] +uucore = { workspace = true, features = ["utmpx", "systemd-logind", "entries"] } [lints] workspace = true diff --git a/src/uu/pinky/src/platform/unix.rs b/src/uu/pinky/src/platform/unix.rs index f9f6e4c2a2f..ca4506e9460 100644 --- a/src/uu/pinky/src/platform/unix.rs +++ b/src/uu/pinky/src/platform/unix.rs @@ -192,6 +192,13 @@ fn format_timestamp(ut: &UtmpxRecord) -> String { }; } + #[cfg(target_os = "linux")] + if let UtmpxRecord::Systemd(systemd) = ut { + return systemd.try_login_time().map_or_else( + || "?".into(), + |time| TIME_FORMAT.with(|description| time.format(description).unwrap()), + ); + } TIME_FORMAT.with(|description| ut.login_time().format(description).unwrap()) } @@ -368,6 +375,47 @@ impl Pinky { mod tests { use super::{format_quiet_time, real_name}; + #[test] + #[cfg(target_os = "linux")] + fn missing_session_time_is_displayed_as_unknown() { + use super::*; + use uucore::systemd_logind::{SystemdLoginRecord, SystemdRecordType, SystemdUtmpxCompat}; + + let record = UtmpxRecord::Systemd(SystemdUtmpxCompat::new(SystemdLoginRecord { + user: "user".into(), + session_id: "legacy".into(), + seat_or_tty: "pts/test".into(), + raw_device: "pts/test".into(), + host: "alias.test".into(), + login_time: std::time::UNIX_EPOCH, + pid: 0, + session_leader_pid: 0, + record_type: SystemdRecordType::UserProcess, + })); + let pinky = Pinky { + resolve_hosts: false, + layout: Layout { + header: false, + real_name: false, + idle: true, + origin: true, + }, + details: Details { + home_and_shell: false, + project: false, + plan: false, + }, + names: Vec::new(), + }; + assert_eq!( + pinky + .session_row(&record) + .split_whitespace() + .collect::>(), + ["user", "?pts/test", "?????", "?", "alias.test"] + ); + } + #[test] fn idle_under_a_minute_is_blank() { assert_eq!(format_quiet_time(0), " "); diff --git a/src/uu/uptime/Cargo.toml b/src/uu/uptime/Cargo.toml index cde8b1159f3..eb1b2e1481e 100644 --- a/src/uu/uptime/Cargo.toml +++ b/src/uu/uptime/Cargo.toml @@ -23,10 +23,12 @@ clap = { workspace = true } fluent = { workspace = true } jiff = { workspace = true } thiserror = { workspace = true } -uucore = { workspace = true, features = ["libc", "utmpx", "uptime"] } - -[features] -systemd_logind = ["uucore/systemd_logind"] +uucore = { workspace = true, features = [ + "libc", + "utmpx", + "systemd-logind", + "uptime", +] } [lints] workspace = true diff --git a/src/uu/users/Cargo.toml b/src/uu/users/Cargo.toml index a049fed31a0..f7db6604110 100644 --- a/src/uu/users/Cargo.toml +++ b/src/uu/users/Cargo.toml @@ -19,7 +19,7 @@ test = false doctest = false [target.'cfg(any(target_vendor = "apple", target_os = "cygwin", target_os = "freebsd", target_os = "linux", target_os = "netbsd"))'.dependencies] -uucore = { workspace = true, features = ["utmpx"] } +uucore = { workspace = true, features = ["utmpx", "systemd-logind"] } [target.'cfg(any(target_vendor = "apple", target_os = "cygwin", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "openbsd"))'.dependencies] clap = { workspace = true } @@ -29,9 +29,6 @@ uucore = { workspace = true, features = [] } [target.'cfg(target_os = "openbsd")'.dependencies] utmp-classic = { workspace = true } -[features] -systemd_logind = ["uucore/systemd_logind"] - [lints] workspace = true diff --git a/src/uu/who/Cargo.toml b/src/uu/who/Cargo.toml index 1e8d2d2298d..5412777ec67 100644 --- a/src/uu/who/Cargo.toml +++ b/src/uu/who/Cargo.toml @@ -15,17 +15,13 @@ readme.workspace = true [lib] path = "src/who.rs" -test = false doctest = false [dependencies] clap = { workspace = true } fluent = { workspace = true } rustix = { workspace = true, features = ["fs", "termios"] } -uucore = { workspace = true, features = ["utmpx"] } - -[features] -systemd_logind = ["uucore/systemd_logind"] +uucore = { workspace = true, features = ["utmpx", "systemd-logind"] } [lints] workspace = true diff --git a/src/uu/who/src/platform/unix.rs b/src/uu/who/src/platform/unix.rs index 9203da6eb6e..b117cb414dc 100644 --- a/src/uu/who/src/platform/unix.rs +++ b/src/uu/who/src/platform/unix.rs @@ -217,9 +217,48 @@ fn format_timestamp(ut: &UtmpxRecord) -> String { ) .unwrap() }; + #[cfg(target_os = "linux")] + if let UtmpxRecord::Systemd(systemd) = ut { + return systemd + .try_login_time() + .map_or_else(|| "?".into(), |time| time.format(&pattern).unwrap()); + } ut.login_time().format(&pattern).unwrap() } +fn format_pid(ut: &UtmpxRecord) -> String { + #[cfg(target_os = "linux")] + if let UtmpxRecord::Systemd(systemd) = ut { + return systemd + .try_pid() + .map_or_else(|| "?".into(), |pid| pid.to_string()); + } + ut.pid().to_string() +} + +#[cfg(all(test, target_os = "linux"))] +mod logind_tests { + use super::*; + use uucore::systemd_logind::{SystemdLoginRecord, SystemdRecordType, SystemdUtmpxCompat}; + + #[test] + fn unavailable_time_and_pid_are_question_marks() { + let record = UtmpxRecord::Systemd(SystemdUtmpxCompat::new(SystemdLoginRecord { + user: "user".into(), + session_id: "legacy".into(), + seat_or_tty: "pts/test".into(), + raw_device: "pts/test".into(), + host: String::new(), + login_time: std::time::UNIX_EPOCH, + pid: 0, + session_leader_pid: 0, + record_type: SystemdRecordType::UserProcess, + })); + assert_eq!(format_timestamp(&record), "?"); + assert_eq!(format_pid(&record), "?"); + } +} + fn current_tty() -> String { rustix::termios::ttyname(std::io::stdin(), Vec::with_capacity(16)) .map(|s| s.to_string_lossy().trim_start_matches("/dev/").to_owned()) @@ -301,7 +340,7 @@ impl Who { fn emit_event(&self, ut: &UtmpxRecord, event: Event) -> UResult<()> { let time = format_timestamp(ut); - let pid = format!("{}", ut.pid()); + let pid = format_pid(ut); let note = translate!("who-login-id", "id" => ut.terminal_suffix()); // Held outside the match so the borrows below outlive it. @@ -420,7 +459,7 @@ impl Who { line: &ut.tty_device(), time: &format_timestamp(ut), idle: &idle, - pid: &format!("{}", ut.pid()), + pid: &format_pid(ut), note: ¬e, exit: "", })?; diff --git a/src/uucore/Cargo.toml b/src/uucore/Cargo.toml index 0977333fd4c..5635ac90c57 100644 --- a/src/uucore/Cargo.toml +++ b/src/uucore/Cargo.toml @@ -89,6 +89,7 @@ thiserror = { workspace = true } cfg_aliases = { workspace = true } [dev-dependencies] +rstest = { workspace = true } tempfile = { workspace = true } temp-env = { workspace = true } @@ -120,6 +121,7 @@ time = { workspace = true, optional = true, features = [ walkdir = { workspace = true, optional = true } [target.'cfg(target_os = "linux")'.dependencies] +libloading = { workspace = true, optional = true } procfs = { workspace = true, optional = true } [target.'cfg(windows)'.dependencies] @@ -228,7 +230,6 @@ sum = [ "crc-fast", "data-encoding", ] -systemd_logind = ["utmpx", "libc"] # Use OpenSSL (libcrypto) for md5/sha1/sha2-family digests instead of the # pure-Rust crates. This dramatically speeds up checksum utilities on CPUs # without SHA-NI by using OpenSSL's optimized assembly implementations. @@ -236,6 +237,7 @@ openssl = ["dep:openssl"] update-control = ["parser"] utf8 = [] utmpx = ["time", "time/macros", "libc", "dns-lookup"] +systemd-logind = ["utmpx", "dep:libloading"] version-cmp = [] wide = [] tty = [] diff --git a/src/uucore/src/lib/features.rs b/src/uucore/src/lib/features.rs index 8cfa2d52808..2149ce34165 100644 --- a/src/uucore/src/lib/features.rs +++ b/src/uucore/src/lib/features.rs @@ -131,7 +131,7 @@ pub mod selinux; pub mod signals; #[cfg(all(feature = "smack", target_os = "linux"))] pub mod smack; -#[cfg(all(feature = "systemd_logind", target_os = "linux"))] +#[cfg(all(target_os = "linux", feature = "systemd-logind"))] pub mod systemd_logind; #[cfg(all( feature = "utmpx", diff --git a/src/uucore/src/lib/features/systemd_logind.rs b/src/uucore/src/lib/features/systemd_logind.rs index 6e0c91c6543..eb18f45d27d 100644 --- a/src/uucore/src/lib/features/systemd_logind.rs +++ b/src/uucore/src/lib/features/systemd_logind.rs @@ -9,8 +9,9 @@ //! //! This module provides systemd-logind based implementation for reading //! login records as an alternative to traditional utmp/utmpx files. -//! When the systemd-logind feature is enabled and systemd is available, -//! this will be used instead of traditional utmp files. +//! On Linux, this is used when the traditional utmp file is unavailable or +//! empty. If systemd-logind is unavailable, callers fall back to the traditional +//! implementation. use core::ffi::CStr; use std::mem::MaybeUninit; @@ -18,23 +19,106 @@ use std::time::{SystemTime, UNIX_EPOCH}; use crate::error::{UResult, USimpleError}; -/// FFI bindings for libsystemd login and D-Bus functions +/// Dynamically loaded FFI bindings for libsystemd login functions. mod ffi { use core::ffi::{c_char, c_int, c_uint}; + use libloading::Library; + use std::path::Path; + + type SdGetSessions = unsafe extern "C" fn(*mut *mut *mut c_char) -> c_int; + type SdSessionGetUid = unsafe extern "C" fn(*const c_char, *mut c_uint) -> c_int; + type SdSessionGetStartTime = unsafe extern "C" fn(*const c_char, *mut u64) -> c_int; + type SdSessionGetLeader = unsafe extern "C" fn(*const c_char, *mut c_int) -> c_int; + type SdSessionGetString = unsafe extern "C" fn(*const c_char, *mut *mut c_char) -> c_int; + + pub(super) struct SystemdLoginApi { + // The library must remain loaded while any of these function pointers are used. + _library: Library, + pub(super) sd_get_sessions: SdGetSessions, + pub(super) sd_session_get_uid: SdSessionGetUid, + pub(super) sd_session_get_start_time: Option, + pub(super) sd_session_get_leader: Option, + pub(super) sd_session_get_tty: SdSessionGetString, + pub(super) sd_session_get_remote_host: SdSessionGetString, + pub(super) sd_session_get_display: SdSessionGetString, + pub(super) sd_session_get_seat: SdSessionGetString, + } + + impl SystemdLoginApi { + pub(super) fn load() -> Result> { + Self::load_from(Path::new("libsystemd.so.0")) + } + + fn load_from(path: &Path) -> Result> { + // SAFETY: The loaded symbols use the signatures declared by libsystemd's + // stable public API. The Library is retained in Self for at least as long + // as the copied function pointers can be called. + unsafe { + let library = Library::new(path)?; + let sd_get_sessions = *library.get::(b"sd_get_sessions\0")?; + let sd_session_get_uid = + *library.get::(b"sd_session_get_uid\0")?; + // This function was added in systemd 254; older libraries can + // still provide the rest of the session information. + let sd_session_get_start_time = library + .get::(b"sd_session_get_start_time\0") + .ok() + .map(|symbol| *symbol); + let sd_session_get_leader = library + .get::(b"sd_session_get_leader\0") + .ok() + .map(|symbol| *symbol); + let sd_session_get_tty = + *library.get::(b"sd_session_get_tty\0")?; + let sd_session_get_remote_host = + *library.get::(b"sd_session_get_remote_host\0")?; + let sd_session_get_display = + *library.get::(b"sd_session_get_display\0")?; + let sd_session_get_seat = + *library.get::(b"sd_session_get_seat\0")?; + + Ok(Self { + _library: library, + sd_get_sessions, + sd_session_get_uid, + sd_session_get_start_time, + sd_session_get_leader, + sd_session_get_tty, + sd_session_get_remote_host, + sd_session_get_display, + sd_session_get_seat, + }) + } + } + } + + #[cfg(test)] + mod tests { + use super::SystemdLoginApi; + use std::path::Path; - #[link(name = "systemd")] - unsafe extern "C" { - pub fn sd_get_sessions(sessions: *mut *mut *mut c_char) -> c_int; - pub fn sd_session_get_uid(session: *const c_char, uid: *mut c_uint) -> c_int; - pub fn sd_session_get_start_time(session: *const c_char, usec: *mut u64) -> c_int; - pub fn sd_session_get_tty(session: *const c_char, tty: *mut *mut c_char) -> c_int; - pub fn sd_session_get_remote_host( - session: *const c_char, - remote_host: *mut *mut c_char, - ) -> c_int; - pub fn sd_session_get_display(session: *const c_char, display: *mut *mut c_char) -> c_int; - pub fn sd_session_get_seat(session: *const c_char, seat: *mut *mut c_char) -> c_int; + #[test] + fn missing_library_is_reported() { + assert!( + SystemdLoginApi::load_from(Path::new("libsystemd-uutils-does-not-exist.so")) + .is_err() + ); + } + #[test] + fn invalid_library_is_reported() { + let library = tempfile::NamedTempFile::new().unwrap(); + assert!(SystemdLoginApi::load_from(library.path()).is_err()); + } + + #[test] + #[cfg(all(target_env = "gnu", not(target_feature = "crt-static")))] + fn missing_login_symbols_are_reported() { + let error = SystemdLoginApi::load_from(Path::new("libc.so.6")) + .err() + .unwrap(); + assert!(error.to_string().contains("sd_get_sessions"), "{error}"); + } } } @@ -47,10 +131,13 @@ mod login { use std::time::SystemTime; /// Get all active sessions - pub fn get_sessions() -> Result, Box> { + pub fn get_sessions( + api: &ffi::SystemdLoginApi, + ) -> Result, Box> { let mut sessions_ptr: *mut *mut c_char = ptr::null_mut(); - let result = unsafe { ffi::sd_get_sessions(&raw mut sessions_ptr) }; + // SAFETY: api retains the library, and sessions_ptr is a writable output. + let result = unsafe { (api.sd_get_sessions)(&raw mut sessions_ptr) }; if result < 0 { return Err(format!("sd_get_sessions failed: {result}").into()); @@ -79,11 +166,15 @@ mod login { } /// Get UID for a session - pub fn get_session_uid(session_id: &str) -> Result> { + pub fn get_session_uid( + api: &ffi::SystemdLoginApi, + session_id: &str, + ) -> Result> { let session_cstring = CString::new(session_id)?; let mut uid: core::ffi::c_uint = 0; - let result = unsafe { ffi::sd_session_get_uid(session_cstring.as_ptr(), &raw mut uid) }; + // SAFETY: api retains the library; the session is NUL-terminated and uid is writable. + let result = unsafe { (api.sd_session_get_uid)(session_cstring.as_ptr(), &raw mut uid) }; if result < 0 { return Err( @@ -95,14 +186,20 @@ mod login { } /// Get start time for a session (in microseconds since Unix epoch) - pub fn get_session_start_time(session_id: &str) -> Result> { + pub fn get_session_start_time( + api: &ffi::SystemdLoginApi, + session_id: &str, + ) -> Result> { + let get_start_time = api + .sd_session_get_start_time + .ok_or("sd_session_get_start_time is unavailable")?; let session_cstring = CString::new(session_id)?; let mut usec: u64 = 0; - let result = - unsafe { ffi::sd_session_get_start_time(session_cstring.as_ptr(), &raw mut usec) }; + // SAFETY: api retains the library; the session is NUL-terminated and usec is writable. + let result = unsafe { get_start_time(session_cstring.as_ptr(), &raw mut usec) }; - if result < 0 { + if result < 0 || usec == 0 { return Err(format!( "sd_session_get_start_time failed for session '{session_id}': {result}", ) @@ -112,6 +209,15 @@ mod login { Ok(usec) } + pub fn get_session_leader(api: &ffi::SystemdLoginApi, session_id: &str) -> Option { + let get_leader = api.sd_session_get_leader?; + let session = CString::new(session_id).ok()?; + let mut leader = 0; + // SAFETY: session is NUL-terminated and leader is a writable pid_t. + let result = unsafe { get_leader(session.as_ptr(), &raw mut leader) }; + (result >= 0 && leader > 0).then_some(leader as u32) + } + /// Read a string property of a session, such as its TTY or seat, with one of /// the `sd_session_get_*` getters. An error or an unset property gives an /// empty string. @@ -170,6 +276,8 @@ pub struct SystemdLoginRecord { pub seat_or_tty: String, pub raw_device: String, pub host: String, + /// The Unix epoch represents an unavailable session timestamp. + /// Use [`Self::try_login_time_offset`] to distinguish missing values. pub login_time: SystemTime, pub pid: u32, pub session_leader_pid: u32, @@ -190,60 +298,61 @@ impl SystemdLoginRecord { } /// Get login time as [`time::OffsetDateTime`] compatible with utmpx - pub fn login_time_offset(&self) -> time::OffsetDateTime { - let duration = self - .login_time - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - let ts_nanos: i128 = (duration.as_nanos()).try_into().unwrap_or(0); + pub fn try_login_time_offset(&self) -> Option { + let duration = self.login_time.duration_since(UNIX_EPOCH).ok()?; + if duration.is_zero() { + return None; + } + let ts_nanos: i128 = duration.as_nanos().try_into().ok()?; + let datetime = time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos).ok()?; let local_offset = time::OffsetDateTime::now_local() .map_or_else(|_| time::UtcOffset::UTC, time::OffsetDateTime::offset); - time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos) - .unwrap_or_else(|_| { - time::OffsetDateTime::now_local() - .unwrap_or_else(|_| time::OffsetDateTime::now_utc()) - }) - .to_offset(local_offset) + Some(datetime.to_offset(local_offset)) + } + + /// Get the login time, or the Unix epoch when it is unavailable. + /// Use [`Self::try_login_time_offset`] when displaying timestamps. + pub fn login_time_offset(&self) -> time::OffsetDateTime { + self.try_login_time_offset() + .unwrap_or(time::OffsetDateTime::UNIX_EPOCH) } } /// Read login records from systemd-logind using safe wrapper functions /// This matches the approach used by GNU coreutils `read_utmp_from_systemd()` pub fn read_login_records() -> UResult> { - let mut records = Vec::new(); - - // Add boot time record first - if let Ok(boot_time) = login::get_boot_time() { - let boot_record = SystemdLoginRecord { - user: "reboot".to_string(), - session_id: "boot".to_string(), - seat_or_tty: "~".to_string(), // Traditional boot time indicator - raw_device: String::new(), - host: String::new(), - login_time: boot_time, - pid: 0, - session_leader_pid: 0, - record_type: SystemdRecordType::BootTime, - }; - records.push(boot_record); - } + let api = ffi::SystemdLoginApi::load() + .map_err(|e| USimpleError::new(1, format!("Failed to load libsystemd: {e}")))?; + read_login_records_with_api(&api) +} - // Get all active sessions using safe wrapper - let mut sessions = login::get_sessions() - .map_err(|e| USimpleError::new(1, format!("Failed to get systemd sessions: {e}")))?; +#[derive(Clone, Default)] +struct SessionInfo { + user: String, + tty: String, + seat: String, + remote_host: String, + display: String, + start_time: Option, + leader: Option, +} - // Sort sessions consistently for reproducible output (reverse for TTY sessions first) - sessions.sort(); - sessions.reverse(); +/// The safe boundary between sd-login and record assembly. +trait LoginApi { + fn sessions(&self) -> UResult>; + fn session(&self, id: &str) -> Option; +} - // Iterate through all sessions - for session_id in sessions { - // Get session UID using safe wrapper - let Ok(uid) = login::get_session_uid(&session_id) else { - continue; - }; +impl LoginApi for ffi::SystemdLoginApi { + fn sessions(&self) -> UResult> { + login::get_sessions(self) + .map_err(|e| USimpleError::new(1, format!("Failed to get systemd sessions: {e}"))) + } - // Get username from UID + fn session(&self, session_id: &str) -> Option { + let uid = login::get_session_uid(self, session_id).ok()?; + // SAFETY: passwd and result are writable outputs, and buf remains alive + // while getpwuid_r fills them. Only a successful, non-NULL result is read. let user = unsafe { let mut passwd = MaybeUninit::::uninit(); @@ -277,16 +386,62 @@ pub fn read_login_records() -> UResult> { } }; - // Get start time using safe wrapper, fallback to epoch if unavailable - let start_time = login::get_session_start_time(&session_id).map_or(UNIX_EPOCH, |usec| { - UNIX_EPOCH + std::time::Duration::from_micros(usec) - }); + Some(SessionInfo { + user, + tty: login::get_session_string(session_id, self.sd_session_get_tty), + seat: login::get_session_string(session_id, self.sd_session_get_seat), + remote_host: login::get_session_string(session_id, self.sd_session_get_remote_host), + display: login::get_session_string(session_id, self.sd_session_get_display), + start_time: login::get_session_start_time(self, session_id).ok(), + leader: login::get_session_leader(self, session_id), + }) + } +} + +fn read_login_records_with_api(api: &impl LoginApi) -> UResult> { + let mut records = Vec::new(); + + // Add boot time record first + if let Ok(boot_time) = login::get_boot_time() { + let boot_record = SystemdLoginRecord { + user: "reboot".to_string(), + session_id: "boot".to_string(), + seat_or_tty: "~".to_string(), // Traditional boot time indicator + raw_device: String::new(), + host: String::new(), + login_time: boot_time, + pid: 0, + session_leader_pid: 0, + record_type: SystemdRecordType::BootTime, + }; + records.push(boot_record); + } + + // Get all active sessions using safe wrapper + let mut sessions = api.sessions()?; - // Get TTY using safe wrapper - let mut tty = login::get_session_string(&session_id, ffi::sd_session_get_tty); + // Sort sessions consistently for reproducible output (reverse for TTY sessions first) + sessions.sort(); + sessions.reverse(); - // Get seat using safe wrapper - let mut seat = login::get_session_string(&session_id, ffi::sd_session_get_seat); + // Iterate through all sessions + for session_id in sessions { + let Some(SessionInfo { + user, + mut tty, + mut seat, + remote_host, + display, + start_time, + leader, + }) = api.session(&session_id) + else { + continue; + }; + let start_time = start_time + .filter(|usec| *usec > 0) + .and_then(|usec| UNIX_EPOCH.checked_add(std::time::Duration::from_micros(usec))) + .unwrap_or(UNIX_EPOCH); // Strip any existing prefixes from systemd values (if any) if tty.starts_with('?') { @@ -296,12 +451,6 @@ pub fn read_login_records() -> UResult> { seat = seat[1..].to_string(); } - // Get remote host using safe wrapper - let remote_host = login::get_session_string(&session_id, ffi::sd_session_get_remote_host); - - // Get display using safe wrapper (for GUI sessions) - let display = login::get_session_string(&session_id, ffi::sd_session_get_display); - // Determine host (use remote_host if available) // If host is local (non-remote) we use display, let host = if remote_host.is_empty() { @@ -333,8 +482,8 @@ pub fn read_login_records() -> UResult> { raw_device, host, login_time: start_time, - pid: 0, // systemd doesn't directly provide session leader PID in this context - session_leader_pid: 0, + pid: leader.unwrap_or(0), + session_leader_pid: leader.unwrap_or(0), record_type: SystemdRecordType::UserProcess, } }; @@ -403,8 +552,13 @@ impl SystemdUtmpxCompat { } /// A.K.A. `ut.ut_pid` + pub fn try_pid(&self) -> Option { + i32::try_from(self.record.pid).ok().filter(|pid| *pid > 0) + } + + /// Session leader PID, or zero when unavailable. pub fn pid(&self) -> i32 { - self.record.pid as i32 + self.try_pid().unwrap_or_default() } /// A.K.A. `ut.ut_id` @@ -438,6 +592,11 @@ impl SystemdUtmpxCompat { self.record.login_time_offset() } + /// Login time, or None when sd-login could not provide one. + pub fn try_login_time(&self) -> Option { + self.record.try_login_time_offset() + } + /// Exit status (not available from systemd) pub fn exit_status(&self) -> (i16, i16) { (0, 0) // Not available from systemd @@ -450,8 +609,6 @@ impl SystemdUtmpxCompat { /// Canonical host name pub fn canon_host(&self) -> String { - // Simple implementation - just return the host as-is - // Could be enhanced with DNS lookup like the original self.record.host.clone() } } @@ -526,112 +683,5 @@ impl Iterator for SystemdUtmpxIter { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_empty_iterator() { - let mut iter = SystemdUtmpxIter::empty(); - - assert_eq!(iter.len(), 0); - assert!(iter.is_empty()); - assert!(iter.next().is_none()); - assert!(iter.next_record().is_none()); - } - - #[test] - fn test_iterator_with_mock_data() { - // Create iterator with mock records - let mock_records = vec![ - SystemdLoginRecord { - session_id: "session1".to_string(), - user: "user1".to_string(), - seat_or_tty: "tty1".to_string(), - raw_device: "tty1".to_string(), - host: "host1".to_string(), - login_time: UNIX_EPOCH, - pid: 1234, - session_leader_pid: 1234, - record_type: SystemdRecordType::UserProcess, - }, - SystemdLoginRecord { - session_id: "session2".to_string(), - user: "user2".to_string(), - seat_or_tty: "pts/0".to_string(), - raw_device: "pts/0".to_string(), - host: "host2".to_string(), - login_time: UNIX_EPOCH, - pid: 5678, - session_leader_pid: 5678, - record_type: SystemdRecordType::UserProcess, - }, - ]; - - let mut iter = SystemdUtmpxIter { - records: mock_records, - current_index: 0, - }; - - assert_eq!(iter.len(), 2); - assert!(!iter.is_empty()); - - // Test iterator behavior - let first = iter.next(); - assert!(first.is_some()); - - let second = iter.next(); - assert!(second.is_some()); - - let third = iter.next(); - assert!(third.is_none()); - - // Iterator should be exhausted - assert!(iter.next().is_none()); - } - - #[test] - fn test_get_all_records() { - let mock_records = vec![SystemdLoginRecord { - session_id: "session1".to_string(), - user: "user1".to_string(), - seat_or_tty: "tty1".to_string(), - raw_device: "tty1".to_string(), - host: "host1".to_string(), - login_time: UNIX_EPOCH, - pid: 1234, - session_leader_pid: 1234, - record_type: SystemdRecordType::UserProcess, - }]; - - let iter = SystemdUtmpxIter { - records: mock_records, - current_index: 0, - }; - - let all_records = iter.get_all_records(); - assert_eq!(all_records.len(), 1); - } - - #[test] - fn test_systemd_record_conversion() { - // Test that SystemdLoginRecord converts correctly to SystemdUtmpxCompat - let record = SystemdLoginRecord { - session_id: "c1".to_string(), - user: "testuser".to_string(), - seat_or_tty: "seat0".to_string(), - raw_device: "seat0".to_string(), - host: "localhost".to_string(), - login_time: UNIX_EPOCH + std::time::Duration::from_secs(1000), - pid: 9999, - session_leader_pid: 9999, - record_type: SystemdRecordType::UserProcess, - }; - - let compat = SystemdUtmpxCompat::new(record); - - // Test the actual conversion logic - assert_eq!(compat.user(), "testuser"); - assert_eq!(compat.tty_device().as_str(), "seat0"); - assert_eq!(compat.host(), "localhost"); - } -} +#[path = "systemd_logind/tests.rs"] +mod tests; diff --git a/src/uucore/src/lib/features/systemd_logind/tests.rs b/src/uucore/src/lib/features/systemd_logind/tests.rs new file mode 100644 index 00000000000..db7913555aa --- /dev/null +++ b/src/uucore/src/lib/features/systemd_logind/tests.rs @@ -0,0 +1,237 @@ +// This file is part of the uutils coreutils package. +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +use super::*; + +#[derive(Default)] +struct Login { + records: Vec<(String, SessionInfo)>, + fail: bool, +} + +impl Login { + fn new(time: Option, leader: Option) -> Self { + Self { + records: vec![( + "legacy".into(), + SessionInfo { + user: "user".into(), + tty: "pts/test".into(), + remote_host: "alias.test".into(), + start_time: time, + leader, + ..SessionInfo::default() + }, + )], + ..Self::default() + } + } +} + +impl LoginApi for Login { + fn sessions(&self) -> UResult> { + if self.fail { + return Err(USimpleError::new(1, "session enumeration failed")); + } + Ok(self.records.iter().map(|(id, _)| id.clone()).collect()) + } + + fn session(&self, id: &str) -> Option { + self.records + .iter() + .find(|(name, _)| name == id) + .map(|(_, info)| info.clone()) + } +} + +#[test] +fn enumeration_errors_are_propagated() { + let login = Login { + fail: true, + ..Login::default() + }; + assert!(read_login_records_with_api(&login).is_err()); +} + +#[test] +fn sessions_without_a_terminal_are_skipped() { + let mut login = Login::new(None, None); + login.records[0].1.tty.clear(); + let records = read_login_records_with_api(&login).unwrap(); + assert!(!records.iter().any(SystemdLoginRecord::is_user_process)); +} + +#[test] +fn seat_and_tty_keep_their_metadata() { + let mut login = Login::new(Some(1_700_000_000_000_000), Some(31337)); + login.records[0].1.seat = "?seat0".into(); + login.records[0].1.tty = "?tty1".into(); + let records = read_login_records_with_api(&login) + .unwrap() + .into_iter() + .filter(SystemdLoginRecord::is_user_process) + .collect::>(); + assert_eq!(records.len(), 2); + assert_eq!(records[0].seat_or_tty, "?seat0"); + assert_eq!(records[1].seat_or_tty, "*tty1"); + assert!( + records + .iter() + .all(|r| r.pid == 31337 && r.host == "alias.test") + ); +} + +#[rstest::rstest] +#[case(Some(1_700_000_000_000_000), Some(31337), true, 31337)] +#[case(None, None, false, 0)] +#[case(Some(0), None, false, 0)] +fn session_metadata_is_preserved( + #[case] time: Option, + #[case] leader: Option, + #[case] known_time: bool, + #[case] pid: u32, +) { + let login = Login::new(time, leader); + let records = read_login_records_with_api(&login).unwrap(); + let record = records.iter().find(|r| r.is_user_process()).unwrap(); + assert_eq!(record.login_time != UNIX_EPOCH, known_time); + assert_eq!(record.pid, pid); + assert_eq!(record.session_leader_pid, pid); +} + +#[test] +fn missing_metadata_preserves_legacy_api_types() { + let record = SystemdLoginRecord { + session_id: "missing".into(), + user: "user".into(), + seat_or_tty: "pts/0".into(), + raw_device: "pts/0".into(), + host: String::new(), + login_time: UNIX_EPOCH, + pid: 0, + session_leader_pid: 0, + record_type: SystemdRecordType::UserProcess, + }; + let timestamp: SystemTime = record.login_time; + assert_eq!(timestamp, UNIX_EPOCH); + let offset: time::OffsetDateTime = record.login_time_offset(); + assert_eq!(offset, time::OffsetDateTime::UNIX_EPOCH); + assert_eq!(record.try_login_time_offset(), None); + let compat = SystemdUtmpxCompat::new(record); + let pid: i32 = compat.pid(); + let timestamp: time::OffsetDateTime = compat.login_time(); + let host: String = compat.canon_host(); + assert_eq!(pid, 0); + assert_eq!(timestamp, time::OffsetDateTime::UNIX_EPOCH); + assert!(host.is_empty()); + assert_eq!(compat.try_pid(), None); + assert_eq!(compat.try_login_time(), None); +} + +#[test] +fn test_empty_iterator() { + let mut iter = SystemdUtmpxIter::empty(); + + assert_eq!(iter.len(), 0); + assert!(iter.is_empty()); + assert!(iter.next().is_none()); + assert!(iter.next_record().is_none()); +} + +#[test] +fn test_iterator_with_mock_data() { + // Create iterator with mock records + let mock_records = vec![ + SystemdLoginRecord { + session_id: "session1".to_string(), + user: "user1".to_string(), + seat_or_tty: "tty1".to_string(), + raw_device: "tty1".to_string(), + host: "host1".to_string(), + login_time: UNIX_EPOCH, + pid: 1234, + session_leader_pid: 1234, + record_type: SystemdRecordType::UserProcess, + }, + SystemdLoginRecord { + session_id: "session2".to_string(), + user: "user2".to_string(), + seat_or_tty: "pts/0".to_string(), + raw_device: "pts/0".to_string(), + host: "host2".to_string(), + login_time: UNIX_EPOCH, + pid: 5678, + session_leader_pid: 5678, + record_type: SystemdRecordType::UserProcess, + }, + ]; + + let mut iter = SystemdUtmpxIter { + records: mock_records, + current_index: 0, + }; + + assert_eq!(iter.len(), 2); + assert!(!iter.is_empty()); + + // Test iterator behavior + let first = iter.next(); + assert!(first.is_some()); + + let second = iter.next(); + assert!(second.is_some()); + + let third = iter.next(); + assert!(third.is_none()); + + // Iterator should be exhausted + assert!(iter.next().is_none()); +} + +#[test] +fn test_get_all_records() { + let mock_records = vec![SystemdLoginRecord { + session_id: "session1".to_string(), + user: "user1".to_string(), + seat_or_tty: "tty1".to_string(), + raw_device: "tty1".to_string(), + host: "host1".to_string(), + login_time: UNIX_EPOCH, + pid: 1234, + session_leader_pid: 1234, + record_type: SystemdRecordType::UserProcess, + }]; + + let iter = SystemdUtmpxIter { + records: mock_records, + current_index: 0, + }; + + let all_records = iter.get_all_records(); + assert_eq!(all_records.len(), 1); +} + +#[test] +fn test_systemd_record_conversion() { + // Test that SystemdLoginRecord converts correctly to SystemdUtmpxCompat + let record = SystemdLoginRecord { + session_id: "c1".to_string(), + user: "testuser".to_string(), + seat_or_tty: "seat0".to_string(), + raw_device: "seat0".to_string(), + host: "localhost".to_string(), + login_time: UNIX_EPOCH + std::time::Duration::from_secs(1000), + pid: 9999, + session_leader_pid: 9999, + record_type: SystemdRecordType::UserProcess, + }; + + let compat = SystemdUtmpxCompat::new(record); + + // Test the actual conversion logic + assert_eq!(compat.user(), "testuser"); + assert_eq!(compat.tty_device().as_str(), "seat0"); + assert_eq!(compat.host(), "localhost"); +} diff --git a/src/uucore/src/lib/features/utmpx.rs b/src/uucore/src/lib/features/utmpx.rs index f72bae1b5f2..c6e2e5993f5 100644 --- a/src/uucore/src/lib/features/utmpx.rs +++ b/src/uucore/src/lib/features/utmpx.rs @@ -41,7 +41,7 @@ use std::path::Path; use std::ptr; use std::sync::{Mutex, MutexGuard}; -#[cfg(all(feature = "systemd_logind", target_os = "linux"))] +#[cfg(all(feature = "systemd-logind", target_os = "linux"))] use crate::features::systemd_logind; pub use self::ut::*; @@ -291,142 +291,112 @@ impl Utmpx { Ok(host) } - /// Iterate through all the utmp records. - /// - /// This will use the default location, or the path [`Utmpx::iter_all_records_from`] - /// was most recently called with. - /// - /// On systems with systemd-logind feature enabled at compile time, - /// this will use systemd-logind instead of traditional utmp files. - /// - /// Only one instance of [`UtmpxIter`] may be active at a time. This - /// function will block as long as one is still active. Beware! + /// Read records from the most recently selected path, or the default file. + /// Only one iterator may be active at a time. pub fn iter_all_records() -> UtmpxIter { - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - { - // Use systemd-logind instead of traditional utmp when feature is enabled - UtmpxIter::new_systemd() - } - - #[cfg(not(all(feature = "systemd_logind", target_os = "linux")))] - { - let iter = UtmpxIter::new(); - unsafe { - // This can technically fail, and it would be nice to detect that, - // but it doesn't return anything so we'd have to do nasty things - // with errno. - #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] - setutxent(); - } - iter - } + UtmpxIter::new(None) } - /// Iterate through all the utmp records from a specific file. - /// - /// No failure is reported or detected. - /// - /// This function affects subsequent calls to [`Utmpx::iter_all_records`]. - /// - /// On systems with systemd-logind feature enabled at compile time, - /// if the path matches the default utmp file, this will use systemd-logind - /// instead of traditional utmp files. - /// - /// The same caveats as for [`Utmpx::iter_all_records`] apply. + /// Select a login file for this and subsequent iterators. + /// Linux falls back to logind only when the default file has no complete record. pub fn iter_all_records_from>(path: P) -> UtmpxIter { - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - { - // Use systemd-logind for default utmp file when feature is enabled - if path.as_ref() == Path::new(DEFAULT_FILE) { - return UtmpxIter::new_systemd(); - } - } - - let iter = UtmpxIter::new(); - let path = CString::new(path.as_ref().as_os_str().as_bytes()).unwrap(); - unsafe { - #[cfg(target_os = "freebsd")] - setutxdb(libc::UTXDB_ACTIVE, path.as_ptr()); - - // In glibc, utmpxname() only fails if there's not enough memory - // to copy the string. - // Solaris returns 1 on success instead of 0. Supposedly there also - // exist systems where it returns void. - // GNU who on Debian seems to output nothing if an invalid filename - // is specified, no warning or anything. - // So this function is pretty crazy and we don't try to detect errors. - // Not much we can do besides pray. - #[cfg(not(target_os = "freebsd"))] - #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] - utmpxname(path.as_ptr()); - - #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] - setutxent(); - } - iter + UtmpxIter::new(Some(path.as_ref())) } } -// On some systems these functions are not thread-safe. On others they're -// thread-local. Therefore we use a mutex to allow only one guard to exist at -// a time, and make sure UtmpxIter cannot be sent across threads. -// -// I believe the only technical memory unsafety that could happen is a data -// race while copying the data out of the pointer returned by getutxent(), but -// ordinary race conditions are also very much possible. -static LOCK: Mutex<()> = Mutex::new(()); +// Serialize libc's utmp state and track whether its selected path is DEFAULT_FILE. +// The iterator stays on its creating thread because that state may be thread-local. +static LOCK: Mutex = Mutex::new(true); + +#[cfg(all(target_os = "linux", feature = "systemd-logind"))] +fn has_traditional_records(path: &Path) -> bool { + // musl's utmp functions are stubs, even for populated files. + #[cfg(target_env = "musl")] + { + let _ = path; + false + } + #[cfg(not(target_env = "musl"))] + { + use std::os::unix::fs::OpenOptionsExt; + + // Probe readability without waiting for a FIFO writer. libc still reads + // the records and handles their locking. + std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(path) + .and_then(|file| file.metadata()) + .is_ok_and(|metadata| metadata.is_file() && metadata.len() >= size_of::() as u64) + } +} /// Iterator of login records pub struct UtmpxIter { - #[allow(dead_code)] - guard: MutexGuard<'static, ()>, - /// Ensure [`UtmpxIter`] is !Send. Technically redundant because [`MutexGuard`] - /// is also !Send. + _guard: MutexGuard<'static, bool>, + /// Keep the iterator on the thread that accesses libc's utmp state. phantom: PhantomData>, - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] systemd_iter: Option, } impl UtmpxIter { - fn new() -> Self { - // PoisonErrors can safely be ignored - let guard = LOCK + fn new(path: Option<&Path>) -> Self { + let mut guard = LOCK .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - Self { - guard, - phantom: PhantomData, - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - systemd_iter: None, + if let Some(path) = path { + let filename = CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: LOCK protects libc's selected file, and filename is NUL-terminated. + unsafe { + #[cfg(target_os = "freebsd")] + setutxdb(libc::UTXDB_ACTIVE, filename.as_ptr()); + #[cfg(not(target_os = "freebsd"))] + #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] + utmpxname(filename.as_ptr()); + } + *guard = path == Path::new(DEFAULT_FILE); } - } - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - fn new_systemd() -> Self { - // PoisonErrors can safely be ignored - let guard = LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let systemd_iter = match systemd_logind::SystemdUtmpxIter::new() { - Ok(iter) => iter, - Err(_) => { - // Like GNU coreutils: graceful degradation, not fallback to traditional utmp - // Return empty iterator rather than falling back (GNU coreutils also returns 0 when /var/run/utmp is not present, so we don't need to propagate the error here) - systemd_logind::SystemdUtmpxIter::empty() + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + let systemd_iter = { + if *guard && !has_traditional_records(Path::new(DEFAULT_FILE)) { + systemd_logind::SystemdUtmpxIter::new().ok() + } else { + None } }; + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + if let Some(systemd_iter) = systemd_iter { + return Self { + _guard: guard, + phantom: PhantomData, + systemd_iter: Some(systemd_iter), + }; + } + + // SAFETY: The iterator holds LOCK while resetting libc's utmp cursor. + unsafe { + #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] + setutxent(); + } Self { - guard, + _guard: guard, phantom: PhantomData, - systemd_iter: Some(systemd_iter), + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + systemd_iter: None, } } } +#[cfg(all(test, target_os = "linux", feature = "systemd-logind"))] +#[path = "utmpx/tests.rs"] +mod tests; + /// Wrapper type that can hold either traditional utmpx records or systemd records pub enum UtmpxRecord { Traditional(Box), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Systemd(systemd_logind::SystemdUtmpxCompat), } @@ -435,7 +405,7 @@ impl UtmpxRecord { pub fn record_type(&self) -> i16 { match self { Self::Traditional(utmpx) => utmpx.record_type(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.record_type(), } } @@ -444,7 +414,7 @@ impl UtmpxRecord { pub fn pid(&self) -> i32 { match self { Self::Traditional(utmpx) => utmpx.pid(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.pid(), } } @@ -453,7 +423,7 @@ impl UtmpxRecord { pub fn terminal_suffix(&self) -> String { match self { Self::Traditional(utmpx) => utmpx.terminal_suffix(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.terminal_suffix(), } } @@ -462,7 +432,7 @@ impl UtmpxRecord { pub fn user(&self) -> String { match self { Self::Traditional(utmpx) => utmpx.user(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.user(), } } @@ -471,7 +441,7 @@ impl UtmpxRecord { pub fn host(&self) -> String { match self { Self::Traditional(utmpx) => utmpx.host(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.host(), } } @@ -480,7 +450,7 @@ impl UtmpxRecord { pub fn tty_device(&self) -> String { match self { Self::Traditional(utmpx) => utmpx.tty_device(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.tty_device(), } } @@ -489,7 +459,7 @@ impl UtmpxRecord { pub fn login_time(&self) -> time::OffsetDateTime { match self { Self::Traditional(utmpx) => utmpx.login_time(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.login_time(), } } @@ -500,7 +470,7 @@ impl UtmpxRecord { pub fn exit_status(&self) -> (i16, i16) { match self { Self::Traditional(utmpx) => utmpx.exit_status(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.exit_status(), } } @@ -509,7 +479,7 @@ impl UtmpxRecord { pub fn is_user_process(&self) -> bool { match self { Self::Traditional(utmpx) => utmpx.is_user_process(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => systemd.is_user_process(), } } @@ -518,7 +488,7 @@ impl UtmpxRecord { pub fn canon_host(&self) -> IOResult { match self { Self::Traditional(utmpx) => utmpx.canon_host(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] Self::Systemd(systemd) => Ok(systemd.canon_host()), } } @@ -527,7 +497,7 @@ impl UtmpxRecord { impl Iterator for UtmpxIter { type Item = UtmpxRecord; fn next(&mut self) -> Option { - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(feature = "systemd-logind", target_os = "linux"))] { if let Some(ref mut systemd_iter) = self.systemd_iter { // We have a systemd iterator - use it exclusively (never fall back to traditional utmp) diff --git a/src/uucore/src/lib/features/utmpx/tests.rs b/src/uucore/src/lib/features/utmpx/tests.rs new file mode 100644 index 00000000000..3f7235fdd0b --- /dev/null +++ b/src/uucore/src/lib/features/utmpx/tests.rs @@ -0,0 +1,78 @@ +// This file is part of the uutils coreutils package. +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +use super::*; + +#[rstest::rstest] +#[case(0, false)] +#[case(size_of::() - 1, false)] +#[case(size_of::(), true)] +#[case(size_of::() + 1, true)] +#[case(2 * size_of::(), true)] +fn traditional_availability_depends_on_complete_records( + #[case] length: usize, + #[case] available: bool, +) { + let file = tempfile::NamedTempFile::new().unwrap(); + file.as_file().set_len(length as u64).unwrap(); + // Empty records still select the traditional reader; their contents do not + // cause populated utmp files to be replaced by logind sessions. + assert_eq!( + has_traditional_records(file.path()), + available && !cfg!(target_env = "musl") + ); +} + +#[test] +fn missing_files_and_directories_have_no_traditional_records() { + let directory = tempfile::tempdir().unwrap(); + assert!(!has_traditional_records(directory.path())); + assert!(!has_traditional_records(&directory.path().join("missing"))); +} + +#[test] +#[cfg(not(target_env = "musl"))] +fn custom_file_selection_persists_and_uses_libc_records() { + mod support { + include!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/support/utmpx.rs" + )); + } + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + let mut bytes = support::utmpx_record("first"); + bytes.extend(support::utmpx_record("second")); + // A trailing partial record must not prevent reading complete records. + bytes.push(0); + std::fs::write(&path, bytes).unwrap(); + + let users = Utmpx::iter_all_records_from(&path) + .map(|record| record.user()) + .collect::>(); + assert_eq!(users, ["first", "second"]); + let users = Utmpx::iter_all_records() + .map(|record| record.user()) + .collect::>(); + assert_eq!(users, ["first", "second"]); + + // Explicit empty or missing files must not be replaced by logind records. + let empty = directory.path().join("empty"); + std::fs::write(&empty, []).unwrap(); + let mut iter = Utmpx::iter_all_records_from(&empty); + assert!(iter.systemd_iter.is_none()); + assert!(iter.next().is_none()); + drop(iter); + let mut iter = Utmpx::iter_all_records(); + assert!(iter.systemd_iter.is_none()); + assert!(iter.next().is_none()); + drop(iter); + let mut iter = Utmpx::iter_all_records_from(directory.path().join("missing")); + assert!(iter.systemd_iter.is_none()); + assert!(iter.next().is_none()); + drop(iter); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); +} diff --git a/src/uucore/src/lib/lib.rs b/src/uucore/src/lib/lib.rs index dbb055df37d..90dad5f09d0 100644 --- a/src/uucore/src/lib/lib.rs +++ b/src/uucore/src/lib/lib.rs @@ -87,7 +87,7 @@ pub use crate::features::ranges; pub use crate::features::ringbuffer; #[cfg(feature = "sum")] pub use crate::features::sum; -#[cfg(all(feature = "systemd_logind", target_os = "linux"))] +#[cfg(all(target_os = "linux", feature = "systemd-logind"))] pub use crate::features::systemd_logind; #[cfg(feature = "time")] pub use crate::features::time; diff --git a/src/uucore/tests/support/utmpx.rs b/src/uucore/tests/support/utmpx.rs new file mode 100644 index 00000000000..e3650c4a362 --- /dev/null +++ b/src/uucore/tests/support/utmpx.rs @@ -0,0 +1,23 @@ +// This file is part of the uutils coreutils package. +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +use std::mem::offset_of; + +#[cfg(target_env = "gnu")] +use libc::__UT_NAMESIZE as UT_NAMESIZE; +#[cfg(not(target_env = "gnu"))] +use libc::UT_NAMESIZE; + +// Build a native Linux user record for unit and integration tests. +pub(crate) fn utmpx_record(user: &str) -> Vec { + let mut bytes = vec![0; size_of::()]; + let record_type = libc::USER_PROCESS.to_ne_bytes(); + let type_offset = offset_of!(libc::utmpx, ut_type); + bytes[type_offset..type_offset + record_type.len()].copy_from_slice(&record_type); + let user_offset = offset_of!(libc::utmpx, ut_user); + assert!(user.len() <= UT_NAMESIZE); + bytes[user_offset..user_offset + user.len()].copy_from_slice(user.as_bytes()); + bytes +} diff --git a/tests/by-util/test_who.rs b/tests/by-util/test_who.rs index 2456ad0fbb2..645313ef993 100644 --- a/tests/by-util/test_who.rs +++ b/tests/by-util/test_who.rs @@ -9,6 +9,234 @@ use uutests::new_ucmd; use uutests::unwrap_or_return; use uutests::util::{TestScenario, expected_result, gnu_cmd_result}; use uutests::util_name; + +#[cfg(all(target_os = "linux", target_env = "gnu", feature = "test_logind"))] +mod logind { + use std::collections::HashMap; + use std::process::{Child, Command, Stdio}; + use std::time::{Duration, Instant}; + use uutests::util::TestScenario; + + mod support { + include!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/src/uucore/tests/support/utmpx.rs" + )); + } + + fn systemd(command: &str, args: &[&str]) -> String { + let output = Command::new(command) + .args(args) + .env("LC_ALL", "C") + .env("TZ", "UTC") + .output() + .unwrap(); + assert!( + output.status.success(), + "{command}: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + struct Session { + child: Child, + unit: String, + } + + impl Drop for Session { + fn drop(&mut self) { + let _ = Command::new("systemctl") + .args(["stop", &self.unit]) + .output(); + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + #[test] + #[ignore = "requires systemd, PAM, and permission to create a system service; see DEVELOPMENT.md"] + #[uutests::wasi_ignore(NoSubprocessSpawning)] + fn sessions_match_loginctl() { + use uucore::utmpx::time::{UtcOffset, macros::format_description}; + + // The caller supplies an empty utmp in a private mount namespace. + assert!( + std::fs::metadata(uucore::utmpx::DEFAULT_FILE) + .map_or(true, |m| m.is_file() && m.len() == 0) + ); + let unit = format!("uutils-logind-test-{}", std::process::id()); + let user = format!("User={}", rustix::process::getuid().as_raw()); + let child = Command::new("systemd-run") + .args([ + "--quiet", + "--collect", + "--pty", + "--unit", + &unit, + "--property", + &user, + "--property=PAMName=login", + "/bin/sleep", + "60", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let _session = Session { + child, + unit: unit.clone(), + }; + let started = Instant::now(); + let properties = loop { + let leader = systemd( + "systemctl", + &["show", &unit, "--property=MainPID", "--value"], + ); + let sessions = systemd("loginctl", &["list-sessions", "--no-legend", "--no-pager"]); + let found = sessions + .lines() + .filter_map(|line| line.split_whitespace().next()) + .find_map(|id| { + let properties = systemd( + "loginctl", + &[ + "show-session", + id, + "--property=Name", + "--property=TTY", + "--property=Timestamp", + "--property=Leader", + ], + ); + let properties: HashMap<_, _> = properties + .lines() + .filter_map(|line| line.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + (properties + .get("Leader") + .is_some_and(|pid| pid == leader.trim()) + && properties.get("TTY").is_some_and(|tty| !tty.is_empty())) + .then_some(properties) + }); + if let Some(properties) = found { + break properties; + } + assert!( + started.elapsed() < Duration::from_secs(10), + "systemd-run did not create a TTY session" + ); + std::thread::sleep(Duration::from_millis(20)); + }; + let name = &properties["Name"]; + let tty = &properties["TTY"]; + let pid: u32 = properties["Leader"].parse().unwrap(); + let records = uucore::systemd_logind::read_login_records().unwrap(); + let record = records.iter().find(|r| r.raw_device == *tty).unwrap(); + assert_eq!(&record.user, name); + let version = systemd("systemctl", &["--version"]); + let version: u32 = version.split_whitespace().nth(1).unwrap().parse().unwrap(); + let has_metadata = version >= 254; + assert_eq!(record.try_login_time_offset().is_some(), has_metadata); + assert_eq!(record.pid, if has_metadata { pid } else { 0 }); + let displayed = if let Some(timestamp) = record.try_login_time_offset() { + let timestamp = timestamp.to_offset(UtcOffset::UTC); + let expected = timestamp + .format(format_description!( + "[year]-[month]-[day] [hour]:[minute]:[second]" + )) + .unwrap(); + assert!(properties["Timestamp"].contains(&expected)); + timestamp + .format(format_description!( + "[month repr:short] [day padding:space] [hour]:[minute]" + )) + .unwrap() + } else { + "?".to_owned() + }; + let displayed_pid = if has_metadata { + properties["Leader"].as_str() + } else { + "?" + }; + let ts = TestScenario::new("who"); + let who = ts + .ucmd() + .arg("-u") + .env("LC_ALL", "C") + .env("TZ", "UTC") + .succeeds() + .stdout_move_str(); + let row = who + .lines() + .find(|row| row.split_whitespace().nth(1) == Some(tty.as_str())) + .unwrap(); + assert_eq!(row.split_whitespace().next(), Some(name.as_str())); + assert!(row.contains(&displayed)); + assert!(row.split_whitespace().any(|field| field == displayed_pid)); + ts.ccmd("pinky") + .env("LC_ALL", "C") + .env("TZ", "UTC") + .succeeds() + .stdout_contains(tty) + .stdout_contains(&displayed); + let names = ts.ccmd("users").succeeds().stdout_move_str(); + assert!(names.split_whitespace().any(|user| user == name)); + let users = records.iter().filter(|r| r.is_user_process()).count(); + ts.ucmd() + .arg("-q") + .env("LC_ALL", "C") + .succeeds() + .stdout_contains(format!("={users}")); + ts.ccmd("uptime") + .env("LC_ALL", "C") + .succeeds() + .stdout_contains(format!("{users} user")); + + let traditional = support::utmpx_record("traditional"); + let custom = ts.fixtures.plus("custom-utmp"); + std::fs::write(&custom, &traditional).unwrap(); + ts.ucmd() + .arg("-q") + .arg(&custom) + .env("LC_ALL", "C") + .succeeds() + .stdout_is("traditional\n# user=1\n"); + std::fs::write(&custom, []).unwrap(); + ts.ucmd() + .arg("-q") + .arg(&custom) + .env("LC_ALL", "C") + .succeeds() + .stdout_is("\n# users=0\n"); + + // This file is bound inside the private test service's namespace. + std::fs::write(uucore::utmpx::DEFAULT_FILE, &traditional).unwrap(); + ts.ucmd() + .arg("-q") + .env("LC_ALL", "C") + .succeeds() + .stdout_is("traditional\n# user=1\n"); + ts.ccmd("users").succeeds().stdout_is("traditional\n"); + std::fs::write(uucore::utmpx::DEFAULT_FILE, []).unwrap(); + + // A failed runtime load must quietly return to the traditional reader. + let invalid_library = tempfile::tempdir().unwrap(); + std::fs::write(invalid_library.path().join("libsystemd.so.0"), b"invalid").unwrap(); + ts.ucmd() + .arg("-q") + .env("LC_ALL", "C") + .env("LD_LIBRARY_PATH", invalid_library.path()) + .succeeds() + .stdout_is("\n# users=0\n") + .no_stderr(); + } +} + #[test] fn test_invalid_arg() { new_ucmd!().arg("--definitely-invalid").fails_with_code(1); diff --git a/util/test-logind.sh b/util/test-logind.sh new file mode 100755 index 00000000000..43e1812827f --- /dev/null +++ b/util/test-logind.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# This file is part of the uutils coreutils package. +# +# For the full copyright and license information, please view the LICENSE +# file that was distributed with this source code. + +set -euo pipefail + +if [[ $# != 1 || ! -x $1 ]]; then + echo "Usage: bash util/test-logind.sh /absolute/path/to/tests-binary" >&2 + exit 1 +fi + +logind_test_binary=$(realpath "$1") +logind_utmp_fixture=$(mktemp) +trap 'rm -f "$logind_utmp_fixture"' EXIT + +logind_privilege=() +if [[ $EUID != 0 ]]; then + logind_privilege=(sudo) +fi + +# Hide utmp only in the test service's mount namespace, leaving the host's +# records intact. The test creates and stops its own PAM/TTY session. +"${logind_privilege[@]}" systemd-run --quiet --wait --pipe --collect \ + "--property=BindPaths=$logind_utmp_fixture:/run/utmp" \ + "$logind_test_binary" --ignored --exact \ + test_who::logind::sessions_match_loginctl --nocapture From d5ff7fc163092562c55e10bdf6347e3cb3b6fd9a Mon Sep 17 00:00:00 2001 From: mattsu Date: Wed, 18 Nov 2026 22:59:39 +0900 Subject: [PATCH 2/2] utmpx: read logind sessions on static musl --- .../dependencies.wordlist.txt | 2 + .../workspace.wordlist.txt | 1 + Cargo.lock | 151 ++++++++++++++++++ DEVELOPMENT.md | 3 + src/uu/pinky/locales/en-US.ftl | 5 +- src/uu/pinky/locales/fr-FR.ftl | 5 +- src/uu/pinky/src/pinky.rs | 6 +- src/uu/uptime/locales/en-US.ftl | 4 +- src/uu/uptime/locales/fr-FR.ftl | 4 +- src/uu/uptime/src/uptime.rs | 6 +- src/uu/users/locales/en-US.ftl | 4 +- src/uu/users/locales/fr-FR.ftl | 4 +- src/uu/users/src/users.rs | 6 +- src/uu/who/locales/en-US.ftl | 4 +- src/uu/who/locales/fr-FR.ftl | 4 +- src/uu/who/src/who.rs | 6 +- src/uucore/Cargo.toml | 6 +- src/uucore/src/lib/features/systemd_logind.rs | 46 +++--- .../src/lib/features/systemd_logind/bus.rs | 118 ++++++++++++++ tests/by-util/test_who.rs | 33 +++- 20 files changed, 358 insertions(+), 60 deletions(-) create mode 100644 src/uucore/src/lib/features/systemd_logind/bus.rs diff --git a/.vscode/cspell.dictionaries/dependencies.wordlist.txt b/.vscode/cspell.dictionaries/dependencies.wordlist.txt index 185e2bd5611..ef412c1c3f3 100644 --- a/.vscode/cspell.dictionaries/dependencies.wordlist.txt +++ b/.vscode/cspell.dictionaries/dependencies.wordlist.txt @@ -21,4 +21,6 @@ textwrap thiserror walkdir winapi +zbus zerocopy +zruntime diff --git a/.vscode/cspell.dictionaries/workspace.wordlist.txt b/.vscode/cspell.dictionaries/workspace.wordlist.txt index 7a9f3c0aa3b..b8b9ca81025 100644 --- a/.vscode/cspell.dictionaries/workspace.wordlist.txt +++ b/.vscode/cspell.dictionaries/workspace.wordlist.txt @@ -14,6 +14,7 @@ uumain rlimit mkfifo logind +dbus urandom uchild ello diff --git a/Cargo.lock b/Cargo.lock index 242b8aba244..f090149c4d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -107,6 +107,17 @@ version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -908,6 +919,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + [[package]] name = "equivalent" version = "1.0.2" @@ -1072,6 +1089,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + [[package]] name = "futures-task" version = "0.3.34" @@ -1814,6 +1837,15 @@ dependencies = [ "libc", ] +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2065,6 +2097,16 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "os_display" version = "0.1.4" @@ -2609,6 +2651,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "sha1" version = "0.11.0" @@ -2988,6 +3041,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys", +] + [[package]] name = "unic-langid" version = "0.9.6" @@ -4428,6 +4492,8 @@ dependencies = [ "windows-sys", "xattr", "z85", + "zbus", + "zruntime", ] [[package]] @@ -4438,6 +4504,17 @@ dependencies = [ "quote", ] +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + [[package]] name = "uutests" version = "0.13.0" @@ -4696,6 +4773,67 @@ version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6e61e59a957b7ccee15d2049f86e8bfd6f66968fcd88f018950662d9b86e675" +[[package]] +name = "zbus" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4" +dependencies = [ + "async-trait", + "bitflags", + "endi", + "futures-core", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "socket2", + "uds_windows", + "uuid", + "windows-sys", + "winnow", + "zbus_macros", + "zbus_utils", + "zcheapstr", + "zruntime", +] + +[[package]] +name = "zbus_macros" +version = "6.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "zbus_utils", +] + +[[package]] +name = "zbus_utils" +version = "6.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow", +] + +[[package]] +name = "zcheapstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" +dependencies = [ + "serde", +] + [[package]] name = "zerocopy" version = "0.8.57" @@ -4835,3 +4973,16 @@ dependencies = [ "log", "simd-adler32", ] + +[[package]] +name = "zruntime" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72" +dependencies = [ + "futures-core", + "futures-io", + "rustix", + "socket2", + "windows-sys", +] diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index cd8c40a4a9d..5946f926c69 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -160,6 +160,9 @@ loginctl and the four utilities, then stops its session. The Logind CI jobs run this comparison on Ubuntu 22.04 and 24.04 to cover older and newer sd-login APIs. Older libraries cannot supply session timestamps or PIDs; the comparison checks that the utilities show `?` for these fields. +For the static musl backend, build the same test for a static musl target, such +as `--target x86_64-unknown-linux-musl`, and run it on a host with systemd-logind. +The musl test expects D-Bus to supply timestamps and PIDs on both Ubuntu releases. If you also want to test the core utilities: diff --git a/src/uu/pinky/locales/en-US.ftl b/src/uu/pinky/locales/en-US.ftl index eba1148b7c2..b84dbdfe034 100644 --- a/src/uu/pinky/locales/en-US.ftl +++ b/src/uu/pinky/locales/en-US.ftl @@ -1,9 +1,6 @@ pinky-about = Displays brief user information on Unix-based systems pinky-usage = pinky [OPTION]... [USER]... -pinky-about-musl-warning = Warning: When built with musl libc, the `pinky` utility may show incomplete - or missing user information due to musl's stub implementation of `utmpx` - functions. This limitation affects the ability to retrieve accurate details - about logged-in users. +pinky-about-musl-warning = With musl libc, listing logged-in users requires access to systemd-logind. # Long usage description pinky-long-usage-description = A lightweight 'finger' program; print user information. diff --git a/src/uu/pinky/locales/fr-FR.ftl b/src/uu/pinky/locales/fr-FR.ftl index 81a0b3f3ce8..5e4d2ccbffc 100644 --- a/src/uu/pinky/locales/fr-FR.ftl +++ b/src/uu/pinky/locales/fr-FR.ftl @@ -1,9 +1,6 @@ pinky-about = Affiche des informations brèves sur les utilisateurs des systèmes Unix pinky-usage = pinky [OPTION]... [UTILISATEUR]... -pinky-about-musl-warning = Avertissement : Lorsque compilé avec musl libc, l'utilitaire `pinky` peut afficher des - informations utilisateur incomplètes ou manquantes en raison de l'implémentation - factice des fonctions `utmpx` de musl. Cette limitation affecte la capacité - à récupérer des détails précis sur les utilisateurs connectés. +pinky-about-musl-warning = Avec musl libc, l’affichage des utilisateurs connectés nécessite un accès à systemd-logind. # Description d'utilisation longue pinky-long-usage-description = Un programme 'finger' léger ; affiche les informations utilisateur. diff --git a/src/uu/pinky/src/pinky.rs b/src/uu/pinky/src/pinky.rs index 9dea772e479..272907278c4 100644 --- a/src/uu/pinky/src/pinky.rs +++ b/src/uu/pinky/src/pinky.rs @@ -31,7 +31,11 @@ pub fn uu_app() -> Command { #[cfg(not(target_env = "musl"))] let about = translate!("pinky-about"); #[cfg(target_env = "musl")] - let about = translate!("pinky-about") + &translate!("pinky-about-musl-warning"); + let about = format!( + "{}\n\n{}", + translate!("pinky-about"), + translate!("pinky-about-musl-warning") + ); let cmd = Command::new("pinky") .version(uucore::crate_version!()) diff --git a/src/uu/uptime/locales/en-US.ftl b/src/uu/uptime/locales/en-US.ftl index 84704c95196..6d7078ab019 100644 --- a/src/uu/uptime/locales/en-US.ftl +++ b/src/uu/uptime/locales/en-US.ftl @@ -2,9 +2,7 @@ uptime-about = Display the current time, the length of time the system has been the number of users on the system, and the average number of jobs in the run queue over the last 1, 5 and 15 minutes. uptime-usage = uptime [OPTION]... -uptime-about-musl-warning = Warning: When built with musl libc, the `uptime` utility may show '0 users' - due to musl's stub implementation of utmpx functions. Boot time and load averages - are still calculated using alternative mechanisms. +uptime-about-musl-warning = With musl libc, counting logged-in users requires access to systemd-logind. # Help messages uptime-help-since = system up since diff --git a/src/uu/uptime/locales/fr-FR.ftl b/src/uu/uptime/locales/fr-FR.ftl index 895ec08922c..dfdf4313d24 100644 --- a/src/uu/uptime/locales/fr-FR.ftl +++ b/src/uu/uptime/locales/fr-FR.ftl @@ -2,9 +2,7 @@ uptime-about = Afficher l'heure actuelle, la durée pendant laquelle le système le nombre d'utilisateurs sur le système, et le nombre moyen de tâches dans la file d'attente d'exécution au cours des 1, 5 et 15 dernières minutes. uptime-usage = uptime [OPTION]... -uptime-about-musl-warning = Avertissement : Lorsque compilé avec musl libc, l'utilitaire `uptime` peut afficher '0 utilisateur' - en raison de l'implémentation stub des fonctions utmpx de musl. L'heure de démarrage et les moyennes de charge - sont toujours calculées en utilisant des mécanismes alternatifs. +uptime-about-musl-warning = Avec musl libc, le comptage des utilisateurs connectés nécessite un accès à systemd-logind. # Messages d'aide uptime-help-since = système actif depuis diff --git a/src/uu/uptime/src/uptime.rs b/src/uu/uptime/src/uptime.rs index 187fc53c598..215cd20eb3a 100644 --- a/src/uu/uptime/src/uptime.rs +++ b/src/uu/uptime/src/uptime.rs @@ -62,7 +62,11 @@ pub fn uu_app() -> Command { #[cfg(not(target_env = "musl"))] let about = translate!("uptime-about"); #[cfg(target_env = "musl")] - let about = translate!("uptime-about") + &translate!("uptime-about-musl-warning"); + let about = format!( + "{}\n\n{}", + translate!("uptime-about"), + translate!("uptime-about-musl-warning") + ); let cmd = Command::new("uptime") .version(uucore::crate_version!()) diff --git a/src/uu/users/locales/en-US.ftl b/src/uu/users/locales/en-US.ftl index ec54112c854..85bf317df53 100644 --- a/src/uu/users/locales/en-US.ftl +++ b/src/uu/users/locales/en-US.ftl @@ -1,7 +1,5 @@ users-about = Print the user names of users currently logged in to the current host. users-usage = users [FILE] -users-about-musl-warning = - Warning: When built with musl libc, the `users` utility may show '0 users', - due to musl's stub implementation of utmpx functions. +users-about-musl-warning = With musl libc, listing logged-in users requires access to systemd-logind. users-long-usage = Output who is currently logged in according to FILE. If FILE is not specified, use { $default_path }. /var/log/wtmp as FILE is common. diff --git a/src/uu/users/locales/fr-FR.ftl b/src/uu/users/locales/fr-FR.ftl index e62b48cc4f0..71087f637ff 100644 --- a/src/uu/users/locales/fr-FR.ftl +++ b/src/uu/users/locales/fr-FR.ftl @@ -1,7 +1,5 @@ users-about = Afficher les noms d'utilisateur des utilisateurs actuellement connectés à l'hôte actuel. users-usage = users [FICHIER] -users-about-musl-warning = - Avertissement : Lorsqu'il est compilé avec musl libc, l'utilitaire `users` peut afficher '0 utilisateurs', - à cause de l'implémentation stub des fonctions utmpx de musl. +users-about-musl-warning = Avec musl libc, l’affichage des utilisateurs connectés nécessite un accès à systemd-logind. users-long-usage = Afficher qui est actuellement connecté selon FICHIER. Si FICHIER n'est pas spécifié, utiliser { $default_path }. /var/log/wtmp comme FICHIER est courant. diff --git a/src/uu/users/src/users.rs b/src/uu/users/src/users.rs index e71281548cf..6997fe49b38 100644 --- a/src/uu/users/src/users.rs +++ b/src/uu/users/src/users.rs @@ -92,7 +92,11 @@ pub fn uu_app() -> Command { #[cfg(not(target_env = "musl"))] let about = translate!("users-about"); #[cfg(target_env = "musl")] - let about = translate!("users-about") + &translate!("users-about-musl-warning"); + let about = format!( + "{}\n\n{}", + translate!("users-about"), + translate!("users-about-musl-warning") + ); Command::new("users") .version(uucore::crate_version!()) diff --git a/src/uu/who/locales/en-US.ftl b/src/uu/who/locales/en-US.ftl index 2984c2fdcc5..e23c5a0ba1b 100644 --- a/src/uu/who/locales/en-US.ftl +++ b/src/uu/who/locales/en-US.ftl @@ -1,8 +1,6 @@ who-about = Print information about users who are currently logged in. who-usage = who [OPTION]... [ FILE | ARG1 ARG2 ] -who-about-musl-warning = Note: When built with musl libc, the `who` utility will not display any - information about logged-in users. This is due to musl's stub implementation - of `utmpx` functions, which prevents access to the necessary data. +who-about-musl-warning = With musl libc, listing logged-in users requires access to systemd-logind. # Long usage help text who-long-usage = If FILE is not specified, use { $default_file }. /var/log/wtmp as FILE is common. diff --git a/src/uu/who/locales/fr-FR.ftl b/src/uu/who/locales/fr-FR.ftl index 0c853e51ee9..ae8ce363559 100644 --- a/src/uu/who/locales/fr-FR.ftl +++ b/src/uu/who/locales/fr-FR.ftl @@ -1,8 +1,6 @@ who-about = Affiche des informations sur les utilisateurs actuellement connectés. who-usage = who [OPTION]... [ FICHIER | ARG1 ARG2 ] -who-about-musl-warning = Note : Lors de la compilation avec musl libc, l'utilitaire `who` n'affichera aucune - information sur les utilisateurs connectés. Ceci est dû à l'implémentation - stub des fonctions `utmpx` de musl, qui empêche l'accès aux données nécessaires. +who-about-musl-warning = Avec musl libc, l’affichage des utilisateurs connectés nécessite un accès à systemd-logind. who-long-usage = Si FICHIER n'est pas spécifié, utilise { $default_file }. /var/log/wtmp comme FICHIER est courant. Si ARG1 ARG2 sont donnés, -m est présumé : 'am i' ou 'mom likes' sont usuels. diff --git a/src/uu/who/src/who.rs b/src/uu/who/src/who.rs index e82990b7924..a5097211b7f 100644 --- a/src/uu/who/src/who.rs +++ b/src/uu/who/src/who.rs @@ -43,7 +43,11 @@ pub fn uu_app() -> Command { #[cfg(not(target_env = "musl"))] let about = translate!("who-about"); #[cfg(target_env = "musl")] - let about = translate!("who-about") + &translate!("who-about-musl-warning"); + let about = format!( + "{}\n\n{}", + translate!("who-about"), + translate!("who-about-musl-warning") + ); let cmd = Command::new("who") .version(uucore::crate_version!()) diff --git a/src/uucore/Cargo.toml b/src/uucore/Cargo.toml index 5635ac90c57..05e46dec362 100644 --- a/src/uucore/Cargo.toml +++ b/src/uucore/Cargo.toml @@ -124,6 +124,10 @@ walkdir = { workspace = true, optional = true } libloading = { workspace = true, optional = true } procfs = { workspace = true, optional = true } +[target.'cfg(all(target_os = "linux", target_env = "musl"))'.dependencies] +zbus = { version = "6.2.1", default-features = false, features = ["default-rt"], optional = true } +zruntime = { version = "0.2.2", default-features = false, features = ["helper"], optional = true } + [target.'cfg(windows)'.dependencies] wild = { workspace = true } windows-sys = { workspace = true, optional = true, default-features = false, features = [ @@ -237,7 +241,7 @@ openssl = ["dep:openssl"] update-control = ["parser"] utf8 = [] utmpx = ["time", "time/macros", "libc", "dns-lookup"] -systemd-logind = ["utmpx", "dep:libloading"] +systemd-logind = ["utmpx", "dep:libloading", "dep:zbus", "dep:zruntime"] version-cmp = [] wide = [] tty = [] diff --git a/src/uucore/src/lib/features/systemd_logind.rs b/src/uucore/src/lib/features/systemd_logind.rs index eb18f45d27d..1745c080c56 100644 --- a/src/uucore/src/lib/features/systemd_logind.rs +++ b/src/uucore/src/lib/features/systemd_logind.rs @@ -13,13 +13,15 @@ //! empty. If systemd-logind is unavailable, callers fall back to the traditional //! implementation. -use core::ffi::CStr; -use std::mem::MaybeUninit; use std::time::{SystemTime, UNIX_EPOCH}; use crate::error::{UResult, USimpleError}; +#[cfg(all(target_env = "musl", target_feature = "crt-static"))] +mod bus; + /// Dynamically loaded FFI bindings for libsystemd login functions. +#[cfg(not(all(target_env = "musl", target_feature = "crt-static")))] mod ffi { use core::ffi::{c_char, c_int, c_uint}; use libloading::Library; @@ -123,12 +125,12 @@ mod ffi { } /// Safe wrapper functions for libsystemd FFI calls +#[cfg(not(all(target_env = "musl", target_feature = "crt-static")))] mod login { use super::ffi; use core::ffi::{CStr, c_char, c_int}; use std::ffi::CString; use std::ptr; - use std::time::SystemTime; /// Get all active sessions pub fn get_sessions( @@ -245,27 +247,6 @@ mod login { unsafe { libc::free(value_ptr.cast()) }; value } - - /// Get system boot time using systemd random-seed file fallback - /// - /// TODO: This replicates GNU coreutils' fallback behavior for compatibility. - /// GNU coreutils uses the mtime of /var/lib/systemd/random-seed as a heuristic for boot time - /// when utmp is unavailable, rather than querying systemd's authoritative `KernelTimestamp`. - /// This creates inconsistency: `uptime -s` shows the actual kernel boot time - /// while `who -b` shows ~1 minute later when systemd services start. - /// - /// Ideally, both should use the same source (`KernelTimestamp`) for semantic consistency. - /// Consider proposing to GNU coreutils to use systemd's `KernelTimestamp` property instead. - pub fn get_boot_time() -> Result> { - use std::fs; - - let metadata = fs::metadata("/var/lib/systemd/random-seed") - .map_err(|e| format!("Failed to read /var/lib/systemd/random-seed: {e}"))?; - - metadata - .modified() - .map_err(|e| format!("Failed to get modification time: {e}").into()) - } } /// Login record compatible with utmpx structure @@ -321,6 +302,11 @@ impl SystemdLoginRecord { /// Read login records from systemd-logind using safe wrapper functions /// This matches the approach used by GNU coreutils `read_utmp_from_systemd()` pub fn read_login_records() -> UResult> { + #[cfg(all(target_env = "musl", target_feature = "crt-static"))] + let api = bus::BusLogin::connect(zbus::connection::Builder::system()).map_err(|e| { + USimpleError::new(1, format!("Failed to read logind sessions over D-Bus: {e}")) + })?; + #[cfg(not(all(target_env = "musl", target_feature = "crt-static")))] let api = ffi::SystemdLoginApi::load() .map_err(|e| USimpleError::new(1, format!("Failed to load libsystemd: {e}")))?; read_login_records_with_api(&api) @@ -337,12 +323,13 @@ struct SessionInfo { leader: Option, } -/// The safe boundary between sd-login and record assembly. +/// The boundary between logind session retrieval and record assembly. trait LoginApi { fn sessions(&self) -> UResult>; fn session(&self, id: &str) -> Option; } +#[cfg(not(all(target_env = "musl", target_feature = "crt-static")))] impl LoginApi for ffi::SystemdLoginApi { fn sessions(&self) -> UResult> { login::get_sessions(self) @@ -350,6 +337,9 @@ impl LoginApi for ffi::SystemdLoginApi { } fn session(&self, session_id: &str) -> Option { + use core::ffi::CStr; + use std::mem::MaybeUninit; + let uid = login::get_session_uid(self, session_id).ok()?; // SAFETY: passwd and result are writable outputs, and buf remains alive // while getpwuid_r fills them. Only a successful, non-NULL result is read. @@ -401,8 +391,10 @@ impl LoginApi for ffi::SystemdLoginApi { fn read_login_records_with_api(api: &impl LoginApi) -> UResult> { let mut records = Vec::new(); - // Add boot time record first - if let Ok(boot_time) = login::get_boot_time() { + // Use the random-seed mtime for the boot record to match existing output. + if let Ok(boot_time) = + std::fs::metadata("/var/lib/systemd/random-seed").and_then(|metadata| metadata.modified()) + { let boot_record = SystemdLoginRecord { user: "reboot".to_string(), session_id: "boot".to_string(), diff --git a/src/uucore/src/lib/features/systemd_logind/bus.rs b/src/uucore/src/lib/features/systemd_logind/bus.rs new file mode 100644 index 00000000000..4efcba9f784 --- /dev/null +++ b/src/uucore/src/lib/features/systemd_logind/bus.rs @@ -0,0 +1,118 @@ +// This file is part of the uutils coreutils package. +// +// For the full copyright and license information, please view the LICENSE +// file that was distributed with this source code. + +//! The static musl backend queries logind without loading a shared library. + +use std::collections::HashMap; +use std::time::Duration; + +use zbus::connection::Builder; +use zbus::{OwnedObjectPath, OwnedVariant}; +use zruntime::SharedRuntime; + +use super::{LoginApi, SessionInfo}; +use crate::error::UResult; + +const DESTINATION: &str = "org.freedesktop.login1"; +const SESSION_INTERFACE: &str = "org.freedesktop.login1.Session"; +const READ_TIMEOUT: Duration = Duration::from_secs(1); + +type ListedSession = (String, u32, String, String, OwnedObjectPath); + +pub(super) struct BusLogin(HashMap); + +impl BusLogin { + pub(super) fn connect(builder: Builder<'_>) -> Result> { + let runtime = SharedRuntime::current()?; + // Bound connection setup and all session requests with one deadline. + Ok(runtime.block_on(runtime.timeout(READ_TIMEOUT, Self::read_sessions(builder)))??) + } + + async fn read_sessions(builder: Builder<'_>) -> zbus::Result { + let connection = builder.build().await?; + let reply = connection + .call_method( + Some(DESTINATION), + "/org/freedesktop/login1", + Some("org.freedesktop.login1.Manager"), + "ListSessions", + &(), + ) + .await?; + let sessions: Vec = reply.body().deserialize()?; + let mut records = HashMap::with_capacity(sessions.len()); + for (id, uid, user, seat, path) in sessions { + // A session can end while we are reading its properties. + let properties = connection + .call_method( + Some(DESTINATION), + path.as_str(), + Some("org.freedesktop.DBus.Properties"), + "GetAll", + &SESSION_INTERFACE, + ) + .await + .and_then(|reply| reply.body().deserialize::>()); + if let Ok(mut properties) = properties { + let mut string = |name: &str| { + properties + .remove(name) + .and_then(|value| String::try_from(value).ok()) + .unwrap_or_default() + }; + records.insert( + id, + SessionInfo { + user: if user.is_empty() { + uid.to_string() + } else { + user + }, + tty: string("TTY"), + seat, + remote_host: string("RemoteHost"), + display: string("Display"), + start_time: properties + .remove("Timestamp") + .and_then(|value| u64::try_from(value).ok()), + leader: properties + .remove("Leader") + .and_then(|value| u32::try_from(value).ok()) + .filter(|&pid| pid > 0), + }, + ); + } + } + Ok(Self(records)) + } +} + +impl LoginApi for BusLogin { + fn sessions(&self) -> UResult> { + Ok(self.0.keys().cloned().collect()) + } + + fn session(&self, id: &str) -> Option { + self.0.get(id).cloned() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::net::UnixListener; + + #[test] + fn an_unresponsive_bus_times_out_during_authentication() { + let directory = tempfile::tempdir().unwrap(); + let socket = directory.path().join("bus"); + // Accept no traffic, so the client will connect but receive no response. + let _listener = UnixListener::bind(&socket).unwrap(); + let address = format!("unix:path={}", socket.display()); + let builder = Builder::address(address.as_str()); + let error = BusLogin::connect(builder).err().unwrap(); + assert!(error.is::(), "{error:?}"); + } +} diff --git a/tests/by-util/test_who.rs b/tests/by-util/test_who.rs index 645313ef993..d9a9f89c5fa 100644 --- a/tests/by-util/test_who.rs +++ b/tests/by-util/test_who.rs @@ -10,13 +10,21 @@ use uutests::unwrap_or_return; use uutests::util::{TestScenario, expected_result, gnu_cmd_result}; use uutests::util_name; -#[cfg(all(target_os = "linux", target_env = "gnu", feature = "test_logind"))] +#[cfg(all( + target_os = "linux", + any( + target_env = "gnu", + all(target_env = "musl", target_feature = "crt-static") + ), + feature = "test_logind" +))] mod logind { use std::collections::HashMap; use std::process::{Child, Command, Stdio}; use std::time::{Duration, Instant}; use uutests::util::TestScenario; + #[cfg(target_env = "gnu")] mod support { include!(concat!( env!("CARGO_MANIFEST_DIR"), @@ -139,7 +147,8 @@ mod logind { assert_eq!(&record.user, name); let version = systemd("systemctl", &["--version"]); let version: u32 = version.split_whitespace().nth(1).unwrap().parse().unwrap(); - let has_metadata = version >= 254; + // The D-Bus properties also exist on logind versions older than 254. + let has_metadata = cfg!(target_env = "musl") || version >= 254; assert_eq!(record.try_login_time_offset().is_some(), has_metadata); assert_eq!(record.pid, if has_metadata { pid } else { 0 }); let displayed = if let Some(timestamp) = record.try_login_time_offset() { @@ -197,6 +206,12 @@ mod logind { .succeeds() .stdout_contains(format!("{users} user")); + #[cfg(target_env = "gnu")] + check_traditional_records(&ts); + } + + #[cfg(target_env = "gnu")] + fn check_traditional_records(ts: &TestScenario) { let traditional = support::utmpx_record("traditional"); let custom = ts.fixtures.plus("custom-utmp"); std::fs::write(&custom, &traditional).unwrap(); @@ -235,6 +250,20 @@ mod logind { .stdout_is("\n# users=0\n") .no_stderr(); } + + #[cfg(all(target_env = "musl", target_feature = "crt-static"))] + #[test] + fn unavailable_bus_leaves_the_login_list_empty() { + let ts = TestScenario::new("who"); + let missing_bus = format!("unix:path={}", ts.fixtures.plus("missing-bus").display()); + ts.ucmd() + .arg("-q") + .env("LC_ALL", "C") + .env("DBUS_SYSTEM_BUS_ADDRESS", missing_bus) + .succeeds() + .stdout_is("\n# users=0\n") + .no_stderr(); + } } #[test]