Skip to main content

sysinfo/common/
user.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::cmp::Ordering;
4
5use crate::{Error, Gid, Uid, UserInner};
6
7/// Type containing user information.
8///
9/// It is returned by [`Users`][crate::Users].
10///
11/// ```no_run
12/// use sysinfo::Users;
13///
14/// if let Ok(users) = Users::new_with_refreshed_list() {
15///     for user in &users {
16///         println!("{:?}", user);
17///     }
18/// }
19/// ```
20pub struct User {
21    pub(crate) inner: UserInner,
22}
23
24impl PartialEq for User {
25    fn eq(&self, other: &Self) -> bool {
26        self.id() == other.id()
27            && self.group_id() == other.group_id()
28            && self.name() == other.name()
29    }
30}
31
32impl Eq for User {}
33
34impl PartialOrd for User {
35    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
36        Some(self.cmp(other))
37    }
38}
39
40impl Ord for User {
41    fn cmp(&self, other: &Self) -> Ordering {
42        self.name().cmp(other.name())
43    }
44}
45
46impl User {
47    /// Returns the ID of the user.
48    ///
49    /// ```no_run
50    /// use sysinfo::Users;
51    ///
52    /// if let Ok(users) = Users::new_with_refreshed_list() {
53    ///     for user in &users {
54    ///         println!("{:?}", *user.id());
55    ///     }
56    /// }
57    /// ```
58    pub fn id(&self) -> &Uid {
59        self.inner.id()
60    }
61
62    /// Returns the group ID of the user.
63    ///
64    /// ⚠️ This information is not set on Windows.  Windows doesn't have a `username` specific
65    /// group assigned to the user. They do however have unique
66    /// [Security Identifiers](https://docs.microsoft.com/en-us/windows/win32/secauthz/security-identifiers)
67    /// made up of various [Components](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-components).
68    /// Pieces of the SID may be a candidate for this field, but it doesn't map well to a single
69    /// group ID.
70    ///
71    /// ```no_run
72    /// use sysinfo::Users;
73    ///
74    /// if let Ok(users) = Users::new_with_refreshed_list() {
75    ///     for user in &users {
76    ///         println!("{}", *user.group_id());
77    ///     }
78    /// }
79    /// ```
80    pub fn group_id(&self) -> Gid {
81        self.inner.group_id()
82    }
83
84    /// Returns the name of the user.
85    ///
86    /// ```no_run
87    /// use sysinfo::Users;
88    ///
89    /// if let Ok(users) = Users::new_with_refreshed_list() {
90    ///     for user in &users {
91    ///         println!("{}", user.name());
92    ///     }
93    /// }
94    /// ```
95    pub fn name(&self) -> &str {
96        self.inner.name()
97    }
98
99    /// Returns the groups of the user.
100    ///
101    /// ⚠️ This is computed every time this method is called.
102    ///
103    /// ```no_run
104    /// use sysinfo::Users;
105    ///
106    /// if let Ok(users) = Users::new_with_refreshed_list() {
107    ///     for user in &users {
108    ///         println!("{} is in {:?}", user.name(), user.groups());
109    ///     }
110    /// }
111    /// ```
112    pub fn groups(&self) -> Vec<Group> {
113        self.inner.groups()
114    }
115}
116
117#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
118pub(crate) struct GroupInner {
119    pub(crate) id: Gid,
120    pub(crate) name: String,
121}
122
123/// Type containing group information.
124///
125/// It is returned by [`User::groups`].
126///
127/// ```no_run
128/// use sysinfo::Users;
129///
130/// if let Ok(users) = Users::new_with_refreshed_list() {
131///     for user in &users {
132///         println!(
133///             "user: (ID: {:?}, group ID: {:?}, name: {:?})",
134///             user.id(),
135///             user.group_id(),
136///             user.name(),
137///         );
138///         for group in user.groups() {
139///             println!("group: (ID: {:?}, name: {:?})", group.id(), group.name());
140///         }
141///     }
142/// }
143/// ```
144#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
145pub struct Group {
146    pub(crate) inner: GroupInner,
147}
148
149impl Group {
150    /// Returns the ID of the group.
151    ///
152    /// ⚠️ This information is not set on Windows.
153    ///
154    /// ```no_run
155    /// use sysinfo::Users;
156    ///
157    /// if let Ok(users) = Users::new_with_refreshed_list() {
158    ///     for user in &users {
159    ///         for group in user.groups() {
160    ///             println!("{:?}", group.id());
161    ///         }
162    ///     }
163    /// }
164    /// ```
165    pub fn id(&self) -> &Gid {
166        self.inner.id()
167    }
168
169    /// Returns the name of the group.
170    ///
171    /// ```no_run
172    /// use sysinfo::Users;
173    ///
174    /// if let Ok(users) = Users::new_with_refreshed_list() {
175    ///     for user in &users {
176    ///         for group in user.groups() {
177    ///             println!("{}", group.name());
178    ///         }
179    ///     }
180    /// }
181    /// ```
182    pub fn name(&self) -> &str {
183        self.inner.name()
184    }
185}
186
187/// Interacting with users.
188///
189/// ```no_run
190/// use sysinfo::Users;
191///
192/// if let Ok(users) = Users::new_with_refreshed_list() {
193///     for user in &users {
194///         println!("{} is in {} groups", user.name(), user.groups().len());
195///     }
196/// }
197/// ```
198pub struct Users {
199    users: Vec<User>,
200}
201
202impl std::ops::Deref for Users {
203    type Target = [User];
204
205    fn deref(&self) -> &Self::Target {
206        &self.users
207    }
208}
209
210impl std::ops::DerefMut for Users {
211    fn deref_mut(&mut self) -> &mut Self::Target {
212        &mut self.users
213    }
214}
215
216impl<'a> IntoIterator for &'a Users {
217    type Item = &'a User;
218    type IntoIter = std::slice::Iter<'a, User>;
219
220    fn into_iter(self) -> Self::IntoIter {
221        self.users.iter()
222    }
223}
224
225impl<'a> IntoIterator for &'a mut Users {
226    type Item = &'a mut User;
227    type IntoIter = std::slice::IterMut<'a, User>;
228
229    fn into_iter(self) -> Self::IntoIter {
230        self.users.iter_mut()
231    }
232}
233
234impl From<Users> for Vec<User> {
235    fn from(users: Users) -> Self {
236        users.users
237    }
238}
239
240impl Users {
241    /// Creates a new empty [`Users`][crate::Users] type.
242    ///
243    /// If you want it to be filled directly, take a look at [`Users::new_with_refreshed_list`].
244    ///
245    /// ```no_run
246    /// use sysinfo::Users;
247    ///
248    /// if let Ok(mut users) = Users::new() {
249    ///     users.refresh();
250    ///     for user in &users {
251    ///         println!("{user:?}");
252    ///     }
253    /// }
254    /// ```
255    pub fn new() -> Result<Self, Error> {
256        Ok(Self {
257            users: crate::sys::new_users()?,
258        })
259    }
260
261    /// Creates a new [`Users`][crate::Users] type with the user list loaded.
262    ///
263    /// ```no_run
264    /// use sysinfo::Users;
265    ///
266    /// if let Ok(users) = Users::new_with_refreshed_list() {
267    ///     for user in &users {
268    ///         println!("{user:?}");
269    ///     }
270    /// }
271    /// ```
272    pub fn new_with_refreshed_list() -> Result<Self, Error> {
273        let mut users = Self::new()?;
274        users.refresh();
275        Ok(users)
276    }
277
278    /// The user list will be emptied then completely recomputed.
279    ///
280    /// ```no_run
281    /// use sysinfo::Users;
282    ///
283    /// if let Ok(mut users) = Users::new() {
284    ///     users.refresh();
285    /// }
286    /// ```
287    pub fn refresh(&mut self) {
288        crate::sys::get_users(&mut self.users);
289    }
290
291    /// Returns the [`User`] matching the given `user_id`.
292    ///
293    /// **Important**: The user list must be filled before using this method, otherwise it will
294    /// always return `None` (through the `refresh_*` methods).
295    ///
296    /// It is a shorthand for:
297    ///
298    /// ```ignore
299    /// # use sysinfo::Users;
300    /// if let Ok(users) = Users::new_with_refreshed_list() {
301    ///     users.find(|user| user.id() == user_id);
302    /// }
303    /// ```
304    ///
305    /// Full example:
306    ///
307    #[cfg_attr(feature = "system", doc = "```no_run")]
308    #[cfg_attr(not(feature = "system"), doc = "```ignore")]
309    /// use sysinfo::{Pid, System, Users};
310    ///
311    /// if let Ok(mut s) = System::new_all()
312    ///     && let Ok(users) = Users::new_with_refreshed_list()
313    ///     && let Some(process) = s.process(Pid::from(1337))
314    ///     && let Some(user_id) = process.user_id()
315    /// {
316    ///     println!("User for process 1337: {:?}", users.get_user_by_id(user_id));
317    /// }
318    /// ```
319    pub fn get_user_by_id(&self, user_id: &Uid) -> Option<&User> {
320        self.users.iter().find(|user| user.id() == user_id)
321    }
322}
323
324/// Interacting with groups.
325///
326/// ```no_run
327/// use sysinfo::Groups;
328///
329/// if let Ok(groups) = Groups::new_with_refreshed_list() {
330///     for group in &groups {
331///         println!("{}", group.name());
332///     }
333/// }
334/// ```
335pub struct Groups {
336    groups: Vec<Group>,
337}
338
339impl std::ops::Deref for Groups {
340    type Target = [Group];
341
342    fn deref(&self) -> &Self::Target {
343        &self.groups
344    }
345}
346
347impl std::ops::DerefMut for Groups {
348    fn deref_mut(&mut self) -> &mut Self::Target {
349        &mut self.groups
350    }
351}
352
353impl<'a> IntoIterator for &'a Groups {
354    type Item = &'a Group;
355    type IntoIter = std::slice::Iter<'a, Group>;
356
357    fn into_iter(self) -> Self::IntoIter {
358        self.groups.iter()
359    }
360}
361
362impl<'a> IntoIterator for &'a mut Groups {
363    type Item = &'a mut Group;
364    type IntoIter = std::slice::IterMut<'a, Group>;
365
366    fn into_iter(self) -> Self::IntoIter {
367        self.groups.iter_mut()
368    }
369}
370
371impl From<Groups> for Vec<Group> {
372    fn from(groups: Groups) -> Self {
373        groups.groups
374    }
375}
376
377impl Groups {
378    /// Creates a new empty [`Groups`][crate::Groups] type.
379    ///
380    /// If you want it to be filled directly, take a look at [`Groups::new_with_refreshed_list`].
381    ///
382    /// ```no_run
383    /// use sysinfo::Groups;
384    ///
385    /// if let Ok(mut groups) = Groups::new() {
386    ///     groups.refresh();
387    ///     for group in &groups {
388    ///         println!("{group:?}");
389    ///     }
390    /// }
391    /// ```
392    pub fn new() -> Result<Self, Error> {
393        Ok(Self {
394            groups: crate::sys::new_groups()?,
395        })
396    }
397
398    /// Creates a new [`Groups`][crate::Groups] type with the group list loaded.
399    ///
400    /// ```no_run
401    /// use sysinfo::Groups;
402    ///
403    /// if let Ok(groups) = Groups::new_with_refreshed_list() {
404    ///     for group in &groups {
405    ///         println!("{group:?}");
406    ///     }
407    /// }
408    /// ```
409    pub fn new_with_refreshed_list() -> Result<Self, Error> {
410        let mut groups = Self::new()?;
411        groups.refresh();
412        Ok(groups)
413    }
414
415    /// The group list will be emptied then completely recomputed.
416    ///
417    /// ```no_run
418    /// use sysinfo::Groups;
419    ///
420    /// if let Ok(mut groups) = Groups::new() {
421    ///     groups.refresh();
422    /// }
423    /// ```
424    pub fn refresh(&mut self) {
425        crate::sys::get_groups(&mut self.groups);
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use crate::*;
432
433    #[test]
434    fn check_list() {
435        let mut users = check_unsupported!(Users::new());
436        assert!(users.is_empty());
437        users.refresh();
438        assert!(users.len() >= MIN_USERS);
439    }
440
441    // This test exists to ensure that the `TryFrom<usize>` and `FromStr` traits are implemented
442    // on `Uid`, `Gid` and `Pid`.
443    #[allow(clippy::unnecessary_fallible_conversions)]
444    #[test]
445    fn check_uid_gid_from_impls() {
446        use std::convert::TryFrom;
447        use std::str::FromStr;
448
449        #[cfg(not(windows))]
450        {
451            assert!(crate::Uid::try_from(0usize).is_ok());
452            assert!(crate::Uid::from_str("0").is_ok());
453        }
454        #[cfg(windows)]
455        {
456            assert!(crate::Uid::from_str("S-1-5-18").is_ok()); // SECURITY_LOCAL_SYSTEM_RID
457            assert!(crate::Uid::from_str("0").is_err());
458        }
459
460        assert!(crate::Gid::try_from(0usize).is_ok());
461        assert!(crate::Gid::from_str("0").is_ok());
462    }
463
464    #[test]
465    fn check_groups() {
466        let groups = check_unsupported!(Groups::new_with_refreshed_list());
467        assert!(!groups.is_empty());
468    }
469}