Skip to content

Commit 258bc13

Browse files
committed
unistd: getgroups: Resize buffer up to NGROUPS_MAX
Use `reserve_double_buffer_size` up to NGROUPS_MAX as limit. Signed-off-by: Otavio Salvador <[email protected]>
1 parent 8b9a465 commit 258bc13

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/unistd.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1336,7 +1336,15 @@ pub fn setgid(gid: Gid) -> Result<()> {
13361336
/// with the `opendirectoryd` service.
13371337
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
13381338
pub fn getgroups() -> Result<Vec<Gid>> {
1339-
// First get the number of groups so we can size our Vec
1339+
// First get the maximum number of groups. The value returned
1340+
// shall always be greater than or equal to one and less than or
1341+
// equal to the value of {NGROUPS_MAX} + 1.
1342+
let ngroups_max = match sysconf(SysconfVar::NGROUPS_MAX) {
1343+
Ok(Some(n)) => (n + 1) as usize,
1344+
Ok(None) | Err(_) => <usize>::max_value(),
1345+
};
1346+
1347+
// Next, get the number of groups so we can size our Vec
13401348
let ngroups = unsafe { libc::getgroups(0, ptr::null_mut()) };
13411349

13421350
// Now actually get the groups. We try multiple times in case the number of
@@ -1357,12 +1365,10 @@ pub fn getgroups() -> Result<Vec<Gid>> {
13571365
return Ok(groups);
13581366
},
13591367
Err(Error::Sys(Errno::EINVAL)) => {
1360-
// EINVAL indicates that the buffer size was too small. Trigger
1361-
// the internal buffer resizing logic of `Vec` by requiring
1362-
// more space than the current capacity.
1363-
let cap = groups.capacity();
1364-
unsafe { groups.set_len(cap) };
1365-
groups.reserve(1);
1368+
// EINVAL indicates that the buffer size was too
1369+
// small, resize it up to ngroups_max as limit.
1370+
reserve_double_buffer_size(&mut groups, ngroups_max)
1371+
.or(Err(Error::Sys(Errno::EINVAL)))?;
13661372
},
13671373
Err(e) => return Err(e)
13681374
}

0 commit comments

Comments
 (0)