@@ -37,7 +37,7 @@ use std::ffi::CString;
3737use std:: io:: Result as IOResult ;
3838use std:: marker:: PhantomData ;
3939use std:: os:: unix:: ffi:: OsStrExt ;
40- use std:: path:: Path ;
40+ use std:: path:: { Path , PathBuf } ;
4141use std:: ptr;
4242use std:: sync:: { Mutex , MutexGuard } ;
4343
@@ -296,30 +296,28 @@ impl Utmpx {
296296 /// This will use the default location, or the path [`Utmpx::iter_all_records_from`]
297297 /// was most recently called with.
298298 ///
299- /// On systems with systemd-logind feature enabled at compile time,
300- /// this will use systemd-logind instead of traditional utmp files .
299+ /// With `systemd_logind` enabled on Linux, the default path selects systemd.
300+ /// A custom path continues to select its file on subsequent calls .
301301 ///
302302 /// Only one instance of [`UtmpxIter`] may be active at a time. This
303303 /// function will block as long as one is still active. Beware!
304304 pub fn iter_all_records ( ) -> UtmpxIter {
305+ let iter = UtmpxIter :: new ( ) ;
305306 #[ cfg( all( feature = "systemd_logind" , target_os = "linux" ) ) ]
307+ if iter
308+ . guard
309+ . as_deref ( )
310+ . is_none_or ( |path| path == Path :: new ( DEFAULT_FILE ) )
306311 {
307- // Use systemd-logind instead of traditional utmp when feature is enabled
308- UtmpxIter :: new_systemd ( )
312+ return iter. with_systemd ( ) ;
309313 }
310314
311- #[ cfg( not( all( feature = "systemd_logind" , target_os = "linux" ) ) ) ]
312- {
313- let iter = UtmpxIter :: new ( ) ;
314- unsafe {
315- // This can technically fail, and it would be nice to detect that,
316- // but it doesn't return anything so we'd have to do nasty things
317- // with errno.
318- #[ cfg_attr( any( target_env = "musl" , target_env = "ohos" ) , allow( deprecated) ) ]
319- setutxent ( ) ;
320- }
321- iter
315+ // SAFETY: The iterator holds LOCK while accessing libc's global state.
316+ unsafe {
317+ #[ cfg_attr( any( target_env = "musl" , target_env = "ohos" ) , allow( deprecated) ) ]
318+ setutxent ( ) ;
322319 }
320+ iter
323321 }
324322
325323 /// Iterate through all the utmp records from a specific file.
@@ -334,15 +332,13 @@ impl Utmpx {
334332 ///
335333 /// The same caveats as for [`Utmpx::iter_all_records`] apply.
336334 pub fn iter_all_records_from < P : AsRef < Path > > ( path : P ) -> UtmpxIter {
335+ let mut iter = UtmpxIter :: new ( ) ;
336+ * iter. guard = Some ( path. as_ref ( ) . to_path_buf ( ) ) ;
337337 #[ cfg( all( feature = "systemd_logind" , target_os = "linux" ) ) ]
338- {
339- // Use systemd-logind for default utmp file when feature is enabled
340- if path. as_ref ( ) == Path :: new ( DEFAULT_FILE ) {
341- return UtmpxIter :: new_systemd ( ) ;
342- }
338+ if path. as_ref ( ) == Path :: new ( DEFAULT_FILE ) {
339+ return iter. with_systemd ( ) ;
343340 }
344341
345- let iter = UtmpxIter :: new ( ) ;
346342 let path = CString :: new ( path. as_ref ( ) . as_os_str ( ) . as_bytes ( ) ) . unwrap ( ) ;
347343 unsafe {
348344 #[ cfg( target_os = "freebsd" ) ]
@@ -374,12 +370,12 @@ impl Utmpx {
374370// I believe the only technical memory unsafety that could happen is a data
375371// race while copying the data out of the pointer returned by getutxent(), but
376372// ordinary race conditions are also very much possible.
377- static LOCK : Mutex < ( ) > = Mutex :: new ( ( ) ) ;
373+ // Keep source selection under the same lock as libc's selected filename.
374+ static LOCK : Mutex < Option < PathBuf > > = Mutex :: new ( None ) ;
378375
379376/// Iterator of login records
380377pub struct UtmpxIter {
381- #[ allow( dead_code) ]
382- guard : MutexGuard < ' static , ( ) > ,
378+ guard : MutexGuard < ' static , Option < PathBuf > > ,
383379 /// Ensure [`UtmpxIter`] is !Send. Technically redundant because [`MutexGuard`]
384380 /// is also !Send.
385381 phantom : PhantomData < std:: rc:: Rc < ( ) > > ,
@@ -402,11 +398,7 @@ impl UtmpxIter {
402398 }
403399
404400 #[ cfg( all( feature = "systemd_logind" , target_os = "linux" ) ) ]
405- fn new_systemd ( ) -> Self {
406- // PoisonErrors can safely be ignored
407- let guard = LOCK
408- . lock ( )
409- . unwrap_or_else ( std:: sync:: PoisonError :: into_inner) ;
401+ fn with_systemd ( mut self ) -> Self {
410402 let systemd_iter = match systemd_logind:: SystemdUtmpxIter :: new ( ) {
411403 Ok ( iter) => iter,
412404 Err ( _) => {
@@ -415,11 +407,65 @@ impl UtmpxIter {
415407 systemd_logind:: SystemdUtmpxIter :: empty ( )
416408 }
417409 } ;
418- Self {
419- guard,
420- phantom : PhantomData ,
421- systemd_iter : Some ( systemd_iter) ,
422- }
410+ self . systemd_iter = Some ( systemd_iter) ;
411+ self
412+ }
413+ }
414+
415+ #[ cfg( all( test, target_os = "linux" , not( target_env = "musl" ) ) ) ]
416+ mod tests {
417+ use super :: * ;
418+ use std:: mem:: offset_of;
419+
420+ fn utmpx_record ( user : & str ) -> Vec < u8 > {
421+ let mut bytes = vec ! [ 0 ; size_of:: <utmpx>( ) ] ;
422+ let record_type = USER_PROCESS . to_ne_bytes ( ) ;
423+ let type_offset = offset_of ! ( utmpx, ut_type) ;
424+ bytes[ type_offset..type_offset + record_type. len ( ) ] . copy_from_slice ( & record_type) ;
425+ let user_offset = offset_of ! ( utmpx, ut_user) ;
426+ assert ! ( user. len( ) <= UT_NAMESIZE ) ;
427+ bytes[ user_offset..user_offset + user. len ( ) ] . copy_from_slice ( user. as_bytes ( ) ) ;
428+ bytes
429+ }
430+
431+ fn write_utmpx_records ( path : & Path , users : & [ & str ] ) {
432+ let bytes: Vec < u8 > = users. iter ( ) . flat_map ( |user| utmpx_record ( user) ) . collect ( ) ;
433+ std:: fs:: write ( path, bytes) . unwrap ( ) ;
434+ }
435+
436+ #[ test]
437+ fn traditional_paths_persist_across_iterators ( ) {
438+ let directory = tempfile:: tempdir ( ) . unwrap ( ) ;
439+ let custom_path = directory. path ( ) . join ( "custom-utmp" ) ;
440+ let fallback_path = directory. path ( ) . join ( "fallback-utmp" ) ;
441+ write_utmpx_records ( & custom_path, & [ "custom" ] ) ;
442+ write_utmpx_records ( & fallback_path, & [ "fallback" ] ) ;
443+
444+ let custom_users = Utmpx :: iter_all_records_from ( & custom_path)
445+ . map ( |record| record. user ( ) )
446+ . collect :: < Vec < _ > > ( ) ;
447+ let repeated_custom_users = Utmpx :: iter_all_records ( )
448+ . map ( |record| record. user ( ) )
449+ . collect :: < Vec < _ > > ( ) ;
450+ let fallback_users = Utmpx :: iter_all_records_from ( & fallback_path)
451+ . map ( |record| record. user ( ) )
452+ . collect :: < Vec < _ > > ( ) ;
453+ let repeated_fallback_users = Utmpx :: iter_all_records ( )
454+ . map ( |record| record. user ( ) )
455+ . collect :: < Vec < _ > > ( ) ;
456+
457+ // Restore the default before the temporary files are removed.
458+ let default_iter = Utmpx :: iter_all_records_from ( DEFAULT_FILE ) ;
459+ #[ cfg( feature = "systemd_logind" ) ]
460+ assert ! ( default_iter. systemd_iter. is_some( ) ) ;
461+ drop ( default_iter) ;
462+ #[ cfg( feature = "systemd_logind" ) ]
463+ assert ! ( Utmpx :: iter_all_records( ) . systemd_iter. is_some( ) ) ;
464+
465+ assert_eq ! ( custom_users, [ "custom" ] ) ;
466+ assert_eq ! ( repeated_custom_users, custom_users) ;
467+ assert_eq ! ( fallback_users, [ "fallback" ] ) ;
468+ assert_eq ! ( repeated_fallback_users, fallback_users) ;
423469 }
424470}
425471
0 commit comments