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 TERMINAL_ENV_KEYS: &[&str] = &[
46 "TERM",
47 "COLORTERM",
48 "TERM_PROGRAM",
49 "TERM_PROGRAM_VERSION",
50 "TERM_SESSION_ID",
51 "VTE_VERSION",
52 "KONSOLE_VERSION",
53 "KITTY_WINDOW_ID",
54 "WEZTERM_PANE",
55 "WT_SESSION",
56 "LC_TERMINAL",
57 "LC_TERMINAL_VERSION",
58];
59
60#[must_use]
67pub fn is_host_exec_env(key: &str) -> bool {
68 key == "LANG" || TERMINAL_ENV_KEYS.contains(&key)
69}
70
71pub const INTERCEPTORS: &[(&str, &str)] = &[
77 ("notify-send", CAP_NOTIFY),
78 ("xdg-open", CAP_XDG_OPEN),
79 ("podbox-clipboard", CAP_CLIPBOARD),
80 ("host-exec", CAP_HOST_EXEC),
81];
82
83#[derive(Debug, Serialize, Deserialize)]
85#[serde(tag = "type", rename_all = "snake_case")]
86pub enum GuestMessage {
87 Hello {
88 protocol_version: u32,
89 guest_version: String,
90 container: String,
91 capabilities: Vec<String>,
92 },
93 Notify {
94 summary: String,
95 body: String,
96 urgency: String,
97 #[serde(default)]
98 actions: Vec<NotifyAction>,
99 #[serde(default)]
100 app_name: String,
101 },
102 XdgOpen {
103 uri: String,
104 },
105 ClipboardSet {
106 text: String,
107 },
108 ClipboardGet,
109 HostExec {
110 cmd: String,
111 args: Vec<String>,
112 },
113 HostExecV2 {
128 cmd: String,
129 args: Vec<String>,
130 #[serde(default)]
133 env: Vec<(String, String)>,
134 #[serde(default)]
135 cwd: Option<String>,
136 #[serde(default)]
137 tty: bool,
138 },
139 HostExecSignal {
144 sig: i32,
145 },
146 RegisterSession,
149 Busy,
151 IdleTimeout,
153 Info {
155 guest_version: String,
156 protocol_version: u32,
157 },
158}
159
160#[derive(Debug, Serialize, Deserialize, Clone)]
161pub struct NotifyAction {
162 pub key: String,
163 pub label: String,
164}
165
166#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
168#[serde(rename_all = "snake_case")]
169pub enum ExecStream {
170 Stdout,
171 Stderr,
172}
173
174#[derive(Debug, Serialize, Deserialize)]
176#[serde(tag = "type", rename_all = "snake_case")]
177pub enum HostMessage {
178 HelloAck {
179 accepted: Vec<String>,
180 rejected: Vec<String>,
181 #[serde(default)]
182 idle_timeout_secs: u64,
183 #[serde(default)]
185 host_exec_shims: Vec<String>,
186 #[serde(default)]
189 host_version: String,
190 },
191 ClipboardData {
192 text: String,
193 },
194 HostExecStdout {
195 data: String,
196 },
197 HostExecStderr {
198 data: String,
199 },
200 HostExecOutput {
206 stream: ExecStream,
207 data: Vec<u8>,
208 },
209 HostExecDone {
210 exit_code: i32,
211 #[serde(default)]
215 signal: Option<i32>,
216 },
217 NotifyActionResult {
218 notification_id: u32,
219 action_key: String,
220 },
221 Ping,
222 Shutdown,
223 CheckIdle,
226 Error {
229 reason: String,
230 #[serde(default)]
233 code: Option<String>,
234 },
235 GetInfo,
237}
238
239pub fn write_frame<W: Write>(w: &mut W, msg: &impl Serialize) -> io::Result<()> {
241 let json = serde_json::to_vec(msg)?;
242 if json.len() > MAX_FRAME_SIZE {
243 return Err(io::Error::new(
244 io::ErrorKind::InvalidInput,
245 format!(
246 "frame too large: {} bytes (max {MAX_FRAME_SIZE})",
247 json.len()
248 ),
249 ));
250 }
251 let len = u32::try_from(json.len())
252 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame payload exceeds 4 GiB"))?
253 .to_be_bytes();
254 w.write_all(&len)?;
255 w.write_all(&json)?;
256 w.flush()?;
257 Ok(())
258}
259
260const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;
262
263pub const MAX_CLIPBOARD_BYTES: usize = 8 * 1024 * 1024;
269
270pub fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<Vec<u8>>> {
272 let mut len_buf = [0u8; 4];
273 match r.read_exact(&mut len_buf) {
274 Ok(()) => {}
275 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
276 Err(e) => return Err(e),
277 }
278 let len = u32::from_be_bytes(len_buf) as usize;
279 if len > MAX_FRAME_SIZE {
280 return Err(io::Error::new(
281 io::ErrorKind::InvalidData,
282 format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
283 ));
284 }
285 let mut buf = vec![0u8; len];
286 r.read_exact(&mut buf)?;
287 Ok(Some(buf))
288}
289
290#[derive(Debug, Default)]
298pub struct FrameReader {
299 prefix: [u8; 4],
300 prefix_filled: usize,
301 body: Vec<u8>,
302 body_filled: usize,
303 body_len: Option<usize>,
304 started: Option<std::time::Instant>,
306}
307
308#[derive(Debug, PartialEq, Eq)]
310pub enum FrameRead {
311 Frame(Vec<u8>),
313 Eof,
315}
316
317impl FrameReader {
318 pub fn new() -> Self {
319 Self::default()
320 }
321
322 pub fn in_progress(&self) -> bool {
324 self.started.is_some()
325 }
326
327 pub fn stalled_for(&self) -> Option<std::time::Duration> {
329 self.started.map(|t| t.elapsed())
330 }
331
332 pub fn read<R: Read>(&mut self, r: &mut R) -> io::Result<FrameRead> {
335 while self.prefix_filled < 4 {
336 let n = r.read(&mut self.prefix[self.prefix_filled..])?;
337 if n == 0 {
338 return if self.prefix_filled == 0 {
339 Ok(FrameRead::Eof)
340 } else {
341 Err(io::Error::from(io::ErrorKind::UnexpectedEof))
342 };
343 }
344 self.started.get_or_insert_with(std::time::Instant::now);
345 self.prefix_filled += n;
346 }
347 let len = match self.body_len {
348 Some(len) => len,
349 None => {
350 let len = u32::from_be_bytes(self.prefix) as usize;
351 if len > MAX_FRAME_SIZE {
352 return Err(io::Error::new(
353 io::ErrorKind::InvalidData,
354 format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
355 ));
356 }
357 self.body = vec![0u8; len];
358 self.body_len = Some(len);
359 len
360 }
361 };
362 while self.body_filled < len {
363 let n = r.read(&mut self.body[self.body_filled..])?;
364 if n == 0 {
365 return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
366 }
367 self.body_filled += n;
368 }
369 let frame = std::mem::take(&mut self.body);
370 *self = Self::default();
371 Ok(FrameRead::Frame(frame))
372 }
373}
374
375#[cfg(unix)]
377pub mod sysutil;
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 #[test]
384 fn hello_serializes_with_type_tag() {
385 let msg = GuestMessage::Hello {
386 protocol_version: 1,
387 guest_version: "0.2.0".into(),
388 container: "myenv".into(),
389 capabilities: vec!["notify".into()],
390 };
391 let json = serde_json::to_string(&msg).unwrap();
392 assert!(json.contains("\"type\":\"hello\""));
393 }
394
395 #[test]
396 fn frame_length_prefix_matches_payload() {
397 let msg = GuestMessage::ClipboardGet;
398 let mut buf = Vec::new();
399 write_frame(&mut buf, &msg).unwrap();
400 let len = u32::from_be_bytes(buf[..4].try_into().unwrap()) as usize;
401 assert_eq!(len, buf[4..].len());
402 }
403
404 #[test]
405 fn interceptors_cover_known_binaries_and_capabilities() {
406 use std::collections::HashSet;
407 let binaries: HashSet<&str> = INTERCEPTORS.iter().map(|(bin, _)| *bin).collect();
408 assert_eq!(binaries.len(), INTERCEPTORS.len(), "duplicate binary");
409 for (_, cap) in INTERCEPTORS {
410 assert!(ALL_CAPABILITIES.contains(cap), "unknown capability {cap}");
411 }
412 }
413
414 #[test]
415 fn roundtrip_notify_message() {
416 let msg = GuestMessage::Notify {
417 summary: "hello".into(),
418 body: "world".into(),
419 urgency: "normal".into(),
420 actions: vec![],
421 app_name: String::new(),
422 };
423 let mut buf = Vec::new();
424 write_frame(&mut buf, &msg).unwrap();
425
426 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
427 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
428 match decoded {
429 GuestMessage::Notify {
430 summary,
431 body,
432 urgency,
433 actions,
434 app_name: _,
435 } => {
436 assert_eq!(summary, "hello");
437 assert_eq!(body, "world");
438 assert_eq!(urgency, "normal");
439 assert!(actions.is_empty());
440 }
441 _ => panic!("wrong message type"),
442 }
443 }
444
445 #[test]
446 fn roundtrip_clipboard_set() {
447 let msg = GuestMessage::ClipboardSet {
448 text: "clipboard content".into(),
449 };
450 let mut buf = Vec::new();
451 write_frame(&mut buf, &msg).unwrap();
452
453 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
454 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
455 match decoded {
456 GuestMessage::ClipboardSet { text } => {
457 assert_eq!(text, "clipboard content");
458 }
459 _ => panic!("wrong message type"),
460 }
461 }
462
463 #[test]
464 fn hello_ack_with_shims_round_trips() {
465 let msg = HostMessage::HelloAck {
466 accepted: vec!["host_exec".into()],
467 rejected: vec![],
468 idle_timeout_secs: 10,
469 host_exec_shims: vec!["git".into(), "code".into()],
470 host_version: "0.9.5".into(),
471 };
472 let mut buf = Vec::new();
473 write_frame(&mut buf, &msg).unwrap();
474 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
475 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
476 match decoded {
477 HostMessage::HelloAck {
478 accepted,
479 host_exec_shims,
480 host_version,
481 ..
482 } => {
483 assert_eq!(accepted, vec!["host_exec"]);
484 assert_eq!(host_exec_shims, vec!["git", "code"]);
485 assert_eq!(host_version, "0.9.5");
486 }
487 _ => panic!("wrong message type"),
488 }
489 }
490
491 #[test]
492 fn hello_ack_backward_compat_missing_shims() {
493 let json = r#"{"type":"hello_ack","accepted":[],"rejected":[],"idle_timeout_secs":0}"#;
494 let msg: HostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
495 match msg {
496 HostMessage::HelloAck {
497 host_exec_shims,
498 host_version,
499 ..
500 } => {
501 assert!(host_exec_shims.is_empty());
502 assert!(host_version.is_empty());
503 }
504 _ => panic!("wrong message type"),
505 }
506 }
507
508 enum Step {
510 Bytes(Vec<u8>),
511 Timeout,
512 }
513
514 struct Scripted(std::collections::VecDeque<Step>);
515
516 impl Read for Scripted {
517 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
518 match self.0.pop_front() {
519 None => Ok(0),
520 Some(Step::Timeout) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
521 Some(Step::Bytes(mut b)) => {
522 let n = b.len().min(buf.len());
523 buf[..n].copy_from_slice(&b[..n]);
524 if n < b.len() {
525 b.drain(..n);
526 self.0.push_front(Step::Bytes(b));
527 }
528 Ok(n)
529 }
530 }
531 }
532 }
533
534 fn encoded(msg: &str) -> Vec<u8> {
535 let mut buf = Vec::new();
536 write_frame(&mut buf, &msg).unwrap();
537 buf
538 }
539
540 #[test]
543 fn frame_survives_a_timeout_in_the_length_prefix() {
544 let bytes = encoded("hello there");
545 let mut r = Scripted(
546 [
547 Step::Bytes(bytes[..2].to_vec()),
548 Step::Timeout,
549 Step::Bytes(bytes[2..].to_vec()),
550 ]
551 .into(),
552 );
553 let mut fr = FrameReader::new();
554 assert!(fr.read(&mut r).is_err());
555 assert!(fr.in_progress());
556 let got = fr.read(&mut r).unwrap();
557 assert_eq!(
558 got,
559 FrameRead::Frame(serde_json::to_vec("hello there").unwrap())
560 );
561 assert!(!fr.in_progress());
562 }
563
564 #[test]
565 fn frame_survives_a_timeout_in_the_payload() {
566 let bytes = encoded("a longer payload to split");
567 let cut = 4 + 7;
568 let mut r = Scripted(
569 [
570 Step::Bytes(bytes[..cut].to_vec()),
571 Step::Timeout,
572 Step::Bytes(bytes[cut..].to_vec()),
573 ]
574 .into(),
575 );
576 let mut fr = FrameReader::new();
577 assert!(fr.read(&mut r).is_err());
578 assert_eq!(
579 fr.read(&mut r).unwrap(),
580 FrameRead::Frame(serde_json::to_vec("a longer payload to split").unwrap())
581 );
582 }
583
584 #[test]
585 fn clean_eof_between_frames_is_eof_not_an_error() {
586 let mut r = Scripted(std::collections::VecDeque::new());
587 assert_eq!(FrameReader::new().read(&mut r).unwrap(), FrameRead::Eof);
588 }
589
590 #[test]
591 fn eof_inside_a_frame_is_an_error() {
592 let bytes = encoded("cut short");
593 let mut r = Scripted([Step::Bytes(bytes[..6].to_vec())].into());
594 let err = FrameReader::new().read(&mut r).unwrap_err();
595 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
596 }
597
598 #[test]
599 fn host_exec_output_chunk_round_trips_raw_bytes() {
600 let msg = HostMessage::HostExecOutput {
603 stream: ExecStream::Stdout,
604 data: vec![0xff, 0xfe, b'A'],
605 };
606 let mut buf = Vec::new();
607 write_frame(&mut buf, &msg).unwrap();
608 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
609 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
610 match decoded {
611 HostMessage::HostExecOutput { stream, data } => {
612 assert_eq!(stream, ExecStream::Stdout);
613 assert_eq!(data, vec![0xff, 0xfe, b'A']);
614 }
615 _ => panic!("wrong message type"),
616 }
617 }
618
619 #[test]
620 fn host_exec_v2_optional_fields_are_serde_defaulted() {
621 let json = br#"{"type":"host_exec_v2","cmd":"cat","args":["-s"]}"#;
625 let msg: GuestMessage = serde_json::from_slice(json).unwrap();
626 match msg {
627 GuestMessage::HostExecV2 {
628 cmd,
629 args,
630 env,
631 cwd,
632 tty,
633 } => {
634 assert_eq!(cmd, "cat");
635 assert_eq!(args, vec!["-s"]);
636 assert!(env.is_empty());
637 assert!(cwd.is_none());
638 assert!(!tty);
639 }
640 other => panic!("expected HostExecV2, got {other:?}"),
641 }
642 }
643
644 #[test]
645 fn host_exec_v2_round_trips_the_full_field_set() {
646 let msg = GuestMessage::HostExecV2 {
647 cmd: "git".into(),
648 args: vec!["log".into()],
649 env: vec![("TERM".into(), "xterm-256color".into())],
650 cwd: Some("/home/user/project".into()),
651 tty: true,
652 };
653 let mut buf = Vec::new();
654 write_frame(&mut buf, &msg).unwrap();
655 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
656 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
657 match decoded {
658 GuestMessage::HostExecV2 {
659 cmd,
660 args,
661 env,
662 cwd,
663 tty,
664 } => {
665 assert_eq!(cmd, "git");
666 assert_eq!(args, vec!["log"]);
667 assert_eq!(
668 env,
669 vec![("TERM".to_string(), "xterm-256color".to_string())]
670 );
671 assert_eq!(cwd.as_deref(), Some("/home/user/project"));
672 assert!(tty);
673 }
674 other => panic!("expected HostExecV2, got {other:?}"),
675 }
676 }
677
678 #[test]
679 fn terminal_env_allowlist_carries_identity_but_not_host_sockets() {
680 for key in [
681 "TERM",
682 "COLORTERM",
683 "TERM_PROGRAM",
684 "TERM_PROGRAM_VERSION",
685 "VTE_VERSION",
686 "KITTY_WINDOW_ID",
687 "LC_TERMINAL",
688 ] {
689 assert!(TERMINAL_ENV_KEYS.contains(&key), "{key} must be forwarded");
690 assert!(is_host_exec_env(key), "{key} must reach host-exec");
691 }
692 assert!(is_host_exec_env("LANG"));
693 for key in [
694 "PATH",
695 "LD_PRELOAD",
696 "KITTY_LISTEN_ON",
697 "WEZTERM_UNIX_SOCKET",
698 "TMUX",
699 "STY",
700 ] {
701 assert!(!is_host_exec_env(key), "{key} must stay inside");
702 assert!(
703 !TERMINAL_ENV_KEYS.contains(&key),
704 "{key} is not terminal identity"
705 );
706 }
707 }
708
709 #[test]
710 fn host_exec_signal_round_trips() {
711 let msg = GuestMessage::HostExecSignal { sig: 2 };
712 let mut buf = Vec::new();
713 write_frame(&mut buf, &msg).unwrap();
714 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
715 let decoded: GuestMessage = serde_json::from_slice(&payload).unwrap();
716 match decoded {
717 GuestMessage::HostExecSignal { sig } => assert_eq!(sig, 2),
718 other => panic!("expected HostExecSignal, got {other:?}"),
719 }
720 }
721
722 #[test]
727 fn hello_with_an_unknown_capability_parses_on_the_old_schema() {
728 #[allow(dead_code)]
731 #[derive(Deserialize)]
732 #[serde(tag = "type", rename_all = "snake_case")]
733 enum OldGuestMessage {
734 Hello {
735 protocol_version: u32,
736 guest_version: String,
737 container: String,
738 capabilities: Vec<String>,
739 },
740 }
741
742 let json = r#"{"type":"hello","protocol_version":1,"guest_version":"0.2.0",
743 "container":"dev","capabilities":["host_exec","host_exec_fds"]}"#;
744 let msg: OldGuestMessage = serde_json::from_slice(json.as_bytes()).unwrap();
745 let OldGuestMessage::Hello { capabilities, .. } = msg;
746 assert_eq!(capabilities, vec!["host_exec", "host_exec_fds"]);
747 }
748
749 #[test]
750 fn host_exec_done_carries_an_optional_signal() {
751 let msg = HostMessage::HostExecDone {
752 exit_code: 143,
753 signal: Some(15),
754 };
755 let mut buf = Vec::new();
756 write_frame(&mut buf, &msg).unwrap();
757 let payload = read_frame(&mut &buf[..]).unwrap().unwrap();
758 let decoded: HostMessage = serde_json::from_slice(&payload).unwrap();
759 match decoded {
760 HostMessage::HostExecDone { exit_code, signal } => {
761 assert_eq!(exit_code, 143);
762 assert_eq!(signal, Some(15));
763 }
764 _ => panic!("wrong message type"),
765 }
766 }
767
768 #[test]
772 fn host_exec_done_with_signal_parses_under_the_old_schema() {
773 #[derive(Debug, Deserialize, PartialEq, Eq)]
774 #[serde(tag = "type", rename_all = "snake_case")]
775 enum OldHostMessage {
776 HostExecDone { exit_code: i32 },
777 }
778
779 let json = r#"{"type":"host_exec_done","exit_code":143,"signal":15}"#;
780 let msg: OldHostMessage = serde_json::from_slice(json.as_bytes()).unwrap();
781 assert_eq!(msg, OldHostMessage::HostExecDone { exit_code: 143 });
782 }
783}