| 1 | use std::sync::Arc; |
| 2 | |
| 3 | use rustc_hash::FxHashMap as HashMap; |
| 4 | |
| 5 | use crate::collection::error::{CollectionError, CollectionResult}; |
| 6 | |
| 7 | #[derive(Debug, Default)] |
| 8 | pub struct UserTable { |
| 9 | pub uid_user_mapping: HashMap<libc::uid_t, Arc<str>>, |
| 10 | } |
| 11 | |
| 12 | impl UserTable { |
| 13 | /// Get the username associated with a UID. On first access of a name, it |
| 14 | /// will be cached for future accesses. |
| 15 | pub fn uid_to_username(&mut self, uid: libc::uid_t) -> CollectionResult<Arc<str>> { |
| 16 | if let Some(user) = self.uid_user_mapping.get(&uid) { |
| 17 | Ok(user.clone()) |
| 18 | } else { |
| 19 | // SAFETY: getpwuid returns a null pointer if no passwd entry is found for the |
| 20 | // uid which we check. |
| 21 | let passwd = unsafe { libc::getpwuid(uid) }; |
| 22 | |
| 23 | if passwd.is_null() { |
| 24 | Err("passwd is inaccessible".into()) |
| 25 | } else { |
| 26 | // SAFETY: We return early if passwd is null. |
| 27 | let username: Arc<str> = unsafe { std::ffi::CStr::from_ptr((*passwd).pw_name) } |
| 28 | .to_str() |
| 29 | .map_err(|err| CollectionError::General(err.into()))? |
| 30 | .into(); |
| 31 | |
| 32 | self.uid_user_mapping.insert(uid, username.clone()); |
| 33 | |
| 34 | Ok(username) |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | } |