Skip to main content

tilo_render_protocol/
channel.rs

1//! The control channel: one Unix socket per app connection, one message per
2//! packet, descriptors as `SCM_RIGHTS`.
3//!
4//! On Linux the socket is `SOCK_SEQPACKET`. macOS has no sequenced packets on
5//! Unix sockets; there it is `SOCK_DGRAM`, which on a connected Unix pair is
6//! just as reliable and ordered and keeps message boundaries. Its buffers are
7//! sized for the largest message, and a peer's close reads as a reset, which
8//! this end then answers as closed from then on.
9//!
10//! A packet longer than [`MAX_MESSAGE_BYTES`] or carrying more than
11//! [`MAX_MESSAGE_FDS`] descriptors is truncated by the kernel; the receiver
12//! sees the truncation flag and refuses the packet rather than read half a
13//! message. Received descriptors are close-on-exec.
14
15use std::io::{self, IoSlice, IoSliceMut};
16use std::mem::MaybeUninit;
17use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
18use std::sync::atomic::{AtomicBool, Ordering};
19
20use rustix::net::{
21    AddressFamily, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags,
22    SendAncillaryBuffer, SendAncillaryMessage, SendFlags, SocketFlags, SocketType,
23};
24use serde::Serialize;
25use serde::de::DeserializeOwned;
26
27use crate::control::{MAX_MESSAGE_BYTES, MAX_MESSAGE_FDS};
28use crate::{WireError, control};
29
30/// The socket type of a channel: see the module's documentation.
31#[cfg(any(target_os = "linux", target_os = "android"))]
32const SOCKET_TYPE: SocketType = SocketType::SEQPACKET;
33#[cfg(not(any(target_os = "linux", target_os = "android")))]
34const SOCKET_TYPE: SocketType = SocketType::DGRAM;
35
36/// A datagram socket refuses a message larger than its send buffer, and a send its peer has no
37/// room for instead of waiting: room for the largest message out, and for many of them in.
38#[cfg(not(any(target_os = "linux", target_os = "android")))]
39const SEND_BUFFER: usize = MAX_MESSAGE_BYTES * 2;
40#[cfg(not(any(target_os = "linux", target_os = "android")))]
41const RECV_BUFFER: usize = MAX_MESSAGE_BYTES * 64;
42
43/// One end of a control channel.
44pub struct Channel {
45    socket: OwnedFd,
46    /// The peer is gone. A datagram socket reports its peer's close once; every later
47    /// receive and send answers [`ChannelError::Closed`] from this.
48    closed: AtomicBool,
49}
50
51/// A message received, with the descriptors that came with it.
52pub struct Received<T> {
53    pub message: T,
54    pub fds: Vec<OwnedFd>,
55}
56
57/// Why a channel could not carry a message.
58#[derive(Debug, thiserror::Error)]
59pub enum ChannelError {
60    #[error("the peer closed the channel")]
61    Closed,
62    #[error(transparent)]
63    Io(#[from] io::Error),
64    #[error(transparent)]
65    Wire(#[from] WireError),
66}
67
68impl Channel {
69    /// Both ends of a new channel, close-on-exec.
70    pub fn pair() -> io::Result<(Self, Self)> {
71        #[cfg(any(target_os = "linux", target_os = "android"))]
72        let flags = SocketFlags::CLOEXEC;
73        // Set on each end below: macOS's `socketpair` takes no flags.
74        #[cfg(not(any(target_os = "linux", target_os = "android")))]
75        let flags = SocketFlags::empty();
76        let (a, b) = rustix::net::socketpair(AddressFamily::UNIX, SOCKET_TYPE, flags, None)?;
77        #[cfg(not(any(target_os = "linux", target_os = "android")))]
78        for end in [&a, &b] {
79            rustix::io::fcntl_setfd(end, rustix::io::FdFlags::CLOEXEC)?;
80        }
81        Ok((Self::new(a)?, Self::new(b)?))
82    }
83
84    /// Wrap a connected channel socket handed over by a broker.
85    pub fn from_socket(socket: OwnedFd) -> io::Result<Self> {
86        if rustix::net::sockopt::socket_type(&socket)? != SOCKET_TYPE {
87            return Err(io::Error::new(
88                io::ErrorKind::InvalidInput,
89                "a render channel must be a packet socket",
90            ));
91        }
92        Self::new(socket)
93    }
94
95    #[cfg_attr(
96        any(target_os = "linux", target_os = "android"),
97        allow(
98            clippy::unnecessary_wraps,
99            reason = "a socket's options are set, and can fail, on macOS"
100        )
101    )]
102    fn new(socket: OwnedFd) -> io::Result<Self> {
103        // A datagram end's buffers, and a send to a closed peer that answers an error rather
104        // than raising `SIGPIPE`.
105        #[cfg(not(any(target_os = "linux", target_os = "android")))]
106        {
107            rustix::net::sockopt::set_socket_send_buffer_size(&socket, SEND_BUFFER)?;
108            rustix::net::sockopt::set_socket_recv_buffer_size(&socket, RECV_BUFFER)?;
109            rustix::net::sockopt::set_socket_nosigpipe(&socket, true)?;
110        }
111        Ok(Self {
112            socket,
113            closed: AtomicBool::new(false),
114        })
115    }
116
117    /// The peer went: say so now and from now on.
118    fn closed(&self) -> ChannelError {
119        self.closed.store(true, Ordering::Relaxed);
120        ChannelError::Closed
121    }
122
123    /// The socket, to wait on.
124    pub fn as_fd(&self) -> BorrowedFd<'_> {
125        self.socket.as_fd()
126    }
127
128    /// Send `message` with `fds`.
129    pub fn send<T: Serialize>(
130        &self,
131        message: &T,
132        fds: &[BorrowedFd<'_>],
133    ) -> Result<(), ChannelError> {
134        if fds.len() > MAX_MESSAGE_FDS {
135            return Err(WireError::OverLimit("descriptors in one message").into());
136        }
137        if self.closed.load(Ordering::Relaxed) {
138            return Err(ChannelError::Closed);
139        }
140        #[cfg(any(target_os = "linux", target_os = "android"))]
141        let flags = SendFlags::NOSIGNAL;
142        // `SO_NOSIGPIPE`, set when the end was made, keeps the signal away.
143        #[cfg(not(any(target_os = "linux", target_os = "android")))]
144        let flags = SendFlags::empty();
145        let bytes = control::encode(message)?;
146        let mut space =
147            [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(MAX_MESSAGE_FDS))];
148        let mut control = SendAncillaryBuffer::new(&mut space);
149        if !fds.is_empty() && !control.push(SendAncillaryMessage::ScmRights(fds)) {
150            return Err(WireError::OverLimit("descriptors in one message").into());
151        }
152        let sent = loop {
153            match rustix::net::sendmsg(&self.socket, &[IoSlice::new(&bytes)], &mut control, flags) {
154                Err(rustix::io::Errno::INTR) => {}
155                Err(
156                    rustix::io::Errno::PIPE
157                    | rustix::io::Errno::CONNRESET
158                    | rustix::io::Errno::NOTCONN,
159                ) => {
160                    return Err(self.closed());
161                }
162                other => break other.map_err(io::Error::from)?,
163            }
164        };
165        if sent != bytes.len() {
166            return Err(WireError::Malformed("short send").into());
167        }
168        Ok(())
169    }
170
171    /// Receive one message, blocking unless the socket is non-blocking.
172    ///
173    /// # Errors
174    ///
175    /// [`ChannelError::Closed`] at end of stream; a truncated or malformed
176    /// packet, or a receive failure (`WouldBlock` on a non-blocking socket
177    /// with nothing to read).
178    pub fn recv<T: DeserializeOwned>(&self) -> Result<Received<T>, ChannelError> {
179        if self.closed.load(Ordering::Relaxed) {
180            return Err(ChannelError::Closed);
181        }
182        #[cfg(any(target_os = "linux", target_os = "android"))]
183        let flags = RecvFlags::CMSG_CLOEXEC;
184        // Marked close-on-exec below, once received: macOS has no flag for it.
185        #[cfg(not(any(target_os = "linux", target_os = "android")))]
186        let flags = RecvFlags::empty();
187        let mut buffer = vec![0_u8; MAX_MESSAGE_BYTES];
188        let mut space =
189            [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(MAX_MESSAGE_FDS))];
190        let mut control = RecvAncillaryBuffer::new(&mut space);
191        let received = loop {
192            match rustix::net::recvmsg(
193                &self.socket,
194                &mut [IoSliceMut::new(&mut buffer)],
195                &mut control,
196                flags,
197            ) {
198                Err(rustix::io::Errno::INTR) => {}
199                Err(rustix::io::Errno::CONNRESET | rustix::io::Errno::NOTCONN) => {
200                    return Err(self.closed());
201                }
202                other => break other.map_err(io::Error::from)?,
203            }
204        };
205        let mut fds = Vec::new();
206        for message in control.drain() {
207            if let RecvAncillaryMessage::ScmRights(rights) = message {
208                fds.extend(rights);
209            }
210        }
211        #[cfg(not(any(target_os = "linux", target_os = "android")))]
212        for fd in &fds {
213            rustix::io::fcntl_setfd(fd, rustix::io::FdFlags::CLOEXEC).map_err(io::Error::from)?;
214        }
215        if received.bytes == 0 && fds.is_empty() {
216            return Err(self.closed());
217        }
218        if received
219            .flags
220            .intersects(ReturnFlags::TRUNC | ReturnFlags::CTRUNC)
221        {
222            return Err(WireError::OverLimit("message truncated").into());
223        }
224        let bytes = buffer
225            .get(..received.bytes)
226            .ok_or(WireError::Malformed("receive length"))?;
227        let message = control::decode(bytes)?;
228        Ok(Received { message, fds })
229    }
230
231    /// End the channel in both directions: a receive waiting on it, on any
232    /// thread, returns [`ChannelError::Closed`], and so does every later one.
233    pub fn shut_down(&self) -> io::Result<()> {
234        rustix::net::shutdown(&self.socket, rustix::net::Shutdown::Both)?;
235        Ok(())
236    }
237
238    /// Make receives return `WouldBlock` instead of waiting.
239    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
240        let flags = rustix::fs::fcntl_getfl(&self.socket)?;
241        let flags = if nonblocking {
242            flags | rustix::fs::OFlags::NONBLOCK
243        } else {
244            flags.difference(rustix::fs::OFlags::NONBLOCK)
245        };
246        rustix::fs::fcntl_setfl(&self.socket, flags)?;
247        Ok(())
248    }
249}
250
251impl AsFd for Channel {
252    fn as_fd(&self) -> BorrowedFd<'_> {
253        self.socket.as_fd()
254    }
255}