tilo_render_protocol/
channel.rs1use 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#[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#[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
43pub struct Channel {
45 socket: OwnedFd,
46 closed: AtomicBool,
49}
50
51pub struct Received<T> {
53 pub message: T,
54 pub fds: Vec<OwnedFd>,
55}
56
57#[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 pub fn pair() -> io::Result<(Self, Self)> {
71 #[cfg(any(target_os = "linux", target_os = "android"))]
72 let flags = SocketFlags::CLOEXEC;
73 #[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 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 #[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 fn closed(&self) -> ChannelError {
119 self.closed.store(true, Ordering::Relaxed);
120 ChannelError::Closed
121 }
122
123 pub fn as_fd(&self) -> BorrowedFd<'_> {
125 self.socket.as_fd()
126 }
127
128 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 #[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 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 #[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 pub fn shut_down(&self) -> io::Result<()> {
234 rustix::net::shutdown(&self.socket, rustix::net::Shutdown::Both)?;
235 Ok(())
236 }
237
238 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}