Skip to main content

uucore/features/
systemd_logind.rs

1// This file is part of the uutils coreutils package.
2//
3// For the full copyright and license information, please view the LICENSE
4// file that was distributed with this source code.
5
6// spell-checker:ignore logind libsystemd btime unref RAII testuser GETPW sysconf
7
8//! Systemd-logind support for reading login records
9//!
10//! This module provides systemd-logind based implementation for reading
11//! login records as an alternative to traditional utmp/utmpx files.
12//! When the systemd-logind feature is enabled and systemd is available,
13//! this will be used instead of traditional utmp files.
14
15use core::ffi::CStr;
16use std::mem::MaybeUninit;
17use std::time::{SystemTime, UNIX_EPOCH};
18
19use crate::error::{UResult, USimpleError};
20
21/// FFI bindings for libsystemd login and D-Bus functions
22mod ffi {
23    use core::ffi::{c_char, c_int, c_uint};
24
25    #[link(name = "systemd")]
26    unsafe extern "C" {
27        pub fn sd_get_sessions(sessions: *mut *mut *mut c_char) -> c_int;
28        pub fn sd_session_get_uid(session: *const c_char, uid: *mut c_uint) -> c_int;
29        pub fn sd_session_get_start_time(session: *const c_char, usec: *mut u64) -> c_int;
30        pub fn sd_session_get_tty(session: *const c_char, tty: *mut *mut c_char) -> c_int;
31        pub fn sd_session_get_remote_host(
32            session: *const c_char,
33            remote_host: *mut *mut c_char,
34        ) -> c_int;
35        pub fn sd_session_get_display(session: *const c_char, display: *mut *mut c_char) -> c_int;
36        pub fn sd_session_get_seat(session: *const c_char, seat: *mut *mut c_char) -> c_int;
37
38    }
39}
40
41/// Safe wrapper functions for libsystemd FFI calls
42mod login {
43    use super::ffi;
44    use core::ffi::{CStr, c_char, c_int};
45    use std::ffi::CString;
46    use std::ptr;
47    use std::time::SystemTime;
48
49    /// Get all active sessions
50    pub fn get_sessions() -> Result<Vec<String>, Box<dyn std::error::Error>> {
51        let mut sessions_ptr: *mut *mut c_char = ptr::null_mut();
52
53        let result = unsafe { ffi::sd_get_sessions(&raw mut sessions_ptr) };
54
55        if result < 0 {
56            return Err(format!("sd_get_sessions failed: {result}").into());
57        }
58
59        let mut sessions = Vec::new();
60        if !sessions_ptr.is_null() {
61            let mut i = 0;
62            loop {
63                let session_ptr = unsafe { *sessions_ptr.add(i) };
64                if session_ptr.is_null() {
65                    break;
66                }
67
68                let session_cstr = unsafe { CStr::from_ptr(session_ptr) };
69                sessions.push(session_cstr.to_string_lossy().into_owned());
70
71                unsafe { libc::free(session_ptr.cast()) };
72                i += 1;
73            }
74
75            unsafe { libc::free(sessions_ptr.cast()) };
76        }
77
78        Ok(sessions)
79    }
80
81    /// Get UID for a session
82    pub fn get_session_uid(session_id: &str) -> Result<u32, Box<dyn std::error::Error>> {
83        let session_cstring = CString::new(session_id)?;
84        let mut uid: core::ffi::c_uint = 0;
85
86        let result = unsafe { ffi::sd_session_get_uid(session_cstring.as_ptr(), &raw mut uid) };
87
88        if result < 0 {
89            return Err(
90                format!("sd_session_get_uid failed for session '{session_id}': {result}").into(),
91            );
92        }
93
94        Ok(uid)
95    }
96
97    /// Get start time for a session (in microseconds since Unix epoch)
98    pub fn get_session_start_time(session_id: &str) -> Result<u64, Box<dyn std::error::Error>> {
99        let session_cstring = CString::new(session_id)?;
100        let mut usec: u64 = 0;
101
102        let result =
103            unsafe { ffi::sd_session_get_start_time(session_cstring.as_ptr(), &raw mut usec) };
104
105        if result < 0 {
106            return Err(format!(
107                "sd_session_get_start_time failed for session '{session_id}': {result}",
108            )
109            .into());
110        }
111
112        Ok(usec)
113    }
114
115    /// Read a string property of a session, such as its TTY or seat, with one of
116    /// the `sd_session_get_*` getters. An error or an unset property gives an
117    /// empty string.
118    pub fn get_session_string(
119        session_id: &str,
120        getter: unsafe extern "C" fn(*const c_char, *mut *mut c_char) -> c_int,
121    ) -> String {
122        let Ok(session_cstring) = CString::new(session_id) else {
123            return String::new();
124        };
125        let mut value_ptr: *mut c_char = ptr::null_mut();
126
127        // SAFETY: `session_cstring` is NUL-terminated and outlives the call; the
128        // getter only stores a pointer in `value_ptr`.
129        let result = unsafe { getter(session_cstring.as_ptr(), &raw mut value_ptr) };
130        if result < 0 || value_ptr.is_null() {
131            return String::new();
132        }
133
134        // SAFETY: on success `value_ptr` is a NUL-terminated string allocated by
135        // libsystemd, which we own and free once copied.
136        let value = unsafe { CStr::from_ptr(value_ptr) }
137            .to_string_lossy()
138            .into_owned();
139        unsafe { libc::free(value_ptr.cast()) };
140        value
141    }
142
143    /// Get system boot time using systemd random-seed file fallback
144    ///
145    /// TODO: This replicates GNU coreutils' fallback behavior for compatibility.
146    /// GNU coreutils uses the mtime of /var/lib/systemd/random-seed as a heuristic for boot time
147    /// when utmp is unavailable, rather than querying systemd's authoritative `KernelTimestamp`.
148    /// This creates inconsistency: `uptime -s` shows the actual kernel boot time
149    /// while `who -b` shows ~1 minute later when systemd services start.
150    ///
151    /// Ideally, both should use the same source (`KernelTimestamp`) for semantic consistency.
152    /// Consider proposing to GNU coreutils to use systemd's `KernelTimestamp` property instead.
153    pub fn get_boot_time() -> Result<SystemTime, Box<dyn std::error::Error>> {
154        use std::fs;
155
156        let metadata = fs::metadata("/var/lib/systemd/random-seed")
157            .map_err(|e| format!("Failed to read /var/lib/systemd/random-seed: {e}"))?;
158
159        metadata
160            .modified()
161            .map_err(|e| format!("Failed to get modification time: {e}").into())
162    }
163}
164
165/// Login record compatible with utmpx structure
166#[derive(Debug, Clone)]
167pub struct SystemdLoginRecord {
168    pub user: String,
169    pub session_id: String,
170    pub seat_or_tty: String,
171    pub raw_device: String,
172    pub host: String,
173    pub login_time: SystemTime,
174    pub pid: u32,
175    pub session_leader_pid: u32,
176    pub record_type: SystemdRecordType,
177}
178
179#[derive(Debug, Clone, Copy, PartialEq)]
180pub enum SystemdRecordType {
181    UserProcess = 7,  // USER_PROCESS
182    LoginProcess = 6, // LOGIN_PROCESS
183    BootTime = 2,     // BOOT_TIME
184}
185
186impl SystemdLoginRecord {
187    /// Check if this is a user process record
188    pub fn is_user_process(&self) -> bool {
189        !self.user.is_empty() && self.record_type == SystemdRecordType::UserProcess
190    }
191
192    /// Get login time as [`time::OffsetDateTime`] compatible with utmpx
193    pub fn login_time_offset(&self) -> time::OffsetDateTime {
194        let duration = self
195            .login_time
196            .duration_since(UNIX_EPOCH)
197            .unwrap_or_default();
198        let ts_nanos: i128 = (duration.as_nanos()).try_into().unwrap_or(0);
199        let local_offset = time::OffsetDateTime::now_local()
200            .map_or_else(|_| time::UtcOffset::UTC, time::OffsetDateTime::offset);
201        time::OffsetDateTime::from_unix_timestamp_nanos(ts_nanos)
202            .unwrap_or_else(|_| {
203                time::OffsetDateTime::now_local()
204                    .unwrap_or_else(|_| time::OffsetDateTime::now_utc())
205            })
206            .to_offset(local_offset)
207    }
208}
209
210/// Read login records from systemd-logind using safe wrapper functions
211/// This matches the approach used by GNU coreutils `read_utmp_from_systemd()`
212pub fn read_login_records() -> UResult<Vec<SystemdLoginRecord>> {
213    let mut records = Vec::new();
214
215    // Add boot time record first
216    if let Ok(boot_time) = login::get_boot_time() {
217        let boot_record = SystemdLoginRecord {
218            user: "reboot".to_string(),
219            session_id: "boot".to_string(),
220            seat_or_tty: "~".to_string(), // Traditional boot time indicator
221            raw_device: String::new(),
222            host: String::new(),
223            login_time: boot_time,
224            pid: 0,
225            session_leader_pid: 0,
226            record_type: SystemdRecordType::BootTime,
227        };
228        records.push(boot_record);
229    }
230
231    // Get all active sessions using safe wrapper
232    let mut sessions = login::get_sessions()
233        .map_err(|e| USimpleError::new(1, format!("Failed to get systemd sessions: {e}")))?;
234
235    // Sort sessions consistently for reproducible output (reverse for TTY sessions first)
236    sessions.sort();
237    sessions.reverse();
238
239    // Iterate through all sessions
240    for session_id in sessions {
241        // Get session UID using safe wrapper
242        let Ok(uid) = login::get_session_uid(&session_id) else {
243            continue;
244        };
245
246        // Get username from UID
247        let user = unsafe {
248            let mut passwd = MaybeUninit::<libc::passwd>::uninit();
249
250            // Get recommended buffer size, fall back if indeterminate
251            let buf_size = {
252                let size = libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX);
253                if size == -1 {
254                    16384 // Value was indeterminate, use fallback from getpwuid_r man page
255                } else {
256                    size as usize
257                }
258            };
259            let mut buf = vec![0u8; buf_size];
260            let mut result: *mut libc::passwd = std::ptr::null_mut();
261
262            let ret = libc::getpwuid_r(
263                uid,
264                passwd.as_mut_ptr(),
265                buf.as_mut_ptr().cast(),
266                buf.len(),
267                &raw mut result,
268            );
269
270            if ret == 0 && !result.is_null() {
271                let passwd = passwd.assume_init();
272                CStr::from_ptr(passwd.pw_name)
273                    .to_string_lossy()
274                    .into_owned()
275            } else {
276                format!("{uid}") // fallback to UID if username not found
277            }
278        };
279
280        // Get start time using safe wrapper, fallback to epoch if unavailable
281        let start_time = login::get_session_start_time(&session_id).map_or(UNIX_EPOCH, |usec| {
282            UNIX_EPOCH + std::time::Duration::from_micros(usec)
283        });
284
285        // Get TTY using safe wrapper
286        let mut tty = login::get_session_string(&session_id, ffi::sd_session_get_tty);
287
288        // Get seat using safe wrapper
289        let mut seat = login::get_session_string(&session_id, ffi::sd_session_get_seat);
290
291        // Strip any existing prefixes from systemd values (if any)
292        if tty.starts_with('?') {
293            tty = tty[1..].to_string();
294        }
295        if seat.starts_with('?') {
296            seat = seat[1..].to_string();
297        }
298
299        // Get remote host using safe wrapper
300        let remote_host = login::get_session_string(&session_id, ffi::sd_session_get_remote_host);
301
302        // Get display using safe wrapper (for GUI sessions)
303        let display = login::get_session_string(&session_id, ffi::sd_session_get_display);
304
305        // Determine host (use remote_host if available)
306        // If host is local (non-remote) we use display,
307        let host = if remote_host.is_empty() {
308            display.clone()
309        } else {
310            remote_host
311        };
312
313        // Skip sessions that have neither TTY nor seat (e.g., manager sessions)
314        if tty.is_empty() && seat.is_empty() && display.is_empty() {
315            continue;
316        }
317
318        // A single session can be associated with both a TTY and a seat.
319        // GNU `who` and `pinky` create separate records for each.
320        // We replicate that behavior here.
321        // Order: seat first, then TTY to match expected output
322
323        // Helper closure to create a record
324        let create_record = |seat_or_tty: String,
325                             raw_device: String,
326                             user: String,
327                             session_id: String,
328                             host: String| {
329            SystemdLoginRecord {
330                user,
331                session_id,
332                seat_or_tty,
333                raw_device,
334                host,
335                login_time: start_time,
336                pid: 0, // systemd doesn't directly provide session leader PID in this context
337                session_leader_pid: 0,
338                record_type: SystemdRecordType::UserProcess,
339            }
340        };
341
342        // Create records based on available seat/tty/display
343        if !seat.is_empty() && !tty.is_empty() {
344            // Both seat and tty - need 2 records, clone for first.
345            // The seat is prefixed with '?' to match GNU's output.
346            let seat_formatted = format!("?{seat}");
347            records.push(create_record(
348                seat_formatted,
349                seat,
350                user.clone(),
351                session_id.clone(),
352                host.clone(),
353            ));
354
355            let tty_formatted = if tty.starts_with("tty") {
356                format!("*{tty}")
357            } else {
358                tty.clone()
359            };
360            records.push(create_record(tty_formatted, tty, user, session_id, host)); // Move for second (and last) record
361        } else if !seat.is_empty() {
362            // Only seat
363            let seat_formatted = format!("?{seat}");
364            records.push(create_record(seat_formatted, seat, user, session_id, host));
365        } else if !tty.is_empty() {
366            // Only tty
367            let tty_formatted = if tty.starts_with("tty") {
368                format!("*{tty}")
369            } else {
370                tty.clone()
371            };
372            records.push(create_record(tty_formatted, tty, user, session_id, host));
373        } else if !display.is_empty() {
374            // Only display
375            // No raw device for display sessions
376            records.push(create_record(
377                display,
378                String::new(),
379                user,
380                session_id,
381                host,
382            ));
383        }
384    }
385
386    Ok(records)
387}
388
389/// Wrapper to provide utmpx-compatible interface for a single record
390pub struct SystemdUtmpxCompat {
391    record: SystemdLoginRecord,
392}
393
394impl SystemdUtmpxCompat {
395    /// Create new instance from a [`SystemdLoginRecord`]
396    pub fn new(record: SystemdLoginRecord) -> Self {
397        Self { record }
398    }
399
400    /// A.K.A. `ut.ut_type`
401    pub fn record_type(&self) -> i16 {
402        self.record.record_type as i16
403    }
404
405    /// A.K.A. `ut.ut_pid`
406    pub fn pid(&self) -> i32 {
407        self.record.pid as i32
408    }
409
410    /// A.K.A. `ut.ut_id`
411    pub fn terminal_suffix(&self) -> String {
412        // Extract last part of session ID or use session ID
413        self.record.session_id.clone()
414    }
415
416    /// A.K.A. `ut.ut_user`
417    pub fn user(&self) -> String {
418        self.record.user.clone()
419    }
420
421    /// A.K.A. `ut.ut_host`
422    pub fn host(&self) -> String {
423        self.record.host.clone()
424    }
425
426    /// A.K.A. `ut.ut_line`
427    pub fn tty_device(&self) -> String {
428        // Return raw device name for device access if available, otherwise formatted seat_or_tty
429        if self.record.raw_device.is_empty() {
430            self.record.seat_or_tty.clone()
431        } else {
432            self.record.raw_device.clone()
433        }
434    }
435
436    /// Login time
437    pub fn login_time(&self) -> time::OffsetDateTime {
438        self.record.login_time_offset()
439    }
440
441    /// Exit status (not available from systemd)
442    pub fn exit_status(&self) -> (i16, i16) {
443        (0, 0) // Not available from systemd
444    }
445
446    /// Check if this is a user process record
447    pub fn is_user_process(&self) -> bool {
448        self.record.is_user_process()
449    }
450
451    /// Canonical host name
452    pub fn canon_host(&self) -> String {
453        // Simple implementation - just return the host as-is
454        // Could be enhanced with DNS lookup like the original
455        self.record.host.clone()
456    }
457}
458
459/// Container for reading multiple systemd records
460pub struct SystemdUtmpxIter {
461    records: Vec<SystemdLoginRecord>,
462    current_index: usize,
463}
464
465impl SystemdUtmpxIter {
466    /// Create new instance and read records from systemd-logind
467    pub fn new() -> UResult<Self> {
468        let records = read_login_records()?;
469        Ok(Self {
470            records,
471            current_index: 0,
472        })
473    }
474
475    /// Create empty iterator (for when systemd initialization fails)
476    pub fn empty() -> Self {
477        Self {
478            records: Vec::new(),
479            current_index: 0,
480        }
481    }
482
483    /// Get next record (similar to getutxent)
484    pub fn next_record(&mut self) -> Option<SystemdUtmpxCompat> {
485        if self.current_index >= self.records.len() {
486            return None;
487        }
488
489        let record = self.records[self.current_index].clone();
490        self.current_index += 1;
491
492        Some(SystemdUtmpxCompat::new(record))
493    }
494
495    /// Get all records at once
496    pub fn get_all_records(&self) -> Vec<SystemdUtmpxCompat> {
497        self.records
498            .iter()
499            .cloned()
500            .map(SystemdUtmpxCompat::new)
501            .collect()
502    }
503
504    /// Reset iterator to beginning
505    pub fn reset(&mut self) {
506        self.current_index = 0;
507    }
508
509    /// Get number of records
510    pub fn len(&self) -> usize {
511        self.records.len()
512    }
513
514    /// Check if empty
515    pub fn is_empty(&self) -> bool {
516        self.records.is_empty()
517    }
518}
519
520impl Iterator for SystemdUtmpxIter {
521    type Item = SystemdUtmpxCompat;
522
523    fn next(&mut self) -> Option<Self::Item> {
524        self.next_record()
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    #[test]
533    fn test_empty_iterator() {
534        let mut iter = SystemdUtmpxIter::empty();
535
536        assert_eq!(iter.len(), 0);
537        assert!(iter.is_empty());
538        assert!(iter.next().is_none());
539        assert!(iter.next_record().is_none());
540    }
541
542    #[test]
543    fn test_iterator_with_mock_data() {
544        // Create iterator with mock records
545        let mock_records = vec![
546            SystemdLoginRecord {
547                session_id: "session1".to_string(),
548                user: "user1".to_string(),
549                seat_or_tty: "tty1".to_string(),
550                raw_device: "tty1".to_string(),
551                host: "host1".to_string(),
552                login_time: UNIX_EPOCH,
553                pid: 1234,
554                session_leader_pid: 1234,
555                record_type: SystemdRecordType::UserProcess,
556            },
557            SystemdLoginRecord {
558                session_id: "session2".to_string(),
559                user: "user2".to_string(),
560                seat_or_tty: "pts/0".to_string(),
561                raw_device: "pts/0".to_string(),
562                host: "host2".to_string(),
563                login_time: UNIX_EPOCH,
564                pid: 5678,
565                session_leader_pid: 5678,
566                record_type: SystemdRecordType::UserProcess,
567            },
568        ];
569
570        let mut iter = SystemdUtmpxIter {
571            records: mock_records,
572            current_index: 0,
573        };
574
575        assert_eq!(iter.len(), 2);
576        assert!(!iter.is_empty());
577
578        // Test iterator behavior
579        let first = iter.next();
580        assert!(first.is_some());
581
582        let second = iter.next();
583        assert!(second.is_some());
584
585        let third = iter.next();
586        assert!(third.is_none());
587
588        // Iterator should be exhausted
589        assert!(iter.next().is_none());
590    }
591
592    #[test]
593    fn test_get_all_records() {
594        let mock_records = vec![SystemdLoginRecord {
595            session_id: "session1".to_string(),
596            user: "user1".to_string(),
597            seat_or_tty: "tty1".to_string(),
598            raw_device: "tty1".to_string(),
599            host: "host1".to_string(),
600            login_time: UNIX_EPOCH,
601            pid: 1234,
602            session_leader_pid: 1234,
603            record_type: SystemdRecordType::UserProcess,
604        }];
605
606        let iter = SystemdUtmpxIter {
607            records: mock_records,
608            current_index: 0,
609        };
610
611        let all_records = iter.get_all_records();
612        assert_eq!(all_records.len(), 1);
613    }
614
615    #[test]
616    fn test_systemd_record_conversion() {
617        // Test that SystemdLoginRecord converts correctly to SystemdUtmpxCompat
618        let record = SystemdLoginRecord {
619            session_id: "c1".to_string(),
620            user: "testuser".to_string(),
621            seat_or_tty: "seat0".to_string(),
622            raw_device: "seat0".to_string(),
623            host: "localhost".to_string(),
624            login_time: UNIX_EPOCH + std::time::Duration::from_secs(1000),
625            pid: 9999,
626            session_leader_pid: 9999,
627            record_type: SystemdRecordType::UserProcess,
628        };
629
630        let compat = SystemdUtmpxCompat::new(record);
631
632        // Test the actual conversion logic
633        assert_eq!(compat.user(), "testuser");
634        assert_eq!(compat.tty_device().as_str(), "seat0");
635        assert_eq!(compat.host(), "localhost");
636    }
637}