1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-08-03 22:47:46 +00:00

Handle null pointer return value for getpwuid on Linux

This commit is contained in:
Danilo Bargen 2015-09-18 10:41:29 +02:00
parent a8f9b40674
commit 0e7223cfb0

View file

@ -17,8 +17,16 @@ extern {
} }
pub unsafe fn getusername() -> Result<String, String> { pub unsafe fn getusername() -> Result<String, String> {
let passwd: *const c_passwd = getpwuid(geteuid()); // Get effective user id
let uid = geteuid();
// Try to find username for uid
let passwd: *const c_passwd = getpwuid(uid);
if passwd.is_null() {
return Err(format!("cannot find name for user ID {}", uid))
}
// Extract username from passwd struct
let pw_name: *const libc::c_char = (*passwd).pw_name; let pw_name: *const libc::c_char = (*passwd).pw_name;
let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string(); let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string();
Ok(username) Ok(username)