From b963d0c64723087a5dc871a74457f48b487e33b9 Mon Sep 17 00:00:00 2001 From: ripytide Date: Thu, 7 Nov 2024 16:56:09 +0000 Subject: [PATCH] fix: make the use of sudo only work on unix systems --- src/cmd.rs | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/cmd.rs b/src/cmd.rs index e268714..2e7cb2e 100644 --- a/src/cmd.rs +++ b/src/cmd.rs @@ -26,19 +26,15 @@ where S: Into, I: IntoIterator, { - let we_are_root = { - let uid = unsafe { libc::geteuid() }; - uid == 0 - }; - let args: Vec = args.into_iter().map(Into::into).collect::>(); 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::>(); @@ -65,19 +61,15 @@ where S: Into, I: IntoIterator, { - let we_are_root = { - let uid = unsafe { libc::geteuid() }; - uid == 0 - }; - let args: Vec = args.into_iter().map(Into::into).collect::>(); 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::>(); @@ -98,3 +90,16 @@ where Err(eyre!("command failed: {:?}", args.into_iter().join(" "))) } } + +fn use_sudo(perms: Perms) -> Result { + #[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); +}