Skip to content

Commit

Permalink
fix: make the use of sudo only work on unix systems
Browse files Browse the repository at this point in the history
  • Loading branch information
ripytide committed Nov 7, 2024
1 parent d720d29 commit b963d0c
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,15 @@ where
S: Into<String>,
I: IntoIterator<Item = S>,
{
let we_are_root = {
let uid = unsafe { libc::geteuid() };
uid == 0
};

let args: Vec<String> = args.into_iter().map(Into::into).collect::<Vec<_>>();

if args.is_empty() {
return Err(eyre!("cannot run an empty command"));
}

let use_sudo = use_sudo(perms)?;
let args = Some("sudo".to_string())
.filter(|_| matches!(perms, Perms::Sudo) && !we_are_root)
.filter(|_| use_sudo)
.into_iter()
.chain(args)
.collect::<Vec<_>>();
Expand All @@ -65,19 +61,15 @@ where
S: Into<String>,
I: IntoIterator<Item = S>,
{
let we_are_root = {
let uid = unsafe { libc::geteuid() };
uid == 0
};

let args: Vec<String> = args.into_iter().map(Into::into).collect::<Vec<_>>();

if args.is_empty() {
return Err(eyre!("cannot run an empty command"));
}

let use_sudo = use_sudo(perms)?;
let args = Some("sudo".to_string())
.filter(|_| matches!(perms, Perms::Sudo) && !we_are_root)
.filter(|_| use_sudo)
.into_iter()
.chain(args)
.collect::<Vec<_>>();
Expand All @@ -98,3 +90,16 @@ where
Err(eyre!("command failed: {:?}", args.into_iter().join(" ")))
}
}

fn use_sudo(perms: Perms) -> Result<bool> {
#[cfg(unix)]
return Ok(matches!(perms, Perms::Sudo) && unsafe { libc::geteuid() } != 0);
#[cfg(windows)]
if matches!(perms, Perms::Sudo) {
return Err(eyre!(
"sudo for privilege escalation is not supported on windows"
));
}
#[cfg(windows)]
return Ok(false);
}

0 comments on commit b963d0c

Please sign in to comment.