acde-wire 1.1.5

The session manager's control channel (JSON frames with fds) and the acompositor client protocols, for acdes and acdev's guest agent
Documentation
use std::fs::File;
use std::io::{IoSlice, IoSliceMut};
use std::mem::MaybeUninit;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::fs::FileExt;

use rustix::io::Errno;
use rustix::net::{
    AddressFamily, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, SendAncillaryMessage, SendFlags, SocketFlags,
    SocketType, recvmsg, sendmsg, socketpair,
};
use serde_json::{Value, json};

#[cfg(target_vendor = "apple")]
mod apple;

pub fn pair() -> Result<(OwnedFd, OwnedFd), String> {
    let kind = if cfg!(target_vendor = "apple") { SocketType::STREAM } else { SocketType::SEQPACKET };
    socket_pair(kind).map_err(|e| format!("the manager's channel: {e}"))
}

fn socket_pair(kind: SocketType) -> Result<(OwnedFd, OwnedFd), Errno> {
    #[cfg(not(target_vendor = "apple"))]
    return socketpair(AddressFamily::UNIX, kind, SocketFlags::CLOEXEC, None);

    #[cfg(target_vendor = "apple")]
    {
        let (a, b) = socketpair(AddressFamily::UNIX, kind, SocketFlags::empty(), None)?;
        apple::cloexec(&a)?;
        apple::cloexec(&b)?;
        Ok((a, b))
    }
}

fn frame_file(bytes: &[u8]) -> std::io::Result<File> {
    #[cfg(not(target_vendor = "apple"))]
    let file = File::from(rustix::fs::memfd_create("acde-frame", rustix::fs::MemfdFlags::CLOEXEC)?);
    #[cfg(target_vendor = "apple")]
    let file = tempfile::tempfile()?;
    file.write_all_at(bytes, 0)?;
    Ok(file)
}

pub struct Packet {
    bytes: Vec<u8>,
    fds: Vec<OwnedFd>,
    size: usize,
}

impl Packet {
    pub fn size(&self) -> usize {
        self.size
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum Received {
    Frame(Value),
    Nothing,
    Closed,
}

pub struct Channel {
    fd: OwnedFd,
}

impl Channel {
    pub const FRAME_MAX: usize = 256 * 1024;
    pub const FDS_MAX: usize = 64;
    pub const BIG_MAX: usize = 64 << 20;
    const INLINE_MAX: usize = 128 * 1024;
    const BIG: &str = "@memfd";
    const TRANSPORT_FDS: usize = Self::FDS_MAX + cfg!(target_vendor = "apple") as usize;

    pub fn new(fd: OwnedFd) -> Self {
        Self { fd }
    }

    pub fn try_clone(&self) -> Result<Self, String> {
        self.fd.try_clone().map(Self::new).map_err(|e| format!("the manager's channel: {e}"))
    }

    pub fn send(&self, frame: &Value, wait: bool) -> Result<(), String> {
        let packet = Self::pack(frame)?;
        self.send_bytes(&packet.bytes, &borrowed(&packet.fds), wait)
    }

    pub fn pack(frame: &Value) -> Result<Packet, String> {
        let bytes = serde_json::to_vec(frame).map_err(|e| e.to_string())?;
        if bytes.len() <= Self::INLINE_MAX {
            return Ok(Packet { size: bytes.len(), bytes, fds: Vec::new() });
        }
        if bytes.len() > Self::BIG_MAX {
            return Err(format!("a frame of {} bytes is over {}", bytes.len(), Self::BIG_MAX));
        }
        let file = frame_file(&bytes).map_err(|e| format!("a big frame: {e}"))?;
        let head = serde_json::to_vec(&json!({ Self::BIG: bytes.len() })).map_err(|e| e.to_string())?;
        Ok(Packet { bytes: head, fds: vec![OwnedFd::from(file)], size: bytes.len() })
    }

    pub fn pack_with_fd(frame: &Value, fd: OwnedFd) -> Result<Packet, String> {
        Self::pack_with_fds(frame, vec![fd])
    }

    pub fn pack_with_fds(frame: &Value, fds: Vec<OwnedFd>) -> Result<Packet, String> {
        let bytes = Self::inline_with_fds(frame, fds.len())?;
        Ok(Packet { size: bytes.len(), bytes, fds })
    }

    fn inline_with_fds(frame: &Value, fds: usize) -> Result<Vec<u8>, String> {
        if fds > Self::FDS_MAX {
            return Err(format!("a frame carries at most {} fds, not {fds}", Self::FDS_MAX));
        }
        let bytes = serde_json::to_vec(frame).map_err(|e| e.to_string())?;
        if bytes.len() > Self::INLINE_MAX {
            return Err(format!("a frame with fds fits inline ({} bytes is over {})", bytes.len(), Self::INLINE_MAX));
        }
        Ok(bytes)
    }

    pub fn offer(&self, packet: &Packet) -> Result<bool, String> {
        match self.send_raw(&packet.bytes, &borrowed(&packet.fds), false) {
            Ok(()) => Ok(true),
            Err(Errno::AGAIN) => Ok(false),
            Err(e) => Err(e.to_string()),
        }
    }

    pub fn send_with_fd(&self, frame: &Value, fd: BorrowedFd<'_>, wait: bool) -> Result<(), String> {
        self.send_with_fds(frame, &[fd], wait)
    }

    pub fn send_with_fds(&self, frame: &Value, fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), String> {
        let bytes = Self::inline_with_fds(frame, fds.len())?;
        self.send_bytes(&bytes, fds, wait)
    }

    fn send_bytes(&self, bytes: &[u8], fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), String> {
        self.send_raw(bytes, fds, wait).map_err(|e| e.to_string())
    }

    fn send_raw(&self, bytes: &[u8], fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), Errno> {
        #[cfg(target_vendor = "apple")]
        let (carrier, bytes) = apple::encode(&self.fd, bytes)?;
        #[cfg(target_vendor = "apple")]
        let rights: Vec<_> = std::iter::once(carrier.as_fd()).chain(fds.iter().copied()).collect();
        #[cfg(target_vendor = "apple")]
        let fds = rights.as_slice();
        #[cfg(not(target_vendor = "apple"))]
        let base = SendFlags::NOSIGNAL;
        #[cfg(target_vendor = "apple")]
        let base = SendFlags::empty();
        let flags = if wait { base } else { base | SendFlags::DONTWAIT };
        let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(Self::TRANSPORT_FDS))];
        let mut ancillary = SendAncillaryBuffer::new(&mut space);
        if !fds.is_empty() && !ancillary.push(SendAncillaryMessage::ScmRights(fds)) {
            return Err(Errno::INVAL);
        }
        loop {
            match sendmsg(&self.fd, &[IoSlice::new(bytes)], &mut ancillary, flags) {
                Ok(_) => return Ok(()),
                Err(Errno::INTR) => continue,
                #[cfg(target_vendor = "apple")]
                Err(Errno::AGAIN) if wait => apple::wait_to_write(&self.fd)?,
                Err(e) => return Err(e),
            }
        }
    }

    fn unpack(frame: Value, mut fds: Vec<OwnedFd>) -> Result<(Value, Vec<OwnedFd>), String> {
        let Some(length) = frame.get(Self::BIG).and_then(Value::as_u64).filter(|_| frame.as_object().is_some_and(|o| o.len() == 1)) else {
            return Ok((frame, fds));
        };
        let fd = (fds.len() == 1).then(|| fds.remove(0));
        let length =
            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))?;
        let file = std::fs::File::from(fd.ok_or("a big frame came without its memfd")?);
        let mut bytes = vec![0u8; length];
        file.read_exact_at(&mut bytes, 0).map_err(|e| format!("a big frame: {e}"))?;
        serde_json::from_slice(&bytes).map(|frame| (frame, Vec::new())).map_err(|e| format!("not a JSON frame: {e}"))
    }

    pub fn receive(&self, wait: bool) -> Result<Received, String> {
        self.receive_with_fd(wait).map(|(received, _)| received)
    }

    pub fn receive_with_fd(&self, wait: bool) -> Result<(Received, Option<OwnedFd>), String> {
        self.receive_with_fds(wait).map(|(received, fds)| (received, fds.into_iter().next()))
    }

    pub fn receive_with_fds(&self, wait: bool) -> Result<(Received, Vec<OwnedFd>), String> {
        #[cfg(not(target_vendor = "apple"))]
        let (mut buf, base) = (vec![0u8; Self::FRAME_MAX], RecvFlags::CMSG_CLOEXEC);
        #[cfg(target_vendor = "apple")]
        let (mut buf, base) = {
            apple::nonblocking(&self.fd).map_err(|e| e.to_string())?;
            ([0u8; 1], RecvFlags::empty())
        };
        let flags = if wait { base } else { base | RecvFlags::DONTWAIT };
        loop {
            let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(Self::TRANSPORT_FDS))];
            let mut ancillary = RecvAncillaryBuffer::new(&mut space);
            let got = recvmsg(&self.fd, &mut [IoSliceMut::new(&mut buf)], &mut ancillary, flags);
            let fds: Vec<OwnedFd> = ancillary
                .drain()
                .flat_map(|message| match message {
                    RecvAncillaryMessage::ScmRights(fds) => fds.collect(),
                    _ => Vec::new(),
                })
                .collect();
            #[cfg(target_vendor = "apple")]
            if matches!(got, Err(Errno::AGAIN)) && wait {
                apple::wait_to_read(&self.fd).map_err(|e| e.to_string())?;
                continue;
            }
            return match got {
                Ok(msg) if msg.bytes == 0 => Ok((Received::Closed, Vec::new())),
                Ok(msg) if msg.flags.contains(ReturnFlags::CTRUNC) || fds.len() > Self::TRANSPORT_FDS => {
                    Err(format!("a frame came with more than {} fds", Self::FDS_MAX))
                }
                Ok(msg) if msg.flags.contains(ReturnFlags::TRUNC) => Err(format!("a frame over {} bytes came inline", Self::FRAME_MAX)),
                Ok(msg) => Self::receive_frame(&buf[..msg.bytes], fds),
                Err(Errno::INTR) => continue,
                Err(Errno::AGAIN) => Ok((Received::Nothing, Vec::new())),
                Err(Errno::CONNRESET) => Ok((Received::Closed, Vec::new())),
                Err(e) => Err(e.to_string()),
            };
        }
    }

    fn receive_frame(bytes: &[u8], fds: Vec<OwnedFd>) -> Result<(Received, Vec<OwnedFd>), String> {
        #[cfg(target_vendor = "apple")]
        let (frame_bytes, fds) = apple::decode(bytes, fds)?;
        #[cfg(target_vendor = "apple")]
        let bytes = frame_bytes.as_slice();
        serde_json::from_slice(bytes)
            .map_err(|e| format!("not a JSON frame: {e}"))
            .and_then(|frame| Self::unpack(frame, fds))
            .map(|(frame, fds)| (Received::Frame(frame), fds))
    }
}

impl AsFd for Channel {
    fn as_fd(&self) -> BorrowedFd<'_> {
        self.fd.as_fd()
    }
}

pub type FdKeeper = Box<dyn Fn(Vec<OwnedFd>) -> Vec<String> + Send + Sync>;

pub fn handed(keeper: Option<&FdKeeper>, mut value: Value, fds: Vec<OwnedFd>) -> Value {
    if let (false, Some(keeper), Some(object)) = (fds.is_empty(), keeper, value.as_object_mut()) {
        object.insert("fds".into(), json!(keeper(fds)));
    }
    value
}

fn borrowed(fds: &[OwnedFd]) -> Vec<BorrowedFd<'_>> {
    fds.iter().map(AsFd::as_fd).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_frame_over_the_inline_size_goes_through_a_file() {
        let (a, b) = pair().unwrap();
        let (a, b) = (Channel::new(a), Channel::new(b));
        let catalog: Vec<Value> = (0..20_000).map(|i| json!({ "id": i, "name": format!("package {i}") })).collect();
        let big = json!({ "id": 1, "ok": catalog });
        a.send(&big, true).unwrap();
        a.send(&json!({ "id": 2, "ok": null }), true).unwrap();
        assert_eq!(b.receive(true).unwrap(), Received::Frame(big));
        assert_eq!(b.receive(true).unwrap(), Received::Frame(json!({ "id": 2, "ok": null })));
    }

    #[test]
    fn a_small_frame_carries_an_fd_across() {
        let (a, b) = pair().unwrap();
        let (a, b) = (Channel::new(a), Channel::new(b));
        let (ours, theirs) = socket_pair(SocketType::STREAM).unwrap();
        a.send_with_fd(&json!({ "id": 1, "ok": { "role": "desktop" } }), theirs.as_fd(), true).unwrap();
        drop(theirs);
        let (frame, fd) = b.receive_with_fd(true).unwrap();
        assert_eq!(frame, Received::Frame(json!({ "id": 1, "ok": { "role": "desktop" } })));
        let fd = fd.expect("the fd came with the frame");
        assert!(rustix::io::fcntl_getfd(&fd).unwrap().contains(rustix::io::FdFlags::CLOEXEC));
        rustix::io::write(&fd, b"hi").unwrap();
        let mut got = [0u8; 2];
        rustix::io::read(&ours, &mut got).unwrap();
        assert_eq!(&got, b"hi");
        a.send(&json!({ "id": 2, "ok": null }), true).unwrap();
        assert!(b.receive_with_fd(true).unwrap().1.is_none(), "a frame without an fd brings none");
    }

    #[test]
    fn a_frame_carries_several_fds_in_order() {
        let (a, b) = pair().unwrap();
        let (a, b) = (Channel::new(a), Channel::new(b));
        let ends: Vec<(OwnedFd, OwnedFd)> = (0..3).map(|_| socket_pair(SocketType::STREAM).unwrap()).collect();
        let theirs: Vec<BorrowedFd<'_>> = ends.iter().map(|(_, theirs)| theirs.as_fd()).collect();
        a.send_with_fds(&json!({ "id": 1, "ok": { "files": 3 } }), &theirs, true).unwrap();
        let (frame, fds) = b.receive_with_fds(true).unwrap();
        assert_eq!(frame, Received::Frame(json!({ "id": 1, "ok": { "files": 3 } })));
        assert_eq!(fds.len(), 3);
        for (i, (fd, (ours, _))) in fds.iter().zip(&ends).enumerate() {
            rustix::io::write(fd, &[i as u8]).unwrap();
            let mut got = [0u8; 1];
            rustix::io::read(ours, &mut got).unwrap();
            assert_eq!(got[0], i as u8, "fd {i} keeps its place");
        }
        let many: Vec<BorrowedFd<'_>> = (0..=Channel::FDS_MAX).map(|_| theirs[0]).collect();
        assert!(a.send_with_fds(&json!({ "id": 2 }), &many, true).is_err());
    }

    #[test]
    fn the_channel_preserves_nonblocking_packets_and_peer_close() {
        let (a, b) = pair().unwrap();
        assert!(rustix::io::fcntl_getfd(&a).unwrap().contains(rustix::io::FdFlags::CLOEXEC));
        assert!(rustix::io::fcntl_getfd(&b).unwrap().contains(rustix::io::FdFlags::CLOEXEC));
        rustix::net::sockopt::set_socket_send_buffer_size(&a, 1024).unwrap();
        let (a, b) = (Channel::new(a), Channel::new(b));
        assert_eq!(b.receive(false).unwrap(), Received::Nothing);

        let frame = json!({ "id": 42 });
        let packet = Channel::pack(&frame).unwrap();
        let offered = (0..1000).find(|_| !a.offer(&packet).unwrap()).expect("the channel fills up");
        assert!(offered > 0);
        for _ in 0..offered {
            assert_eq!(b.receive(false).unwrap(), Received::Frame(frame.clone()));
        }
        assert_eq!(b.receive(false).unwrap(), Received::Nothing);
        drop(b);
        assert!(a.offer(&packet).is_err());
        assert_eq!(a.receive(false).unwrap(), Received::Closed);
        #[cfg(target_vendor = "apple")]
        assert!(rustix::net::sockopt::socket_nosigpipe(&a).unwrap());
    }

    #[cfg(target_vendor = "apple")]
    #[test]
    fn a_malformed_stream_frame_does_not_keep_its_rights() {
        let (a, b) = pair().unwrap();
        let b = Channel::new(b);
        let (ours, theirs) = socket_pair(SocketType::STREAM).unwrap();
        let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(1))];
        let mut ancillary = SendAncillaryBuffer::new(&mut space);
        let rights = [theirs.as_fd()];
        assert!(ancillary.push(SendAncillaryMessage::ScmRights(&rights)));
        sendmsg(&a, &[IoSlice::new(b"x")], &mut ancillary, SendFlags::empty()).unwrap();
        drop(theirs);
        assert_eq!(b.receive(false).unwrap_err(), "a frame came without its marker");
        apple::nonblocking(&ours).unwrap();
        assert_eq!(rustix::io::read(&ours, &mut [0u8; 1]), Ok(0));
    }

    #[test]
    fn fds_become_the_keepers_tokens_or_are_closed() {
        let keeper: FdKeeper = Box::new(|fds| fds.iter().enumerate().map(|(i, _)| format!("token-{i}")).collect());
        let (_, theirs) = socket_pair(SocketType::STREAM).unwrap();
        let kept = handed(Some(&keeper), json!({ "name": "work", "fd": 0 }), vec![theirs]);
        assert_eq!(kept, json!({ "name": "work", "fd": 0, "fds": ["token-0"] }));
        let (ours, theirs) = socket_pair(SocketType::STREAM).unwrap();
        let dropped = handed(None, json!({ "name": "work", "fd": 0 }), vec![theirs]);
        assert_eq!(dropped, json!({ "name": "work", "fd": 0 }), "no keeper, no fds");
        let mut got = [0u8; 1];
        assert_eq!(rustix::io::read(&ours, &mut got).unwrap(), 0, "the fd was closed");
    }
}