diff --git a/src/whoami/platform/unix.rs b/src/whoami/platform/unix.rs index e69034bfe..009a7ef6b 100644 --- a/src/whoami/platform/unix.rs +++ b/src/whoami/platform/unix.rs @@ -7,6 +7,7 @@ * file that was distributed with this source code. */ +use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid}; @@ -16,9 +17,18 @@ extern { pub fn geteuid() -> libc::uid_t; } -pub unsafe fn getusername() -> String { - let passwd: *const c_passwd = getpwuid(geteuid()); +pub unsafe fn getusername() -> Result { + // 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(Error::last_os_error()) + } + + // Extract username from passwd struct let pw_name: *const libc::c_char = (*passwd).pw_name; - 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) } diff --git a/src/whoami/platform/windows.rs b/src/whoami/platform/windows.rs index 9676d6d18..28d36cbfc 100644 --- a/src/whoami/platform/windows.rs +++ b/src/whoami/platform/windows.rs @@ -10,6 +10,8 @@ extern crate winapi; extern crate advapi32; +use std::io::{Result, Error}; + #[path = "../../common/wide.rs"] #[macro_use] mod wide; use std::mem; @@ -18,11 +20,12 @@ use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use self::wide::FromWide; -pub unsafe fn getusername() -> String { +pub unsafe fn getusername() -> Result { let mut buffer: [winapi::WCHAR; winapi::UNLEN as usize + 1] = mem::uninitialized(); let mut len = buffer.len() as winapi::DWORD; if advapi32::GetUserNameW(buffer.as_mut_ptr(), &mut len) == 0 { - crash!(1, "failed to get username"); + return Err(Error::last_os_error()) } - String::from_wide(&buffer[..len as usize - 1]) + let username = String::from_wide(&buffer[..len as usize - 1]); + Ok(username) } diff --git a/src/whoami/whoami.rs b/src/whoami/whoami.rs index 5216688bf..fbcf90f27 100644 --- a/src/whoami/whoami.rs +++ b/src/whoami/whoami.rs @@ -54,7 +54,12 @@ pub fn uumain(args: Vec) -> i32 { pub fn exec() { unsafe { - let username = platform::getusername(); - println!("{}", username); + match platform::getusername() { + Ok(username) => println!("{}", username), + Err(err) => match err.raw_os_error() { + Some(0) | None => crash!(1, "failed to get username"), + Some(_) => crash!(1, "failed to get username: {}", err), + } + } } }