Skip to content

Commit

Permalink
remove use of nix::unistd::getgrouplist
Browse files Browse the repository at this point in the history
  • Loading branch information
nibon7 committed Jul 5, 2023
1 parent d46d9e1 commit 82c7ec5
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions crates/nu-command/src/filesystem/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ pub fn is_older(src: &Path, dst: &Path) -> bool {

#[cfg(unix)]
pub mod users {
use libc::{gid_t, uid_t};
use libc::{c_int, gid_t, uid_t};
use nix::unistd::{Gid, Group, Uid, User};
use std::ffi::CString;

Expand All @@ -190,15 +190,6 @@ pub mod users {
.map(|user| user.name)
}

#[cfg(not(target_os = "macos"))]
pub fn get_user_groups(user: &str, gid: gid_t) -> Option<Vec<Gid>> {
let Ok(user) = CString::new(user) else {
return None;
};

nix::unistd::getgrouplist(user.as_c_str(), Gid::from_raw(gid)).ok()
}

/// Returns groups for a provided user name and primary group id.
///
/// # libc functions used
Expand All @@ -208,18 +199,18 @@ pub mod users {
/// # Examples
///
/// ```no_run
/// use nu_command::filesystem::util::get_user_groups
/// use nu_command::filesystem::util::users::get_user_groups;
///
/// for group in get_user_groups("stevedore", 1001).expect("Error looking up groups") {
/// println!("User is a member of group #{group}");
/// }
/// ```
#[cfg(target_os = "macos")]
pub fn get_user_groups(username: &str, gid: gid_t) -> Option<Vec<Gid>> {
use libc::c_int;

// MacOS uses i32 instead of gid_t in getgrouplist for unknown reasons
#[cfg(target_os = "macos")]
let mut buff: Vec<i32> = vec![0; 1024];
#[cfg(not(target_os = "macos"))]
let mut buff: Vec<gid_t> = vec![0; 1024];

let Ok(name) = CString::new(username.as_bytes()) else {
return None;
Expand All @@ -235,8 +226,13 @@ pub mod users {
// every valid value will be accepted for `group`
// The capacity for `*groups` is passed in as `*ngroups` which is the buffer max length/capacity (as we initialize with 0)
// Following reads from `*groups`/`buff` will only happen after `buff.truncate(*ngroups)`
#[cfg(target_os = "macos")]
let res =
unsafe { libc::getgrouplist(name.as_ptr(), gid as i32, buff.as_mut_ptr(), &mut count) };

#[cfg(not(target_os = "macos"))]
let res = unsafe { libc::getgrouplist(name.as_ptr(), gid, buff.as_mut_ptr(), &mut count) };

if res < 0 {
None
} else {
Expand Down

0 comments on commit 82c7ec5

Please sign in to comment.