mirror of
https://github.com/RGBCube/uutils-coreutils
synced 2025-08-03 14:37:45 +00:00
commit
b18a2122ae
3 changed files with 26 additions and 8 deletions
|
@ -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<String> {
|
||||
// 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)
|
||||
}
|
||||
|
|
|
@ -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<String> {
|
||||
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)
|
||||
}
|
||||
|
|
|
@ -54,7 +54,12 @@ pub fn uumain(args: Vec<String>) -> 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue