about summary refs log tree commit diff
path: root/src/unix.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/unix.rs')
-rw-r--r--src/unix.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/unix.rs b/src/unix.rs
new file mode 100644
index 0000000..5561292
--- /dev/null
+++ b/src/unix.rs
@@ -0,0 +1,35 @@
+use crate::error::Result;
+
+use std::ffi::CStr;
+use std::mem::{ size_of_val, MaybeUninit };
+use std::ptr::null_mut;
+
+use libc::{ getpwuid_r, passwd };
+use rustix::io::Errno;
+use rustix::process::{ getuid, Uid };
+
+
+pub async fn get_username() -> Result<String> {
+  let uid: Uid = getuid();
+
+  let mut buffer: [i8; 512] = [0; 512];
+  let mut entry: MaybeUninit<passwd> = MaybeUninit::uninit();
+  let mut result = null_mut();
+
+  let error = unsafe {
+    getpwuid_r(uid.as_raw(),
+               &raw mut entry as *mut passwd,
+               &raw mut buffer as *mut i8,
+               size_of_val(&buffer),
+               &mut result)
+  };
+  if error != 0 {
+    return Err(Errno::from_raw_os_error(error).into());
+  }
+
+  let name = unsafe { entry.assume_init() }.pw_name;
+  let name = unsafe { CStr::from_ptr(name) };
+
+  Ok(name.to_string_lossy().into_owned())
+}
+