sysinfo/unix/
groups.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use crate::{Gid, Group, GroupInner};
4
5impl GroupInner {
6    pub(crate) fn new(id: crate::Gid, name: String) -> Self {
7        Self { id, name }
8    }
9
10    pub(crate) fn id(&self) -> &crate::Gid {
11        &self.id
12    }
13
14    pub(crate) fn name(&self) -> &str {
15        &self.name
16    }
17}
18
19pub(crate) fn get_groups(groups: &mut Vec<Group>) {
20    groups.clear();
21
22    let mut groups_map = std::collections::HashMap::with_capacity(10);
23
24    unsafe {
25        libc::setgrent();
26        loop {
27            let gr = libc::getgrent();
28            if gr.is_null() {
29                // The call was interrupted by a signal, retrying.
30                if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
31                    continue;
32                }
33                break;
34            }
35
36            if let Some(name) = crate::unix::utils::cstr_to_rust((*gr).gr_name) {
37                if groups_map.contains_key(&name) {
38                    continue;
39                }
40
41                let gid = (*gr).gr_gid;
42                groups_map.insert(name, Gid(gid));
43            }
44        }
45        libc::endgrent();
46    }
47    for (name, gid) in groups_map {
48        groups.push(Group {
49            inner: GroupInner::new(gid, name),
50        });
51    }
52}