diff --git a/.github/workflows/CICD.yml b/.github/workflows/CICD.yml index 055c8b7dd6e..73c601c6646 100644 --- a/.github/workflows/CICD.yml +++ b/.github/workflows/CICD.yml @@ -11,7 +11,7 @@ env: PROJECT_NAME: coreutils PROJECT_DESC: "Core universal (cross-platform) utilities" PROJECT_AUTH: "uutils" - RUST_MIN_SRV: "1.88.0" + RUST_MIN_SRV: "1.89" CARGO_INCREMENTAL: "0" # * style job configuration STYLE_FAIL_ON_FAULT: true ## (bool) fail the build if a style job contains a fault (error or warning); may be overridden on a per-job basis @@ -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 --lib --locked --features systemd-logind - name: Upload test results to Codecov if: ${{ !cancelled() }} uses: codecov/codecov-action@v7 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 c99995f9c34..0d1a8cbfac7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4431,6 +4431,7 @@ dependencies = [ "jiff", "jiff-icu", "libc", + "libloading", "md-5", "memchr", "nix", @@ -4439,6 +4440,7 @@ dependencies = [ "openssl", "os_display", "procfs", + "rstest", "rustc-hash", "rustix", "selinux", diff --git a/Cargo.toml b/Cargo.toml index 1d12fc6ce28..7c85ab3d94b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,7 @@ members = [ [workspace.package] categories = ["command-line-utilities"] edition = "2024" -rust-version = "1.88.0" +rust-version = "1.89" homepage = "https://github.com/uutils/coreutils" keywords = ["coreutils", "uutils", "cross-platform", "cli", "utility"] license = "MIT" @@ -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", ] } @@ -435,6 +436,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", @@ -458,14 +461,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/flake.nix b/flake.nix index 4f7234942fd..212ba79e202 100644 --- a/flake.nix +++ b/flake.nix @@ -49,7 +49,7 @@ default = pkgsFor.${system}.pkgs.mkShell { packages = build_deps ++ gnu_testing_deps; - RUSTC_VERSION = "1.88"; + RUSTC_VERSION = "1.89"; LIBCLANG_PATH = pkgsFor.${system}.lib.makeLibraryPath [pkgsFor.${system}.llvmPackages_latest.libclang.lib]; shellHook = '' export PATH=$PATH:''${CARGO_HOME:-~/.cargo}/bin diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index a107691afa2..09cd127fc3d 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -17,7 +17,7 @@ members = ["."] [workspace.package] edition = "2024" -rust-version = "1.88.0" +rust-version = "1.89" license = "MIT" # Enable debug symbols in release builds for readable backtraces 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..1c987ac0afc 100644 --- a/src/uu/pinky/src/platform/unix.rs +++ b/src/uu/pinky/src/platform/unix.rs @@ -192,7 +192,10 @@ fn format_timestamp(ut: &UtmpxRecord) -> String { }; } - TIME_FORMAT.with(|description| ut.login_time().format(description).unwrap()) + ut.try_login_time().map_or_else( + || "?".into(), + |time| TIME_FORMAT.with(|description| time.format(description).unwrap()), + ) } /// Pull the real name out of a password entry's comment field: it is the part @@ -299,7 +302,10 @@ impl Pinky { if self.layout.header { writeln!(writer, "{}", self.header_row())?; } - for ut in Utmpx::iter_all_records() { + for ut in Utmpx::iter_all_records_with_options(utmpx::ReadOptions { + session_time: true, + session_pid: false, + }) { if ut.is_user_process() && (self.names.is_empty() || self.names.iter().any(|n| n.as_str() == ut.user())) { @@ -368,6 +374,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/uptime/src/platform/unix.rs b/src/uu/uptime/src/platform/unix.rs index 4ad18da82d3..a9624720e3e 100644 --- a/src/uu/uptime/src/platform/unix.rs +++ b/src/uu/uptime/src/platform/unix.rs @@ -17,7 +17,7 @@ use uucore::error::UResult; use uucore::translate; use uucore::uptime::get_uptime; #[cfg(not(any(target_os = "openbsd", target_os = "android")))] -use uucore::utmpx::{BOOT_TIME, USER_PROCESS, Utmpx}; +use uucore::utmpx::{BOOT_TIME, ReadOptions, USER_PROCESS, Utmpx}; use crate::{UptimeError, options, print_loadavg, print_nusers, print_time, print_uptime}; @@ -153,16 +153,17 @@ fn process_utmpx(file: Option<&OsString>) -> (Option, usize) { let mut boot_time = None; let records = match file { - Some(f) => Utmpx::iter_all_records_from(f), - None => Utmpx::iter_all_records(), + Some(f) => Utmpx::iter_all_records_from_with_options(f, ReadOptions::BASIC), + None => Utmpx::iter_all_records_with_options(ReadOptions::BASIC), }; for line in records { match line.record_type() { x if x == USER_PROCESS => nusers += 1, x if x == BOOT_TIME => { - let dt = line.login_time(); - if dt.unix_timestamp() > 0 { + if let Some(dt) = line.try_login_time() + && dt.unix_timestamp() > 0 + { boot_time = Some(dt.unix_timestamp()); } } 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/users/src/users.rs b/src/uu/users/src/users.rs index e71281548cf..325b5f42cdc 100644 --- a/src/uu/users/src/users.rs +++ b/src/uu/users/src/users.rs @@ -74,7 +74,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> { { let filename = maybe_file.unwrap_or(utmpx::DEFAULT_FILE.as_ref()); - users = Utmpx::iter_all_records_from(filename) + users = Utmpx::iter_all_records_from_with_options(filename, utmpx::ReadOptions::BASIC) .filter(utmpx::UtmpxRecord::is_user_process) .map(|ut| ut.user()) .collect::>(); 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..590282288dd 100644 --- a/src/uu/who/src/platform/unix.rs +++ b/src/uu/who/src/platform/unix.rs @@ -217,7 +217,36 @@ fn format_timestamp(ut: &UtmpxRecord) -> String { ) .unwrap() }; - ut.login_time().format(&pattern).unwrap() + ut.try_login_time() + .map_or_else(|| "?".into(), |time| time.format(&pattern).unwrap()) +} + +fn format_pid(ut: &UtmpxRecord) -> String { + ut.try_pid() + .map_or_else(|| "?".into(), |pid| 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 { @@ -237,7 +266,13 @@ impl Who { return self.emit_names(f); } - let records = utmpx::Utmpx::iter_all_records_from(f); + let records = utmpx::Utmpx::iter_all_records_from_with_options( + f, + utmpx::ReadOptions { + session_time: self.select.sessions, + session_pid: self.select.sessions && !self.layout.terse, + }, + ); if self.layout.header { self.emit_header()?; @@ -263,10 +298,11 @@ impl Who { /// The `-q` report: every login name on one line, then the total. fn emit_names(&self, path: &str) -> UResult<()> { - let users = utmpx::Utmpx::iter_all_records_from(path) - .filter(UtmpxRecord::is_user_process) - .map(|ut| ut.user()) - .collect::>(); + let users = + utmpx::Utmpx::iter_all_records_from_with_options(path, utmpx::ReadOptions::BASIC) + .filter(UtmpxRecord::is_user_process) + .map(|ut| ut.user()) + .collect::>(); // `println!` panics on a write error; the rest of this file surfaces // it through `?` instead so the caller can report it and exit // non-zero, matching GNU (#13388). @@ -301,7 +337,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. @@ -324,8 +360,9 @@ impl Who { }, #[cfg(target_os = "linux")] Event::Runlevel => { - let last = (ut.pid() / 256) as u8 as char; - let level = (ut.pid() % 256) as u8 as char; + let runlevel = ut.pid(); + let last = (runlevel / 256) as u8 as char; + let level = (runlevel % 256) as u8 as char; runlevel_line = translate!("who-runlevel", "level" => level); // Like GNU, a previous level of 'N' is reported as 'S'; any // other previous level is reported as-is. @@ -420,7 +457,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 d9fe8b481a1..8301d1a9fc4 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 } [target.'cfg(any(target_os = "freebsd", target_os = "hurd", target_os = "linux", target_os = "android", target_os = "macos", target_os = "netbsd"))'.dependencies] @@ -119,6 +120,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] @@ -227,7 +229,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. @@ -235,6 +236,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..db102d3d709 100644 --- a/src/uucore/src/lib/features/systemd_logind.rs +++ b/src/uucore/src/lib/features/systemd_logind.rs @@ -9,32 +9,111 @@ //! //! 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; use std::time::{SystemTime, UNIX_EPOCH}; use crate::error::{UResult, USimpleError}; +use crate::utmpx::ReadOptions; -/// 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("libsystemd.so.0") + } - #[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; + fn load_from(path: impl AsRef) -> 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.as_ref())?; + 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; + + #[test] + fn missing_library_is_reported() { + assert!(SystemdLoginApi::load_from("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("libc.so.6").err().unwrap(); + assert!(error.to_string().contains("sd_get_sessions"), "{error}"); + } } } @@ -47,10 +126,12 @@ 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) }; + 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 +160,14 @@ 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) }; + let result = unsafe { (api.sd_session_get_uid)(session_cstring.as_ptr(), &raw mut uid) }; if result < 0 { return Err( @@ -95,14 +179,19 @@ 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) }; + 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 +201,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 +268,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 +290,65 @@ impl SystemdLoginRecord { } /// Get login time as [`time::OffsetDateTime`] compatible with utmpx + 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()?; + Some(crate::utmpx::local_login_time(datetime)) + } + + /// 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 { - let duration = self - .login_time - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - let ts_nanos: i128 = (duration.as_nanos()).try_into().unwrap_or(0); - 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) + 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(); + read_login_records_with_options(ReadOptions::default()) +} - // 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); - } +/// Read records with explicit requirements for optional session metadata. +/// The boot record is still obtained regardless of these options. +pub fn read_login_records_with_options(options: ReadOptions) -> UResult> { + let api = ffi::SystemdLoginApi::load() + .map_err(|e| USimpleError::new(1, format!("Failed to load libsystemd: {e}")))?; + read_login_records_with_api(&api, options) +} - // 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, options: ReadOptions) -> 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, options: ReadOptions) -> 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 +382,71 @@ 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: options + .session_time + .then(|| login::get_session_start_time(self, session_id).ok()) + .flatten(), + leader: options + .session_pid + .then(|| login::get_session_leader(self, session_id)) + .flatten(), + }) + } +} + +fn read_login_records_with_api( + api: &impl LoginApi, + options: ReadOptions, +) -> 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, options) + 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 +456,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 +487,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 +557,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 +597,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,9 +614,12 @@ 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() + self.try_canon_host().unwrap_or_else(|_| self.host()) + } + + /// Canonical host name, propagating DNS errors. + pub fn try_canon_host(&self) -> std::io::Result { + crate::utmpx::canonicalize_host(self.record.host.clone()) } } @@ -465,7 +632,12 @@ pub struct SystemdUtmpxIter { impl SystemdUtmpxIter { /// Create new instance and read records from systemd-logind pub fn new() -> UResult { - let records = read_login_records()?; + Self::with_options(ReadOptions::default()) + } + + /// Create an iterator with explicit session metadata requirements. + pub fn with_options(options: ReadOptions) -> UResult { + let records = read_login_records_with_options(options)?; Ok(Self { records, current_index: 0, @@ -525,10 +697,43 @@ impl Iterator for SystemdUtmpxIter { } } +#[cfg(test)] +#[path = "systemd_logind/tests.rs"] +mod regression_tests; + #[cfg(test)] mod tests { use super::*; + #[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(); 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..950e7df57d9 --- /dev/null +++ b/src/uucore/src/lib/features/systemd_logind/tests.rs @@ -0,0 +1,119 @@ +// 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::*; +use std::cell::RefCell; + +#[derive(Default)] +struct Login { + records: Vec<(String, SessionInfo)>, + requested: RefCell>, + 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, options: ReadOptions) -> Option { + self.requested.borrow_mut().push(options); + let mut info = self.records.iter().find(|(name, _)| name == id)?.1.clone(); + if !options.session_time { + info.start_time = None; + } + if !options.session_pid { + info.leader = None; + } + Some(info) + } +} + +#[test] +fn enumeration_errors_are_propagated() { + let login = Login { + fail: true, + ..Login::default() + }; + assert!(read_login_records_with_api(&login, ReadOptions::default()).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, ReadOptions::default()).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, ReadOptions::default()) + .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), + ReadOptions::default(), + true, + 31337 +)] +#[case(None, None, ReadOptions::default(), false, 0)] +#[case(Some(0), None, ReadOptions::default(), false, 0)] +#[case(Some(1_700_000_000_000_000), Some(31337), ReadOptions::BASIC, false, 0)] +#[case(Some(1_700_000_000_000_000), Some(31337), ReadOptions { session_time: true, session_pid: false }, true, 0)] +fn requested_session_metadata_is_preserved( + #[case] time: Option, + #[case] leader: Option, + #[case] options: ReadOptions, + #[case] known_time: bool, + #[case] pid: u32, +) { + let login = Login::new(time, leader); + let records = read_login_records_with_api(&login, options).unwrap(); + let record = records.iter().find(|r| r.is_user_process()).unwrap(); + assert_eq!(*login.requested.borrow(), [options]); + assert_eq!(record.login_time != UNIX_EPOCH, known_time); + assert_eq!(record.pid, pid); + assert_eq!(record.session_leader_pid, pid); +} diff --git a/src/uucore/src/lib/features/uptime/unix.rs b/src/uucore/src/lib/features/uptime/unix.rs index 42f21587689..92cd9d1a7f4 100644 --- a/src/uucore/src/lib/features/uptime/unix.rs +++ b/src/uucore/src/lib/features/uptime/unix.rs @@ -96,7 +96,7 @@ pub fn get_uptime(_boot_time: Option) -> UResult { target_os = "openbsd", )))] pub fn get_uptime(boot_time: Option) -> UResult { - use crate::utmpx::{BOOT_TIME, Utmpx}; + use crate::utmpx::{BOOT_TIME, ReadOptions, Utmpx, time}; use jiff::Timestamp; use std::fs::File; use std::io::Read; @@ -116,9 +116,10 @@ pub fn get_uptime(boot_time: Option) -> UResult { // Try provided boot_time or derive from utmpx let derived_boot_time = boot_time.or_else(|| { - Utmpx::iter_all_records() + Utmpx::iter_all_records_with_options(ReadOptions::BASIC) .filter(|r| r.record_type() == BOOT_TIME) - .map(|r| r.login_time().unix_timestamp()) + .filter_map(|record| record.try_login_time()) + .map(time::OffsetDateTime::unix_timestamp) .find(|&ts| ts > 0) }); @@ -164,10 +165,10 @@ pub fn get_uptime(boot_time: Option) -> UResult { #[cfg(not(any(target_os = "openbsd", target_os = "android")))] // see: https://gitlab.com/procps-ng/procps/-/blob/4740a0efa79cade867cfc7b32955fe0f75bf5173/library/uptime.c#L63-L115 pub fn get_nusers() -> usize { - use crate::utmpx::{USER_PROCESS, Utmpx}; + use crate::utmpx::{ReadOptions, USER_PROCESS, Utmpx}; let mut num_user = 0; - Utmpx::iter_all_records().for_each(|ut| { + Utmpx::iter_all_records_with_options(ReadOptions::BASIC).for_each(|ut| { if ut.record_type() == USER_PROCESS { num_user += 1; } diff --git a/src/uucore/src/lib/features/utmpx.rs b/src/uucore/src/lib/features/utmpx.rs index f72bae1b5f2..de598f8c2dd 100644 --- a/src/uucore/src/lib/features/utmpx.rs +++ b/src/uucore/src/lib/features/utmpx.rs @@ -3,7 +3,7 @@ // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -// spell-checker:ignore IDLEN logind ohos setutxdb UTXDB +// spell-checker:ignore IDLEN logind ohos OFD setutxdb UTXDB WRLCK unlocker SETLK EAGAIN RDLCK UNLCK //! Aims to provide platform-independent methods to obtain login records //! @@ -36,12 +36,15 @@ pub extern crate time; use std::ffi::CString; use std::io::Result as IOResult; use std::marker::PhantomData; +#[cfg(target_os = "linux")] +use std::mem::size_of; use std::os::unix::ffi::OsStrExt; -use std::path::Path; +use std::path::{Path, PathBuf}; +#[cfg(not(all(target_os = "linux", target_env = "musl")))] use std::ptr; use std::sync::{Mutex, MutexGuard}; -#[cfg(all(feature = "systemd_logind", target_os = "linux"))] +#[cfg(all(target_os = "linux", feature = "systemd-logind"))] use crate::features::systemd_logind; pub use self::ut::*; @@ -172,6 +175,34 @@ mod ut { }; } +/// Optional session metadata to obtain when reading logind records. +/// The default requests both fields. Traditional utmp records and the boot +/// timestamp are unaffected. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ReadOptions { + /// Obtain a user session's login timestamp. + pub session_time: bool, + /// Obtain a user session's leader PID. + pub session_pid: bool, +} + +impl ReadOptions { + /// Enumerate sessions without querying their login times or leader PIDs. + pub const BASIC: Self = Self { + session_time: false, + session_pid: false, + }; +} + +impl Default for ReadOptions { + fn default() -> Self { + Self { + session_time: true, + session_pid: true, + } + } +} + /// A login record pub struct Utmpx { inner: utmpx, @@ -228,11 +259,7 @@ impl Utmpx { let ts_nanos: i128 = (1_000_000_000_i64 * self.inner.ut_tv.tv_sec as i64 + 1_000_i64 * self.inner.ut_tv.tv_usec as i64) .into(); - 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() - .to_offset(local_offset) + local_login_time(time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos).unwrap()) } /// A.K.A. `ut.ut_exit` /// @@ -259,132 +286,232 @@ impl Utmpx { /// Canonicalize host name using DNS pub fn canon_host(&self) -> IOResult { - let host = self.host(); + canonicalize_host(self.host()) + } - let (hostname, display) = host.split_once(':').unwrap_or((&host, "")); + /// Iterate through all utmp records using the most recently selected path. + /// + /// On Linux with `systemd-logind`, a default file without a complete record + /// falls back to logind. Custom paths always select traditional records. + /// Call [`Self::iter_all_records_from`] with [`DEFAULT_FILE`] to restore + /// the default source selection rules. + /// + /// Only one iterator may be active at a time; this blocks until it is dropped. + pub fn iter_all_records() -> UtmpxIter { + Self::iter_all_records_with_options(ReadOptions::default()) + } - if !hostname.is_empty() { - use dns_lookup::{AddrInfoHints, getaddrinfo}; + /// Iterate through records, selecting which logind session details to obtain. + /// The same locking and selected-path rules as [`Self::iter_all_records`] apply. + pub fn iter_all_records_with_options(options: ReadOptions) -> UtmpxIter { + let iter = UtmpxIter::new(); + #[cfg(target_os = "linux")] + return iter.with_systemd_fallback(options); - const AI_CANONNAME: i32 = 0x2; - let hints = AddrInfoHints { - flags: AI_CANONNAME, - ..AddrInfoHints::default() - }; - if let Ok(sockets) = getaddrinfo(Some(hostname), None, Some(hints)) { - let sockets = sockets.collect::>>()?; - for socket in sockets { - if let Some(ai_canonname) = socket.canonname { - return Ok(if display.is_empty() { - ai_canonname - } else { - format!("{ai_canonname}:{display}") - }); - } - } - } else { - // GNU coreutils has this behavior - return Ok(hostname.to_string()); - } + // SAFETY: The iterator holds LOCK while accessing libc's global utmp state. + #[cfg(not(target_os = "linux"))] + unsafe { + #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] + setutxent(); + } + #[cfg(not(target_os = "linux"))] + { + let _ = options; + iter } - - 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. + /// Read a specific file, remembering it for subsequent iterators. /// - /// On systems with systemd-logind feature enabled at compile time, - /// this will use systemd-logind instead of traditional utmp files. + /// On Linux with `systemd-logind`, a default file without a complete record + /// falls back to logind, then returns to the file if logind is unavailable. + /// Other paths always select traditional records. /// - /// Only one instance of [`UtmpxIter`] may be active at a time. This - /// function will block as long as one is still active. Beware! - pub fn iter_all_records() -> UtmpxIter { - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + /// Only one iterator may be active at a time; failures produce no records. + pub fn iter_all_records_from>(path: P) -> UtmpxIter { + Self::iter_all_records_from_with_options(path, ReadOptions::default()) + } + + /// Read the selected file with explicit logind session metadata requirements. + /// The same rules as [`Self::iter_all_records_from`] apply. + pub fn iter_all_records_from_with_options>( + path: P, + options: ReadOptions, + ) -> UtmpxIter { + let iter = UtmpxIter::new(); + #[cfg(target_os = "linux")] { - // Use systemd-logind instead of traditional utmp when feature is enabled - UtmpxIter::new_systemd() + let mut iter = iter; + *iter.guard = Some(path.as_ref().to_path_buf()); + iter.with_systemd_fallback(options) } - - #[cfg(not(all(feature = "systemd_logind", target_os = "linux")))] + #[cfg(not(target_os = "linux"))] { - let iter = UtmpxIter::new(); + let filename = CString::new(path.as_ref().as_os_str().as_bytes()).unwrap(); + // SAFETY: The iterator holds LOCK, and filename remains valid for these calls. 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))] + #[cfg(target_os = "freebsd")] + setutxdb(libc::UTXDB_ACTIVE, filename.as_ptr()); + + // These APIs report failures inconsistently across platforms. + // Preserve the traditional reader's empty output on invalid paths. + #[cfg(not(target_os = "freebsd"))] + #[cfg_attr(target_env = "ohos", allow(deprecated))] + utmpxname(filename.as_ptr()); + + #[cfg_attr(target_env = "ohos", allow(deprecated))] setutxent(); } + let _ = options; iter } } +} - /// 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. - 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(); +/// Apply the local UTC offset at the record's timestamp, including historical DST. +pub(crate) fn local_login_time(datetime: time::OffsetDateTime) -> time::OffsetDateTime { + let offset = time::UtcOffset::local_offset_at(datetime).unwrap_or(time::UtcOffset::UTC); + datetime.to_offset(offset) +} + +pub(crate) fn canonicalize_host(host: String) -> IOResult { + use dns_lookup::{AddrInfoHints, getaddrinfo}; + + const AI_CANONNAME: i32 = 0x2; + let hints = AddrInfoHints { + flags: AI_CANONNAME, + ..AddrInfoHints::default() + }; + canonicalize_host_with(host, |hostname| { + getaddrinfo(Some(hostname), None, Some(hints)) + .map(|sockets| sockets.map(|socket| socket.map(|info| info.canonname))) + .map_err(|error| std::io::Error::other(error.to_string())) + }) +} + +fn canonicalize_host_with( + host: String, + lookup: impl FnOnce(&str) -> IOResult, +) -> IOResult +where + I: IntoIterator>>, +{ + let (hostname, display) = split_host_display(&host); + if !hostname.is_empty() { + if let Ok(sockets) = lookup(hostname) { + let sockets = sockets.into_iter().collect::>>()?; + if let Some(ai_canonname) = sockets.into_iter().flatten().next() { + return Ok(if display.is_empty() { + ai_canonname + } else { + format!("{ai_canonname}:{display}") + }); } + } else { + return Ok(hostname.to_string()); } + } + Ok(host) +} - 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()); +fn split_host_display(host: &str) -> (&str, &str) { + // Colons inside an IPv6 address are not X11 display separators. + let address = host + .strip_prefix('[') + .and_then(|rest| rest.split_once(']')) + .map_or(host, |(address, _)| address); + let address = address + .split_once('%') + .map_or(address, |(address, _)| address); + if address.parse::().is_ok() { + return (host, ""); + } + host.split_once(':').unwrap_or((host, "")) +} - #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] - setutxent(); - } - iter +// Serialize access to libc's utmp state and the selected path. UtmpxIter must +// stay on its creating thread because libc's utmp state may be thread-local. +static LOCK: Mutex> = Mutex::new(None); + +/// Open a regular file without waiting for FIFO writers. Read this descriptor +/// directly so all record-lock waits can share the iterator's budget. +#[cfg(target_os = "linux")] +fn open_traditional_utmp(path: &Path) -> Option { + #[cfg(target_env = "musl")] + { + // musl's utmp APIs are stubs, even when the file is populated. + let _ = path; + None + } + + #[cfg(not(target_env = "musl"))] + { + use std::os::unix::fs::OpenOptionsExt; + + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK) + .open(path) + .ok()?; + regular_utmp(file) } } -// 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(()); +#[cfg(all(target_os = "linux", not(target_env = "musl")))] +fn regular_utmp(file: std::fs::File) -> Option { + file.metadata().ok()?.is_file().then_some(file) +} + +// Bound the total time spent acquiring record locks across one iterator. +// A per-record timeout can otherwise be spent again for every entry. +#[cfg(all(target_os = "linux", not(target_env = "musl")))] +const UTMP_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +#[cfg(all(target_os = "linux", not(target_env = "musl")))] +fn lock_utmp( + file: &std::fs::File, + lock: &libc::flock, + deadline: std::time::Instant, +) -> IOResult<()> { + use std::os::fd::AsRawFd; + use std::time::{Duration, Instant}; + + loop { + // SAFETY: file owns a live descriptor and lock is initialized. + if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, lock) } >= 0 { + return Ok(()); + } + let error = std::io::Error::last_os_error(); + let interrupted = error.raw_os_error() == Some(libc::EINTR); + if !interrupted && !matches!(error.raw_os_error(), Some(libc::EAGAIN | libc::EACCES)) { + return Err(error); + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + if !interrupted { + std::thread::sleep(remaining.min(Duration::from_millis(10))); + } + } +} /// Iterator of login records pub struct UtmpxIter { - #[allow(dead_code)] - guard: MutexGuard<'static, ()>, /// Ensure [`UtmpxIter`] is !Send. Technically redundant because [`MutexGuard`] /// is also !Send. phantom: PhantomData>, - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] systemd_iter: Option, + #[cfg(target_os = "linux")] + traditional_file: Option, + #[cfg(all(target_os = "linux", not(target_env = "musl")))] + lock_wait_remaining: std::time::Duration, + #[cfg(all(test, target_os = "linux", not(target_env = "musl")))] + drop_observer: Option, + // Close every file before another iterator can acquire process-wide locks. + #[allow(dead_code)] + guard: MutexGuard<'static, Option>, } impl UtmpxIter { @@ -394,39 +521,594 @@ impl UtmpxIter { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); Self { - guard, phantom: PhantomData, - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] systemd_iter: None, + #[cfg(target_os = "linux")] + traditional_file: None, + #[cfg(all(target_os = "linux", not(target_env = "musl")))] + lock_wait_remaining: UTMP_LOCK_TIMEOUT, + #[cfg(all(test, target_os = "linux", not(target_env = "musl")))] + drop_observer: None, + guard, } } - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - fn new_systemd() -> Self { - // PoisonErrors can safely be ignored - let guard = LOCK + #[cfg(target_os = "linux")] + fn with_systemd_fallback(self, options: ReadOptions) -> Self { + #[cfg(feature = "systemd-logind")] + { + self.with_login_reader( + options, + Path::new(DEFAULT_FILE), + systemd_logind::SystemdUtmpxIter::with_options, + ) + } + #[cfg(not(feature = "systemd-logind"))] + { + let _ = options; + let mut iter = self; + let path = iter.guard.as_deref().unwrap_or(Path::new(DEFAULT_FILE)); + iter.traditional_file = open_traditional_utmp(path); + iter + } + } + + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + fn with_login_reader( + mut self, + options: ReadOptions, + default_path: &Path, + read_logind: impl FnOnce(ReadOptions) -> crate::error::UResult, + ) -> Self { + let path = self.guard.as_deref().unwrap_or(default_path); + self.traditional_file = open_traditional_utmp(path); + // Availability, not record contents, determines which source wins. + let usable = self + .traditional_file + .as_ref() + .and_then(|file| file.metadata().ok()) + .is_some_and(|metadata| metadata.len() >= size_of::() as u64); + if path == default_path && !usable { + self.systemd_iter = read_logind(options).ok(); + self.traditional_file = if self.systemd_iter.is_none() { + // The file may have appeared while logind was being tried. + open_traditional_utmp(path) + } else { + None + }; + } + self + } +} + +#[cfg(all(test, target_os = "linux", not(target_env = "musl")))] +mod tests { + use super::*; + #[cfg(feature = "systemd-logind")] + use std::cell::Cell; + use std::fs::File; + use std::io::Write; + use std::os::fd::AsRawFd; + use std::os::unix::fs::{FileTypeExt, OpenOptionsExt}; + use std::time::Duration; + + // The selected utmp path persists between iterators. Keep tests that use + // several iterators together so another test cannot replace that path. + static TEST_LOCK: Mutex<()> = Mutex::new(()); + + pub(super) struct DropObserver(Box); + + impl Drop for DropObserver { + fn drop(&mut self) { + (self.0)(); + } + } + + mod support { + include!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/support/utmpx.rs" + )); + } + use support::utmpx_record; + + fn write_utmpx_records(path: &Path, users: &[&str]) { + let bytes: Vec = users.iter().flat_map(|user| utmpx_record(user)).collect(); + std::fs::write(path, bytes).unwrap(); + } + + fn set_ofd_lock(file: &File, lock_type: libc::c_int) { + // SAFETY: flock contains only integer fields, all initially zero. + let mut lock: libc::flock = unsafe { std::mem::zeroed() }; + lock.l_type = lock_type as _; + lock.l_whence = libc::SEEK_SET as _; + // SAFETY: file owns a live descriptor and lock is initialized. + let result = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_OFD_SETLK, &lock) }; + assert_eq!(result, 0, "{}", std::io::Error::last_os_error()); + } + + #[test] + fn traditional_iteration_reads_complete_records() { + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["first", "second"]); + std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(&[0]) + .unwrap(); + + let users = Utmpx::iter_all_records_from(&path) + .map(|record| record.user()) + .collect::>(); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + assert_eq!(users, ["first", "second"]); + } + + #[test] + fn traditional_paths_persist_across_iterators() { + let _test_lock = TEST_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() + let directory = tempfile::tempdir().unwrap(); + let custom_path = directory.path().join("custom-utmp"); + let fallback_path = directory.path().join("fallback-utmp"); + write_utmpx_records(&custom_path, &["custom"]); + // An incomplete trailing record must not produce another login entry. + std::fs::OpenOptions::new() + .append(true) + .open(&custom_path) + .unwrap() + .write_all(&[0]) + .unwrap(); + write_utmpx_records(&fallback_path, &["fallback"]); + + let custom_users = Utmpx::iter_all_records_from(&custom_path) + .map(|record| { + let pid: i32 = record.pid(); + let timestamp: time::OffsetDateTime = record.login_time(); + assert_eq!(record.try_pid(), Some(pid)); + assert_eq!(record.try_login_time(), Some(timestamp)); + record.user() + }) + .collect::>(); + let repeated_custom_users = Utmpx::iter_all_records() + .map(|record| record.user()) + .collect::>(); + let fallback_users = Utmpx::iter_all_records_from(&fallback_path) + .map(|record| record.user()) + .collect::>(); + let repeated_fallback_users = Utmpx::iter_all_records() + .map(|record| record.user()) + .collect::>(); + + // Restore the default before the temporary files are removed. + let default_iter = Utmpx::iter_all_records_from(DEFAULT_FILE); + assert_eq!(default_iter.guard.as_deref(), Some(Path::new(DEFAULT_FILE))); + drop(default_iter); + assert_eq!( + Utmpx::iter_all_records().guard.as_deref(), + Some(Path::new(DEFAULT_FILE)) + ); + + assert_eq!(custom_users, ["custom"]); + assert_eq!(repeated_custom_users, custom_users); + assert_eq!(fallback_users, ["fallback"]); + assert_eq!(repeated_fallback_users, fallback_users); + } + + #[test] + fn traditional_iterator_closes_file_before_unlocking() { + use std::os::fd::AsRawFd; + use std::os::unix::fs::MetadataExt; + + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["user"]); + let mut iter = Utmpx::iter_all_records_from(&path); + let file = iter.traditional_file.as_ref().unwrap(); + let fd_path = format!("/proc/self/fd/{}", file.as_raw_fd()); + let metadata = file.metadata().unwrap(); + let identity = (metadata.dev(), metadata.ino()); + + // Observe destruction after the file field, before the mutex guard. + iter.drop_observer = Some(DropObserver(Box::new(move || { + let still_open = std::fs::metadata(&fd_path) + .is_ok_and(|metadata| (metadata.dev(), metadata.ino()) == identity); + assert!(!still_open, "utmp descriptor must be closed first"); + assert!( + matches!(LOCK.try_lock(), Err(std::sync::TryLockError::WouldBlock)), + "utmp mutex must remain locked while closing the descriptor" + ); + }))); + drop(iter); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + } + + #[test] + fn traditional_iterator_closes_all_files() { + use std::os::unix::fs::MetadataExt; + + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["user"]); + let mut iter = Utmpx::iter_all_records_from(&path); + let file = iter.traditional_file.as_ref().unwrap(); + let metadata = file.metadata().unwrap(); + let identity = (metadata.dev(), metadata.ino()); + // Read a record before checking that iteration leaves no descriptor open. + assert_eq!(iter.next().unwrap().user(), "user"); + drop(iter); + + let still_open = std::fs::read_dir("/proc/self/fd") + .unwrap() + .filter_map(Result::ok) + .any(|entry| { + std::fs::metadata(entry.path()) + .is_ok_and(|metadata| (metadata.dev(), metadata.ino()) == identity) + }); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + assert!(!still_open, "all utmp descriptors must be closed"); + } + + #[test] + fn traditional_iterator_restores_selected_path_for_libc() { + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["first", "second"]); + let mut iter = Utmpx::iter_all_records_from(&path); + assert_eq!(iter.next().unwrap().user(), "first"); + drop(iter); + + let user = { + let _guard = LOCK.lock().unwrap(); + // SAFETY: LOCK serializes libc's utmp state and the returned record + // is copied before another libc call can replace its buffer. + unsafe { + setutxent(); + let record = getutxent(); + let user = if record.is_null() { + None + } else { + Some( + Utmpx { + inner: ptr::read(record), + } + .user(), + ) + }; + endutxent(); + user } }; - Self { - guard, - phantom: PhantomData, - systemd_iter: Some(systemd_iter), + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + assert_eq!(user.as_deref(), Some("first")); + } + + #[test] + fn traditional_iterator_reopens_selected_path() { + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + let replacement_path = directory.path().join("replacement"); + write_utmpx_records(&path, &["original"]); + write_utmpx_records(&replacement_path, &["replacement"]); + let users = Utmpx::iter_all_records_from(&path) + .map(|record| record.user()) + .collect::>(); + + // A new iterator must resolve the saved pathname again, rather than + // retaining the previous iterator's open descriptor. + let _old_file = File::open(&path).unwrap(); + std::fs::rename(&replacement_path, &path).unwrap(); + let replacement_users = Utmpx::iter_all_records() + .map(|record| record.user()) + .collect::>(); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + assert_eq!(users, ["original"]); + assert_eq!(replacement_users, ["replacement"]); + } + + #[test] + fn traditional_iterator_rejects_invalid_source_after_valid_file() { + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["first", "second"]); + + for invalid_path in [ + directory.path().join("missing"), + directory.path().to_owned(), + ] { + let mut iter = Utmpx::iter_all_records_from(&path); + assert_eq!(iter.next().unwrap().user(), "first"); + drop(iter); + let mut iter = Utmpx::iter_all_records_from(invalid_path); + assert!(iter.next().is_none()); + assert!(iter.next().is_none()); + } + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + } + + #[test] + fn traditional_utmp_opens_only_regular_files() { + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + + assert!(open_traditional_utmp(&path).is_none()); + assert!(open_traditional_utmp(directory.path()).is_none()); + + File::create(&path).unwrap(); + assert_eq!( + open_traditional_utmp(&path) + .unwrap() + .metadata() + .unwrap() + .len(), + 0 + ); + + write_utmpx_records(&path, &["user"]); + assert_eq!( + open_traditional_utmp(&path) + .unwrap() + .metadata() + .unwrap() + .len(), + size_of::() as u64 + ); + } + + #[test] + fn replacing_an_open_file_with_a_fifo_keeps_the_original_record() { + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["original"]); + let file = File::open(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + nix::unistd::mkfifo(&path, nix::sys::stat::Mode::S_IRUSR).unwrap(); + assert!(path.metadata().unwrap().file_type().is_fifo()); + + // Validate after the replacement, just as the reader does after open. + let mut iter = UtmpxIter::new(); + *iter.guard = None; + iter.traditional_file = regular_utmp(file); + assert_eq!(iter.next().unwrap().user(), "original"); + assert!(iter.next().is_none()); + } + + #[cfg(feature = "systemd-logind")] + #[rstest::rstest] + #[case("missing", true)] + #[case("empty", true)] + #[case("short", true)] + #[case("fifo", true)] + #[case("traditional", false)] + #[case("zeros", false)] + #[case("boot-only", false)] + fn default_utmp_source_selection(#[case] contents: &str, #[case] logind: bool) { + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + match contents { + "missing" => {} + "empty" => { + File::create(&path).unwrap(); + } + "short" => std::fs::write(&path, [0]).unwrap(), + "fifo" => nix::unistd::mkfifo(&path, nix::sys::stat::Mode::S_IRUSR).unwrap(), + "zeros" => File::create(&path) + .unwrap() + .set_len(size_of::() as u64) + .unwrap(), + _ => { + write_utmpx_records(&path, &["traditional"]); + if contents == "boot-only" { + File::options() + .write(true) + .open(&path) + .unwrap() + .write_all(&BOOT_TIME.to_ne_bytes()) + .unwrap(); + } + } + } + let called = Cell::new(false); + let mut iter = UtmpxIter::new(); + *iter.guard = None; + let mut iter = iter.with_login_reader(ReadOptions::BASIC, &path, |options| { + called.set(true); + assert_eq!(options, ReadOptions::BASIC); + Ok(systemd_logind::SystemdUtmpxIter::empty()) + }); + assert_eq!(called.get(), logind); + assert_eq!(iter.systemd_iter.is_some(), logind); + assert_eq!(iter.traditional_file.is_none(), logind); + if contents == "traditional" { + assert_eq!(iter.next().unwrap().user(), "traditional"); + } + } + + #[cfg(feature = "systemd-logind")] + #[test] + fn explicit_utmp_path_does_not_try_logind() { + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("explicit-utmp"); + File::create(&path).unwrap(); + let mut iter = UtmpxIter::new(); + *iter.guard = Some(path); + let mut iter = iter.with_login_reader( + ReadOptions::default(), + &directory.path().join("default-utmp"), + |_| panic!("an explicit non-default file must not try logind"), + ); + assert!(iter.next().is_none()); + *iter.guard = None; + } + + #[cfg(feature = "systemd-logind")] + #[rstest::rstest] + #[case(false)] + #[case(true)] + fn failed_logind_reopens_utmp(#[case] initially_exists: bool) { + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + if initially_exists { + File::create(&path).unwrap(); } + let mut iter = UtmpxIter::new(); + *iter.guard = None; + let mut iter = iter.with_login_reader(ReadOptions::default(), &path, |_| { + let replacement = directory.path().join("replacement"); + write_utmpx_records(&replacement, &["fallback"]); + std::fs::rename(&replacement, &path).unwrap(); + Err(crate::error::USimpleError::new(1, "logind unavailable")) + }); + assert!(iter.systemd_iter.is_none()); + assert_eq!(iter.next().unwrap().user(), "fallback"); + assert!(iter.next().is_none()); + } + + #[cfg(feature = "systemd-logind")] + #[rstest::rstest] + #[case(false)] + #[case(true)] + fn failed_logind_without_a_regular_utmp_is_empty(#[case] fifo: bool) { + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + if fifo { + nix::unistd::mkfifo(&path, nix::sys::stat::Mode::S_IRUSR).unwrap(); + } + let mut iter = UtmpxIter::new(); + *iter.guard = None; + let mut iter = iter.with_login_reader(ReadOptions::default(), &path, |_| { + Err(crate::error::USimpleError::new(1, "logind unavailable")) + }); + assert!(iter.next().is_none()); + } + + #[test] + fn traditional_iterator_keeps_file_after_fifo_replacement() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + + let _test_lock = TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["first", "second"]); + let mut iter = Utmpx::iter_all_records_from(&path); + + std::fs::remove_file(&path).unwrap(); + let fifo_path = CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: fifo_path is a live, null-terminated path. + assert_eq!(unsafe { libc::mkfifo(fifo_path.as_ptr(), 0o600) }, 0); + // Supply a different record so reopening the FIFO fails the assertions + // without waiting indefinitely for a writer or for record data. + let mut replacement = std::fs::OpenOptions::new() + .read(true) + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(&path) + .unwrap(); + replacement.write_all(&utmpx_record("replacement")).unwrap(); + + assert_eq!(iter.next().unwrap().user(), "first"); + assert_eq!(iter.next().unwrap().user(), "second"); + assert!(iter.next().is_none()); + drop(iter); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + } + + #[test] + fn traditional_lock_wait_budget_is_shared_across_records() { + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["first", "second"]); + let writer = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + let mut iter = Utmpx::iter_all_records_from(&path); + // Exercise the production wait policy with a short private budget. + let budget = Duration::from_millis(500); + iter.lock_wait_remaining = budget; + + // OFD locks conflict with the iterator's process-associated locks even + // within this process, unlike two process-associated locks. + set_ofd_lock(&writer, libc::F_WRLCK); + std::thread::scope(|scope| { + let unlocker = scope.spawn(|| { + std::thread::sleep(Duration::from_millis(50)); + set_ofd_lock(&writer, libc::F_UNLCK); + }); + assert_eq!(iter.next().unwrap().user(), "first"); + unlocker.join().unwrap(); + }); + let remaining = iter.lock_wait_remaining; + assert!(remaining < budget); + assert!(!remaining.is_zero()); + + set_ofd_lock(&writer, libc::F_WRLCK); + std::thread::scope(|scope| { + let unlocker = scope.spawn(|| { + // Release eventually so a blocking or reset-per-record reader + // returns the second record and fails instead of hanging. + std::thread::sleep(remaining + Duration::from_millis(100)); + set_ofd_lock(&writer, libc::F_UNLCK); + }); + assert!(iter.next().is_none()); + unlocker.join().unwrap(); + }); + assert!(iter.lock_wait_remaining.is_zero()); + assert!(iter.next().is_none()); + drop(iter); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); + } + + #[test] + fn exhausted_wait_budget_still_reads_uncontended_records() { + let _guard = TEST_LOCK.lock().unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("utmp"); + write_utmpx_records(&path, &["first", "second"]); + let mut iter = Utmpx::iter_all_records_from(&path); + iter.lock_wait_remaining = Duration::ZERO; + + assert_eq!(iter.next().unwrap().user(), "first"); + assert_eq!(iter.next().unwrap().user(), "second"); + assert!(iter.next().is_none()); + drop(iter); + drop(Utmpx::iter_all_records_from(DEFAULT_FILE)); } } /// 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(target_os = "linux", feature = "systemd-logind"))] Systemd(systemd_logind::SystemdUtmpxCompat), } @@ -435,25 +1117,36 @@ 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(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.record_type(), } } /// A.K.A. `ut.ut_pid` - pub fn pid(&self) -> i32 { + /// Returns None when logind could not provide a session leader PID. + #[cfg_attr( + not(all(target_os = "linux", feature = "systemd-logind")), + allow(clippy::unnecessary_wraps) + )] + pub fn try_pid(&self) -> Option { match self { - Self::Traditional(utmpx) => utmpx.pid(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - Self::Systemd(systemd) => systemd.pid(), + Self::Traditional(utmpx) => Some(utmpx.pid()), + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + Self::Systemd(systemd) => systemd.try_pid(), } } + /// A.K.A. `ut.ut_pid`. Returns zero when a logind PID is unavailable. + /// Use [`Self::try_pid`] to distinguish an unavailable PID. + pub fn pid(&self) -> i32 { + self.try_pid().unwrap_or_default() + } + /// A.K.A. `ut.ut_id` pub fn terminal_suffix(&self) -> String { match self { Self::Traditional(utmpx) => utmpx.terminal_suffix(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.terminal_suffix(), } } @@ -462,7 +1155,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(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.user(), } } @@ -471,7 +1164,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(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.host(), } } @@ -480,27 +1173,39 @@ 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(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.tty_device(), } } /// A.K.A. `ut.ut_tv` - pub fn login_time(&self) -> time::OffsetDateTime { + /// Returns None when a systemd record has no known login time. + #[cfg_attr( + not(all(target_os = "linux", feature = "systemd-logind")), + allow(clippy::unnecessary_wraps) + )] + pub fn try_login_time(&self) -> Option { match self { - Self::Traditional(utmpx) => utmpx.login_time(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - Self::Systemd(systemd) => systemd.login_time(), + Self::Traditional(utmpx) => Some(utmpx.login_time()), + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + Self::Systemd(systemd) => systemd.try_login_time(), } } + /// A.K.A. `ut.ut_tv`. Returns the Unix epoch when a logind time is unavailable. + /// Use [`Self::try_login_time`] when displaying a login time to users. + pub fn login_time(&self) -> time::OffsetDateTime { + self.try_login_time() + .unwrap_or(time::OffsetDateTime::UNIX_EPOCH) + } + /// A.K.A. `ut.ut_exit` /// /// Return (`e_termination`, `e_exit`) 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(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.exit_status(), } } @@ -509,7 +1214,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(target_os = "linux", feature = "systemd-logind"))] Self::Systemd(systemd) => systemd.is_user_process(), } } @@ -518,8 +1223,8 @@ impl UtmpxRecord { pub fn canon_host(&self) -> IOResult { match self { Self::Traditional(utmpx) => utmpx.canon_host(), - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] - Self::Systemd(systemd) => Ok(systemd.canon_host()), + #[cfg(all(target_os = "linux", feature = "systemd-logind"))] + Self::Systemd(systemd) => systemd.try_canon_host(), } } } @@ -527,15 +1232,59 @@ impl UtmpxRecord { impl Iterator for UtmpxIter { type Item = UtmpxRecord; fn next(&mut self) -> Option { - #[cfg(all(feature = "systemd_logind", target_os = "linux"))] + #[cfg(target_os = "linux")] { + #[cfg(feature = "systemd-logind")] if let Some(ref mut systemd_iter) = self.systemd_iter { - // We have a systemd iterator - use it exclusively (never fall back to traditional utmp) + // Once a systemd iterator was successfully created, use it exclusively. + // If systemd initialization failed, `systemd_iter` is None and we use + // traditional utmp below. return systemd_iter.next().map(UtmpxRecord::Systemd); } + #[cfg(not(target_env = "musl"))] + { + use std::io::Read; + use std::os::fd::AsRawFd; + + let file = self.traditional_file.as_mut()?; + // Cooperate with utmp writers while copying a complete record. + // SAFETY: flock contains only integer fields, all initially zero. + let mut lock: libc::flock = unsafe { std::mem::zeroed() }; + lock.l_type = libc::F_RDLCK as _; + lock.l_whence = libc::SEEK_SET as _; + let started = std::time::Instant::now(); + let acquired = lock_utmp(file, &lock, started + self.lock_wait_remaining); + self.lock_wait_remaining = + self.lock_wait_remaining.saturating_sub(started.elapsed()); + if acquired.is_err() { + self.traditional_file = None; + return None; + } + let mut bytes = [0_u8; size_of::()]; + let result = file.read_exact(&mut bytes); + lock.l_type = libc::F_UNLCK as _; + // SAFETY: The descriptor and lock remain live through the unlock. + let unlocked = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETLK, &lock) } >= 0; + if result.is_err() || !unlocked { + // Closing also releases the lock if the explicit unlock failed. + self.traditional_file = None; + } + // An unlock failure must not discard a record already read. + result.ok()?; + // SAFETY: Linux utmp files contain native utmpx records. Every + // field is an integer or an integer array, so all bit patterns + // are valid. read_unaligned does not require an aligned buffer. + let inner = unsafe { ptr::read_unaligned(bytes.as_ptr().cast::()) }; + Some(UtmpxRecord::Traditional(Box::new(Utmpx { inner }))) + } + #[cfg(target_env = "musl")] + { + None + } } // Traditional utmp path + #[cfg(not(target_os = "linux"))] unsafe { #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] let res = getutxent(); @@ -556,9 +1305,73 @@ impl Iterator for UtmpxIter { impl Drop for UtmpxIter { fn drop(&mut self) { + // SAFETY: The iterator still holds LOCK while closing libc's file. unsafe { #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] endutxent(); } + + #[cfg(target_os = "linux")] + { + // Preserve the selected pathname for callers of the re-exported libc API. + let path = self.guard.as_deref().unwrap_or(Path::new(DEFAULT_FILE)); + if let Ok(path) = CString::new(path.as_os_str().as_bytes()) { + // SAFETY: LOCK is held and path is a live, null-terminated path. + #[cfg_attr(any(target_env = "musl", target_env = "ohos"), allow(deprecated))] + unsafe { + utmpxname(path.as_ptr()); + } + } + } + } +} + +#[cfg(test)] +mod host_tests { + use super::{canonicalize_host_with, split_host_display}; + + #[rstest::rstest] + #[case("alias.test", "alias.test", "canonical.test")] + #[case("alias.test:0", "alias.test", "canonical.test:0")] + #[case("192.0.2.1", "192.0.2.1", "canonical.test")] + #[case("dead:beef::1", "dead:beef::1", "canonical.test")] + #[case("[dead:beef::1]:0", "[dead:beef::1]:0", "canonical.test")] + fn canonical_names_preserve_display_suffixes( + #[case] host: &str, + #[case] lookup: &str, + #[case] expected: &str, + ) { + let result = canonicalize_host_with(host.into(), |name| { + assert_eq!(name, lookup); + Ok([Ok(None), Ok(Some("canonical.test".into()))]) + }) + .unwrap(); + assert_eq!(result, expected); + } + + #[test] + fn addresses_without_a_canonical_name_are_preserved() { + for host in ["192.0.2.1", "dead:beef::1", "[dead:beef::1]:0"] { + assert_eq!( + canonicalize_host_with(host.into(), |_| Ok([Ok(None)])).unwrap(), + host + ); + } + } + + #[rstest::rstest] + #[case("192.0.2.1", "192.0.2.1", "")] + #[case("dead:beef::1", "dead:beef::1", "")] + #[case("fe80::1%eth0", "fe80::1%eth0", "")] + #[case("[dead:beef::1]:0", "[dead:beef::1]:0", "")] + #[case("host.example", "host.example", "")] + #[case("host.example:0.1", "host.example", "0.1")] + #[case(":0", "", "0")] + fn ipv6_colons_are_not_display_separators( + #[case] host: &str, + #[case] hostname: &str, + #[case] display: &str, + ) { + assert_eq!(split_host_display(host), (hostname, display)); } } 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..e8b5550a54b 100644 --- a/tests/by-util/test_who.rs +++ b/tests/by-util/test_who.rs @@ -9,6 +9,247 @@ 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; + + 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_or_else(|| panic!("expected TTY {tty:?} in {who:?}")); + let mut fields = row.split_whitespace(); + for expected in [name.as_str(), tty.as_str()] + .into_iter() + .chain(displayed.split_whitespace()) + { + assert_eq!(fields.next(), Some(expected), "unexpected field in {row:?}"); + } + // After the time, who -u displays the idle time followed by the PID. + assert_eq!(fields.nth(1), Some(displayed_pid), "wrong PID in {row:?}"); + let pinky = ts + .ccmd("pinky") + .arg("-fq") + .env("LC_ALL", "C") + .env("TZ", "UTC") + .succeeds() + .stdout_move_str(); + assert!( + pinky.lines().any(|row| { + let mut fields = row.split_whitespace(); + fields.next() == Some(name.as_str()) + && fields + .next() + .is_some_and(|line| line.trim_start_matches(['*', '?']) == tty) + && fields.eq(displayed.split_whitespace()) + }), + "expected time {displayed:?} for {name} on {tty} in {pinky:?}" + ); + 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")); + } +} + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +#[path = "../../src/uucore/tests/support/utmpx.rs"] +mod utmpx_support; + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +#[uutests::wasi_ignore(NoFifo)] +#[rstest::rstest] +#[case(false)] +#[case(true)] +fn test_utmp_fifo_is_rejected(#[case] with_writer: bool) { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + use std::time::Duration; + + let ts = TestScenario::new(util_name!()); + ts.fixtures.mkfifo("utmp"); + let path = ts.fixtures.plus("utmp"); + let _writer = with_writer.then(|| { + // Linux permits opening a FIFO for both reading and writing without + // another endpoint, so the test does not block during setup. + let mut writer = std::fs::OpenOptions::new() + .read(true) + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(&path) + .unwrap(); + writer + .write_all(&utmpx_support::utmpx_record("fifo")) + .unwrap(); + writer + }); + + ts.ucmd() + .arg("-q") + .arg(&path) + .timeout(Duration::from_secs(5)) + .succeeds() + .stdout_is("\n# users=0\n"); +} + #[test] fn test_invalid_arg() { new_ucmd!().arg("--definitely-invalid").fails_with_code(1); @@ -343,6 +584,7 @@ mod utmp_file { user: &'a str, host: &'a str, exit: (i16, i16), + timestamp: Option, } impl Record<'_> { @@ -364,7 +606,7 @@ mod utmp_file { buf.extend_from_slice(&self.exit.0.to_ne_bytes()); buf.extend_from_slice(&self.exit.1.to_ne_bytes()); buf.extend_from_slice(&0_i32.to_ne_bytes()); // ut_session - buf.extend_from_slice(&TIMESTAMP.to_ne_bytes()); // ut_tv.tv_sec + buf.extend_from_slice(&self.timestamp.unwrap_or(TIMESTAMP).to_ne_bytes()); // ut_tv.tv_sec buf.extend_from_slice(&0_i32.to_ne_bytes()); // ut_tv.tv_usec buf.extend_from_slice(&[0; 16]); // ut_addr_v6 buf.extend_from_slice(&[0; 20]); // reserved @@ -450,6 +692,31 @@ mod utmp_file { .succeeds() } + #[rstest::rstest] + #[case(1_782_907_200, "Jul 1 08:00")] + #[case(1_767_268_800, "Jan 1 07:00")] + #[uutests::wasi_ignore(NoLocaleData)] + fn login_time_uses_the_offset_at_login(#[case] timestamp: i32, #[case] expected: &str) { + let (at, mut command) = at_and_ucmd!(); + at.write_bytes( + "utmp", + &Record { + kind: USER_PROCESS, + line: "pts/test", + user: "alice", + timestamp: Some(timestamp), + ..Record::default() + } + .to_bytes(), + ); + command + .env("LC_ALL", "C") + .env("TZ", "EST5EDT,M3.2.0/2,M11.1.0/2") + .arg("utmp") + .succeeds() + .stdout_contains(expected); + } + #[test] fn test_default_lists_user_sessions() { run_who(&records(), &[]).stdout_is("alice ttyNotThere Nov 14 22:13 (example.org)\n"); diff --git a/util/test-logind.sh b/util/test-logind.sh new file mode 100755 index 00000000000..388fced6e75 --- /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=BindReadOnlyPaths=$logind_utmp_fixture:/run/utmp" \ + "$logind_test_binary" --ignored --exact \ + test_who::logind::sessions_match_loginctl --nocapture