#![allow(clippy::bool_comparison)]
use libc::setuid;
use log::trace;
use std::process::Command;
#[derive(Debug, PartialEq)]
pub enum RunningAs {
Root,
User,
Suid,
}
use RunningAs::*;
#[cfg(unix)]
pub fn check() -> RunningAs {
let uid = unsafe { libc::getuid() };
let euid = unsafe { libc::geteuid() };
match (uid, euid) {
(0, 0) => Root,
(_, 0) => Suid,
(_, _) => User,
}
}
#[cfg(unix)]
#[inline]
pub fn escalate_if_needed() -> bool {
with_env(&[])
}
#[cfg(unix)]
pub fn with_env(prefixes: &[&str]) -> bool {
let current = check();
trace!("Running as {:?}", current);
match current {
Root => {
trace!("already running as Root");
return true;
}
Suid => {
trace!("setuid(0)");
unsafe {
setuid(0);
}
return true;
}
User => {
log::debug!("Escalating privileges");
}
}
let mut args: Vec<_> = std::env::args().collect();
if let Some(absolute_path) = std::env::current_exe()
.ok()
.and_then(|p| p.to_str().map(|p| p.to_string()))
{
args[0] = absolute_path;
}
let mut command: Command = Command::new("/usr/bin/sudo");
if let Ok(trace) = std::env::var("RUST_BACKTRACE") {
let value = match &*trace.to_lowercase() {
"" => None,
"1" | "true" => Some("1"),
"full" => Some("full"),
invalid => {
log::warn!(
"RUST_BACKTRACE has invalid value {:?} -> defaulting to \"full\"",
invalid
);
Some("full")
}
};
if let Some(value) = value {
trace!("relaying RUST_BACKTRACE={}", value);
command.arg(format!("RUST_BACKTRACE={}", value));
}
}
if prefixes.is_empty() == false {
for (name, value) in std::env::vars().filter(|(name, _)| name != "RUST_BACKTRACE") {
if prefixes.iter().any(|prefix| name.starts_with(prefix)) {
trace!("propagating {}={}", name, value);
command.arg(format!("{}={}", name, value));
}
}
}
let mut child = command.args(args).spawn().expect("failed to execute child");
let ecode = child.wait().expect("failed to wait on child");
ecode.success()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let _ = check();
}
}