1use std::io::{self, Read, Write};
2
3use serde::{Deserialize, Serialize};
4
5pub const PROTOCOL_VERSION: u32 = 1;
8
9pub const CAP_NOTIFY: &str = "notify";
14pub const CAP_XDG_OPEN: &str = "xdg_open";
15pub const CAP_CLIPBOARD: &str = "clipboard";
16pub const CAP_HOST_EXEC: &str = "host_exec";
17pub const CAP_HOST_EXEC_STREAM: &str = "host_exec_stream";
22pub const CAP_HOST_EXEC_FDS: &str = "host_exec_fds";
27
28pub const ALL_CAPABILITIES: &[&str] = &[
30 CAP_NOTIFY,
31 CAP_XDG_OPEN,
32 CAP_CLIPBOARD,
33 CAP_HOST_EXEC,
34 CAP_HOST_EXEC_STREAM,
35 CAP_HOST_EXEC_FDS,
36];
37
38pub const INTERCEPTORS: &[(&str, &str)] = &[
44 ("notify-send", CAP_NOTIFY),
45 ("xdg-open", CAP_XDG_OPEN),
46 ("podbox-clipboard", CAP_CLIPBOARD),
47 ("host-exec", CAP_HOST_EXEC),
48];
49
50#[derive(Debug, Serialize, Deserialize)]
52#[serde(tag = "type", rename_all = "snake_case")]
53pub enum GuestMessage {
54 Hello {
55 protocol_version: u32,
56 guest_version: String,
57 container: String,
58 capabilities: Vec<String>,
59 },
60 Notify {
61 summary: String,
62 body: String,
63 urgency: String,
64 #[serde(default)]
65 actions: Vec<NotifyAction>,
66 #[serde(default)]
67 app_name: String,
68 },
69 XdgOpen {
70 uri: String,
71 },
72 ClipboardSet {
73 text: String,
74 },
75 ClipboardGet,
76 HostExec {
77 cmd: String,
78 args: Vec<String>,
79 },
80 HostExecV2 {
95 cmd: String,
96 args: Vec<String>,
97 #[serde(default)]
100 env: Vec<(String, String)>,
101 #[serde(default)]
102 cwd: Option<String>,
103 #[serde(default)]
104 tty: bool,
105 },
106 HostExecSignal {
111 sig: i32,
112 },
113 RegisterSession,
116 Busy,
118 IdleTimeout,
120 Info {
122 guest_version: String,
123 protocol_version: u32,
124 },
125}
126
127#[derive(Debug, Serialize, Deserialize, Clone)]
128pub struct NotifyAction {
129 pub key: String,
130 pub label: String,
131}
132
133#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
135#[serde(rename_all = "snake_case")]
136pub enum ExecStream {
137 Stdout,
138 Stderr,
139}
140
141#[derive(Debug, Serialize, Deserialize)]
143#[serde(tag = "type", rename_all = "snake_case")]
144pub enum HostMessage {
145 HelloAck {
146 accepted: Vec<String>,
147 rejected: Vec<String>,
148 #[serde(default)]
149 idle_timeout_secs: u64,
150 #[serde(default)]
152 host_exec_shims: Vec<String>,
153 },
154 ClipboardData {
155 text: String,
156 },
157 HostExecStdout {
158 data: String,
159 },
160 HostExecStderr {
161 data: String,
162 },
163 HostExecOutput {
169 stream: ExecStream,
170 data: Vec<u8>,
171 },
172 HostExecDone {
173 exit_code: i32,
174 #[serde(default)]
178 signal: Option<i32>,
179 },
180 NotifyActionResult {
181 notification_id: u32,
182 action_key: String,
183 },
184 Ping,
185 Shutdown,
186 CheckIdle,
189 Error {
192 reason: String,
193 #[serde(default)]
196 code: Option<String>,
197 },
198 GetInfo,
200}
201
202pub fn write_frame<W: Write>(w: &mut W, msg: &impl Serialize) -> io::Result<()> {
204 let json = serde_json::to_vec(msg)?;
205 let len = u32::try_from(json.len())
206 .expect("frame payload exceeds 4 GiB")
207 .to_be_bytes();
208 w.write_all(&len)?;
209 w.write_all(&json)?;
210 w.flush()?;
211 Ok(())
212}
213
214const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
216
217pub const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;
223
224pub fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<Vec<u8>>> {
226 let mut len_buf = [0u8; 4];
227 match r.read_exact(&mut len_buf) {
228 Ok(()) => {}
229 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
230 Err(e) => return Err(e),
231 }
232 let len = u32::from_be_bytes(len_buf) as usize;
233 if len > MAX_FRAME_SIZE {
234 return Err(io::Error::new(
235 io::ErrorKind::InvalidData,
236 format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
237 ));
238 }
239 let mut buf = vec![0u8; len];
240 r.read_exact(&mut buf)?;
241 Ok(Some(buf))
242}
243
244#[derive(Debug, Default)]
252pub struct FrameReader {
253 prefix: [u8; 4],
254 prefix_filled: usize,
255 body: Vec<u8>,
256 body_filled: usize,
257 body_len: Option<usize>,
258 started: Option<std::time::Instant>,
260}
261
262#[derive(Debug, PartialEq, Eq)]
264pub enum FrameRead {
265 Frame(Vec<u8>),
267 Eof,
269}
270
271impl FrameReader {
272 pub fn new() -> Self {
273 Self::default()
274 }
275
276 pub fn in_progress(&self) -> bool {
278 self.started.is_some()
279 }
280
281 pub fn stalled_for(&self) -> Option<std::time::Duration> {
283 self.started.map(|t| t.elapsed())
284 }
285
286 pub fn read<R: Read>(&mut self, r: &mut R) -> io::Result<FrameRead> {
289 while self.prefix_filled < 4 {
290 let n = r.read(&mut self.prefix[self.prefix_filled..])?;
291 if n == 0 {
292 return if self.prefix_filled == 0 {
293 Ok(FrameRead::Eof)
294 } else {
295 Err(io::Error::from(io::ErrorKind::UnexpectedEof))
296 };
297 }
298 self.started.get_or_insert_with(std::time::Instant::now);
299 self.prefix_filled += n;
300 }
301 let len = match self.body_len {
302 Some(len) => len,
303 None => {
304 let len = u32::from_be_bytes(self.prefix) as usize;
305 if len > MAX_FRAME_SIZE {
306 return Err(io::Error::new(
307 io::ErrorKind::InvalidData,
308 format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
309 ));
310 }
311 self.body = vec![0u8; len];
312 self.body_len = Some(len);
313 len
314 }
315 };
316 while self.body_filled < len {
317 let n = r.read(&mut self.body[self.body_filled..])?;
318 if n == 0 {
319 return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
320 }
321 self.body_filled += n;
322 }
323 let frame = std::mem::take(&mut self.body);
324 *self = Self::default();
325 Ok(FrameRead::Frame(frame))
326 }
327}
328
329#[cfg(unix)]
331pub mod sysutil;
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 #[test]
338 fn hello_serializes_with_type_tag() {
339 let msg = GuestMessage::Hello {
340 protocol_version: 1,
341 guest_version: "0.2.0".into(),
342 container: "myenv".into(),
343 capabilities: vec!["notify".into()],
344 };
345 let json = serde_json::to_string(&msg).unwrap();
346 assert!(json.contains("\"type\":\"hello\""));
347 }
348
349 #[test]
350 fn frame_length_prefix_matches_payload() {
351 let msg = GuestMessage::ClipboardGet;
352 let mut buf = Vec::new();
353 write_frame(&mut buf, &msg).unwrap();
354 let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
355 assert_eq!(len, buf[4..].len());
356 }
357
358 #[test]
359 fn interceptors_cover_known_binaries_and_capabilities() {
360 use std::collections::HashSet;
361 let binaries: HashSet<&str> = INTERCEPTORS.iter().map(|(bin, _)| *bin).collect();
362 assert_eq!(binaries.len(), INTERCEPTORS.len(), "duplicate binary");
363 for (_, cap) in INTERCEPTORS {
364 assert!(ALL_CAPABILITIES.contains(cap), "unknown capability {cap}");
365 }
366 }
367
368 #[test]
369 fn roundtrip_notify_message() {
370 let msg = GuestMessage::Notify {
371 summary: "hello".into(),
372 body: "world".into(),
373 urgency: "normal".into(),
374 actions: vec![],
375 app_name: String::new(),
376 };
377 let mut buf = Vec::new();
378 write_frame(&mut buf, &msg).unwrap();
379
380 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
381 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
382 match decoded {
383 GuestMessage::Notify {
384 summary,
385 body,
386 urgency,
387 actions,
388 app_name: _,
389 } => {
390 assert_eq!(summary, "hello");
391 assert_eq!(body, "world");
392 assert_eq!(urgency, "normal");
393 assert!(actions.is_empty());
394 }
395 _ => panic!("wrong message type"),
396 }
397 }
398
399 #[test]
400 fn roundtrip_clipboard_set() {
401 let msg = GuestMessage::ClipboardSet {
402 text: "clipboard content".into(),
403 };
404 let mut buf = Vec::new();
405 write_frame(&mut buf, &msg).unwrap();
406
407 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
408 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
409 match decoded {
410 GuestMessage::ClipboardSet { text } => {
411 assert_eq!(text, "clipboard content");
412 }
413 _ => panic!("wrong message type"),
414 }
415 }
416
417 #[test]
418 fn hello_ack_with_shims_round_trips() {
419 let msg = HostMessage::HelloAck {
420 accepted: vec!["host_exec".into()],
421 rejected: vec![],
422 idle_timeout_secs: 10,
423 host_exec_shims: vec!["git".into(), "code".into()],
424 };
425 let mut buf = Vec::new();
426 write_frame(&mut buf, &msg).unwrap();
427 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
428 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
429 match decoded {
430 HostMessage::HelloAck {
431 accepted,
432 host_exec_shims,
433 ..
434 } => {
435 assert_eq!(accepted, vec!["host_exec"]);
436 assert_eq!(host_exec_shims, vec!["git", "code"]);
437 }
438 _ => panic!("wrong message type"),
439 }
440 }
441
442 #[test]
443 fn hello_ack_backward_compat_missing_shims() {
444 let json = r#"{"type":"hello_ack","accepted":[],"rejected":[],"idle_timeout_secs":0}"#;
445 let msg: HostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
446 match msg {
447 HostMessage::HelloAck {
448 host_exec_shims, ..
449 } => assert!(host_exec_shims.is_empty()),
450 _ => panic!("wrong message type"),
451 }
452 }
453
454 enum Step {
456 Bytes(Vec<u8>),
457 Timeout,
458 }
459
460 struct Scripted(std::collections::VecDeque<Step>);
461
462 impl Read for Scripted {
463 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
464 match self.0.pop_front() {
465 None => Ok(0),
466 Some(Step::Timeout) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
467 Some(Step::Bytes(mut b)) => {
468 let n = b.len().min(buf.len());
469 buf[..n].copy_from_slice(&b[..n]);
470 if n < b.len() {
471 b.drain(..n);
472 self.0.push_front(Step::Bytes(b));
473 }
474 Ok(n)
475 }
476 }
477 }
478 }
479
480 fn encoded(msg: &str) -> Vec<u8> {
481 let mut buf = Vec::new();
482 write_frame(&mut buf, &msg).unwrap();
483 buf
484 }
485
486 #[test]
489 fn frame_survives_a_timeout_in_the_length_prefix() {
490 let bytes = encoded("hello there");
491 let mut r = Scripted(
492 [
493 Step::Bytes(bytes[..2].to_vec()),
494 Step::Timeout,
495 Step::Bytes(bytes[2..].to_vec()),
496 ]
497 .into(),
498 );
499 let mut fr = FrameReader::new();
500 assert!(fr.read(&mut r).is_err());
501 assert!(fr.in_progress());
502 let got = fr.read(&mut r).unwrap();
503 assert_eq!(
504 got,
505 FrameRead::Frame(serde_json::to_vec("hello there").unwrap())
506 );
507 assert!(!fr.in_progress());
508 }
509
510 #[test]
511 fn frame_survives_a_timeout_in_the_payload() {
512 let bytes = encoded("a longer payload to split");
513 let cut = 4 + 7;
514 let mut r = Scripted(
515 [
516 Step::Bytes(bytes[..cut].to_vec()),
517 Step::Timeout,
518 Step::Bytes(bytes[cut..].to_vec()),
519 ]
520 .into(),
521 );
522 let mut fr = FrameReader::new();
523 assert!(fr.read(&mut r).is_err());
524 assert_eq!(
525 fr.read(&mut r).unwrap(),
526 FrameRead::Frame(serde_json::to_vec("a longer payload to split").unwrap())
527 );
528 }
529
530 #[test]
531 fn clean_eof_between_frames_is_eof_not_an_error() {
532 let mut r = Scripted(std::collections::VecDeque::new());
533 assert_eq!(FrameReader::new().read(&mut r).unwrap(), FrameRead::Eof);
534 }
535
536 #[test]
537 fn eof_inside_a_frame_is_an_error() {
538 let bytes = encoded("cut short");
539 let mut r = Scripted([Step::Bytes(bytes[..6].to_vec())].into());
540 let err = FrameReader::new().read(&mut r).unwrap_err();
541 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
542 }
543
544 #[test]
545 fn host_exec_output_chunk_round_trips_raw_bytes() {
546 let msg = HostMessage::HostExecOutput {
549 stream: ExecStream::Stdout,
550 data: vec![0xff, 0xfe, b'A'],
551 };
552 let mut buf = Vec::new();
553 write_frame(&mut buf, &msg).unwrap();
554 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
555 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
556 match decoded {
557 HostMessage::HostExecOutput { stream, data } => {
558 assert_eq!(stream, ExecStream::Stdout);
559 assert_eq!(data, vec![0xff, 0xfe, b'A']);
560 }
561 _ => panic!("wrong message type"),
562 }
563 }
564
565 #[test]
566 fn host_exec_v2_optional_fields_are_serde_defaulted() {
567 let json = br#"{"type":"host_exec_v2","cmd":"cat","args":["-s"]}"#;
571 let msg: GuestMessage = serde_json::from_slice(json).unwrap();
572 match msg {
573 GuestMessage::HostExecV2 {
574 cmd,
575 args,
576 env,
577 cwd,
578 tty,
579 } => {
580 assert_eq!(cmd, "cat");
581 assert_eq!(args, vec!["-s"]);
582 assert!(env.is_empty());
583 assert!(cwd.is_none());
584 assert!(!tty);
585 }
586 other => panic!("expected HostExecV2, got {other:?}"),
587 }
588 }
589
590 #[test]
591 fn host_exec_v2_round_trips_the_full_field_set() {
592 let msg = GuestMessage::HostExecV2 {
593 cmd: "git".into(),
594 args: vec!["log".into()],
595 env: vec![("TERM".into(), "xterm-256color".into())],
596 cwd: Some("/home/user/project".into()),
597 tty: true,
598 };
599 let mut buf = Vec::new();
600 write_frame(&mut buf, &msg).unwrap();
601 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
602 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
603 match decoded {
604 GuestMessage::HostExecV2 {
605 cmd,
606 args,
607 env,
608 cwd,
609 tty,
610 } => {
611 assert_eq!(cmd, "git");
612 assert_eq!(args, vec!["log"]);
613 assert_eq!(
614 env,
615 vec![("TERM".to_string(), "xterm-256color".to_string())]
616 );
617 assert_eq!(cwd.as_deref(), Some("/home/user/project"));
618 assert!(tty);
619 }
620 other => panic!("expected HostExecV2, got {other:?}"),
621 }
622 }
623
624 #[test]
625 fn host_exec_signal_round_trips() {
626 let msg = GuestMessage::HostExecSignal { sig: 2 };
627 let mut buf = Vec::new();
628 write_frame(&mut buf, &msg).unwrap();
629 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
630 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
631 match decoded {
632 GuestMessage::HostExecSignal { sig } => assert_eq!(sig, 2),
633 other => panic!("expected HostExecSignal, got {other:?}"),
634 }
635 }
636
637 #[test]
642 fn hello_with_an_unknown_capability_parses_on_the_old_schema() {
643 #[allow(dead_code)]
646 #[derive(Deserialize)]
647 #[serde(tag = "type", rename_all = "snake_case")]
648 enum OldGuestMessage {
649 Hello {
650 protocol_version: u32,
651 guest_version: String,
652 container: String,
653 capabilities: Vec<String>,
654 },
655 }
656
657 let json = r#"{"type":"hello","protocol_version":1,"guest_version":"0.2.0",
658 "container":"dev","capabilities":["host_exec","host_exec_fds"]}"#;
659 let msg: OldGuestMessage = serde_json::from_slice(json.as_bytes()).unwrap();
660 let OldGuestMessage::Hello { capabilities, .. } = msg;
661 assert_eq!(capabilities, vec!["host_exec", "host_exec_fds"]);
662 }
663
664 #[test]
665 fn host_exec_done_carries_an_optional_signal() {
666 let msg = HostMessage::HostExecDone {
667 exit_code: 143,
668 signal: Some(15),
669 };
670 let mut buf = Vec::new();
671 write_frame(&mut buf, &msg).unwrap();
672 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
673 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
674 match decoded {
675 HostMessage::HostExecDone { exit_code, signal } => {
676 assert_eq!(exit_code, 143);
677 assert_eq!(signal, Some(15));
678 }
679 _ => panic!("wrong message type"),
680 }
681 }
682
683 #[test]
687 fn host_exec_done_with_signal_parses_under_the_old_schema() {
688 #[derive(Debug, Deserialize, PartialEq, Eq)]
689 #[serde(tag = "type", rename_all = "snake_case")]
690 enum OldHostMessage {
691 HostExecDone { exit_code: i32 },
692 }
693
694 let json = r#"{"type":"host_exec_done","exit_code":143,"signal":15}"#;
695 let msg: OldHostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
696 assert_eq!(msg, OldHostMessage::HostExecDone { exit_code: 143 });
697 }
698}