use std::io::{self, IoSlice};
use std::os::fd::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::process::Child;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
pub fn xdg_runtime_dir() -> PathBuf {
std::env::var_os("XDG_RUNTIME_DIR")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(format!("/run/user/{}", nix::unistd::getuid().as_raw())))
}
pub fn open_pidfd(pid: i32) -> std::io::Result<std::os::fd::OwnedFd> {
let pid = rustix::process::Pid::from_raw(pid)
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid PID"))?;
rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty())
.map_err(std::io::Error::from)
}
pub fn install_shutdown_signal_handler() -> Arc<AtomicBool> {
use signal_hook::consts::{SIGINT, SIGTERM};
let shutdown = Arc::new(AtomicBool::new(false));
for sig in [SIGTERM, SIGINT] {
let _ = signal_hook::flag::register(sig, Arc::clone(&shutdown));
}
shutdown
}
pub fn wait_child_timeout(
child: Child,
timeout: Duration,
) -> std::io::Result<std::process::Output> {
let pid = nix::unistd::Pid::from_raw(child.id().cast_signed());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
if rx.recv_timeout(timeout).is_err() {
let _ = nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGKILL);
}
});
let output = child.wait_with_output()?;
let _ = tx.send(());
Ok(output)
}
pub fn send_bytes_with_fds(stream: &UnixStream, data: &[&[u8]], fds: &[RawFd]) -> io::Result<()> {
use nix::sys::socket::{ControlMessage, MsgFlags, sendmsg};
let raw_fd = stream.as_raw_fd();
let cmsg = ControlMessage::ScmRights(fds);
let total: usize = data.iter().map(|chunk| chunk.len()).sum();
let mut sent = 0usize;
let mut first = true;
loop {
let mut skip = sent;
let mut iov: Vec<IoSlice<'_>> = Vec::with_capacity(data.len());
for chunk in data {
if skip >= chunk.len() {
skip -= chunk.len();
continue;
}
iov.push(IoSlice::new(&chunk[skip..]));
skip = 0;
}
let cmsgs: &[ControlMessage<'_>] = if first {
std::slice::from_ref(&cmsg)
} else {
&[]
};
match sendmsg::<()>(raw_fd, &iov, cmsgs, MsgFlags::empty(), None) {
Ok(n) => {
if n == 0 && sent == 0 {
return Ok(());
}
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"sendmsg made no progress on a non-empty frame",
));
}
sent += n;
first = false;
if sent >= total {
return Ok(());
}
}
Err(nix::errno::Errno::EINTR) => {}
Err(e) => return Err(io::Error::from(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::IoSliceMut;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
#[test]
fn runtime_dir_prefers_the_env_and_falls_back_per_uid() {
let saved = std::env::var_os("XDG_RUNTIME_DIR");
#[allow(unsafe_code)]
unsafe {
std::env::set_var("XDG_RUNTIME_DIR", "/run/user/4242");
}
assert_eq!(xdg_runtime_dir(), PathBuf::from("/run/user/4242"));
#[allow(unsafe_code)]
unsafe {
std::env::remove_var("XDG_RUNTIME_DIR");
}
let fallback = xdg_runtime_dir();
if let Some(v) = saved {
#[allow(unsafe_code)]
unsafe {
std::env::set_var("XDG_RUNTIME_DIR", v);
}
}
assert!(
fallback.starts_with("/run/user/") && !fallback.to_string_lossy().ends_with("4242"),
"unexpected fallback {fallback:?}"
);
}
#[test]
fn send_bytes_with_fds_delivers_data_and_descriptors_together() {
let (tx, rx) = UnixStream::pair().unwrap();
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"sent-by-test").unwrap();
let file = std::fs::File::open(tmp.path()).unwrap();
let frame = b"proton frame bytes";
send_bytes_with_fds(&tx, &[&frame[..], b""], &[file.as_raw_fd()])
.expect("sendmsg with rights");
let mut buf = [0u8; 64];
let (n, owned) = {
let mut iov = [IoSliceMut::new(&mut buf)];
let mut cmsg = vec![0u8; 64];
let msg = nix::sys::socket::recvmsg::<()>(
rx.as_raw_fd(),
&mut iov,
Some(&mut cmsg),
nix::sys::socket::MsgFlags::MSG_CMSG_CLOEXEC,
)
.unwrap();
let n = msg.bytes;
let mut owned: Vec<OwnedFd> = Vec::new();
if let Ok(cmsgs) = msg.cmsgs() {
for cmsg in cmsgs {
if let nix::sys::socket::ControlMessageOwned::ScmRights(fds) = cmsg {
owned.extend(fds.into_iter().map(|r| {
#[allow(unsafe_code)]
unsafe {
OwnedFd::from_raw_fd(r)
}
}));
}
}
}
(n, owned)
};
assert_eq!(&buf[..n], frame, "frame bytes did not arrive");
assert_eq!(owned.len(), 1);
let target = tmp.path().to_path_buf();
let mut fd_file = std::fs::File::from(owned.into_iter().next().unwrap());
let mut contents = String::new();
std::io::Read::read_to_string(&mut fd_file, &mut contents).unwrap();
assert_eq!(contents, "sent-by-test");
drop(target);
}
#[test]
fn send_bytes_with_fds_handles_partial_writes() {
use std::io::Read;
let (tx, mut rx) = UnixStream::pair().unwrap();
let reader = std::thread::spawn(move || {
let mut received = Vec::new();
rx.read_to_end(&mut received).unwrap();
received
});
let a = vec![b'a'; 256 * 1024];
let b = vec![b'b'; 128 * 1024];
send_bytes_with_fds(&tx, &[&a, &b], &[]).expect("large frame");
drop(tx);
let received = reader.join().unwrap();
let mut expected = a;
expected.extend_from_slice(&b);
assert_eq!(received, expected);
}
}