|
| 1 | +//! SCM_RIGHTS file-descriptor passing over the supervisor control socket. |
| 2 | +//! |
| 3 | +//! `exec` is the only control command that carries open fds (the CLI's |
| 4 | +//! stdin/stdout/stderr, which the container shim wired to the exec stream). |
| 5 | +//! The daemon must receive those fds with the SAME `recvmsg` that reads the |
| 6 | +//! command bytes, because ancillary data binds to specific bytes. All other |
| 7 | +//! commands send an empty ancillary payload, so the receive path is uniform. |
| 8 | +
|
| 9 | +use std::io; |
| 10 | +use std::os::unix::io::{FromRawFd, OwnedFd, RawFd}; |
| 11 | + |
| 12 | +/// Send `data` plus `fds` (as SCM_RIGHTS) over a blocking unix socket. |
| 13 | +pub fn send_with_fds( |
| 14 | + stream: &std::os::unix::net::UnixStream, |
| 15 | + data: &[u8], |
| 16 | + fds: &[RawFd], |
| 17 | +) -> io::Result<()> { |
| 18 | + use std::os::unix::io::AsRawFd; |
| 19 | + |
| 20 | + let mut iov = libc::iovec { |
| 21 | + iov_base: data.as_ptr() as *mut libc::c_void, |
| 22 | + iov_len: data.len(), |
| 23 | + }; |
| 24 | + let fds_bytes = std::mem::size_of_val(fds) as u32; |
| 25 | + let cmsg_space = if fds.is_empty() { |
| 26 | + 0usize |
| 27 | + } else { |
| 28 | + unsafe { libc::CMSG_SPACE(fds_bytes) as usize } |
| 29 | + }; |
| 30 | + let mut cmsg_buf = vec![0u8; cmsg_space]; |
| 31 | + |
| 32 | + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; |
| 33 | + msg.msg_iov = &mut iov; |
| 34 | + msg.msg_iovlen = 1; |
| 35 | + if !fds.is_empty() { |
| 36 | + msg.msg_control = cmsg_buf.as_mut_ptr() as *mut libc::c_void; |
| 37 | + msg.msg_controllen = cmsg_space as _; |
| 38 | + unsafe { |
| 39 | + let cmsg = libc::CMSG_FIRSTHDR(&msg); |
| 40 | + (*cmsg).cmsg_level = libc::SOL_SOCKET; |
| 41 | + (*cmsg).cmsg_type = libc::SCM_RIGHTS; |
| 42 | + (*cmsg).cmsg_len = libc::CMSG_LEN(fds_bytes) as _; |
| 43 | + std::ptr::copy_nonoverlapping( |
| 44 | + fds.as_ptr(), |
| 45 | + libc::CMSG_DATA(cmsg) as *mut RawFd, |
| 46 | + fds.len(), |
| 47 | + ); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + let n = unsafe { libc::sendmsg(stream.as_raw_fd(), &msg, 0) }; |
| 52 | + if n < 0 { |
| 53 | + return Err(io::Error::last_os_error()); |
| 54 | + } |
| 55 | + Ok(()) |
| 56 | +} |
| 57 | + |
| 58 | +/// Receive bytes plus up to `max_fds` SCM_RIGHTS fds from a raw socket fd |
| 59 | +/// (one `recvmsg`). Returns the data and any received `OwnedFd`s. |
| 60 | +pub fn recv_with_fds(fd: RawFd, max_fds: usize) -> io::Result<(Vec<u8>, Vec<OwnedFd>)> { |
| 61 | + let mut buf = vec![0u8; 8192]; |
| 62 | + let mut iov = libc::iovec { |
| 63 | + iov_base: buf.as_mut_ptr() as *mut libc::c_void, |
| 64 | + iov_len: buf.len(), |
| 65 | + }; |
| 66 | + let cmsg_space = |
| 67 | + unsafe { libc::CMSG_SPACE((max_fds * std::mem::size_of::<RawFd>()) as u32) as usize }; |
| 68 | + let mut cmsg_buf = vec![0u8; cmsg_space]; |
| 69 | + |
| 70 | + let mut msg: libc::msghdr = unsafe { std::mem::zeroed() }; |
| 71 | + msg.msg_iov = &mut iov; |
| 72 | + msg.msg_iovlen = 1; |
| 73 | + msg.msg_control = cmsg_buf.as_mut_ptr() as *mut libc::c_void; |
| 74 | + msg.msg_controllen = cmsg_space as _; |
| 75 | + |
| 76 | + let n = unsafe { libc::recvmsg(fd, &mut msg, 0) }; |
| 77 | + if n < 0 { |
| 78 | + return Err(io::Error::last_os_error()); |
| 79 | + } |
| 80 | + |
| 81 | + let mut fds = Vec::new(); |
| 82 | + unsafe { |
| 83 | + let mut cmsg = libc::CMSG_FIRSTHDR(&msg); |
| 84 | + while !cmsg.is_null() { |
| 85 | + if (*cmsg).cmsg_level == libc::SOL_SOCKET && (*cmsg).cmsg_type == libc::SCM_RIGHTS { |
| 86 | + let payload = (*cmsg).cmsg_len as usize - libc::CMSG_LEN(0) as usize; |
| 87 | + let count = payload / std::mem::size_of::<RawFd>(); |
| 88 | + let data_ptr = libc::CMSG_DATA(cmsg) as *const RawFd; |
| 89 | + for i in 0..count { |
| 90 | + fds.push(OwnedFd::from_raw_fd(*data_ptr.add(i))); |
| 91 | + } |
| 92 | + } |
| 93 | + cmsg = libc::CMSG_NXTHDR(&msg, cmsg); |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + buf.truncate(n as usize); |
| 98 | + Ok((buf, fds)) |
| 99 | +} |
| 100 | + |
| 101 | +/// Tokio wrapper: await readability, then one `recv_with_fds` on the raw fd. |
| 102 | +/// `recvmsg` returns `EAGAIN` (`WouldBlock`) if the socket was not actually |
| 103 | +/// ready; loop until it yields data. |
| 104 | +pub async fn recv_with_fds_async( |
| 105 | + stream: &tokio::net::UnixStream, |
| 106 | + max_fds: usize, |
| 107 | +) -> io::Result<(Vec<u8>, Vec<OwnedFd>)> { |
| 108 | + use std::os::unix::io::AsRawFd; |
| 109 | + loop { |
| 110 | + stream.readable().await?; |
| 111 | + match stream.try_io(tokio::io::Interest::READABLE, || { |
| 112 | + recv_with_fds(stream.as_raw_fd(), max_fds) |
| 113 | + }) { |
| 114 | + Ok(res) => return Ok(res), |
| 115 | + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, |
| 116 | + Err(e) => return Err(e), |
| 117 | + } |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +#[cfg(test)] |
| 122 | +mod tests { |
| 123 | + use super::*; |
| 124 | + use std::io::Write; |
| 125 | + use std::os::unix::io::AsRawFd; |
| 126 | + use std::os::unix::net::UnixStream; |
| 127 | + |
| 128 | + /// Send a pipe's write-end across a socketpair, then prove the received fd |
| 129 | + /// is the SAME open file: writing through it is readable from the original |
| 130 | + /// read-end. |
| 131 | + #[test] |
| 132 | + fn send_and_recv_one_fd_roundtrip() { |
| 133 | + let (a, b) = UnixStream::pair().unwrap(); |
| 134 | + |
| 135 | + // A pipe whose write end we will pass over the socket. |
| 136 | + let mut fds = [0i32; 2]; |
| 137 | + assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0); |
| 138 | + let (pipe_r, pipe_w) = (fds[0], fds[1]); |
| 139 | + |
| 140 | + send_with_fds(&a, b"PING", &[pipe_w]).unwrap(); |
| 141 | + let (data, got) = recv_with_fds(b.as_raw_fd(), 3).unwrap(); |
| 142 | + |
| 143 | + assert_eq!(&data, b"PING"); |
| 144 | + assert_eq!(got.len(), 1); |
| 145 | + |
| 146 | + // Write through the RECEIVED fd, read from the original pipe read end. |
| 147 | + let received_w = got[0].as_raw_fd(); |
| 148 | + assert_eq!(unsafe { libc::write(received_w, b"Z".as_ptr() as *const _, 1) }, 1); |
| 149 | + let mut buf = [0u8; 1]; |
| 150 | + assert_eq!(unsafe { libc::read(pipe_r, buf.as_mut_ptr() as *mut _, 1) }, 1); |
| 151 | + assert_eq!(buf[0], b'Z'); |
| 152 | + |
| 153 | + unsafe { libc::close(pipe_r); libc::close(pipe_w); } |
| 154 | + let _ = (a, b); |
| 155 | + } |
| 156 | + |
| 157 | + #[test] |
| 158 | + fn recv_without_fds_returns_empty_vec() { |
| 159 | + let (mut a, b) = UnixStream::pair().unwrap(); |
| 160 | + a.write_all(b"hello").unwrap(); |
| 161 | + let (data, got) = recv_with_fds(b.as_raw_fd(), 3).unwrap(); |
| 162 | + assert_eq!(&data, b"hello"); |
| 163 | + assert!(got.is_empty()); |
| 164 | + } |
| 165 | +} |
0 commit comments