Skip to content

Getgroups reserve up to limit #1129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 25, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions src/unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1336,33 +1336,39 @@ pub fn setgid(gid: Gid) -> Result<()> {
/// with the `opendirectoryd` service.
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
pub fn getgroups() -> Result<Vec<Gid>> {
// First get the number of groups so we can size our Vec
let ret = unsafe { libc::getgroups(0, ptr::null_mut()) };
// First get the maximum number of groups. The value returned
// shall always be greater than or equal to one and less than or
// equal to the value of {NGROUPS_MAX} + 1.
let ngroups_max = match sysconf(SysconfVar::NGROUPS_MAX) {
Ok(Some(n)) => (n + 1) as usize,
Ok(None) | Err(_) => <usize>::max_value(),
};

// Next, get the number of groups so we can size our Vec
let ngroups = unsafe { libc::getgroups(0, ptr::null_mut()) };

// Now actually get the groups. We try multiple times in case the number of
// groups has changed since the first call to getgroups() and the buffer is
// now too small.
let mut groups = Vec::<Gid>::with_capacity(Errno::result(ret)? as usize);
let mut groups = Vec::<Gid>::with_capacity(Errno::result(ngroups)? as usize);
loop {
// FIXME: On the platforms we currently support, the `Gid` struct has
// the same representation in memory as a bare `gid_t`. This is not
// necessarily the case on all Rust platforms, though. See RFC 1785.
let ret = unsafe {
let ngroups = unsafe {
libc::getgroups(groups.capacity() as c_int, groups.as_mut_ptr() as *mut gid_t)
};

match Errno::result(ret) {
match Errno::result(ngroups) {
Ok(s) => {
unsafe { groups.set_len(s as usize) };
return Ok(groups);
},
Err(Error::Sys(Errno::EINVAL)) => {
// EINVAL indicates that the buffer size was too small. Trigger
// the internal buffer resizing logic of `Vec` by requiring
// more space than the current capacity.
let cap = groups.capacity();
unsafe { groups.set_len(cap) };
groups.reserve(1);
// EINVAL indicates that the buffer size was too
// small, resize it up to ngroups_max as limit.
reserve_double_buffer_size(&mut groups, ngroups_max)
.or(Err(Error::Sys(Errno::EINVAL)))?;
},
Err(e) => return Err(e)
}
Expand Down