#![allow(dead_code)]
use std::os::fd::AsRawFd;
pub fn geteuid() -> u32 {
unsafe { libc::geteuid() }
}
pub fn getuid() -> u32 {
unsafe { libc::getuid() }
}
pub fn passwd_entry(uid: u32) -> Option<(String, String)> {
let mut buf = vec![0u8; 1024];
loop {
let mut pw: libc::passwd = unsafe { core::mem::zeroed() };
let mut result: *mut libc::passwd = core::ptr::null_mut();
let rc = unsafe {
libc::getpwuid_r(
uid,
&mut pw,
buf.as_mut_ptr().cast(),
buf.len(),
&mut result,
)
};
if rc == libc::ERANGE && buf.len() < 1 << 20 {
buf.resize(buf.len() * 2, 0);
continue;
}
if rc != 0 || result.is_null() {
return None;
}
let field = |p: *const libc::c_char| {
(!p.is_null()).then(|| {
unsafe { std::ffi::CStr::from_ptr(p) }
.to_string_lossy()
.into_owned()
})
};
return Some((field(pw.pw_name)?, field(pw.pw_dir).unwrap_or_default()));
}
}
pub fn dup2(f: &impl AsRawFd, fd: i32) -> std::io::Result<()> {
if unsafe { libc::dup2(f.as_raw_fd(), fd) } == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}