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 #[serde(default)]
156 host_version: String,
157 },
158 ClipboardData {
159 text: String,
160 },
161 HostExecStdout {
162 data: String,
163 },
164 HostExecStderr {
165 data: String,
166 },
167 HostExecOutput {
173 stream: ExecStream,
174 data: Vec<u8>,
175 },
176 HostExecDone {
177 exit_code: i32,
178 #[serde(default)]
182 signal: Option<i32>,
183 },
184 NotifyActionResult {
185 notification_id: u32,
186 action_key: String,
187 },
188 Ping,
189 Shutdown,
190 CheckIdle,
193 Error {
196 reason: String,
197 #[serde(default)]
200 code: Option<String>,
201 },
202 GetInfo,
204}
205
206pub fn write_frame<W: Write>(w: &mut W, msg: &impl Serialize) -> io::Result<()> {
208 let json = serde_json::to_vec(msg)?;
209 if json.len() > MAX_FRAME_SIZE {
210 return Err(io::Error::new(
211 io::ErrorKind::InvalidInput,
212 format!(
213 "frame too large: {} bytes (max {MAX_FRAME_SIZE})",
214 json.len()
215 ),
216 ));
217 }
218 let len = u32::try_from(json.len())
219 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame payload exceeds 4 GiB"))?
220 .to_be_bytes();
221 w.write_all(&len)?;
222 w.write_all(&json)?;
223 w.flush()?;
224 Ok(())
225}
226
227const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
229
230pub const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;
236
237pub fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<Vec<u8>>> {
239 let mut len_buf = [0u8; 4];
240 match r.read_exact(&mut len_buf) {
241 Ok(()) => {}
242 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
243 Err(e) => return Err(e),
244 }
245 let len = u32::from_be_bytes(len_buf) as usize;
246 if len > MAX_FRAME_SIZE {
247 return Err(io::Error::new(
248 io::ErrorKind::InvalidData,
249 format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
250 ));
251 }
252 let mut buf = vec![0u8; len];
253 r.read_exact(&mut buf)?;
254 Ok(Some(buf))
255}
256
257#[derive(Debug, Default)]
265pub struct FrameReader {
266 prefix: [u8; 4],
267 prefix_filled: usize,
268 body: Vec<u8>,
269 body_filled: usize,
270 body_len: Option<usize>,
271 started: Option<std::time::Instant>,
273}
274
275#[derive(Debug, PartialEq, Eq)]
277pub enum FrameRead {
278 Frame(Vec<u8>),
280 Eof,
282}
283
284impl FrameReader {
285 pub fn new() -> Self {
286 Self::default()
287 }
288
289 pub fn in_progress(&self) -> bool {
291 self.started.is_some()
292 }
293
294 pub fn stalled_for(&self) -> Option<std::time::Duration> {
296 self.started.map(|t| t.elapsed())
297 }
298
299 pub fn read<R: Read>(&mut self, r: &mut R) -> io::Result<FrameRead> {
302 while self.prefix_filled < 4 {
303 let n = r.read(&mut self.prefix[self.prefix_filled..])?;
304 if n == 0 {
305 return if self.prefix_filled == 0 {
306 Ok(FrameRead::Eof)
307 } else {
308 Err(io::Error::from(io::ErrorKind::UnexpectedEof))
309 };
310 }
311 self.started.get_or_insert_with(std::time::Instant::now);
312 self.prefix_filled += n;
313 }
314 let len = match self.body_len {
315 Some(len) => len,
316 None => {
317 let len = u32::from_be_bytes(self.prefix) as usize;
318 if len > MAX_FRAME_SIZE {
319 return Err(io::Error::new(
320 io::ErrorKind::InvalidData,
321 format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
322 ));
323 }
324 self.body = vec![0u8; len];
325 self.body_len = Some(len);
326 len
327 }
328 };
329 while self.body_filled < len {
330 let n = r.read(&mut self.body[self.body_filled..])?;
331 if n == 0 {
332 return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
333 }
334 self.body_filled += n;
335 }
336 let frame = std::mem::take(&mut self.body);
337 *self = Self::default();
338 Ok(FrameRead::Frame(frame))
339 }
340}
341
342#[cfg(unix)]
344pub mod sysutil;
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349
350 #[test]
351 fn hello_serializes_with_type_tag() {
352 let msg = GuestMessage::Hello {
353 protocol_version: 1,
354 guest_version: "0.2.0".into(),
355 container: "myenv".into(),
356 capabilities: vec!["notify".into()],
357 };
358 let json = serde_json::to_string(&msg).unwrap();
359 assert!(json.contains("\"type\":\"hello\""));
360 }
361
362 #[test]
363 fn frame_length_prefix_matches_payload() {
364 let msg = GuestMessage::ClipboardGet;
365 let mut buf = Vec::new();
366 write_frame(&mut buf, &msg).unwrap();
367 let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
368 assert_eq!(len, buf[4..].len());
369 }
370
371 #[test]
372 fn interceptors_cover_known_binaries_and_capabilities() {
373 use std::collections::HashSet;
374 let binaries: HashSet<&str> = INTERCEPTORS.iter().map(|(bin, _)| *bin).collect();
375 assert_eq!(binaries.len(), INTERCEPTORS.len(), "duplicate binary");
376 for (_, cap) in INTERCEPTORS {
377 assert!(ALL_CAPABILITIES.contains(cap), "unknown capability {cap}");
378 }
379 }
380
381 #[test]
382 fn roundtrip_notify_message() {
383 let msg = GuestMessage::Notify {
384 summary: "hello".into(),
385 body: "world".into(),
386 urgency: "normal".into(),
387 actions: vec![],
388 app_name: String::new(),
389 };
390 let mut buf = Vec::new();
391 write_frame(&mut buf, &msg).unwrap();
392
393 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
394 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
395 match decoded {
396 GuestMessage::Notify {
397 summary,
398 body,
399 urgency,
400 actions,
401 app_name: _,
402 } => {
403 assert_eq!(summary, "hello");
404 assert_eq!(body, "world");
405 assert_eq!(urgency, "normal");
406 assert!(actions.is_empty());
407 }
408 _ => panic!("wrong message type"),
409 }
410 }
411
412 #[test]
413 fn roundtrip_clipboard_set() {
414 let msg = GuestMessage::ClipboardSet {
415 text: "clipboard content".into(),
416 };
417 let mut buf = Vec::new();
418 write_frame(&mut buf, &msg).unwrap();
419
420 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
421 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
422 match decoded {
423 GuestMessage::ClipboardSet { text } => {
424 assert_eq!(text, "clipboard content");
425 }
426 _ => panic!("wrong message type"),
427 }
428 }
429
430 #[test]
431 fn hello_ack_with_shims_round_trips() {
432 let msg = HostMessage::HelloAck {
433 accepted: vec!["host_exec".into()],
434 rejected: vec![],
435 idle_timeout_secs: 10,
436 host_exec_shims: vec!["git".into(), "code".into()],
437 host_version: "0.9.5".into(),
438 };
439 let mut buf = Vec::new();
440 write_frame(&mut buf, &msg).unwrap();
441 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
442 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
443 match decoded {
444 HostMessage::HelloAck {
445 accepted,
446 host_exec_shims,
447 host_version,
448 ..
449 } => {
450 assert_eq!(accepted, vec!["host_exec"]);
451 assert_eq!(host_exec_shims, vec!["git", "code"]);
452 assert_eq!(host_version, "0.9.5");
453 }
454 _ => panic!("wrong message type"),
455 }
456 }
457
458 #[test]
459 fn hello_ack_backward_compat_missing_shims() {
460 let json = r#"{"type":"hello_ack","accepted":[],"rejected":[],"idle_timeout_secs":0}"#;
461 let msg: HostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
462 match msg {
463 HostMessage::HelloAck {
464 host_exec_shims,
465 host_version,
466 ..
467 } => {
468 assert!(host_exec_shims.is_empty());
469 assert!(host_version.is_empty());
470 }
471 _ => panic!("wrong message type"),
472 }
473 }
474
475 enum Step {
477 Bytes(Vec<u8>),
478 Timeout,
479 }
480
481 struct Scripted(std::collections::VecDeque<Step>);
482
483 impl Read for Scripted {
484 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
485 match self.0.pop_front() {
486 None => Ok(0),
487 Some(Step::Timeout) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
488 Some(Step::Bytes(mut b)) => {
489 let n = b.len().min(buf.len());
490 buf[..n].copy_from_slice(&b[..n]);
491 if n < b.len() {
492 b.drain(..n);
493 self.0.push_front(Step::Bytes(b));
494 }
495 Ok(n)
496 }
497 }
498 }
499 }
500
501 fn encoded(msg: &str) -> Vec<u8> {
502 let mut buf = Vec::new();
503 write_frame(&mut buf, &msg).unwrap();
504 buf
505 }
506
507 #[test]
510 fn frame_survives_a_timeout_in_the_length_prefix() {
511 let bytes = encoded("hello there");
512 let mut r = Scripted(
513 [
514 Step::Bytes(bytes[..2].to_vec()),
515 Step::Timeout,
516 Step::Bytes(bytes[2..].to_vec()),
517 ]
518 .into(),
519 );
520 let mut fr = FrameReader::new();
521 assert!(fr.read(&mut r).is_err());
522 assert!(fr.in_progress());
523 let got = fr.read(&mut r).unwrap();
524 assert_eq!(
525 got,
526 FrameRead::Frame(serde_json::to_vec("hello there").unwrap())
527 );
528 assert!(!fr.in_progress());
529 }
530
531 #[test]
532 fn frame_survives_a_timeout_in_the_payload() {
533 let bytes = encoded("a longer payload to split");
534 let cut = 4 + 7;
535 let mut r = Scripted(
536 [
537 Step::Bytes(bytes[..cut].to_vec()),
538 Step::Timeout,
539 Step::Bytes(bytes[cut..].to_vec()),
540 ]
541 .into(),
542 );
543 let mut fr = FrameReader::new();
544 assert!(fr.read(&mut r).is_err());
545 assert_eq!(
546 fr.read(&mut r).unwrap(),
547 FrameRead::Frame(serde_json::to_vec("a longer payload to split").unwrap())
548 );
549 }
550
551 #[test]
552 fn clean_eof_between_frames_is_eof_not_an_error() {
553 let mut r = Scripted(std::collections::VecDeque::new());
554 assert_eq!(FrameReader::new().read(&mut r).unwrap(), FrameRead::Eof);
555 }
556
557 #[test]
558 fn eof_inside_a_frame_is_an_error() {
559 let bytes = encoded("cut short");
560 let mut r = Scripted([Step::Bytes(bytes[..6].to_vec())].into());
561 let err = FrameReader::new().read(&mut r).unwrap_err();
562 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
563 }
564
565 #[test]
566 fn host_exec_output_chunk_round_trips_raw_bytes() {
567 let msg = HostMessage::HostExecOutput {
570 stream: ExecStream::Stdout,
571 data: vec![0xff, 0xfe, b'A'],
572 };
573 let mut buf = Vec::new();
574 write_frame(&mut buf, &msg).unwrap();
575 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
576 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
577 match decoded {
578 HostMessage::HostExecOutput { stream, data } => {
579 assert_eq!(stream, ExecStream::Stdout);
580 assert_eq!(data, vec![0xff, 0xfe, b'A']);
581 }
582 _ => panic!("wrong message type"),
583 }
584 }
585
586 #[test]
587 fn host_exec_v2_optional_fields_are_serde_defaulted() {
588 let json = br#"{"type":"host_exec_v2","cmd":"cat","args":["-s"]}"#;
592 let msg: GuestMessage = serde_json::from_slice(json).unwrap();
593 match msg {
594 GuestMessage::HostExecV2 {
595 cmd,
596 args,
597 env,
598 cwd,
599 tty,
600 } => {
601 assert_eq!(cmd, "cat");
602 assert_eq!(args, vec!["-s"]);
603 assert!(env.is_empty());
604 assert!(cwd.is_none());
605 assert!(!tty);
606 }
607 other => panic!("expected HostExecV2, got {other:?}"),
608 }
609 }
610
611 #[test]
612 fn host_exec_v2_round_trips_the_full_field_set() {
613 let msg = GuestMessage::HostExecV2 {
614 cmd: "git".into(),
615 args: vec!["log".into()],
616 env: vec![("TERM".into(), "xterm-256color".into())],
617 cwd: Some("/home/user/project".into()),
618 tty: true,
619 };
620 let mut buf = Vec::new();
621 write_frame(&mut buf, &msg).unwrap();
622 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
623 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
624 match decoded {
625 GuestMessage::HostExecV2 {
626 cmd,
627 args,
628 env,
629 cwd,
630 tty,
631 } => {
632 assert_eq!(cmd, "git");
633 assert_eq!(args, vec!["log"]);
634 assert_eq!(
635 env,
636 vec![("TERM".to_string(), "xterm-256color".to_string())]
637 );
638 assert_eq!(cwd.as_deref(), Some("/home/user/project"));
639 assert!(tty);
640 }
641 other => panic!("expected HostExecV2, got {other:?}"),
642 }
643 }
644
645 #[test]
646 fn host_exec_signal_round_trips() {
647 let msg = GuestMessage::HostExecSignal { sig: 2 };
648 let mut buf = Vec::new();
649 write_frame(&mut buf, &msg).unwrap();
650 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
651 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
652 match decoded {
653 GuestMessage::HostExecSignal { sig } => assert_eq!(sig, 2),
654 other => panic!("expected HostExecSignal, got {other:?}"),
655 }
656 }
657
658 #[test]
663 fn hello_with_an_unknown_capability_parses_on_the_old_schema() {
664 #[allow(dead_code)]
667 #[derive(Deserialize)]
668 #[serde(tag = "type", rename_all = "snake_case")]
669 enum OldGuestMessage {
670 Hello {
671 protocol_version: u32,
672 guest_version: String,
673 container: String,
674 capabilities: Vec<String>,
675 },
676 }
677
678 let json = r#"{"type":"hello","protocol_version":1,"guest_version":"0.2.0",
679 "container":"dev","capabilities":["host_exec","host_exec_fds"]}"#;
680 let msg: OldGuestMessage = serde_json::from_slice(json.as_bytes()).unwrap();
681 let OldGuestMessage::Hello { capabilities, .. } = msg;
682 assert_eq!(capabilities, vec!["host_exec", "host_exec_fds"]);
683 }
684
685 #[test]
686 fn host_exec_done_carries_an_optional_signal() {
687 let msg = HostMessage::HostExecDone {
688 exit_code: 143,
689 signal: Some(15),
690 };
691 let mut buf = Vec::new();
692 write_frame(&mut buf, &msg).unwrap();
693 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
694 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
695 match decoded {
696 HostMessage::HostExecDone { exit_code, signal } => {
697 assert_eq!(exit_code, 143);
698 assert_eq!(signal, Some(15));
699 }
700 _ => panic!("wrong message type"),
701 }
702 }
703
704 #[test]
708 fn host_exec_done_with_signal_parses_under_the_old_schema() {
709 #[derive(Debug, Deserialize, PartialEq, Eq)]
710 #[serde(tag = "type", rename_all = "snake_case")]
711 enum OldHostMessage {
712 HostExecDone { exit_code: i32 },
713 }
714
715 let json = r#"{"type":"host_exec_done","exit_code":143,"signal":15}"#;
716 let msg: OldHostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
717 assert_eq!(msg, OldHostMessage::HostExecDone { exit_code: 143 });
718 }
719}