#[must_use]
pub fn is_elevated() -> bool {
imp::is_elevated()
}
#[cfg(unix)]
mod imp {
pub fn is_elevated() -> bool {
unsafe { libc::geteuid() == 0 }
}
}
#[cfg(windows)]
mod imp {
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::Security::{
GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation,
};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
pub fn is_elevated() -> bool {
let mut token: HANDLE = std::ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return false;
}
let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
let mut returned = 0u32;
let ok = unsafe {
GetTokenInformation(
token,
TokenElevation,
(&raw mut elevation).cast(),
size_of::<TOKEN_ELEVATION>() as u32,
&mut returned,
)
} != 0;
unsafe { CloseHandle(token) };
ok && elevation.TokenIsElevated != 0
}
}
#[cfg(not(any(unix, windows)))]
mod imp {
pub fn is_elevated() -> bool {
false
}
}