1use std::io::{IoSlice, IoSliceMut};
2use std::mem::MaybeUninit;
3use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
4use std::os::unix::fs::FileExt;
5
6use rustix::io::Errno;
7use rustix::net::{
8 AddressFamily, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, SendAncillaryMessage, SendFlags, SocketFlags,
9 SocketType, recvmsg, sendmsg, socketpair,
10};
11use serde_json::{Value, json};
12
13pub const API_LEVEL: u32 = parse_level(include_str!("../acde-api/api-level"));
14pub const MIN_API_LEVEL: u32 = parse_level(include_str!("../acde-api/min-api-level"));
15
16pub fn speaks(level: u64) -> bool {
17 (u64::from(MIN_API_LEVEL)..=u64::from(API_LEVEL)).contains(&level)
18}
19
20pub fn levels() -> String {
21 if MIN_API_LEVEL == API_LEVEL { format!("level {API_LEVEL}") } else { format!("levels {MIN_API_LEVEL} to {API_LEVEL}") }
22}
23
24const fn parse_level(text: &str) -> u32 {
25 let bytes = text.as_bytes();
26 let mut level = 0;
27 let mut i = 0;
28 while i < bytes.len() {
29 if bytes[i].is_ascii_digit() {
30 level = level * 10 + (bytes[i] - b'0') as u32;
31 }
32 i += 1;
33 }
34 level
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Refusal {
39 pub status: u16,
40 pub code: &'static str,
41 pub message: String,
42 pub retry_after_ms: Option<u64>,
43}
44
45impl Refusal {
46 pub fn bad_request(message: impl Into<String>) -> Self {
47 Self { status: 400, code: "bad_request", message: message.into(), retry_after_ms: None }
48 }
49
50 pub fn forbidden(message: impl Into<String>) -> Self {
51 Self { status: 403, code: "forbidden", message: message.into(), retry_after_ms: None }
52 }
53
54 pub fn not_found(message: impl Into<String>) -> Self {
55 Self { status: 404, code: "not_found", message: message.into(), retry_after_ms: None }
56 }
57
58 pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
59 Self { status: 409, code, message: message.into(), retry_after_ms: None }
60 }
61
62 pub fn unsupported(service: &str, method: &str) -> Self {
63 Self { status: 501, code: "unsupported", message: format!("{service}.{method} is not supported by the session's manager yet"), retry_after_ms: None }
64 }
65
66 pub fn unavailable(message: impl Into<String>) -> Self {
67 Self { status: 503, code: "unavailable", message: message.into(), retry_after_ms: None }
68 }
69
70 pub fn to_json(&self) -> Value {
71 let mut refusal = json!({ "status": self.status, "code": self.code, "message": self.message });
72 if let Some(ms) = self.retry_after_ms {
73 refusal["retryAfterMs"] = json!(ms);
74 refusal["retryAfter"] = json!(ms.div_ceil(1000).max(1));
75 }
76 refusal
77 }
78}
79
80#[derive(Debug, PartialEq)]
81pub enum Frame {
82 Hello { api: u32, pid: u32, dev_key: Option<String> },
83 Call { id: u64, service: String, method: String, args: Vec<Value> },
84 Answer { id: u64, result: Result<Value, Value> },
85 Ready { provides: serde_json::Map<String, Value> },
86 Invoke { function: u64, args: Value },
87 Release { function: u64 },
88 DevResponse { id: u64, ok: bool, payload: String },
89 DevEvent { text: String },
90 DevTools { port: u64 },
91 DevInject { event: Value },
92 DevWindow { change: Value },
93 Panels { user_only: Vec<[i32; 4]> },
94}
95
96impl Frame {
97 pub fn parse(value: Value) -> Result<Self, String> {
98 if let Some(hello) = value.get("hello") {
99 let api = hello.get("api").and_then(Value::as_u64).ok_or("hello needs api")?;
100 let pid = hello.get("pid").and_then(Value::as_u64).unwrap_or(0);
101 let dev_key = hello.get("dev_key").and_then(Value::as_str).map(String::from);
102 return Ok(Frame::Hello { api: api as u32, pid: pid as u32, dev_key });
103 }
104 if let Some(ready) = value.get("ready") {
105 let provides = ready.get("provides").and_then(Value::as_object).cloned().ok_or("ready needs provides")?;
106 return Ok(Frame::Ready { provides });
107 }
108 let function = |frame: &Value| frame.get("fn").and_then(Value::as_u64).ok_or("needs a numeric fn");
109 if let Some(invoke) = value.get("invoke") {
110 return Ok(Frame::Invoke { function: function(invoke)?, args: invoke.get("args").cloned().unwrap_or(Value::Array(Vec::new())) });
111 }
112 if let Some(release) = value.get("release") {
113 return Ok(Frame::Release { function: function(release)? });
114 }
115 if let Some(response) = value.get("devresponse") {
116 let id = response.get("id").and_then(Value::as_u64).ok_or("devresponse needs a numeric id")?;
117 let ok = response.get("ok").and_then(Value::as_bool).unwrap_or(false);
118 let payload = response.get("payload").and_then(Value::as_str).unwrap_or_default().to_string();
119 return Ok(Frame::DevResponse { id, ok, payload });
120 }
121 if let Some(text) = value.get("devevent") {
122 return Ok(Frame::DevEvent { text: text.as_str().ok_or("devevent is JSON text")?.to_string() });
123 }
124 if let Some(change) = value.get("devwindow") {
125 return Ok(Frame::DevWindow { change: change.clone() });
126 }
127 if let Some(event) = value.get("devinject") {
128 return Ok(Frame::DevInject { event: event.clone() });
129 }
130 if let Some(panels) = value.get("panels") {
131 let rects = panels.get("user_only").and_then(Value::as_array).ok_or("panels needs user_only")?;
132 let rect = |r: &Value| -> Option<[i32; 4]> {
133 let r = r.as_array().filter(|r| r.len() == 4)?;
134 let n = |i: usize| r[i].as_i64().and_then(|v| i32::try_from(v).ok());
135 Some([n(0)?, n(1)?, n(2)?, n(3)?])
136 };
137 let user_only = rects.iter().map(rect).collect::<Option<Vec<_>>>().ok_or("panels: each rect is [x, y, width, height]")?;
138 return Ok(Frame::Panels { user_only });
139 }
140 if let Some(devtools) = value.get("devtools") {
141 return Ok(Frame::DevTools { port: devtools.get("port").and_then(Value::as_u64).ok_or("devtools needs a port")? });
142 }
143 let id = value.get("id").and_then(Value::as_u64).ok_or("a call needs a numeric id")?;
144 if value.get("service").is_none() {
145 if let Some(error) = value.get("error") {
146 return Ok(Frame::Answer { id, result: Err(error.clone()) });
147 }
148 if let Some(ok) = value.get("ok") {
149 return Ok(Frame::Answer { id, result: Ok(ok.clone()) });
150 }
151 }
152 let text = |key: &str| value.get(key).and_then(Value::as_str).map(String::from).ok_or_else(|| format!("call {id} needs {key}"));
153 let args = match value.get("args") {
154 None | Some(Value::Null) => Vec::new(),
155 Some(Value::Array(args)) => args.clone(),
156 Some(_) => return Err(format!("call {id}: args is an array")),
157 };
158 Ok(Frame::Call { id, service: text("service")?, method: text("method")?, args })
159 }
160}
161
162pub fn answer(id: u64, result: Result<Value, Refusal>) -> Value {
163 match result {
164 Ok(ok) => json!({ "id": id, "ok": ok }),
165 Err(refusal) => json!({ "id": id, "error": refusal.to_json() }),
166 }
167}
168
169pub fn event(event: Value) -> Value {
170 json!({ "event": event })
171}
172
173pub fn pair() -> Result<(OwnedFd, OwnedFd), String> {
174 socketpair(AddressFamily::UNIX, SocketType::SEQPACKET, SocketFlags::CLOEXEC, None).map_err(|e| format!("the manager's channel: {e}"))
175}
176
177pub struct Packet {
178 bytes: Vec<u8>,
179 fds: Vec<OwnedFd>,
180 size: usize,
181}
182
183impl Packet {
184 pub fn size(&self) -> usize {
185 self.size
186 }
187}
188
189#[derive(Debug, PartialEq, Eq)]
190pub enum Received {
191 Frame(Value),
192 Nothing,
193 Closed,
194}
195
196pub struct Channel {
197 fd: OwnedFd,
198}
199
200impl Channel {
201 pub const FRAME_MAX: usize = 256 * 1024;
202 pub const FDS_MAX: usize = 64;
203 pub const BIG_MAX: usize = 64 << 20;
204 const INLINE_MAX: usize = 128 * 1024;
205 const BIG: &str = "@memfd";
206
207 pub fn new(fd: OwnedFd) -> Self {
208 Self { fd }
209 }
210
211 pub fn try_clone(&self) -> Result<Self, String> {
212 self.fd.try_clone().map(Self::new).map_err(|e| format!("the manager's channel: {e}"))
213 }
214
215 pub fn send(&self, frame: &Value, wait: bool) -> Result<(), String> {
216 let packet = Self::pack(frame)?;
217 self.send_bytes(&packet.bytes, &borrowed(&packet.fds), wait)
218 }
219
220 pub fn pack(frame: &Value) -> Result<Packet, String> {
221 let bytes = serde_json::to_vec(frame).map_err(|e| e.to_string())?;
222 if bytes.len() <= Self::INLINE_MAX {
223 return Ok(Packet { size: bytes.len(), bytes, fds: Vec::new() });
224 }
225 if bytes.len() > Self::BIG_MAX {
226 return Err(format!("a frame of {} bytes is over {}", bytes.len(), Self::BIG_MAX));
227 }
228 let memfd = rustix::fs::memfd_create("acde-frame", rustix::fs::MemfdFlags::CLOEXEC).map_err(|e| format!("a big frame: {e}"))?;
229 let file = std::fs::File::from(memfd);
230 file.write_all_at(&bytes, 0).map_err(|e| format!("a big frame: {e}"))?;
231 let head = serde_json::to_vec(&json!({ Self::BIG: bytes.len() })).map_err(|e| e.to_string())?;
232 Ok(Packet { bytes: head, fds: vec![OwnedFd::from(file)], size: bytes.len() })
233 }
234
235 pub fn pack_with_fd(frame: &Value, fd: OwnedFd) -> Result<Packet, String> {
236 Self::pack_with_fds(frame, vec![fd])
237 }
238
239 pub fn pack_with_fds(frame: &Value, fds: Vec<OwnedFd>) -> Result<Packet, String> {
240 let bytes = Self::inline_with_fds(frame, fds.len())?;
241 Ok(Packet { size: bytes.len(), bytes, fds })
242 }
243
244 fn inline_with_fds(frame: &Value, fds: usize) -> Result<Vec<u8>, String> {
245 if fds > Self::FDS_MAX {
246 return Err(format!("a frame carries at most {} fds, not {fds}", Self::FDS_MAX));
247 }
248 let bytes = serde_json::to_vec(frame).map_err(|e| e.to_string())?;
249 if bytes.len() > Self::INLINE_MAX {
250 return Err(format!("a frame with fds fits inline ({} bytes is over {})", bytes.len(), Self::INLINE_MAX));
251 }
252 Ok(bytes)
253 }
254
255 pub fn offer(&self, packet: &Packet) -> Result<bool, String> {
256 match self.send_raw(&packet.bytes, &borrowed(&packet.fds), false) {
257 Ok(()) => Ok(true),
258 Err(Errno::AGAIN) => Ok(false),
259 Err(e) => Err(e.to_string()),
260 }
261 }
262
263 pub fn send_with_fd(&self, frame: &Value, fd: BorrowedFd<'_>, wait: bool) -> Result<(), String> {
264 self.send_with_fds(frame, &[fd], wait)
265 }
266
267 pub fn send_with_fds(&self, frame: &Value, fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), String> {
268 let bytes = Self::inline_with_fds(frame, fds.len())?;
269 self.send_bytes(&bytes, fds, wait)
270 }
271
272 fn send_bytes(&self, bytes: &[u8], fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), String> {
273 self.send_raw(bytes, fds, wait).map_err(|e| e.to_string())
274 }
275
276 fn send_raw(&self, bytes: &[u8], fds: &[BorrowedFd<'_>], wait: bool) -> Result<(), Errno> {
277 let flags = if wait { SendFlags::NOSIGNAL } else { SendFlags::NOSIGNAL | SendFlags::DONTWAIT };
278 let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(Channel::FDS_MAX))];
279 let mut ancillary = SendAncillaryBuffer::new(&mut space);
280 if !fds.is_empty() && !ancillary.push(SendAncillaryMessage::ScmRights(fds)) {
281 return Err(Errno::INVAL);
282 }
283 loop {
284 match sendmsg(&self.fd, &[IoSlice::new(bytes)], &mut ancillary, flags) {
285 Ok(_) => return Ok(()),
286 Err(Errno::INTR) => continue,
287 Err(e) => return Err(e),
288 }
289 }
290 }
291
292 fn unpack(frame: Value, mut fds: Vec<OwnedFd>) -> Result<(Value, Vec<OwnedFd>), String> {
293 let Some(length) = frame.get(Self::BIG).and_then(Value::as_u64).filter(|_| frame.as_object().is_some_and(|o| o.len() == 1)) else {
294 return Ok((frame, fds));
295 };
296 let fd = (fds.len() == 1).then(|| fds.remove(0));
297 let length =
298 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))?;
299 let file = std::fs::File::from(fd.ok_or("a big frame came without its memfd")?);
300 let mut bytes = vec![0u8; length];
301 file.read_exact_at(&mut bytes, 0).map_err(|e| format!("a big frame: {e}"))?;
302 serde_json::from_slice(&bytes).map(|frame| (frame, Vec::new())).map_err(|e| format!("not a JSON frame: {e}"))
303 }
304
305 pub fn receive(&self, wait: bool) -> Result<Received, String> {
306 self.receive_with_fd(wait).map(|(received, _)| received)
307 }
308
309 pub fn receive_with_fd(&self, wait: bool) -> Result<(Received, Option<OwnedFd>), String> {
310 self.receive_with_fds(wait).map(|(received, fds)| (received, fds.into_iter().next()))
311 }
312
313 pub fn receive_with_fds(&self, wait: bool) -> Result<(Received, Vec<OwnedFd>), String> {
314 let mut buf = vec![0u8; Self::FRAME_MAX];
315 let flags = if wait { RecvFlags::CMSG_CLOEXEC } else { RecvFlags::CMSG_CLOEXEC | RecvFlags::DONTWAIT };
316 loop {
317 let mut space = [MaybeUninit::<u8>::uninit(); rustix::cmsg_space!(ScmRights(Channel::FDS_MAX))];
318 let mut ancillary = RecvAncillaryBuffer::new(&mut space);
319 let got = recvmsg(&self.fd, &mut [IoSliceMut::new(&mut buf)], &mut ancillary, flags);
320 let fds: Vec<OwnedFd> = ancillary
321 .drain()
322 .flat_map(|message| match message {
323 RecvAncillaryMessage::ScmRights(fds) => fds.collect(),
324 _ => Vec::new(),
325 })
326 .collect();
327 return match got {
328 Ok(msg) if msg.bytes == 0 => Ok((Received::Closed, Vec::new())),
329 Ok(msg) if msg.flags.contains(ReturnFlags::CTRUNC) => Err(format!("a frame came with more than {} fds", Self::FDS_MAX)),
330 Ok(msg) if msg.flags.contains(ReturnFlags::TRUNC) => Err(format!("a frame over {} bytes came inline", Self::FRAME_MAX)),
331 Ok(msg) => serde_json::from_slice(&buf[..msg.bytes])
332 .map_err(|e| format!("not a JSON frame: {e}"))
333 .and_then(|frame| Self::unpack(frame, fds))
334 .map(|(frame, fds)| (Received::Frame(frame), fds)),
335 Err(Errno::INTR) => continue,
336 Err(Errno::AGAIN) => Ok((Received::Nothing, Vec::new())),
337 Err(Errno::CONNRESET) => Ok((Received::Closed, Vec::new())),
338 Err(e) => Err(e.to_string()),
339 };
340 }
341 }
342}
343
344impl AsFd for Channel {
345 fn as_fd(&self) -> BorrowedFd<'_> {
346 self.fd.as_fd()
347 }
348}
349
350pub type FdKeeper = Box<dyn Fn(Vec<OwnedFd>) -> Vec<String> + Send + Sync>;
351
352pub fn handed(keeper: Option<&FdKeeper>, mut value: Value, fds: Vec<OwnedFd>) -> Value {
353 if let (false, Some(keeper), Some(object)) = (fds.is_empty(), keeper, value.as_object_mut()) {
354 object.insert("fds".into(), json!(keeper(fds)));
355 }
356 value
357}
358
359fn borrowed(fds: &[OwnedFd]) -> Vec<BorrowedFd<'_>> {
360 fds.iter().map(AsFd::as_fd).collect()
361}
362
363pub fn base64(bytes: &[u8]) -> String {
364 const DIGITS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
365 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
366 for chunk in bytes.chunks(3) {
367 let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
368 for i in 0..4 {
369 out.push(if i <= chunk.len() { DIGITS[(n >> (18 - 6 * i) & 63) as usize] as char } else { '=' });
370 }
371 }
372 out
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn base64_pads_like_rfc_4648() {
381 assert_eq!(base64(b""), "");
382 assert_eq!(base64(b"f"), "Zg==");
383 assert_eq!(base64(b"fo"), "Zm8=");
384 assert_eq!(base64(b"foo"), "Zm9v");
385 assert_eq!(base64(b"foobar"), "Zm9vYmFy");
386 }
387
388 #[test]
389 fn a_frame_over_the_inline_size_goes_through_a_memfd() {
390 let (a, b) = pair().unwrap();
391 let (a, b) = (Channel::new(a), Channel::new(b));
392 let catalog: Vec<Value> = (0..20_000).map(|i| json!({ "id": i, "name": format!("package {i}") })).collect();
393 let big = json!({ "id": 1, "ok": catalog });
394 a.send(&big, true).unwrap();
395 a.send(&json!({ "id": 2, "ok": null }), true).unwrap();
396 assert_eq!(b.receive(true).unwrap(), Received::Frame(big));
397 assert_eq!(b.receive(true).unwrap(), Received::Frame(json!({ "id": 2, "ok": null })));
398 }
399
400 #[test]
401 fn a_small_frame_carries_an_fd_across() {
402 let (a, b) = pair().unwrap();
403 let (a, b) = (Channel::new(a), Channel::new(b));
404 let (ours, theirs) = rustix::net::socketpair(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::CLOEXEC, None).unwrap();
405 a.send_with_fd(&json!({ "id": 1, "ok": { "role": "desktop" } }), theirs.as_fd(), true).unwrap();
406 drop(theirs);
407 let (frame, fd) = b.receive_with_fd(true).unwrap();
408 assert_eq!(frame, Received::Frame(json!({ "id": 1, "ok": { "role": "desktop" } })));
409 let fd = fd.expect("the fd came with the frame");
410 rustix::io::write(&fd, b"hi").unwrap();
411 let mut got = [0u8; 2];
412 rustix::io::read(&ours, &mut got).unwrap();
413 assert_eq!(&got, b"hi");
414 a.send(&json!({ "id": 2, "ok": null }), true).unwrap();
415 assert!(b.receive_with_fd(true).unwrap().1.is_none(), "a frame without an fd brings none");
416 }
417
418 #[test]
419 fn a_frame_carries_several_fds_in_order() {
420 let (a, b) = pair().unwrap();
421 let (a, b) = (Channel::new(a), Channel::new(b));
422 let ends: Vec<(OwnedFd, OwnedFd)> =
423 (0..3).map(|_| rustix::net::socketpair(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::CLOEXEC, None).unwrap()).collect();
424 let theirs: Vec<BorrowedFd<'_>> = ends.iter().map(|(_, theirs)| theirs.as_fd()).collect();
425 a.send_with_fds(&json!({ "id": 1, "ok": { "files": 3 } }), &theirs, true).unwrap();
426 let (frame, fds) = b.receive_with_fds(true).unwrap();
427 assert_eq!(frame, Received::Frame(json!({ "id": 1, "ok": { "files": 3 } })));
428 assert_eq!(fds.len(), 3);
429 for (i, (fd, (ours, _))) in fds.iter().zip(&ends).enumerate() {
430 rustix::io::write(fd, &[i as u8]).unwrap();
431 let mut got = [0u8; 1];
432 rustix::io::read(ours, &mut got).unwrap();
433 assert_eq!(got[0], i as u8, "fd {i} keeps its place");
434 }
435 let many: Vec<BorrowedFd<'_>> = (0..=Channel::FDS_MAX).map(|_| theirs[0]).collect();
436 assert!(a.send_with_fds(&json!({ "id": 2 }), &many, true).is_err());
437 }
438
439 #[test]
440 fn fds_become_the_keepers_tokens_or_are_closed() {
441 let keeper: FdKeeper = Box::new(|fds| fds.iter().enumerate().map(|(i, _)| format!("token-{i}")).collect());
442 let (_, theirs) = rustix::net::socketpair(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::CLOEXEC, None).unwrap();
443 let kept = handed(Some(&keeper), json!({ "name": "work", "fd": 0 }), vec![theirs]);
444 assert_eq!(kept, json!({ "name": "work", "fd": 0, "fds": ["token-0"] }));
445 let (ours, theirs) = rustix::net::socketpair(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::CLOEXEC, None).unwrap();
446 let dropped = handed(None, json!({ "name": "work", "fd": 0 }), vec![theirs]);
447 assert_eq!(dropped, json!({ "name": "work", "fd": 0 }), "no keeper, no fds");
448 let mut got = [0u8; 1];
449 assert_eq!(rustix::io::read(&ours, &mut got).unwrap(), 0, "the fd was closed");
450 }
451}