1use core::ffi::CStr;
16use std::mem::MaybeUninit;
17use std::time::{SystemTime, UNIX_EPOCH};
18
19use crate::error::{UResult, USimpleError};
20
21mod 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
41mod 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 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 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 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 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 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 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 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#[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, LoginProcess = 6, BootTime = 2, }
185
186impl SystemdLoginRecord {
187 pub fn is_user_process(&self) -> bool {
189 !self.user.is_empty() && self.record_type == SystemdRecordType::UserProcess
190 }
191
192 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
210pub fn read_login_records() -> UResult<Vec<SystemdLoginRecord>> {
213 let mut records = Vec::new();
214
215 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(), 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 let mut sessions = login::get_sessions()
233 .map_err(|e| USimpleError::new(1, format!("Failed to get systemd sessions: {e}")))?;
234
235 sessions.sort();
237 sessions.reverse();
238
239 for session_id in sessions {
241 let Ok(uid) = login::get_session_uid(&session_id) else {
243 continue;
244 };
245
246 let user = unsafe {
248 let mut passwd = MaybeUninit::<libc::passwd>::uninit();
249
250 let buf_size = {
252 let size = libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX);
253 if size == -1 {
254 16384 } 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}") }
278 };
279
280 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 let mut tty = login::get_session_string(&session_id, ffi::sd_session_get_tty);
287
288 let mut seat = login::get_session_string(&session_id, ffi::sd_session_get_seat);
290
291 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 let remote_host = login::get_session_string(&session_id, ffi::sd_session_get_remote_host);
301
302 let display = login::get_session_string(&session_id, ffi::sd_session_get_display);
304
305 let host = if remote_host.is_empty() {
308 display.clone()
309 } else {
310 remote_host
311 };
312
313 if tty.is_empty() && seat.is_empty() && display.is_empty() {
315 continue;
316 }
317
318 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, session_leader_pid: 0,
338 record_type: SystemdRecordType::UserProcess,
339 }
340 };
341
342 if !seat.is_empty() && !tty.is_empty() {
344 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)); } else if !seat.is_empty() {
362 let seat_formatted = format!("?{seat}");
364 records.push(create_record(seat_formatted, seat, user, session_id, host));
365 } else if !tty.is_empty() {
366 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 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
389pub struct SystemdUtmpxCompat {
391 record: SystemdLoginRecord,
392}
393
394impl SystemdUtmpxCompat {
395 pub fn new(record: SystemdLoginRecord) -> Self {
397 Self { record }
398 }
399
400 pub fn record_type(&self) -> i16 {
402 self.record.record_type as i16
403 }
404
405 pub fn pid(&self) -> i32 {
407 self.record.pid as i32
408 }
409
410 pub fn terminal_suffix(&self) -> String {
412 self.record.session_id.clone()
414 }
415
416 pub fn user(&self) -> String {
418 self.record.user.clone()
419 }
420
421 pub fn host(&self) -> String {
423 self.record.host.clone()
424 }
425
426 pub fn tty_device(&self) -> String {
428 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 pub fn login_time(&self) -> time::OffsetDateTime {
438 self.record.login_time_offset()
439 }
440
441 pub fn exit_status(&self) -> (i16, i16) {
443 (0, 0) }
445
446 pub fn is_user_process(&self) -> bool {
448 self.record.is_user_process()
449 }
450
451 pub fn canon_host(&self) -> String {
453 self.record.host.clone()
456 }
457}
458
459pub struct SystemdUtmpxIter {
461 records: Vec<SystemdLoginRecord>,
462 current_index: usize,
463}
464
465impl SystemdUtmpxIter {
466 pub fn new() -> UResult<Self> {
468 let records = read_login_records()?;
469 Ok(Self {
470 records,
471 current_index: 0,
472 })
473 }
474
475 pub fn empty() -> Self {
477 Self {
478 records: Vec::new(),
479 current_index: 0,
480 }
481 }
482
483 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 pub fn get_all_records(&self) -> Vec<SystemdUtmpxCompat> {
497 self.records
498 .iter()
499 .cloned()
500 .map(SystemdUtmpxCompat::new)
501 .collect()
502 }
503
504 pub fn reset(&mut self) {
506 self.current_index = 0;
507 }
508
509 pub fn len(&self) -> usize {
511 self.records.len()
512 }
513
514 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 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 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 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 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 assert_eq!(compat.user(), "testuser");
634 assert_eq!(compat.tty_device().as_str(), "seat0");
635 assert_eq!(compat.host(), "localhost");
636 }
637}