tilo_render_protocol/
broker.rs1use std::io::{self, IoSlice, IoSliceMut, Write};
16use std::mem::MaybeUninit;
17use std::os::fd::BorrowedFd;
18
19use rustix::net::{
20 RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, SendAncillaryBuffer,
21 SendAncillaryMessage, SendFlags,
22};
23
24use crate::channel::Channel;
25
26pub const SERVICE: &str = "render";
29
30pub const FD_ENV: &str = "TILO_SVC_RENDER_FD";
32
33pub const SOCKET_ENV: &str = "TILO_RENDER_SOCKET";
36
37pub const PROTOCOL: u16 = 1;
39
40const REQUEST: u8 = b'C';
42const GRANTED: u8 = b'K';
44const REFUSED: u8 = b'N';
46
47pub const MAX_HANDSHAKE: usize = 4096;
49
50pub fn handshake(app_id: &str, workspace_id: Option<&str>) -> io::Result<Vec<u8>> {
52 #[derive(serde::Serialize)]
53 struct Line<'a> {
54 protocol: u16,
55 app_id: &'a str,
56 workspace_id: Option<&'a str>,
57 }
58 let mut line = postcard::to_allocvec(&Line {
59 protocol: PROTOCOL,
60 app_id,
61 workspace_id,
62 })
63 .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?;
64 if line.len() > MAX_HANDSHAKE.saturating_sub(4) {
65 return Err(io::Error::from(io::ErrorKind::InvalidInput));
66 }
67 let mut framed = u32::try_from(line.len())
68 .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?
69 .to_le_bytes()
70 .to_vec();
71 framed.append(&mut line);
72 Ok(framed)
73}
74
75#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
76pub struct Handshake {
77 pub protocol: u16,
78 pub app_id: String,
79 pub workspace_id: Option<String>,
80}
81
82pub fn read_handshake(stream: &mut impl io::Read) -> io::Result<Handshake> {
83 let mut length = [0_u8; 4];
84 stream.read_exact(&mut length)?;
85 let length = u32::from_le_bytes(length) as usize;
86 if length == 0 || length > MAX_HANDSHAKE {
87 return Err(io::Error::from(io::ErrorKind::InvalidData));
88 }
89 let mut line = vec![0_u8; length];
90 stream.read_exact(&mut line)?;
91 let handshake: Handshake =
92 postcard::from_bytes(&line).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?;
93 if handshake.protocol != PROTOCOL || handshake.app_id.is_empty() {
94 return Err(io::Error::from(io::ErrorKind::InvalidData));
95 }
96 Ok(handshake)
97}
98
99pub fn write_handshake(
100 stream: &mut impl Write,
101 app_id: &str,
102 workspace_id: Option<&str>,
103) -> io::Result<()> {
104 stream.write_all(&handshake(app_id, workspace_id)?)?;
105 stream.flush()
106}
107
108pub fn request_channel(broker: BorrowedFd<'_>) -> io::Result<Channel> {
110 let sent = rustix::net::send(broker, &[REQUEST], SendFlags::NOSIGNAL)?;
111 if sent != 1 {
112 return Err(io::Error::from(io::ErrorKind::WriteZero));
113 }
114 let mut answer = [0_u8; 1];
115 let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(1))];
116 let mut control = RecvAncillaryBuffer::new(&mut space);
117 let received = loop {
118 match rustix::net::recvmsg(
119 broker,
120 &mut [IoSliceMut::new(&mut answer)],
121 &mut control,
122 RecvFlags::CMSG_CLOEXEC,
123 ) {
124 Err(rustix::io::Errno::INTR) => {}
125 other => break other?,
126 }
127 };
128 let mut fds = Vec::new();
129 for message in control.drain() {
130 if let RecvAncillaryMessage::ScmRights(rights) = message {
131 fds.extend(rights);
132 }
133 }
134 match (received.bytes, answer, fds.pop()) {
135 (1, [GRANTED], Some(fd)) => Channel::from_socket(fd),
136 (1, [REFUSED], _) => Err(io::Error::new(
137 io::ErrorKind::ConnectionRefused,
138 "no render service for this workspace",
139 )),
140 (0, _, _) => Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
141 _ => Err(io::Error::from(io::ErrorKind::InvalidData)),
142 }
143}
144
145pub fn read_request(broker: BorrowedFd<'_>) -> io::Result<bool> {
148 let mut byte = [0_u8; 1];
149 let read = loop {
150 match rustix::io::read(broker, &mut byte) {
151 Err(rustix::io::Errno::INTR) => {}
152 other => break other?,
153 }
154 };
155 match (read, byte) {
156 (0, _) => Ok(false),
157 (1, [REQUEST]) => Ok(true),
158 _ => Err(io::Error::from(io::ErrorKind::InvalidData)),
159 }
160}
161
162pub fn answer(broker: BorrowedFd<'_>, channel: Option<&Channel>) -> io::Result<()> {
164 let fds: Vec<BorrowedFd<'_>> = channel.map(Channel::as_fd).into_iter().collect();
165 let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(1))];
166 let mut control = SendAncillaryBuffer::new(&mut space);
167 let byte = if fds.is_empty() {
168 REFUSED
169 } else {
170 if !control.push(SendAncillaryMessage::ScmRights(&fds)) {
171 return Err(io::Error::from(io::ErrorKind::InvalidInput));
172 }
173 GRANTED
174 };
175 rustix::net::sendmsg(
176 broker,
177 &[IoSlice::new(&[byte])],
178 &mut control,
179 SendFlags::NOSIGNAL,
180 )?;
181 Ok(())
182}