//! Versioned terminal-server protocol, shared by local and SSH transports. //! The GUI receives rendered grid state; only the server owns a VTE parser. use std::io::{Read, Write}; use alacritty_terminal::{ term::cell::Cell, vte::ansi::{CursorShape, Rgb}, }; use anyhow::{Context, Result, bail}; use bincode::Options; use serde::{Deserialize, Serialize, de::DeserializeOwned}; pub const VERSION: u32 = 6; // Version 6 reports an empty attach selection as a ServerMessage::Error string. pub const NO_SESSIONS_TO_ATTACH: &str = "no sessions to attach to"; pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024; pub type PaneId = u64; pub type TabId = u64; pub type SessionId = u64; #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)] pub struct SessionIdentity { pub server: [u8; 16], pub session: SessionId, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum SessionTarget { New { cwd: Option, }, Attach(Option), /// Local launcher request. The transport attaches by numeric ID on the v6 /// wire and verifies the daemon identity in the first snapshot. Remembered(SessionIdentity), } /// SSH settings inherited from the shell that requested a remote session. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SshOptions { pub executable: Option, pub agent_socket: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RemoteWindow { pub destination: String, pub ssh: SshOptions, } impl RemoteWindow { /// Older launch requests carry only the host and inherit the launcher's settings. pub fn from_env(destination: String) -> Self { Self { destination, ssh: SshOptions::from_env(), } } } /// Reconnect using the original remote binary and verify the daemon that owned the shell. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DetachedRemote { pub destination: String, pub identity: SessionIdentity, pub executable: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SessionInfo { pub id: SessionId, pub attached: usize, pub tabs: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] // Keep variants append-only: the shutdown command can retire an older server. pub enum ClientMessage { Hello { version: u32, }, Connect(SessionTarget), Input { pane: PaneId, bytes: Vec, }, Resize { pane: PaneId, columns: u16, lines: u16, cell_width: u16, cell_height: u16, }, Scroll { pane: PaneId, kind: ScrollKind, }, Selection { pane: PaneId, selection: SelectionCommand, }, Copy { pane: PaneId, }, NewTab { cwd: Option, }, Split { pane: PaneId, cwd: Option, }, FocusTab { tab: TabId, }, FocusPane { pane: PaneId, }, /// Close a pane or an entire local tab. Pane and tab IDs are allocated /// from the same sequence. Older v6 daemons only recognize pane IDs here. Close { id: u64, }, OpenWindow { target: Option, session: SessionTarget, }, Detach, Shutdown, Ping, /// Inspect the layout of the session this client has joined. List, /// A blank/absent name returns to program-title/CWD naming. RenamePane { pane: PaneId, name: Option, }, /// Insert above/below a pane, or current server focus when omitted. NewStackPane { pane: Option, direction: VerticalDirection, cwd: Option, }, /// Expand the adjacent pane in this column, stopping at either end. FocusStackPane { pane: PaneId, direction: VerticalDirection, }, /// Navigate from authoritative server focus. Horizontal edges switch tabs. FocusDirection { direction: Direction, }, /// Cycle relative to current server focus, preserving repeated key presses. CycleTab { forward: bool, }, /// Cycle expanded columns in the current tab, with wraparound. CyclePane { forward: bool, }, /// A blank/absent name returns to the selected pane's effective name. RenameTab { tab: TabId, name: Option, }, ListSessions, OpenRemoteTab { session: SessionIdentity, pane: PaneId, destination: String, target: SessionTarget, ssh: SshOptions, }, /// Detach the SSH session displayed by this tab. Older v6 servers accept /// this same wire command only while the connection is pending. DetachRemote { tab: TabId, }, /// Local launcher requests used to reopen a detached SSH connection. LastDetachedRemote { origin: Option, }, RememberDetachedRemote(DetachedRemote), OpenRemoteWindow { target: RemoteWindow, session: SessionTarget, }, /// Resolve a mounted connection on the user's joined local workspace. OpenWindowForRemoteTab { tab: TabId, cwd: Option, fallback: SshOptions, }, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum VerticalDirection { Up, Down, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Direction { Left, Right, Up, Down, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum ScrollKind { Delta(i32), PageUp, PageDown, Top, Bottom, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum SelectionKind { Simple, Word, Line, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum SelectionSide { Left, Right, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum SelectionCommand { Start { column: u16, row: u16, side: SelectionSide, kind: SelectionKind, }, Update { column: u16, row: u16, side: SelectionSide, }, Clear, } #[derive(Debug, Clone, Serialize, Deserialize)] // Hello and Closing also retain their v1 wire representation during upgrades. pub enum ServerMessage { Hello { version: u32, server_pid: u32 }, Snapshot(Snapshot), Clipboard(String), Error(String), Pong, Closing, Connected { session: SessionId }, Sessions(Vec), DetachedRemote(DetachedRemote), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Snapshot { /// This session and the other sessions contributing tabs to its layout. pub lineage: Vec, pub revision: u64, pub tabs: Vec, pub active_tab: TabId, /// Only expanded panes in the active tab are transferred. Every pane remains live on the server. pub panes: Vec, } impl Snapshot { pub fn active_tab(&self) -> Option<&TabInfo> { self.tabs.iter().find(|tab| tab.id == self.active_tab) } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TabInfo { pub id: TabId, /// SSH destination for a tab mounted from another host. pub remote: Option, /// Effective display name: manual override, then the selected pane's name. pub title: String, pub manual_title: Option, /// All pane IDs, flattened in column/stack order. pub panes: Vec, pub active_pane: PaneId, /// Side-by-side columns; each expands one of its vertically ordered panes. pub stacks: Vec, } impl TabInfo { pub fn is_connecting(&self) -> bool { self.remote.is_some() && self.panes.is_empty() && self.stacks.is_empty() && self.active_pane == 0 } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StackInfo { pub panes: Vec, pub active_pane: PaneId, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StackPaneInfo { pub id: PaneId, pub title: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaneSnapshot { pub id: PaneId, /// Effective display name: manual override, program title, then CWD. pub title: String, pub manual_title: Option, pub cwd: String, pub columns: u16, pub lines: u16, pub cell_width: u16, pub cell_height: u16, pub cells: Vec, pub selected: Vec, pub colors: Vec>, pub cursor: Cursor, pub display_offset: u32, pub mode: u32, pub exited: bool, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct Cursor { pub column: u16, /// Viewport-relative row; negative or past the viewport when scrolled away. pub row: i32, pub shape: CursorKind, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum CursorKind { Block, Underline, Beam, HollowBlock, Hidden, } impl From for CursorKind { fn from(shape: CursorShape) -> Self { match shape { CursorShape::Block => Self::Block, CursorShape::Underline => Self::Underline, CursorShape::Beam => Self::Beam, CursorShape::HollowBlock => Self::HollowBlock, CursorShape::Hidden => Self::Hidden, } } } impl From for CursorShape { fn from(shape: CursorKind) -> Self { match shape { CursorKind::Block => Self::Block, CursorKind::Underline => Self::Underline, CursorKind::Beam => Self::Beam, CursorKind::HollowBlock => Self::HollowBlock, CursorKind::Hidden => Self::Hidden, } } } /// Little-endian u32 byte length followed by bounded bincode 1.3 payload. pub fn write_message(writer: &mut impl Write, message: &impl Serialize) -> Result<()> { let bytes = bincode::DefaultOptions::new() .with_fixint_encoding() .with_limit(MAX_MESSAGE_BYTES as u64) .serialize(message) .context("encode protocol message")?; if bytes.len() > MAX_MESSAGE_BYTES { bail!("protocol message is too large"); } writer.write_all(&(bytes.len() as u32).to_le_bytes())?; writer.write_all(&bytes)?; writer.flush()?; Ok(()) } pub fn read_message(reader: &mut impl Read) -> Result { let mut length = [0; 4]; reader .read_exact(&mut length) .context("read protocol frame length")?; let length = u32::from_le_bytes(length) as usize; if length == 0 || length > MAX_MESSAGE_BYTES { bail!("invalid protocol frame length: {length}"); } let mut bytes = vec![0; length]; reader .read_exact(&mut bytes) .context("read protocol frame")?; bincode::DefaultOptions::new() .with_fixint_encoding() .with_limit(MAX_MESSAGE_BYTES as u64) .reject_trailing_bytes() .deserialize(&bytes) .context("decode protocol message") } #[cfg(test)] mod tests { use super::*; #[test] fn legacy_shutdown_handshake_retains_its_wire_representation() { fn frame(message: &impl Serialize) -> Vec { let mut bytes = Vec::new(); write_message(&mut bytes, message).unwrap(); bytes } // These literal frames are from protocol v1. The upgrade path only // exchanges Hello, Shutdown and Closing, never versioned snapshots. let client_hello = [8, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]; let shutdown = [4, 0, 0, 0, 14, 0, 0, 0]; let server_hello = [12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0x78, 0x56, 0x34, 0x12]; let closing = [4, 0, 0, 0, 5, 0, 0, 0]; assert_eq!(frame(&ClientMessage::Hello { version: 1 }), client_hello); assert_eq!(frame(&ClientMessage::Shutdown), shutdown); assert_eq!( frame(&ServerMessage::Hello { version: 1, server_pid: 0x1234_5678, }), server_hello ); assert_eq!(frame(&ServerMessage::Closing), closing); assert!(matches!( read_message::(&mut client_hello.as_slice()).unwrap(), ClientMessage::Hello { version: 1 } )); assert!(matches!( read_message::(&mut shutdown.as_slice()).unwrap(), ClientMessage::Shutdown )); assert!(matches!( read_message::(&mut server_hello.as_slice()).unwrap(), ServerMessage::Hello { version: 1, server_pid: 0x1234_5678, } )); assert!(matches!( read_message::(&mut closing.as_slice()).unwrap(), ServerMessage::Closing )); } #[test] fn rejects_oversized_frames_before_allocating_payload() { let mut input = ((MAX_MESSAGE_BYTES + 1) as u32) .to_le_bytes() .as_slice() .to_vec(); assert!(read_message::(&mut input.as_slice()).is_err()); input = 0u32.to_le_bytes().to_vec(); assert!(read_message::(&mut input.as_slice()).is_err()); } #[test] fn frames_round_trip_and_reject_trailing_payload() { let mut bytes = Vec::new(); write_message( &mut bytes, &ClientMessage::Input { pane: 42, bytes: b"hello".to_vec(), }, ) .unwrap(); let result: ClientMessage = read_message(&mut bytes.as_slice()).unwrap(); assert!(matches!(result, ClientMessage::Input { pane: 42, bytes } if bytes == b"hello")); let len = u32::from_le_bytes(bytes[..4].try_into().unwrap()) + 1; bytes[..4].copy_from_slice(&len.to_le_bytes()); bytes.push(0); assert!(read_message::(&mut bytes.as_slice()).is_err()); } }