Skip to main content

podbox_protocol/
sysutil.rs

1//! Unix-only process helpers both the host CLI and the guest daemon need.
2//!
3//! Small, dependency-light implementations shared so each of them exists
4//! exactly once: the built-in guest cannot be rebuilt for users, but its
5//! behaviour tracks the host whenever the helpers agree. Keep this module
6//! free of podbox types — it only touches the standard library plus the
7//! `nix`/`rustix`/`signal-hook` shims, so the wire-pure core of the crate
8//! stays usable from wasm targets (this module is compiled out there).
9
10use std::io::{self, IoSlice};
11use std::os::fd::{AsRawFd, RawFd};
12use std::os::unix::net::UnixStream;
13use std::path::PathBuf;
14use std::process::Child;
15use std::sync::Arc;
16use std::sync::atomic::AtomicBool;
17use std::time::Duration;
18
19/// `$XDG_RUNTIME_DIR`, or the fallback every caller re-derived by hand: the
20/// uid's systemd user-runtime directory. Matches how systemd populates the
21/// variable for user sessions, so the fallback only ever fires outside one.
22pub fn xdg_runtime_dir() -> PathBuf {
23    std::env::var_os("XDG_RUNTIME_DIR")
24        .filter(|v| !v.is_empty())
25        .map(PathBuf::from)
26        .unwrap_or_else(|| PathBuf::from(format!("/run/user/{}", nix::unistd::getuid().as_raw())))
27}
28
29/// Open a pidfd for `pid` (Linux 5.3+).
30///
31/// Returns `Err` on old kernels or when the pid does not exist.
32pub fn open_pidfd(pid: i32) -> std::io::Result<std::os::fd::OwnedFd> {
33    let pid = rustix::process::Pid::from_raw(pid)
34        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid PID"))?;
35    rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty())
36        .map_err(std::io::Error::from)
37}
38
39/// Register SIGTERM/SIGINT handlers that set the returned flag.
40///
41/// Callers poll this on their loop tick, so no SA_RESTART/EINTR coordination
42/// is needed and every event loop turns the same flag into a clean exit.
43pub fn install_shutdown_signal_handler() -> Arc<AtomicBool> {
44    use signal_hook::consts::{SIGINT, SIGTERM};
45
46    let shutdown = Arc::new(AtomicBool::new(false));
47    for sig in [SIGTERM, SIGINT] {
48        // Registration failure only happens before the flag exists; nothing
49        // to return can express it better than ignoring a failed signal
50        // handler like every duplicated copy did.
51        let _ = signal_hook::flag::register(sig, Arc::clone(&shutdown));
52    }
53    shutdown
54}
55
56/// Wait for `child`, SIGKILLing it once `timeout` has elapsed.
57pub fn wait_child_timeout(
58    child: Child,
59    timeout: Duration,
60) -> std::io::Result<std::process::Output> {
61    let pid = nix::unistd::Pid::from_raw(child.id().cast_signed());
62    let (tx, rx) = std::sync::mpsc::channel();
63    std::thread::spawn(move || {
64        if rx.recv_timeout(timeout).is_err() {
65            let _ = nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGKILL);
66        }
67    });
68    let output = child.wait_with_output()?;
69    let _ = tx.send(());
70    Ok(output)
71}
72
73/// Send `data` on a Unix stream with file descriptors attached, so the
74/// receiver reads both in one message.
75///
76/// This is the guest→host direction of descriptor passing (the host's
77/// `process::recv_bytes_with_fds` mirrors it). Descriptors and frame bytes
78/// travel together: when a `HostExecV2` request arrives, the host has the
79/// stdio descriptors before it parses the frame. Retries on `EINTR`.
80pub fn send_bytes_with_fds(stream: &UnixStream, data: &[&[u8]], fds: &[RawFd]) -> io::Result<()> {
81    use nix::sys::socket::{ControlMessage, MsgFlags, sendmsg};
82
83    let raw_fd = stream.as_raw_fd();
84    let cmsg = ControlMessage::ScmRights(fds);
85    let total: usize = data.iter().map(|chunk| chunk.len()).sum();
86    let mut sent = 0usize;
87    let mut first = true;
88    loop {
89        // A SOCK_STREAM sendmsg may write fewer bytes than requested. Send
90        // the remaining slices again, but pass the descriptors only once.
91        let mut skip = sent;
92        let mut iov: Vec<IoSlice<'_>> = Vec::with_capacity(data.len());
93        for chunk in data {
94            if skip >= chunk.len() {
95                skip -= chunk.len();
96                continue;
97            }
98            iov.push(IoSlice::new(&chunk[skip..]));
99            skip = 0;
100        }
101        let cmsgs: &[ControlMessage<'_>] = if first {
102            std::slice::from_ref(&cmsg)
103        } else {
104            &[]
105        };
106        match sendmsg::<()>(raw_fd, &iov, cmsgs, MsgFlags::empty(), None) {
107            Ok(n) => {
108                if n == 0 && sent == 0 {
109                    // An empty frame still carries the descriptors.
110                    return Ok(());
111                }
112                if n == 0 {
113                    return Err(io::Error::new(
114                        io::ErrorKind::WriteZero,
115                        "sendmsg made no progress on a non-empty frame",
116                    ));
117                }
118                sent += n;
119                first = false;
120                if sent >= total {
121                    return Ok(());
122                }
123            }
124            Err(nix::errno::Errno::EINTR) => {}
125            Err(e) => return Err(io::Error::from(e)),
126        }
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use std::io::IoSliceMut;
134    use std::os::fd::AsRawFd;
135    use std::os::fd::FromRawFd;
136    use std::os::fd::OwnedFd;
137
138    // Single-threaded test: set_var/remove_var are process-global and unsafe
139    // in edition 2024, so this is wrapped in a targeted allowance.
140    #[test]
141    fn runtime_dir_prefers_the_env_and_falls_back_per_uid() {
142        let saved = std::env::var_os("XDG_RUNTIME_DIR");
143        // SAFETY: this test binary runs test bodies one at a time and no
144        // other thread is spawned, so the global environment has no peer
145        // reader while it is temporarily rewritten.
146        #[allow(unsafe_code)]
147        unsafe {
148            std::env::set_var("XDG_RUNTIME_DIR", "/run/user/4242");
149        }
150        assert_eq!(xdg_runtime_dir(), PathBuf::from("/run/user/4242"));
151        // SAFETY: same single-threaded contract as the set above.
152        #[allow(unsafe_code)]
153        unsafe {
154            std::env::remove_var("XDG_RUNTIME_DIR");
155        }
156        let fallback = xdg_runtime_dir();
157        // SAFETY: restoring the original value for any later test.
158        if let Some(v) = saved {
159            // SAFETY: restoration of a prior env var under single-threaded
160            // test conditions; matches the contract above.
161            #[allow(unsafe_code)]
162            unsafe {
163                std::env::set_var("XDG_RUNTIME_DIR", v);
164            }
165        }
166        assert!(
167            fallback.starts_with("/run/user/") && !fallback.to_string_lossy().ends_with("4242"),
168            "unexpected fallback {fallback:?}"
169        );
170    }
171
172    /// Data and descriptors travel in one message: the frame payload is
173    /// readable on the other end and the descriptor points at the file the
174    /// sender chose.
175    #[test]
176    fn send_bytes_with_fds_delivers_data_and_descriptors_together() {
177        let (tx, rx) = UnixStream::pair().unwrap();
178        let tmp = tempfile::NamedTempFile::new().unwrap();
179        std::fs::write(tmp.path(), b"sent-by-test").unwrap();
180        let file = std::fs::File::open(tmp.path()).unwrap();
181
182        let frame = b"proton frame bytes";
183        send_bytes_with_fds(&tx, &[&frame[..], b""], &[file.as_raw_fd()])
184            .expect("sendmsg with rights");
185
186        let mut buf = [0u8; 64];
187        let (n, owned) = {
188            let mut iov = [IoSliceMut::new(&mut buf)];
189            let mut cmsg = vec![0u8; 64];
190            let msg = nix::sys::socket::recvmsg::<()>(
191                rx.as_raw_fd(),
192                &mut iov,
193                Some(&mut cmsg),
194                nix::sys::socket::MsgFlags::MSG_CMSG_CLOEXEC,
195            )
196            .unwrap();
197            let n = msg.bytes;
198            let mut owned: Vec<OwnedFd> = Vec::new();
199            if let Ok(cmsgs) = msg.cmsgs() {
200                for cmsg in cmsgs {
201                    if let nix::sys::socket::ControlMessageOwned::ScmRights(fds) = cmsg {
202                        owned.extend(fds.into_iter().map(|r| {
203                            // SAFETY: SCM_RIGHTS delivery transferred exactly one
204                            // reference per descriptor to this process.
205                            #[allow(unsafe_code)]
206                            unsafe {
207                                OwnedFd::from_raw_fd(r)
208                            }
209                        }));
210                    }
211                }
212            }
213            (n, owned)
214        };
215        assert_eq!(&buf[..n], frame, "frame bytes did not arrive");
216        assert_eq!(owned.len(), 1);
217        // Reopening through the descriptor proves it is the temp file.
218        let target = tmp.path().to_path_buf();
219        // Reopening through the descriptor proves it is the temp file.
220        let mut fd_file = std::fs::File::from(owned.into_iter().next().unwrap());
221        let mut contents = String::new();
222        std::io::Read::read_to_string(&mut fd_file, &mut contents).unwrap();
223        assert_eq!(contents, "sent-by-test");
224        drop(target);
225    }
226
227    /// Large multi-slice frames may need several sendmsg calls on a stream
228    /// socket; every byte must arrive exactly once.
229    #[test]
230    fn send_bytes_with_fds_handles_partial_writes() {
231        use std::io::Read;
232
233        let (tx, mut rx) = UnixStream::pair().unwrap();
234        // Drain in parallel: a blocking sendmsg of more than the socket
235        // buffer would otherwise wait for a reader that has not started.
236        let reader = std::thread::spawn(move || {
237            let mut received = Vec::new();
238            rx.read_to_end(&mut received).unwrap();
239            received
240        });
241        let a = vec![b'a'; 256 * 1024];
242        let b = vec![b'b'; 128 * 1024];
243        send_bytes_with_fds(&tx, &[&a, &b], &[]).expect("large frame");
244        drop(tx);
245
246        let received = reader.join().unwrap();
247        let mut expected = a;
248        expected.extend_from_slice(&b);
249        assert_eq!(received, expected);
250    }
251}