1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#![deny(unsafe_code)]
use std::error::Error;
#[macro_use]
extern crate log;
#[derive(Debug, PartialEq)]
pub enum RunningAs {
Root,
User,
}
use RunningAs::*;
#[cfg(unix)]
pub fn check() -> Result<RunningAs, Box<dyn Error>> {
let uid: String = match std::env::var("UID") {
Ok(s) => s,
Err(_) => {
const NO_UID: &str = "/proc/self/status does not contain uid";
let status = std::fs::read_to_string("/proc/self/status")?;
let lines = status.lines();
let uid_line = lines.filter(|&l| l.to_lowercase().starts_with("uid")).next().expect(NO_UID);
uid_line.split_whitespace().skip(1).next().expect(NO_UID).to_string()
}
};
Ok(if uid.parse::<usize>()? == 0 { Root } else { User })
}
#[cfg(unix)]
pub fn escalate_if_needed() -> Result<(), Box<dyn Error>> {
let current = check()?;
if current == Root {
trace!("already running as Root");
return Ok(());
}
debug!("Escalating privileges");
let args = std::env::args();
let mut child = std::process::Command::new("/usr/bin/sudo")
.args(args)
.spawn()
.expect("failed to execute child");
let ecode = child.wait().expect("failed to wait on child");
if ecode.success() == false {
std::process::exit(ecode.code().unwrap_or(1));
} else {
std::process::exit(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let c = check();
assert!(c.is_ok(), "{:?}", c);
}
}