← Back to Pull requests

utmpx: fall back to logind when default utmp is unavailable #11579

Open
mattsu2020 opened this pull request with 1446 lines diff across 23 files
View on GitHub
mattsu2020 mattsu2020 commented on Apr 01, 2026 12:14 UTC
Author

When Linux's default utmp has no complete record, try logind for who, users, pinky and uptime. Keep populated traditional files first.

Related to #3219 and #8376; zbus support follows in #16231.

Diff: 1446 lines (+1099 / -347) across 23 files Reviewer: oech3 Review duration: 355668m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.79) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.79 · 1446 lines diff across 23 files
0.79
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.90 · 5 substantive comment(s)
0.90
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
46 items
oech3 oech3 commented on Apr 01, 2026 12:16 UTC
Contributor

Is this dynamically linked againsyt libsystemd.so? If so, this should be disabled by default.

mattsu2020 mattsu2020 commented on Apr 01, 2026 12:19 UTC
Author

Is this dynamically linked againsyt libsystemd.so? If so, this should be disabled by default.

Change to fallback only

github-actions[bot] github-actions[bot] commented on Apr 01, 2026 12:35 UTC
Bot

GNU testsuite comparison:

Skip an intermittent issue tests/date/date-locale-hour (fails in this run but passes in the 'main' branch)
Note: The gnu test tests/tail/tail-n0f is now being skipped but was previously passing.

github-actions[bot] github-actions[bot] commented on Apr 02, 2026 10:33 UTC
Bot

GNU testsuite comparison:

Note: The gnu test tests/pr/bounded-memory is now being skipped but was previously passing.
Note: The gnu test tests/rm/many-dir-entries-vs-OOM is now being skipped but was previously passing.
Congrats! The gnu test tests/tail/pipe-f is now passing!
Skip an intermittent issue tests/cut/bounded-memory (was skipped on 'main', now failing)

github-actions[bot] github-actions[bot] commented on Apr 07, 2026 10:04 UTC
Bot

GNU testsuite comparison:

GNU test failed: tests/tail/tail-n0f. tests/tail/tail-n0f is passing on 'main'. Maybe you have to rebase?
Skip an intermittent issue tests/tail/inotify-dir-recreate (fails in this run but passes in the 'main' branch)
Skipping an intermittent issue tests/pr/bounded-memory (passes in this run but fails in the 'main' branch)
Note: The gnu test tests/cut/bounded-memory is now being skipped but was previously passing.
Note: The gnu test tests/rm/many-dir-entries-vs-OOM is now being skipped but was previously passing.
Note: The gnu test tests/seq/seq-epipe is now being skipped but was previously passing.
Note: The gnu test tests/env/env-signal-handler was skipped on 'main' but is now failing.

github-actions[bot] github-actions[bot] commented on Apr 17, 2026 10:16 UTC
Bot

<!-- gnu-comment-bot -->
GNU testsuite comparison:

Congrats! The gnu test tests/tail/follow-name is no longer failing!
Congrats! The gnu test tests/tail/pid-pipe is no longer failing!

codspeed[bot] codspeed[bot] commented on Jun 10, 2026 13:52 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will regress 2 benchmarks

<details>
<summary><b>1 warning, 1 note</b></summary>

:warning: 122 benchmarks are dominated by system calls

> System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

> Learn more about system calls

> See affected benchmarks

:information_source: 1 benchmark has no flamegraph

> The flamegraph wasn't generated: most of the time was spent in runtime internals, which would leave nothing useful to analyze.

> See affected benchmarks

</details>

⚡ 1 improved benchmark
❌ 2 regressed benchmarks
✅ 410 untouched benchmarks
⏩ 70 skipped benchmarks[^skipped]

[!WARNING]

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | CPU Simulation | ` dd_copy_4k_blocks | 2.6 ms | 2.7 ms | -3.08% |
| ❌ | CPU Simulation |
dd_copy_with_skip | 4.8 ms | 4.9 ms | -3.03% |
| ⚡ | CPU Simulation |
true_consecutive_calls | 350.2 ns | 294.7 ns | +18.85% |

[!TIP]

Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.

---

<sub>Comparing <code>mattsu2020:users</code> (0dc65d8) with <code>main</code> (293a724)[^unexpected-base]</sub>

<a href="https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Ausers?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 70 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
[^unexpected-base]: No successful run was found on <code>main</code> (91f89c4) during the generation of this report, so 293a724 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

oech3 oech3 commented on Jun 26, 2026 23:05 UTC
Contributor

Is there any way to achieve full feature without runtime strong libsystemd.so dependency?
I think libselinux.so is not serious, but this should be part of binaries published at here.
Just parsing systemd files manually?

mattsu2020 mattsu2020 commented on Jun 27, 2026 05:17 UTC
Author

Is there any way to achieve full feature without runtime strong libsystemd.so dependency? I think libselinux.so is not serious, but this should be part of binaries published at here. Just parsing systemd files manually?

Since I changed it to dynamic load, I'll test to see if this works.

oech3 oech3 commented on Jun 27, 2026 05:24 UTC
Contributor

And remove feat_systemd_logind if succeed.

oech3 oech3 commented on Jun 27, 2026 05:30 UTC
Contributor

It seems pure Rust solution is possible: https://github.com/lucab/zbus_systemd (thought maintainer might not want to add such dep...)

mattsu2020 mattsu2020 commented on Jun 27, 2026 08:00 UTC
Author

Code changes are mostly complete

oech3 oech3 commented on Jun 29, 2026 17:32 UTC
Contributor

An additional reason that we want to have this PR: https://github.com/uutils/coreutils/issues/13212

Ecordonnier Ecordonnier commented on Jul 09, 2026 19:05 UTC
Contributor

It seems pure Rust solution is possible: https://github.com/lucab/zbus_systemd (thought maintainer might not want to add such dep...)

See https://github.com/uutils/coreutils/issues/8376#issuecomment-3193829490 where I explained why I did not use zbus in the implementation of systemd-logind. It is a huge crate.

Ecordonnier Ecordonnier commented on Jul 23, 2026 11:37 UTC
Contributor

Will it still be compatible with GNU coreutils behavior? how much is it deviating? the goal of the initial implementation of systemd-logind was to have the same behavior than GNU coreutils.

oech3 oech3 commented on Jul 29, 2026 05:59 UTC
Contributor

@Ecordonnier How about using zbus keeping feat_systemd_logind optional? Then people can keep binary size by removing it.

mattsu2020 mattsu2020 commented on Jul 29, 2026 10:17 UTC
Author

Will it still be compatible with GNU coreutils behavior? how much is it deviating? the goal of the initial implementation of systemd-logind was to have the same behavior than GNU coreutils.

Mostly, but not completely.

The systemd-derived records are intended to match GNU coreutils, including boot records and separate seat/TTY entries. However, there are still some known differences, such as session PID handling, remote user formatting, and TTY fallback behavior.

Ecordonnier Ecordonnier commented on Jul 29, 2026 10:21 UTC
Contributor

@Ecordonnier How about using zbus keeping feat_systemd_logind optional? Then people can keep binary size by removing it.

Using zbus would grow the binaries by 800KB. I don't think we want this.

oech3 oech3 commented on Jul 29, 2026 11:00 UTC
Contributor

I think it is worth to inc multicall-binary 800KiB for simplicity and consistency of binaries published at here.

oech3 oech3 commented on Aug 30, 2026 10:06 UTC
Contributor

@Ecordonnier Are you fine to merge this?

xtqqczze xtqqczze commented on Oct 12, 2026 12:04 UTC
Contributor

@mattsu2020 drop the merge commit and then rebase, rewrite the commit description, remove GitHub issue link from the commit description, rewrite the PR description

oech3 oech3 commented on Oct 17, 2026 13:47 UTC
Contributor

Needed to rebase.

sylvestre sylvestre commented on Nov 04, 2026 09:11 UTC
Contributor

hi, this one can't be merged as it is:

  • it needs a rebase

  • src/uucore/src/lib/features/systemd_logind.rs: switching boot time from random-seed to /proc/stat changes who -b output, please split that into another pr

  • src/uucore/src/lib/features/utmpx.rs: 5 lines of comment to say no caller does it, please make it shorter (or drop it)

  • src/uucore/src/lib/features/utmpx.rs: please make the doc shorter, the second paragraph can go

  • src/uucore/src/lib/features/utmpx.rs: why always false on musl? please add a short comment

  • src/uucore/src/lib/features/utmpx.rs: this generic exists only for the test, do we really need it?

  • could you please have a look? otherwise, i will close it, thanks

    oech3 oech3 commented on code on Nov 04, 2026 11:25 UTC
    Code Review
    docs/src/platforms.md:1
    @@ -45,3 +45,26 @@ 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
    +
    +`who`, `pinky`, `users`, and `uptime` prefer the default utmp file when it is a
    +readable regular file containing at least one complete record. This checks file
    +availability, not record validity: all-zero records and files containing only
    +boot records still take precedence over systemd-logind. Explicit non-default
    +utmp paths always use the traditional reader.
    +
    +Otherwise these utilities try libsystemd at runtime and return to the
    +traditional reader if loading or session enumeration fails. The former
    +`feat_systemd_logind` feature (and utility-level `systemd_logind` features) has
    +been removed; this selection is automatic on Linux.

    Otherwise these utilities try libsystemd at runtime and return to the
    traditional reader if loading or session enumeration fails.
    

    github-actions[bot] github-actions[bot] commented on Nov 04, 2026 23:26 UTC
    Bot

    <!-- size-comment-bot -->
    Binary size comparison:

    Individual binary size comparison VS main (threshold: >=5% AND >=4 KB).
    
    Total size of compared binaries: 155.61 MB (+232 KB, +0.15%)
    
    Significant per-binary changes:
      env     1.20 MB ->    1.28 MB  (+80 KB, +6.51%)
    

    oech3 oech3 commented on Nov 04, 2026 23:33 UTC
    Contributor

    I'm not sure if we should have many unsafes to avoid zbus adn maintain 1000+ lines. CodSpeed already says +336 KB at here.
    Or we could simply statically link libsystemd.

    mattsu2020 mattsu2020 commented on Nov 05, 2026 13:27 UTC
    Author

    https://github.com/mattsu2020/coreutils/tree/users-zbus
    I tried implementing it using zbus, but it ended up increasing the binary size.

    oech3 oech3 commented on Nov 05, 2026 13:35 UTC
    Contributor

    I think it is acceptible since libsystemd.so itself is large enough. We increased binary size when we dropped oniguruma. But it is not a real disadvantage.

    mattsu2020 mattsu2020 commented on Nov 07, 2026 05:02 UTC
    Author

    I think it is acceptible since libsystemd.so itself is large enough. We increased binary size when we dropped oniguruma. But it is not a real disadvantage.

    I've reworked the PR to use zbus, as I determined that the increase in binary size is not significant enough to be a concern.

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -259,132 +290,197 @@ impl Utmpx {
     
         /// Canonicalize host name using DNS
         pub fn canon_host(&self) -> IOResult<String> {
    -        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::<IOResult<Vec<_>>>()?;
    -                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.
    +    /// Read a specific file, remembering it for subsequent iterators.
         ///
    -    /// This will use the default location, or the path [`Utmpx::iter_all_records_from`]
    -    /// was most recently called with.
    +    /// 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.
         ///
    -    /// On systems with systemd-logind feature enabled at compile time,
    -    /// this will use systemd-logind instead of traditional utmp files.
    -    ///
    -    /// Only one instance of [`UtmpxIter`] may be active at a time. This
    -    /// function will block as long as one is still active. Beware!
    -    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<P: AsRef<Path>>(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<P: AsRef<Path>>(
    +        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<P: AsRef<Path>>(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();
    +pub(crate) fn canonicalize_host(host: String) -> IOResult<String> {
    +    let (hostname, display) = host.split_once(':').unwrap_or((&host, ""));
    +
    +    if !hostname.is_empty() {
    +        use dns_lookup::{AddrInfoHints, getaddrinfo};
    +
    +        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::<IOResult<Vec<_>>>()?;
    +            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());
             }
    +    }
     
    -        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());
    +    Ok(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<Option<PathBuf>> = 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<std::fs::File> {
    +    #[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()?;
    +        file.metadata().ok()?.is_file().then_some(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(());
    +// 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(

    why do we reimplement getutxent() with our own fcntl locking on linux?
    this is a lot of new code unrelated to the logind fallback, please split it into another pr

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/systemd_logind.rs:1
    @@ -190,60 +299,71 @@ impl SystemdLoginRecord {
         }
     
         /// Get login time as [`time::OffsetDateTime`] compatible with utmpx
    -    pub fn login_time_offset(&self) -> time::OffsetDateTime {
    -        let duration = self
    -            .login_time
    -            .duration_since(UNIX_EPOCH)
    -            .unwrap_or_default();
    -        let ts_nanos: i128 = (duration.as_nanos()).try_into().unwrap_or(0);
    +    pub fn try_login_time_offset(&self) -> Option<time::OffsetDateTime> {
    +        let duration = self.login_time.duration_since(UNIX_EPOCH).ok()?;
    +        if duration.is_zero() {
    +            return None;
    +        }
    +        let ts_nanos: i128 = duration.as_nanos().try_into().ok()?;
    +        let datetime = time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos).ok()?;
             let local_offset = time::OffsetDateTime::now_local()
                 .map_or_else(|_| time::UtcOffset::UTC, time::OffsetDateTime::offset);
    -        time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos)
    -            .unwrap_or_else(|_| {
    -                time::OffsetDateTime::now_local()
    -                    .unwrap_or_else(|_| time::OffsetDateTime::now_utc())
    -            })
    -            .to_offset(local_offset)
    +        Some(datetime.to_offset(local_offset))
    +    }
    +
    +    /// Get the login time, or the Unix epoch when it is unavailable.
    +    /// Use [`Self::try_login_time_offset`] when displaying timestamps.
    +    pub fn login_time_offset(&self) -> time::OffsetDateTime {
    +        self.try_login_time_offset()
    +            .unwrap_or(time::OffsetDateTime::UNIX_EPOCH)
         }
     }
     
     /// Read login records from systemd-logind using safe wrapper functions
     /// This matches the approach used by GNU coreutils `read_utmp_from_systemd()`
     pub fn read_login_records() -> UResult<Vec<SystemdLoginRecord>> {
    -    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<Vec<SystemdLoginRecord>> {
    +    let api = ffi::SystemdLoginApi::load().map_err(|e| {
    +        USimpleError::new(
    +            1,
    +            crate::translate!("systemd-logind-error-load-library", "error" => e),

    this error is thrown away by read_logind(options).ok() in utmpx.rs, so nobody will see it
    do we need the translation, the two ftl entries and the test in locale.rs?

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -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 {

    do we really need ReadOptions? asking logind for the start time and the leader is cheap, and every caller would get simpler

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -435,25 +1071,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)

    please avoid the #[allow(...)]

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -259,132 +290,197 @@ impl Utmpx {
     
         /// Canonicalize host name using DNS
         pub fn canon_host(&self) -> IOResult<String> {
    -        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::<IOResult<Vec<_>>>()?;
    -                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.
    +    /// Read a specific file, remembering it for subsequent iterators.
         ///
    -    /// This will use the default location, or the path [`Utmpx::iter_all_records_from`]
    -    /// was most recently called with.
    +    /// 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.
         ///
    -    /// On systems with systemd-logind feature enabled at compile time,
    -    /// this will use systemd-logind instead of traditional utmp files.
    -    ///
    -    /// Only one instance of [`UtmpxIter`] may be active at a time. This
    -    /// function will block as long as one is still active. Beware!
    -    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<P: AsRef<Path>>(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<P: AsRef<Path>>(
    +        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<P: AsRef<Path>>(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();
    +pub(crate) fn canonicalize_host(host: String) -> IOResult<String> {
    +    let (hostname, display) = host.split_once(':').unwrap_or((&host, ""));
    +
    +    if !hostname.is_empty() {
    +        use dns_lookup::{AddrInfoHints, getaddrinfo};
    +
    +        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::<IOResult<Vec<_>>>()?;
    +            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());
             }
    +    }
     
    -        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());
    +    Ok(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<Option<PathBuf>> = 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<std::fs::File> {
    +    #[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()?;
    +        file.metadata().ok()?.is_file().then_some(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(());
    +// 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<std::rc::Rc<()>>,
    -    #[cfg(all(feature = "systemd_logind", target_os = "linux"))]
    +    #[cfg(all(target_os = "linux", feature = "systemd-logind"))]
         systemd_iter: Option<systemd_logind::SystemdUtmpxIter>,
    +    #[cfg(target_os = "linux")]
    +    traditional_file: Option<std::fs::File>,
    +    #[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<tests::DropObserver>,

    please don't add a test-only field to the iterator

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -556,9 +1259,23 @@ 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.

    who needs this? nothing in the tree calls getutxent() on linux anymore

    sylvestre sylvestre commented on code on Nov 17, 2026 07:52 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -394,39 +490,579 @@ 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<systemd_logind::SystemdUtmpxIter>,
    +    ) -> 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::<utmpx>() 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 {

    could you please move these tests into their own file, like systemd_logind/tests.rs?

    sylvestre sylvestre commented on Nov 17, 2026 07:52 UTC
    Contributor

    thanks for the patch!
    The main blocker is the new Linux utmp reader, the one that replaces getutxent(): please split it into another PR (details inline).
    Please also rebase so only your commits are left, and squash them into a single commit.

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:00 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -259,132 +290,197 @@ impl Utmpx {
     
         /// Canonicalize host name using DNS
         pub fn canon_host(&self) -> IOResult<String> {
    -        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::<IOResult<Vec<_>>>()?;
    -                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.
    +    /// Read a specific file, remembering it for subsequent iterators.
         ///
    -    /// This will use the default location, or the path [`Utmpx::iter_all_records_from`]
    -    /// was most recently called with.
    +    /// 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.
         ///
    -    /// On systems with systemd-logind feature enabled at compile time,
    -    /// this will use systemd-logind instead of traditional utmp files.
    -    ///
    -    /// Only one instance of [`UtmpxIter`] may be active at a time. This
    -    /// function will block as long as one is still active. Beware!
    -    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<P: AsRef<Path>>(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<P: AsRef<Path>>(
    +        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<P: AsRef<Path>>(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();
    +pub(crate) fn canonicalize_host(host: String) -> IOResult<String> {
    +    let (hostname, display) = host.split_once(':').unwrap_or((&host, ""));
    +
    +    if !hostname.is_empty() {
    +        use dns_lookup::{AddrInfoHints, getaddrinfo};
    +
    +        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::<IOResult<Vec<_>>>()?;
    +            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());
             }
    +    }
     
    -        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());
    +    Ok(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<Option<PathBuf>> = 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<std::fs::File> {
    +    #[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()?;
    +        file.metadata().ok()?.is_file().then_some(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(());
    +// 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(

    fixed it

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:01 UTC
    Code Review
    src/uucore/src/lib/features/systemd_logind.rs:1
    @@ -190,60 +299,71 @@ impl SystemdLoginRecord {
         }
     
         /// Get login time as [`time::OffsetDateTime`] compatible with utmpx
    -    pub fn login_time_offset(&self) -> time::OffsetDateTime {
    -        let duration = self
    -            .login_time
    -            .duration_since(UNIX_EPOCH)
    -            .unwrap_or_default();
    -        let ts_nanos: i128 = (duration.as_nanos()).try_into().unwrap_or(0);
    +    pub fn try_login_time_offset(&self) -> Option<time::OffsetDateTime> {
    +        let duration = self.login_time.duration_since(UNIX_EPOCH).ok()?;
    +        if duration.is_zero() {
    +            return None;
    +        }
    +        let ts_nanos: i128 = duration.as_nanos().try_into().ok()?;
    +        let datetime = time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos).ok()?;
             let local_offset = time::OffsetDateTime::now_local()
                 .map_or_else(|_| time::UtcOffset::UTC, time::OffsetDateTime::offset);
    -        time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos)
    -            .unwrap_or_else(|_| {
    -                time::OffsetDateTime::now_local()
    -                    .unwrap_or_else(|_| time::OffsetDateTime::now_utc())
    -            })
    -            .to_offset(local_offset)
    +        Some(datetime.to_offset(local_offset))
    +    }
    +
    +    /// Get the login time, or the Unix epoch when it is unavailable.
    +    /// Use [`Self::try_login_time_offset`] when displaying timestamps.
    +    pub fn login_time_offset(&self) -> time::OffsetDateTime {
    +        self.try_login_time_offset()
    +            .unwrap_or(time::OffsetDateTime::UNIX_EPOCH)
         }
     }
     
     /// Read login records from systemd-logind using safe wrapper functions
     /// This matches the approach used by GNU coreutils `read_utmp_from_systemd()`
     pub fn read_login_records() -> UResult<Vec<SystemdLoginRecord>> {
    -    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<Vec<SystemdLoginRecord>> {
    +    let api = ffi::SystemdLoginApi::load().map_err(|e| {
    +        USimpleError::new(
    +            1,
    +            crate::translate!("systemd-logind-error-load-library", "error" => e),

    fixed it

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:01 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -259,132 +290,197 @@ impl Utmpx {
     
         /// Canonicalize host name using DNS
         pub fn canon_host(&self) -> IOResult<String> {
    -        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::<IOResult<Vec<_>>>()?;
    -                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.
    +    /// Read a specific file, remembering it for subsequent iterators.
         ///
    -    /// This will use the default location, or the path [`Utmpx::iter_all_records_from`]
    -    /// was most recently called with.
    +    /// 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.
         ///
    -    /// On systems with systemd-logind feature enabled at compile time,
    -    /// this will use systemd-logind instead of traditional utmp files.
    -    ///
    -    /// Only one instance of [`UtmpxIter`] may be active at a time. This
    -    /// function will block as long as one is still active. Beware!
    -    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<P: AsRef<Path>>(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<P: AsRef<Path>>(
    +        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<P: AsRef<Path>>(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();
    +pub(crate) fn canonicalize_host(host: String) -> IOResult<String> {
    +    let (hostname, display) = host.split_once(':').unwrap_or((&host, ""));
    +
    +    if !hostname.is_empty() {
    +        use dns_lookup::{AddrInfoHints, getaddrinfo};
    +
    +        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::<IOResult<Vec<_>>>()?;
    +            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());
             }
    +    }
     
    -        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());
    +    Ok(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<Option<PathBuf>> = 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<std::fs::File> {
    +    #[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()?;
    +        file.metadata().ok()?.is_file().then_some(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(());
    +// 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<std::rc::Rc<()>>,
    -    #[cfg(all(feature = "systemd_logind", target_os = "linux"))]
    +    #[cfg(all(target_os = "linux", feature = "systemd-logind"))]
         systemd_iter: Option<systemd_logind::SystemdUtmpxIter>,
    +    #[cfg(target_os = "linux")]
    +    traditional_file: Option<std::fs::File>,
    +    #[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<tests::DropObserver>,

    fixed it

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:01 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -556,9 +1259,23 @@ 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.

    fixed it

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:02 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -394,39 +490,579 @@ 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<systemd_logind::SystemdUtmpxIter>,
    +    ) -> 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::<utmpx>() 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 {

    Moved the tests into utmpx/tests.rs.

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:02 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -435,25 +1071,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)

    fixed it

    mattsu2020 mattsu2020 commented on code on Nov 17, 2026 09:03 UTC
    Code Review
    src/uucore/src/lib/features/utmpx.rs:1
    @@ -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 {

    Removed ReadOptions.

    Reviewers
    Assignees
    mattsu2020 mattsu2020
    Labels
    risk: low confidence: 89.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 78.5% (HIGH) · Higher = larger blast radius
    78.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.2% · Lower = rushed or shallow review
    89.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.5% · Safe to merge
    8.5%