summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorqkzk <qu3nt1n@gmail.com>2023-10-08 21:47:45 +0200
committerqkzk <qu3nt1n@gmail.com>2023-10-08 21:47:45 +0200
commit552f7ca40b65395f126132deb13ceaf398c4a274 (patch)
treec7845d5b8e240ac78c2e86baa1a51b92d3fa59ff
parent012d3ae37262677112bf7d8044d839fb72ce9ed4 (diff)
refactor sudo command creation
-rw-r--r--src/password.rs41
1 files changed, 28 insertions, 13 deletions
diff --git a/src/password.rs b/src/password.rs
index c1b16d1..2638eb1 100644
--- a/src/password.rs
+++ b/src/password.rs
@@ -85,36 +85,51 @@ impl PasswordHolder {
}
}
-/// run a sudo command requiring a password (generally to establish the password.)
-/// Since I can't send 2 passwords at a time, it will only work with the sudo password
-/// It requires a path to establish CWD.
-pub fn execute_sudo_command_with_password<S, P>(
- args: &[S],
- password: &str,
- path: P,
-) -> Result<(bool, String, String)>
+/// Spawn a sudo command with stdin, stdout and stderr piped.
+/// Args are sent.
+/// CWD is set to `path`.
+fn new_sudo_command<S, P>(args: &[S], path: P) -> Result<std::process::Child>
where
S: AsRef<std::ffi::OsStr> + std::fmt::Debug,
P: AsRef<std::path::Path> + std::fmt::Debug,
{
- info!("sudo_with_password {args:?} CWD {path:?}");
- let log_line = format!("running sudo command with password. args: {args:?}, CWD: {path:?}");
- write_log_line(log_line);
- let mut child = Command::new("sudo")
+ Ok(Command::new("sudo")
.arg("-S")
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.current_dir(path)
- .spawn()?;
+ .spawn()?)
+}
+/// Send password to a sudo command through its stdin.
+fn inject_password(password: &str, child: &mut std::process::Child) -> Result<()> {
let child_stdin = child
.stdin
.as_mut()
.context("run_privileged_command: couldn't open child stdin")?;
child_stdin.write_all(format!("{password}\n").as_bytes())?;
+ Ok(())
+}
+/// run a sudo command requiring a password (generally to establish the password.)
+/// Since I can't send 2 passwords at a time, it will only work with the sudo password
+/// It requires a path to establish CWD.
+pub fn execute_sudo_command_with_password<S, P>(
+ args: &[S],
+ password: &str,
+ path: P,
+) -> Result<(bool, String, String)>
+where
+ S: AsRef<std::ffi::OsStr> + std::fmt::Debug,
+ P: AsRef<std::path::Path> + std::fmt::Debug,
+{
+ info!("sudo_with_password {args:?} CWD {path:?}");
+ let log_line = format!("running sudo command with password. args: {args:?}, CWD: {path:?}");
+ write_log_line(log_line);
+ let mut child = new_sudo_command(args, path)?;
+ inject_password(password, &mut child)?;
let output = child.wait_with_output()?;
Ok((
output.status.success(),