Skip to content

Commit

Permalink
Replace users with nix crate
Browse files Browse the repository at this point in the history
  • Loading branch information
nibon7 committed Jul 5, 2023
1 parent 1bdec1c commit 8e0ff46
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 81 deletions.
14 changes: 2 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/nu-command/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ winreg = "0.50"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
umask = "2.1"
users = "0.11"
nix = { version = "0.26", default-features = false, features = ["user"] }

[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies.trash]
optional = true
Expand Down
72 changes: 6 additions & 66 deletions crates/nu-command/src/filesystem/cd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ fn have_permission(dir: impl AsRef<Path>) -> PermissionResult<'static> {

#[cfg(unix)]
fn have_permission(dir: impl AsRef<Path>) -> PermissionResult<'static> {
use crate::filesystem::util::users;

match dir.as_ref().metadata() {
Ok(metadata) => {
use std::os::unix::fs::MetadataExt;
Expand Down Expand Up @@ -272,75 +274,13 @@ fn have_permission(dir: impl AsRef<Path>) -> PermissionResult<'static> {
}
}

// NOTE: it's a re-export of https://github.com/ogham/rust-users crate
// we need to use it because the upstream pr isn't merged: https://github.com/ogham/rust-users/pull/45
// once it's merged, we can remove this module
#[cfg(unix)]
mod nu_users {
use libc::c_int;
use std::ffi::{CString, OsStr};
use std::os::unix::ffi::OsStrExt;
use users::{gid_t, Group};
/// Returns groups for a provided user name and primary group id.
///
/// # libc functions used
///
/// - [`getgrouplist`](https://docs.rs/libc/*/libc/fn.getgrouplist.html)
///
/// # Examples
///
/// ```no_run
/// use 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.gid(), group.name());
/// }
/// ```
pub fn get_user_groups<S: AsRef<OsStr> + ?Sized>(
username: &S,
gid: gid_t,
) -> Option<Vec<Group>> {
// MacOS uses i32 instead of gid_t in getgrouplist for unknown reasons
#[cfg(all(unix, target_os = "macos"))]
let mut buff: Vec<i32> = vec![0; 1024];
#[cfg(all(unix, not(target_os = "macos")))]
let mut buff: Vec<gid_t> = vec![0; 1024];
let name = CString::new(username.as_ref().as_bytes()).expect("OsStr is guaranteed to be zero-free, which is the condition for CString::new to succeed");
let mut count = buff.len() as c_int;
// MacOS uses i32 instead of gid_t in getgrouplist for unknown reasons
// SAFETY:
// int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
//
// `name` is valid CStr to be `const char*` for `user`
// 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(all(unix, target_os = "macos"))]
let res =
unsafe { libc::getgrouplist(name.as_ptr(), gid as i32, buff.as_mut_ptr(), &mut count) };
#[cfg(all(unix, not(target_os = "macos")))]
let res = unsafe { libc::getgrouplist(name.as_ptr(), gid, buff.as_mut_ptr(), &mut count) };
if res < 0 {
None
} else {
buff.truncate(count as usize);
buff.sort_unstable();
buff.dedup();
// allow trivial cast: on macos i is i32, on linux it's already gid_t
#[allow(trivial_numeric_casts)]
buff.into_iter()
.filter_map(|i| users::get_group_by_gid(i as gid_t))
.collect::<Vec<_>>()
.into()
}
}
}

#[cfg(unix)]
fn any_group(current_user_gid: gid_t, owner_group: u32) -> bool {
use crate::filesystem::util::users;

users::get_current_username()
.map(|name| nu_users::get_user_groups(&name, current_user_gid).unwrap_or_default())
.and_then(|name| users::get_user_groups(&name, current_user_gid))
.unwrap_or_default()
.into_iter()
.any(|group| group.gid() == owner_group)
.any(|gid| gid.as_raw() == owner_group)
}
5 changes: 3 additions & 2 deletions crates/nu-command/src/filesystem/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ pub(crate) fn dir_entry_dict(

#[cfg(unix)]
{
use crate::filesystem::util::users;
use std::os::unix::fs::MetadataExt;
let mode = md.permissions().mode();
cols.push("mode".into());
Expand All @@ -509,7 +510,7 @@ pub(crate) fn dir_entry_dict(
cols.push("user".into());
if let Some(user) = users::get_user_by_uid(md.uid()) {
vals.push(Value::String {
val: user.name().to_string_lossy().into(),
val: user.name,
span,
});
} else {
Expand All @@ -522,7 +523,7 @@ pub(crate) fn dir_entry_dict(
cols.push("group".into());
if let Some(group) = users::get_group_by_gid(md.gid()) {
vals.push(Value::String {
val: group.name().to_string_lossy().into(),
val: group.name,
span,
});
} else {
Expand Down
89 changes: 89 additions & 0 deletions crates/nu-command/src/filesystem/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,92 @@ pub fn is_older(src: &Path, dst: &Path) -> bool {
src_ctime <= dst_ctime
}
}

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

pub fn get_user_by_uid(uid: uid_t) -> Option<User> {
User::from_uid(Uid::from_raw(uid)).ok().flatten()
}

pub fn get_group_by_gid(gid: gid_t) -> Option<Group> {
Group::from_gid(Gid::from_raw(gid)).ok().flatten()
}

pub fn get_current_uid() -> uid_t {
Uid::current().as_raw()
}

pub fn get_current_gid() -> gid_t {
Gid::current().as_raw()
}

pub fn get_current_username() -> Option<String> {
User::from_uid(Uid::current())
.ok()
.flatten()
.map(|user| user.name)
}

/// Returns groups for a provided user name and primary group id.
///
/// # libc functions used
///
/// - [`getgrouplist`](https://docs.rs/libc/*/libc/fn.getgrouplist.html)
///
/// # Examples
///
/// ```ignore
/// use 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}");
/// }
/// ```
pub fn get_user_groups(username: &str, gid: gid_t) -> Option<Vec<Gid>> {
// 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;
};

let mut count = buff.len() as c_int;

// MacOS uses i32 instead of gid_t in getgrouplist for unknown reasons
// SAFETY:
// int getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups);
//
// `name` is valid CStr to be `const char*` for `user`
// 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 {
buff.truncate(count as usize);
buff.sort_unstable();
buff.dedup();
// allow trivial cast: on macos i is i32, on linux it's already gid_t
#[allow(trivial_numeric_casts)]
buff.into_iter()
.filter_map(|i| get_group_by_gid(i as gid_t))
.map(|group| group.gid)
.collect::<Vec<_>>()
.into()
}
}
}

0 comments on commit 8e0ff46

Please sign in to comment.