Skip to main content

tilo_render_protocol/
broker.rs

1//! How an app gets its channel to its workspace's render service.
2//!
3//! The launcher connects the session's render broker
4//! (`$XDG_RUNTIME_DIR/tilo/services/render.sock`) on the app's behalf and
5//! writes [`handshake`] — the app and its workspace — before the sandboxed
6//! app holds the connection, then hands it in as `TILO_SVC_RENDER_FD`. The
7//! app asks on it for a channel ([`request_channel`]): one byte out, one
8//! byte and the channel's descriptor back. It asks again when a channel
9//! breaks (the service restarted), and once per window, so every window
10//! renders on a channel of its own.
11//!
12//! The broker, not the app, chose the workspace: the app can only ever reach
13//! the service of the workspace it was launched into.
14
15use 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
26/// The service name: the broker's socket is `services/render.sock`, and the
27/// app finds its connection in `TILO_SVC_RENDER_FD`.
28pub const SERVICE: &str = "render";
29
30/// The app's connection to the broker, as the launcher hands it in.
31pub const FD_ENV: &str = "TILO_SVC_RENDER_FD";
32
33/// For a process outside the sandbox (a developer's run, a measurement): the
34/// broker's socket to connect itself, writing its own handshake.
35pub const SOCKET_ENV: &str = "TILO_RENDER_SOCKET";
36
37/// Version of the handshake line.
38pub const PROTOCOL: u16 = 1;
39
40/// The request byte: one channel, please.
41const REQUEST: u8 = b'C';
42/// The answer byte with a channel.
43const GRANTED: u8 = b'K';
44/// The answer byte without one (no service for this workspace right now).
45const REFUSED: u8 = b'N';
46
47/// Longest handshake line the broker reads.
48pub const MAX_HANDSHAKE: usize = 4096;
49
50/// The line that names an app and its workspace on a new broker connection.
51pub 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
108/// Ask the broker on `broker` for a channel. Blocks until it answers.
109pub 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
145/// Wait for the next request on a broker connection. `Ok(false)` at end of
146/// stream.
147pub 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
162/// Answer a request with `channel`, or refuse it.
163pub 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}