Files
psyTerm/src/protocol.rs
T

320 lines
8.8 KiB
Rust
Raw Normal View History

//! 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 = 2;
pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024;
pub type PaneId = u64;
pub type TabId = u64;
#[derive(Debug, Clone, Serialize, Deserialize)]
// Keep variants append-only: the shutdown command can retire an older server.
pub enum ClientMessage {
Hello {
version: u32,
},
Attach,
Input {
pane: PaneId,
bytes: Vec<u8>,
},
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<String>,
},
Split {
pane: PaneId,
cwd: Option<String>,
},
FocusTab {
tab: TabId,
},
FocusPane {
pane: PaneId,
},
ClosePane {
pane: PaneId,
},
OpenWindow {
target: Option<String>,
},
Detach,
Shutdown,
Ping,
/// Read current layout without attaching or creating a shell.
List,
/// A blank/absent name returns to program-title/CWD naming.
RenamePane {
pane: PaneId,
name: Option<String>,
},
}
#[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,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Snapshot {
pub revision: u64,
pub tabs: Vec<TabInfo>,
pub active_tab: TabId,
/// Only panes in the active tab are transferred. Every pane remains live on the server.
pub panes: Vec<PaneSnapshot>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabInfo {
pub id: TabId,
pub title: String,
pub panes: Vec<PaneId>,
pub active_pane: PaneId,
}
#[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<String>,
pub cwd: String,
pub columns: u16,
pub lines: u16,
pub cell_width: u16,
pub cell_height: u16,
pub cells: Vec<Cell>,
pub selected: Vec<bool>,
pub colors: Vec<Option<Rgb>>,
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<CursorShape> 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<CursorKind> 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<T: DeserializeOwned>(reader: &mut impl Read) -> Result<T> {
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<u8> {
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::<ClientMessage>(&mut client_hello.as_slice()).unwrap(),
ClientMessage::Hello { version: 1 }
));
assert!(matches!(
read_message::<ClientMessage>(&mut shutdown.as_slice()).unwrap(),
ClientMessage::Shutdown
));
assert!(matches!(
read_message::<ServerMessage>(&mut server_hello.as_slice()).unwrap(),
ServerMessage::Hello {
version: 1,
server_pid: 0x1234_5678,
}
));
assert!(matches!(
read_message::<ServerMessage>(&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::<ClientMessage>(&mut input.as_slice()).is_err());
input = 0u32.to_le_bytes().to_vec();
assert!(read_message::<ClientMessage>(&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::<ClientMessage>(&mut bytes.as_slice()).is_err());
}
}