Skip to main content

acde_wire/channel/
unix.rs

1use std::fs::File;
2use std::io::{IoSlice, IoSliceMut};
3use std::mem::MaybeUninit;
4use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
5use std::os::unix::fs::FileExt;
6
7use rustix::io::Errno;
8use rustix::net::{
9    AddressFamily, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, SendAncillaryMessage, SendFlags, SocketFlags,
10    SocketType, recvmsg, sendmsg, socketpair,
11};
12use serde_json::{Value, json};
13
14#[cfg(target_vendor = "apple")]
15mod apple;
16
17pub fn pair() -> Result<(OwnedFd, OwnedFd), String> {
18    let kind = if cfg!(target_vendor = "apple") { SocketType::STREAM } else { SocketType::SEQPACKET };
19    socket_pair(kind).map_err(|e| format!("the manager's channel: {e}"))
20}
21
22fn socket_pair(kind: SocketType) -> Result<(OwnedFd, OwnedFd), Errno> {
23    #[cfg(not(target_vendor = "apple"))]
24    return socketpair(AddressFamily::UNIX, kind, SocketFlags::CLOEXEC, None);
25
26    #[cfg(target_vendor = "apple")]
27    {
28        let (a, b) = socketpair(AddressFamily::UNIX, kind, SocketFlags::empty(), None)?;
29        apple::cloexec(&a)?;
30        apple::cloexec(&b)?;
31        Ok((a, b))
32    }
33}
34
35fn frame_file(bytes: &[u8]) -> std::io::Result<File> {
36    #[cfg(not(target_vendor = "apple"))]
37    let file = File::from(rustix::fs::memfd_create("acde-frame", rustix::fs::MemfdFlags::CLOEXEC)?);
38    #[cfg(target_vendor = "apple")]
39    let file = tempfile::tempfile()?;
40    file.write_all_at(bytes, 0)?;
41    Ok(file)
42}
43
44pub struct Packet {
45    bytes: Vec<u8>,
46    fds: Vec<OwnedFd>,
47    size: usize,
48}
49
50impl Packet {
51    pub fn size(&self) -> usize {
52        self.size
53    }
54}
55
56#[derive(Debug, PartialEq, Eq)]
57pub enum Received {
58    Frame(Value),
59    Nothing,
60    Closed,
61}
62
63pub struct Channel {
64    fd: OwnedFd,
65}
66
67impl Channel {
68    pub const FRAME_MAX: usize = 256 * 1024;
69    pub const FDS_MAX: usize = 64;
70    pub const BIG_MAX: usize = 64 << 20;
71    const INLINE_MAX: usize = 128 * 1024;
72    const BIG: &str = "@memfd";
73    const TRANSPORT_FDS: usize = Self::FDS_MAX + cfg!(target_vendor = "apple") as usize;
74
75    pub fn new(fd: OwnedFd) -> Self {
76        Self { fd }
77    }
78
79    pub fn try_clone(&self) -> Result<Self, String> {
80        self.fd.try_clone().map(Self::new).map_err(|e| format!("the manager's channel: {e}"))
81    }
82
83    pub fn send(&self, frame: &Value, wait: bool) -> Result<(), String> {
84        let packet = Self::pack(frame)?;
85        self.send_bytes(&packet.bytes, &borrowed(&packet.fds), wait)
86    }
87
88    pub fn pack(frame: &Value) -> Result<Packet, String> {
89        let bytes = serde_json::to_vec(frame).map_err(|e| e.to_string())?;
90        if bytes.len() <= Self::INLINE_MAX {
91            return Ok(Packet { size: bytes.len(), bytes, fds: Vec::new() });
92        }
93        if bytes.len() > Self::BIG_MAX {
94            return Err(format!("a frame of {} bytes is over {}", bytes.len(), Self::BIG_MAX));
95        }
96        let file = frame_file(&bytes).map_err(|e| format!("a big frame: {e}"))?;
97        let head = serde_json::to_vec(&json!({ Self::BIG: bytes.len() })).map_err(|e| e.to_string())?;
98        Ok(Packet { bytes: head, fds: vec![OwnedFd::from(file)], size: bytes.len() })
99    }
100
101    pub fn pack_with_fd(frame: &Value, fd: OwnedFd) -> Result<Packet, String> {
102        Self::pack_with_fds(frame, vec![fd])
103    }
104
105    pub fn pack_with_fds(frame: &Value, fds: Vec<OwnedFd>) -> Result<Packet, String> {
106        let bytes = Self::inline_with_fds(frame, fds.len())?;
107        Ok(Packet { size: bytes.len(), bytes, fds })
108    }
109
110    fn inline_with_fds(frame: &Value, fds: usize) -> Result<Vec<u8>, String> {
111        if fds > Self::FDS_MAX {
112            return Err(format!("a frame carries at most {} fds, not {fds}", Self::FDS_MAX));
113        }
114        let bytes = serde_json::to_vec(frame).map_err(|e| e.to_string())?;
115        if bytes.len() > Self::INLINE_MAX {
116            return Err(format!("a frame with fds fits inline ({} bytes is over {})", bytes.len(), Self::INLINE_MAX));
117        }
118        Ok(bytes)
119    }
120
121    pub fn offer(&self, packet: &Packet) -> Result<bool, String> {
122        match self.send_raw(&packet.bytes, &borrowed(&packet.fds), false) {
123            Ok(()) => Ok(true),
124            Err(Errno::AGAIN) => Ok(false),
125            Err(e) => Err(e.to_string()),
126        }
127    }
128
129    pub fn send_with_fd(&self, frame: &Value, fd: BorrowedFd<'_>, wait: bool) -> Result<(), String> {
130        self.send_with_fds(frame, &[fd], wait)
131    }
132
133    pub fn send_with_fds(&self, frame: &Value, fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), String> {
134        let bytes = Self::inline_with_fds(frame, fds.len())?;
135        self.send_bytes(&bytes, fds, wait)
136    }
137
138    fn send_bytes(&self, bytes: &[u8], fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), String> {
139        self.send_raw(bytes, fds, wait).map_err(|e| e.to_string())
140    }
141
142    fn send_raw(&self, bytes: &[u8], fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), Errno> {
143        #[cfg(target_vendor = "apple")]
144        let (carrier, bytes) = apple::encode(&self.fd, bytes)?;
145        #[cfg(target_vendor = "apple")]
146        let rights: Vec<_> = std::iter::once(carrier.as_fd()).chain(fds.iter().copied()).collect();
147        #[cfg(target_vendor = "apple")]
148        let fds = rights.as_slice();
149        #[cfg(not(target_vendor = "apple"))]
150        let base = SendFlags::NOSIGNAL;
151        #[cfg(target_vendor = "apple")]
152        let base = SendFlags::empty();
153        let flags = if wait { base } else { base | SendFlags::DONTWAIT };
154        let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(Self::TRANSPORT_FDS))];
155        let mut ancillary = SendAncillaryBuffer::new(&mut space);
156        if !fds.is_empty() && !ancillary.push(SendAncillaryMessage::ScmRights(fds)) {
157            return Err(Errno::INVAL);
158        }
159        loop {
160            match sendmsg(&self.fd, &[IoSlice::new(bytes)], &mut ancillary, flags) {
161                Ok(_) => return Ok(()),
162                Err(Errno::INTR) => continue,
163                #[cfg(target_vendor = "apple")]
164                Err(Errno::AGAIN) if wait => apple::wait_to_write(&self.fd)?,
165                Err(e) => return Err(e),
166            }
167        }
168    }
169
170    fn unpack(frame: Value, mut fds: Vec<OwnedFd>) -> Result<(Value, Vec<OwnedFd>), String> {
171        let Some(length) = frame.get(Self::BIG).and_then(Value::as_u64).filter(|_| frame.as_object().is_some_and(|o| o.len() == 1)) else {
172            return Ok((frame, fds));
173        };
174        let fd = (fds.len() == 1).then(|| fds.remove(0));
175        let length =
176            usize::try_from(length).ok().filter(|n| *n <= Self::BIG_MAX).ok_or_else(|| format!("a frame of {length} bytes is over {}", Self::BIG_MAX))?;
177        let file = std::fs::File::from(fd.ok_or("a big frame came without its memfd")?);
178        let mut bytes = vec![0u8; length];
179        file.read_exact_at(&mut bytes, 0).map_err(|e| format!("a big frame: {e}"))?;
180        serde_json::from_slice(&bytes).map(|frame| (frame, Vec::new())).map_err(|e| format!("not a JSON frame: {e}"))
181    }
182
183    pub fn receive(&self, wait: bool) -> Result<Received, String> {
184        self.receive_with_fd(wait).map(|(received, _)| received)
185    }
186
187    pub fn receive_with_fd(&self, wait: bool) -> Result<(Received, Option<OwnedFd>), String> {
188        self.receive_with_fds(wait).map(|(received, fds)| (received, fds.into_iter().next()))
189    }
190
191    pub fn receive_with_fds(&self, wait: bool) -> Result<(Received, Vec<OwnedFd>), String> {
192        #[cfg(not(target_vendor = "apple"))]
193        let (mut buf, base) = (vec![0u8; Self::FRAME_MAX], RecvFlags::CMSG_CLOEXEC);
194        #[cfg(target_vendor = "apple")]
195        let (mut buf, base) = {
196            apple::nonblocking(&self.fd).map_err(|e| e.to_string())?;
197            ([0u8; 1], RecvFlags::empty())
198        };
199        let flags = if wait { base } else { base | RecvFlags::DONTWAIT };
200        loop {
201            let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(Self::TRANSPORT_FDS))];
202            let mut ancillary = RecvAncillaryBuffer::new(&mut space);
203            let got = recvmsg(&self.fd, &mut [IoSliceMut::new(&mut buf)], &mut ancillary, flags);
204            let fds: Vec<OwnedFd> = ancillary
205                .drain()
206                .flat_map(|message| match message {
207                    RecvAncillaryMessage::ScmRights(fds) => fds.collect(),
208                    _ => Vec::new(),
209                })
210                .collect();
211            #[cfg(target_vendor = "apple")]
212            if matches!(got, Err(Errno::AGAIN)) && wait {
213                apple::wait_to_read(&self.fd).map_err(|e| e.to_string())?;
214                continue;
215            }
216            return match got {
217                Ok(msg) if msg.bytes == 0 => Ok((Received::Closed, Vec::new())),
218                Ok(msg) if msg.flags.contains(ReturnFlags::CTRUNC) || fds.len() > Self::TRANSPORT_FDS => {
219                    Err(format!("a frame came with more than {} fds", Self::FDS_MAX))
220                }
221                Ok(msg) if msg.flags.contains(ReturnFlags::TRUNC) => Err(format!("a frame over {} bytes came inline", Self::FRAME_MAX)),
222                Ok(msg) => Self::receive_frame(&buf[..msg.bytes], fds),
223                Err(Errno::INTR) => continue,
224                Err(Errno::AGAIN) => Ok((Received::Nothing, Vec::new())),
225                Err(Errno::CONNRESET) => Ok((Received::Closed, Vec::new())),
226                Err(e) => Err(e.to_string()),
227            };
228        }
229    }
230
231    fn receive_frame(bytes: &[u8], fds: Vec<OwnedFd>) -> Result<(Received, Vec<OwnedFd>), String> {
232        #[cfg(target_vendor = "apple")]
233        let (frame_bytes, fds) = apple::decode(bytes, fds)?;
234        #[cfg(target_vendor = "apple")]
235        let bytes = frame_bytes.as_slice();
236        serde_json::from_slice(bytes)
237            .map_err(|e| format!("not a JSON frame: {e}"))
238            .and_then(|frame| Self::unpack(frame, fds))
239            .map(|(frame, fds)| (Received::Frame(frame), fds))
240    }
241}
242
243impl AsFd for Channel {
244    fn as_fd(&self) -> BorrowedFd<'_> {
245        self.fd.as_fd()
246    }
247}
248
249pub type FdKeeper = Box<dyn Fn(Vec<OwnedFd>) -> Vec<String> + Send + Sync>;
250
251pub fn handed(keeper: Option<&FdKeeper>, mut value: Value, fds: Vec<OwnedFd>) -> Value {
252    if let (false, Some(keeper), Some(object)) = (fds.is_empty(), keeper, value.as_object_mut()) {
253        object.insert("fds".into(), json!(keeper(fds)));
254    }
255    value
256}
257
258fn borrowed(fds: &[OwnedFd]) -> Vec<BorrowedFd<'_>> {
259    fds.iter().map(AsFd::as_fd).collect()
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn a_frame_over_the_inline_size_goes_through_a_file() {
268        let (a, b) = pair().unwrap();
269        let (a, b) = (Channel::new(a), Channel::new(b));
270        let catalog: Vec<Value> = (0..20_000).map(|i| json!({ "id": i, "name": format!("package {i}") })).collect();
271        let big = json!({ "id": 1, "ok": catalog });
272        a.send(&big, true).unwrap();
273        a.send(&json!({ "id": 2, "ok": null }), true).unwrap();
274        assert_eq!(b.receive(true).unwrap(), Received::Frame(big));
275        assert_eq!(b.receive(true).unwrap(), Received::Frame(json!({ "id": 2, "ok": null })));
276    }
277
278    #[test]
279    fn a_small_frame_carries_an_fd_across() {
280        let (a, b) = pair().unwrap();
281        let (a, b) = (Channel::new(a), Channel::new(b));
282        let (ours, theirs) = socket_pair(SocketType::STREAM).unwrap();
283        a.send_with_fd(&json!({ "id": 1, "ok": { "role": "desktop" } }), theirs.as_fd(), true).unwrap();
284        drop(theirs);
285        let (frame, fd) = b.receive_with_fd(true).unwrap();
286        assert_eq!(frame, Received::Frame(json!({ "id": 1, "ok": { "role": "desktop" } })));
287        let fd = fd.expect("the fd came with the frame");
288        assert!(rustix::io::fcntl_getfd(&fd).unwrap().contains(rustix::io::FdFlags::CLOEXEC));
289        rustix::io::write(&fd, b"hi").unwrap();
290        let mut got = [0u8; 2];
291        rustix::io::read(&ours, &mut got).unwrap();
292        assert_eq!(&got, b"hi");
293        a.send(&json!({ "id": 2, "ok": null }), true).unwrap();
294        assert!(b.receive_with_fd(true).unwrap().1.is_none(), "a frame without an fd brings none");
295    }
296
297    #[test]
298    fn a_frame_carries_several_fds_in_order() {
299        let (a, b) = pair().unwrap();
300        let (a, b) = (Channel::new(a), Channel::new(b));
301        let ends: Vec<(OwnedFd, OwnedFd)> = (0..3).map(|_| socket_pair(SocketType::STREAM).unwrap()).collect();
302        let theirs: Vec<BorrowedFd<'_>> = ends.iter().map(|(_, theirs)| theirs.as_fd()).collect();
303        a.send_with_fds(&json!({ "id": 1, "ok": { "files": 3 } }), &theirs, true).unwrap();
304        let (frame, fds) = b.receive_with_fds(true).unwrap();
305        assert_eq!(frame, Received::Frame(json!({ "id": 1, "ok": { "files": 3 } })));
306        assert_eq!(fds.len(), 3);
307        for (i, (fd, (ours, _))) in fds.iter().zip(&ends).enumerate() {
308            rustix::io::write(fd, &[i as u8]).unwrap();
309            let mut got = [0u8; 1];
310            rustix::io::read(ours, &mut got).unwrap();
311            assert_eq!(got[0], i as u8, "fd {i} keeps its place");
312        }
313        let many: Vec<BorrowedFd<'_>> = (0..=Channel::FDS_MAX).map(|_| theirs[0]).collect();
314        assert!(a.send_with_fds(&json!({ "id": 2 }), &many, true).is_err());
315    }
316
317    #[test]
318    fn the_channel_preserves_nonblocking_packets_and_peer_close() {
319        let (a, b) = pair().unwrap();
320        assert!(rustix::io::fcntl_getfd(&a).unwrap().contains(rustix::io::FdFlags::CLOEXEC));
321        assert!(rustix::io::fcntl_getfd(&b).unwrap().contains(rustix::io::FdFlags::CLOEXEC));
322        rustix::net::sockopt::set_socket_send_buffer_size(&a, 1024).unwrap();
323        let (a, b) = (Channel::new(a), Channel::new(b));
324        assert_eq!(b.receive(false).unwrap(), Received::Nothing);
325
326        let frame = json!({ "id": 42 });
327        let packet = Channel::pack(&frame).unwrap();
328        let offered = (0..1000).find(|_| !a.offer(&packet).unwrap()).expect("the channel fills up");
329        assert!(offered > 0);
330        for _ in 0..offered {
331            assert_eq!(b.receive(false).unwrap(), Received::Frame(frame.clone()));
332        }
333        assert_eq!(b.receive(false).unwrap(), Received::Nothing);
334        drop(b);
335        assert!(a.offer(&packet).is_err());
336        assert_eq!(a.receive(false).unwrap(), Received::Closed);
337        #[cfg(target_vendor = "apple")]
338        assert!(rustix::net::sockopt::socket_nosigpipe(&a).unwrap());
339    }
340
341    #[cfg(target_vendor = "apple")]
342    #[test]
343    fn a_malformed_stream_frame_does_not_keep_its_rights() {
344        let (a, b) = pair().unwrap();
345        let b = Channel::new(b);
346        let (ours, theirs) = socket_pair(SocketType::STREAM).unwrap();
347        let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(1))];
348        let mut ancillary = SendAncillaryBuffer::new(&mut space);
349        let rights = [theirs.as_fd()];
350        assert!(ancillary.push(SendAncillaryMessage::ScmRights(&rights)));
351        sendmsg(&a, &[IoSlice::new(b"x")], &mut ancillary, SendFlags::empty()).unwrap();
352        drop(theirs);
353        assert_eq!(b.receive(false).unwrap_err(), "a frame came without its marker");
354        apple::nonblocking(&ours).unwrap();
355        assert_eq!(rustix::io::read(&ours, &mut [0u8; 1]), Ok(0));
356    }
357
358    #[test]
359    fn fds_become_the_keepers_tokens_or_are_closed() {
360        let keeper: FdKeeper = Box::new(|fds| fds.iter().enumerate().map(|(i, _)| format!("token-{i}")).collect());
361        let (_, theirs) = socket_pair(SocketType::STREAM).unwrap();
362        let kept = handed(Some(&keeper), json!({ "name": "work", "fd": 0 }), vec![theirs]);
363        assert_eq!(kept, json!({ "name": "work", "fd": 0, "fds": ["token-0"] }));
364        let (ours, theirs) = socket_pair(SocketType::STREAM).unwrap();
365        let dropped = handed(None, json!({ "name": "work", "fd": 0 }), vec![theirs]);
366        assert_eq!(dropped, json!({ "name": "work", "fd": 0 }), "no keeper, no fds");
367        let mut got = [0u8; 1];
368        assert_eq!(rustix::io::read(&ours, &mut got).unwrap(), 0, "the fd was closed");
369    }
370}