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
//! Extensions for [`std::process::Command`] that operate on concepts from cap-std.
//!
//! The key APIs here are:
//!
//! - File descriptor passing
//! - Changing to a file-descriptor relative directory
use cap_std::fs::Dir;
use cap_std::io_lifetimes;
use cap_tempfile::cap_std;
use io_lifetimes::OwnedFd;
use rustix::fd::{AsFd, FromRawFd, IntoRawFd};
use std::os::unix::process::CommandExt;
use std::sync::Arc;
/// Extension trait for [`std::process::Command`].
///
/// [`cap_std::fs::Dir`]: https://docs.rs/cap-std/latest/cap_std/fs/struct.Dir.html
pub trait CapStdExtCommandExt {
/// Pass a file descriptor into the target process.
fn take_fd_n(&mut self, fd: Arc<OwnedFd>, target: i32) -> &mut Self;
/// Use the given directory as the current working directory for the process.
fn cwd_dir(&mut self, dir: Dir) -> &mut Self;
}
#[allow(unsafe_code)]
impl CapStdExtCommandExt for std::process::Command {
fn take_fd_n(&mut self, fd: Arc<OwnedFd>, target: i32) -> &mut Self {
unsafe {
self.pre_exec(move || {
let mut target = OwnedFd::from_raw_fd(target);
rustix::io::dup2(&*fd, &mut target)?;
// Intentionally leak into the child.
let _ = target.into_raw_fd();
Ok(())
});
}
self
}
fn cwd_dir(&mut self, dir: Dir) -> &mut Self {
unsafe {
self.pre_exec(move || {
rustix::process::fchdir(dir.as_fd())?;
Ok(())
});
}
self
}
}