A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
security: validate terminal graphics and untrusted mux payloads
RoversXe3a103e42b9f
diff --git a/codec/src/lib.rs b/codec/src/lib.rsindex bb55ca7a..f286bd34 100644--- a/codec/src/lib.rs+++ b/codec/src/lib.rs@@ -1692,7 +1692,7 @@ impl SerializedLines {/// Reconsitute hyperlinks or other attributes that were decomposed for/// serialization, and return the line data.pub fn extract_data(self) -> (Vec<(StableRowIndex, Line)>, Vec<SerializedImageCell>) {- let lines = if self.hyperlinks.is_empty() {+ let mut lines = if self.hyperlinks.is_empty() {self.lines} else {let mut lines = self.lines;@@ -1715,6 +1715,17 @@ impl SerializedLines {lines};+ // Normal wire lines carry image references in `images`, never pixel+ // buffers in cell attributes. A hostile encoder can bypass From<Vec>+ // and inject such buffers directly; discard them before any frontend+ // can see them. Referenced images are fetched and validated separately.+ for (_, line) in &mut lines {+ if line.has_hyperlinks_or_images() {+ for cell in line.cells_mut_for_attr_changes_only() {+ cell.attrs_mut().clear_images();+ }+ }+ }(lines, self.images)}}@@ -2169,6 +2180,53 @@ mod test {use super::*;use termwiz::cell::CellAttributes;+ #[test]+ fn recursive_wire_layout_is_rejected_on_a_reader_sized_stack() {+ std::thread::Builder::new().stack_size(2 * 1024 * 1024).spawn(|| {+ // Vec length 1, then an endless chain of PaneNode::Split.left.+ let bytes = vec![1u8; 10_000];+ let error = varbincode::deserialize::<ListPanesResponse, _>(&bytes[..]).unwrap_err();+ assert!(error.to_string().contains("nests deeper"));+ }).unwrap().join().unwrap();+ }++ #[test]+ fn compressed_line_wide_indices_are_bounded_by_actual_text() {+ let mut line = Line::from_text("a好", &CellAttributes::default(), 1, None);+ line.compress_for_scrollback();+ let bytes = varbincode::serialize(&line).unwrap();+ let normal: Line = varbincode::deserialize(&bytes[..]).unwrap();+ assert_eq!(normal.as_str(), line.as_str());+ let mut wire = serde_json::to_value(&line).unwrap();+ assert!(wire["cells"]["C"]["is_double_wide"].is_array());+ for index in [1_000_000_000usize, usize::MAX] {+ wire["cells"]["C"]["is_double_wide"] = serde_json::json!([index]);+ let error = serde_json::from_value::<Line>(wire.clone()).unwrap_err();+ assert!(error.to_string().contains("wide-cell index exceeds line text"));+ }+ }++ #[test]+ fn inline_image_buffers_cannot_bypass_remote_image_validation() {+ use termwiz::image::{ImageCell, ImageDataType, TextureCoordinate};+ let bad = Arc::new(ImageData::with_data(ImageDataType::Rgba8 {+ width: 512, height: 511, data: vec![0; 4], hash: ImageDataType::content_key(&[0; 4]),+ }));+ let mut attrs = CellAttributes::default();+ attrs.attach_image(Box::new(ImageCell::new(+ TextureCoordinate::new_f32(0.0, 0.0),+ TextureCoordinate::new_f32(1.0, 1.0), bad,+ )));+ let line = Line::from_text("x", &attrs, 1, None);+ let wire = SerializedLines { lines: vec![(0, line)], hyperlinks: vec![], images: vec![] };+ let encoded = varbincode::serialize(&wire).unwrap();+ let decoded: SerializedLines = varbincode::deserialize(&encoded[..]).unwrap();+ let (lines, refs) = decoded.extract_data();+ assert!(refs.is_empty());+ assert!(lines[0].1.visible_cells().all(|cell| cell.attrs().images().is_none()));+ assert_eq!(lines[0].1.as_str(), "x");+ }+#[test]fn serializing_lines_keeps_plain_lines_compressed() {let mut line = Line::from_text("hello world", &CellAttributes::default(), 1, None);diff --git a/deps/varbincode/Cargo.toml b/deps/varbincode/Cargo.tomlindex 7bb61dce..ee0b82ac 100644--- a/deps/varbincode/Cargo.toml+++ b/deps/varbincode/Cargo.toml@@ -1,7 +1,9 @@-# Vendored from crates.io varbincode 0.1.0 (Wez Furlong, MIT) with one-# change: a declared byte/string length no longer allocates up front, so a+# Vendored from crates.io varbincode 0.1.0 (Wez Furlong, MIT) with bounded+# decoding: a declared byte/string length no longer allocates up front, so a# corrupt or hostile length costs only the bytes actually present in the-# stream instead of aborting the process on allocation failure.+# stream instead of aborting the process on allocation failure; and values+# may nest only so deep, so a stream of nested tags cannot run the decoder+# off its stack; aggregate decoded allocation is also bounded.[package]name = "varbincode"version = "0.1.0"diff --git a/deps/varbincode/src/de.rs b/deps/varbincode/src/de.rsindex 224ab6ed..717fa25a 100644--- a/deps/varbincode/src/de.rs+++ b/deps/varbincode/src/de.rs@@ -2,13 +2,42 @@ use crate::error::{Error, Result};use byteorder::{LittleEndian, ReadBytesExt};use serde::de::IntoDeserializer;+/// How deep a value may nest. Every struct, enum, sequence, map and+/// newtype costs a level, so a real message sits well under a hundred;+/// the limit is there because recursion is on the reader thread's stack+/// and the wire could otherwise ask for a million levels.+const MAX_DEPTH: usize = 128;+const MAX_DECODED_BYTES: usize = 256 * 1024 * 1024;+pub struct Deserializer<'a> {reader: &'a mut std::io::Read,+ depth: usize,+ remaining_bytes: usize,}impl<'a> Deserializer<'a> {pub fn new(reader: &'a mut std::io::Read) -> Self {- Self { reader }+ Self { reader, depth: 0, remaining_bytes: MAX_DECODED_BYTES }+ }++ fn charge(&mut self, bytes: usize) -> Result<()> {+ self.remaining_bytes = self.remaining_bytes.checked_sub(bytes)+ .ok_or_else(|| Error::Message("decoded value exceeds allocation budget".into()))?;+ Ok(())+ }++ fn enter(&mut self) -> Result<()> {+ self.depth += 1;+ if self.depth > MAX_DEPTH {+ return Err(Error::Message(format!(+ "value nests deeper than {MAX_DEPTH} levels"+ )));+ }+ Ok(())+ }++ fn leave(&mut self) {+ self.depth = self.depth.saturating_sub(1);}fn read_signed(&mut self) -> Result<i64> {@@ -21,6 +50,7 @@ impl<'a> Deserializer<'a> {fn read_vec(&mut self) -> Result<Vec<u8>> {let len: usize = serde::Deserialize::deserialize(&mut *self)?;+ self.charge(len)?;// Grow as the bytes arrive rather than trusting the declared// length: the stream, not the header, bounds the allocation.const STEP: usize = 64 * 1024;@@ -190,17 +220,23 @@ impl<'de, 'a, 'b> serde::Deserializer<'de> for &'a mut Deserializer<'b> {whereV: serde::de::Visitor<'de>,{- visitor.visit_enum(self)+ self.enter()?;+ let value = visitor.visit_enum(&mut *self);+ self.leave();+ value}fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value>whereV: serde::de::Visitor<'de>,{- visitor.visit_seq(Access {- deserializer: self,+ self.enter()?;+ let value = visitor.visit_seq(Access {+ deserializer: &mut *self,len,- })+ });+ self.leave();+ value}fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>@@ -210,7 +246,12 @@ impl<'de, 'a, 'b> serde::Deserializer<'de> for &'a mut Deserializer<'b> {let value: u8 = serde::de::Deserialize::deserialize(&mut *self)?;match value {0 => visitor.visit_none(),- 1 => visitor.visit_some(&mut *self),+ 1 => {+ self.enter()?;+ let result = visitor.visit_some(&mut *self);+ self.leave();+ result+ }v => Err(Error::InvalidTagEncoding(v as usize)),}}@@ -230,10 +271,13 @@ impl<'de, 'a, 'b> serde::Deserializer<'de> for &'a mut Deserializer<'b> {{let len = serde::Deserialize::deserialize(&mut *self)?;- visitor.visit_map(Access {- deserializer: self,+ self.enter()?;+ let value = visitor.visit_map(Access {+ deserializer: &mut *self,len,- })+ });+ self.leave();+ value}fn deserialize_struct<V>(@@ -259,7 +303,10 @@ impl<'de, 'a, 'b> serde::Deserializer<'de> for &'a mut Deserializer<'b> {whereV: serde::de::Visitor<'de>,{- visitor.visit_newtype_struct(self)+ self.enter()?;+ let value = visitor.visit_newtype_struct(&mut *self);+ self.leave();+ value}fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value>@@ -307,6 +354,7 @@ impl<'de, 'a, 'b> serde::de::SeqAccess<'de> for Access<'a, 'b> {{if self.len > 0 {self.len -= 1;+ self.deserializer.charge(std::mem::size_of::<T::Value>().max(1))?;let value = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;Ok(Some(value))} else {@@ -315,7 +363,7 @@ impl<'de, 'a, 'b> serde::de::SeqAccess<'de> for Access<'a, 'b> {}fn size_hint(&self) -> Option<usize> {- Some(self.len)+ Some(self.len.min(4096))}}@@ -328,6 +376,7 @@ impl<'de, 'a, 'b> serde::de::MapAccess<'de> for Access<'a, 'b> {{if self.len > 0 {self.len -= 1;+ self.deserializer.charge(std::mem::size_of::<K::Value>().max(1))?;let key = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;Ok(Some(key))} else {@@ -339,12 +388,13 @@ impl<'de, 'a, 'b> serde::de::MapAccess<'de> for Access<'a, 'b> {whereV: serde::de::DeserializeSeed<'de>,{+ self.deserializer.charge(std::mem::size_of::<V::Value>().max(1))?;let value = serde::de::DeserializeSeed::deserialize(seed, &mut *self.deserializer)?;Ok(value)}fn size_hint(&self) -> Option<usize> {- Some(self.len)+ Some(self.len.min(4096))}}@@ -390,3 +440,39 @@ impl<'de, 'a, 'b> serde::de::VariantAccess<'de> for &'a mut Deserializer<'b> {serde::de::Deserializer::deserialize_tuple(self, fields.len(), visitor)}}++#[cfg(test)]+mod security_tests {+ use super::*;++ fn limited<T: serde::de::DeserializeOwned>(data: &[u8], limit: usize) -> Result<T> {+ let mut input = data;+ let mut decoder = Deserializer::new(&mut input);+ decoder.remaining_bytes = limit;+ T::deserialize(&mut decoder)+ }++ #[test]+ fn flat_and_nested_collections_share_the_allocation_budget() {+ let flat = crate::serialize(&vec![String::new(); 100]).unwrap();+ assert!(limited::<Vec<String>>(&flat, 128).is_err());+ let nested = crate::serialize(&vec![vec![String::new(); 4]; 10]).unwrap();+ assert!(limited::<Vec<Vec<String>>>(&nested, 256).is_err());+ let normal = vec!["one".to_string(), "two".to_string()];+ let bytes = crate::serialize(&normal).unwrap();+ assert_eq!(limited::<Vec<String>>(&bytes, 256).unwrap(), normal);+ let map: std::collections::BTreeMap<u32, String> = (0..100).map(|n| (n, String::new())).collect();+ assert!(limited::<std::collections::BTreeMap<u32, String>>(&crate::serialize(&map).unwrap(), 128).is_err());+ }++ #[test]+ fn recursive_option_values_are_bounded_on_a_reader_sized_stack() {+ #[derive(serde_derive::Deserialize)]+ struct Chain(#[allow(dead_code)] Option<Box<Chain>>);+ // Every byte is Some, avoiding an enormous in-memory source fixture.+ let bytes = vec![1u8; 10_000];+ std::thread::Builder::new().stack_size(2 * 1024 * 1024).spawn(move || {+ assert!(crate::deserialize::<Chain, _>(&bytes[..]).is_err());+ }).unwrap().join().unwrap();+ }+}diff --git a/deps/varbincode/src/lib.rs b/deps/varbincode/src/lib.rsindex 026a3140..b274998e 100644--- a/deps/varbincode/src/lib.rs+++ b/deps/varbincode/src/lib.rs@@ -1,4 +1,4 @@-// Vendored: see Cargo.toml. Kept as upstream wrote it apart from `read_vec`.+// Vendored: see Cargo.toml for decoder resource limits.#![allow(bare_trait_objects, deprecated, unused_attributes, unused_mut, dropping_references)]//! varbincode is a binary serialization format that uses variable//! length encoding for integer values, which typically results indiff --git a/mux/src/tab.rs b/mux/src/tab.rsindex 640ae833..29347ad5 100644--- a/mux/src/tab.rs+++ b/mux/src/tab.rs@@ -946,8 +946,8 @@ fn cell_dimensions(size: &TerminalSize) -> TerminalSize {TerminalSize {rows: 1,cols: 1,- pixel_width: size.pixel_width / size.cols,- pixel_height: size.pixel_height / size.rows,+ pixel_width: size.pixel_width / size.cols.max(1),+ pixel_height: size.pixel_height / size.rows.max(1),dpi: size.dpi,}}diff --git a/term/src/terminalstate/kitty.rs b/term/src/terminalstate/kitty.rsindex 41bfc969..77bc6355 100644--- a/term/src/terminalstate/kitty.rs+++ b/term/src/terminalstate/kitty.rs@@ -505,6 +505,12 @@ impl TerminalState {// once and re-placed on every redraw must outlive frames streamed// after it, or the client's next `a=p` fails on a missing id.self.kitty_img.mark_newest(image_id);+ // A placement spanning more cells than the grid has is clamped to+ // the grid: cells are assigned one column at a time below, and a+ // count near u32::MAX would allocate them until the process died,+ // holding the terminal lock the whole way.+ let grid_cols = self.screen().physical_cols.max(1);+ let grid_rows = self.screen().physical_rows.max(1);let info = self.assign_image_to_cells(ImageAttachParams {image_width,image_height,@@ -517,8 +523,8 @@ impl TerminalState {data: img,style: ImageAttachStyle::Kitty,z_index: placement.z_index.unwrap_or(0),- columns: placement.columns.map(|x| x as usize),- rows: placement.rows.map(|x| x as usize),+ columns: placement.columns.map(|x| (x as usize).min(grid_cols)),+ rows: placement.rows.map(|x| (x as usize).min(grid_rows)),image_id: Some(image_id),placement_id: placement.placement_id,do_not_move_cursor: placement.do_not_move_cursor,@@ -995,6 +1001,15 @@ impl TerminalState {}log::trace!("Query Response: {}", message);+ // The message can carry text the application chose (a shm name, a+ // file path in an error), and this reply is written to the pty as+ // if typed. A control byte in it would be a keystroke in the user's+ // shell, so only printable ASCII goes out, and not much of it.+ let message: String = message+ .chars()+ .filter(|c| (' '..='~').contains(c))+ .take(256)+ .collect();match (image_id, image_no) {(Some(id), Some(no)) => {diff --git a/term/src/terminalstate/sixel.rs b/term/src/terminalstate/sixel.rsindex e2224837..f3bbc3ec 100644--- a/term/src/terminalstate/sixel.rs+++ b/term/src/terminalstate/sixel.rs@@ -62,7 +62,11 @@ impl TerminalState {}SixelData::Repeat { repeat_count, data } => {- for _ in 0..*repeat_count {+ // Past the right edge every repeat is a no-op, and a+ // count near u32::MAX would spin here for seconds+ // holding the terminal lock. Emit only what fits.+ let repeat = (*repeat_count).min(width.saturating_sub(x));+ for _ in 0..repeat {emit_sixel(data, &foreground_color, x, y);x += 1;}diff --git a/term/src/test/graphics.rs b/term/src/test/graphics.rsindex 7503c688..a5d7981a 100644--- a/term/src/test/graphics.rs+++ b/term/src/test/graphics.rs@@ -1256,3 +1256,45 @@ fn a_frame_for_a_placement_on_the_other_screen_dirties_that_screen() {"the primary-screen row holding the placement must be marked changed");}++#[test]+fn security_sixel_repeat_is_bounded_by_the_declared_image() {+ let mut terminal = term(640, 384, false);+ for repeat in ["!4294967295?", "!?"] {+ terminal.advance_bytes(format!("\x1bPq\"1;1;1;1{repeat}\x1b\\"));+ }+ terminal.advance_bytes("still alive");+}++#[test]+fn security_kitty_reply_filters_control_bytes_for_all_transmits() {+ use wezterm_escape_parser::apc::{KittyImage, KittyImageData};+ use wezterm_escape_parser::Action;+ let (mut terminal, tap) = term_with_tap(640, 384);+ for action in ["q", "t", "T"] {+ let mut image = KittyImage::parse_apc(format!("Ga={action},i=42,f=32,s=1,v=1;AAAAAA==").as_bytes()).unwrap();+ let data = KittyImageData::MaterializedError {+ kind: std::io::ErrorKind::InvalidInput,+ message: format!("bad\n\r\x1b[31m\x07\x7f非ASCII{}", "x".repeat(400)),+ };+ match &mut image {+ KittyImage::Query { transmit, .. }+ | KittyImage::TransmitData { transmit, .. }+ | KittyImage::TransmitDataAndDisplay { transmit, .. } => transmit.data = data,+ _ => unreachable!(),+ }+ terminal.perform_actions(vec![Action::KittyImage(Box::new(image))]);+ }+ let replies = drain(&mut terminal, &tap);+ assert_eq!(replies.matches("\x1b_Gi=42;").count(), 3);+ for reply in replies.split("\x1b_Gi=42;").skip(1) {+ let text = reply.strip_suffix("\x1b\\").unwrap();+ assert!(text.len() <= 256);+ assert!(text.bytes().all(|b| (b' '..=b'~').contains(&b)));+ }+}++#[test]+fn security_kitty_placement_caps_wire_cell_counts() {+ kitty(640, 384, "\x1b_Ga=p,i=1,c=4294967295,r=4294967295\x1b\\");+}diff --git a/thinkterm-session/src/hydrate.rs b/thinkterm-session/src/hydrate.rsindex 8a97dae5..e1b96e1c 100644--- a/thinkterm-session/src/hydrate.rs+++ b/thinkterm-session/src/hydrate.rs@@ -151,7 +151,7 @@ async fn get_image_cell<H: SessionHost>(/// second Arc under the same hash would leave the painter on the old one/// for good. A whole image the copy still will not take (it would shrink/// under a painter) leaves the copy as it is.-async fn fetch_image<H: SessionHost>(+pub(crate) async fn fetch_image<H: SessionHost>(host: &H,held: Option<Arc<ImageData>>,request: GetImageCell,@@ -185,6 +185,15 @@ async fn fetch_image<H: SessionHost>(frames_from,..}) => {+ // The wire built this field by field; nothing between it+ // and the GPU checks the buffer against the size it claims.+ if !fresh.data().is_well_formed_tail(frames_from) {+ log::warn!(+ "the server sent an image whose pixel data does not match its \+ declared size; ignoring it"+ );+ return None;+ }if fresh.hash() != whole.data_hash {// Not the picture asked for but the one now in the cell:// a newer frame. Its own copy, never merged into thediff --git a/thinkterm-session/src/images.rs b/thinkterm-session/src/images.rsindex 37a186fa..11d7a2d9 100644--- a/thinkterm-session/src/images.rs+++ b/thinkterm-session/src/images.rs@@ -21,6 +21,14 @@ pub fn frame_count(data: &ImageDataType) -> u32 {}}+fn image_size(data: &ImageDataType) -> Option<(u32, u32)> {+ match data {+ ImageDataType::Rgba8 { width, height, .. }+ | ImageDataType::AnimRgba8 { width, height, .. } => Some((*width, *height)),+ _ => None,+ }+}+/// Bring `held` up to date from `fetched`, in place. `frames_from` is 0/// when `fetched` is the whole image, otherwise the index its frames start/// at, in which case its durations and hashes cover every frame and the@@ -41,6 +49,9 @@ pub fn merge_into(// order cannot cross anyone else's.let mut mine = held.data();let mut theirs = fetched.data();+ if !mine.is_well_formed() || !theirs.is_well_formed_tail(frames_from) {+ return false;+ }let merged = if frames_from == 0 {if frame_count(&theirs) < frame_count(&mine) {@@ -75,7 +86,10 @@ pub fn merge_into() => from == 1 && hashes.len() == 1 + tail.len() && hashes[0] == *hash,_ => false,};- if !matches {+ // The tail's frames are appended to the held ones and drawn at+ // the held size; a tail of another size would be frames of the+ // wrong length under it.+ if !matches || image_size(&theirs) != image_size(&mine) {return false;}// `theirs` is taken apart first; `mine` is emptied last and fordiff --git a/thinkterm-session/src/pane.rs b/thinkterm-session/src/pane.rsindex 45e52121..99da9cc4 100644--- a/thinkterm-session/src/pane.rs+++ b/thinkterm-session/src/pane.rs@@ -725,6 +725,15 @@ impl<H: SessionHost> PaneSession<H> {delta: GetPaneRenderChangesResponse,bonus_lines: Vec<(StableRowIndex, Line)>,) {+ // Reject impossible geometry before it reaches cache seeding or any+ // frontend. Clamping only dirty ranges leaves those other walks open.+ if delta.dimensions.viewport_rows > 10_000+ || delta.dimensions.cols > 10_000+ || delta.dimensions.physical_top.checked_add(delta.dimensions.viewport_rows as StableRowIndex).is_none()+ {+ log::warn!("ignoring render update with invalid pane dimensions");+ return;+ }log::trace!("apply_changes_to_surface local={} remote={}",self.host_pane_id,@@ -751,9 +760,40 @@ impl<H: SessionHost> PaneSession<H> {|| render_dimensions_match_terminal_size(delta.dimensions, preview.size)});+ // Every row of every dirty range is walked below under the lock,+ // and the ranges come off the wire, so the walk has to be bounded+ // by something the wire does not set. Below the viewport's top the+ // bound is a viewport taller than any screen; above it, the walk+ // only marks cached rows stale, and past as many rows as the cache+ // holds that is the same work as marking the whole cache stale, so+ // the walk stops there and the one sweep takes over.+ const MAX_VIEWPORT_ROWS: usize = 10_000;+ let physical_top = delta.dimensions.physical_top;+ let row_end = physical_top.saturating_add(+ delta.dimensions.viewport_rows.min(MAX_VIEWPORT_ROWS) as StableRowIndex,+ );+ let cache_rows = st.lines.cap().get() as StableRowIndex;+ let walk_start = physical_top+ .saturating_sub(cache_rows)+ .max(delta.dimensions.scrollback_top);let mut dirty = RangeSet::new();+ let mut sweep_cache = false;for r in delta.dirty_lines {- dirty.add_range(r.clone());+ let lo = r.start.max(delta.dimensions.scrollback_top);+ let hi = r.end.min(row_end);+ if lo >= hi {+ continue;+ }+ if lo < walk_start {+ sweep_cache = true;+ }+ let lo = lo.max(walk_start);+ if lo < hi {+ dirty.add_range(lo..hi);+ }+ }+ if sweep_cache {+ invalidate_line_entries(&mut st.lines, true);}if delta.cursor_position != st.cursor_position {dirty.add(st.cursor_position.y);@@ -1312,6 +1352,7 @@ mod tests {asked: RefCell<Vec<&'static str>>,rows_asked: Cell<usize>,image: RefCell<Option<Arc<ImageData>>>,+ image_frames_from: Cell<u32>,line_reply_ready: RefCell<Option<Rc<Cell<bool>>>>,image_reply_ready: RefCell<Option<Rc<Cell<bool>>>>,}@@ -1372,7 +1413,7 @@ mod tests {pane_id: req.pane_id,data: self.image.borrow().clone(),data_generation: req.data_generation,- frames_from: 0,+ frames_from: self.image_frames_from.get(),}),_ => Pdu::UnitResponse(UnitResponse {}),};@@ -1512,6 +1553,61 @@ mod tests {}}+ #[test]+ fn render_updates_reject_unbounded_geometry_and_bound_dirty_ranges() {+ let (host, session) = session(&[]);+ let mut huge = delta(1, false, false);+ huge.dimensions.physical_top = 1;+ huge.dimensions.viewport_rows = usize::MAX;+ session.queue_render_delta(huge);+ host.spawner.run_all();+ assert_eq!(session.state().dimensions, dims());+ let mut dirty = delta(2, false, false);+ dirty.dirty_lines = vec![0..isize::MAX];+ session.queue_render_delta(dirty);+ host.spawner.run_all();+ assert_eq!(session.state().seqno, 2);+ assert!(session.state().lines.len() <= 256);+ }++ #[test]+ fn image_hydration_accepts_animation_tails_and_rejects_bad_pixels() {+ use termwiz::image::ImageDataType;+ let (host, _) = session(&[]);+ let held = Arc::new(ImageData::with_data(+ ImageDataType::new_single_frame_content_hashed(1, 1, vec![1; 4]),+ ));+ let first_hash = match &*held.data() {+ ImageDataType::Rgba8 { hash, .. } => *hash,+ _ => unreachable!(),+ };+ let request = codec::GetImageCell {+ pane_id: 9, line_idx: 0, cell_idx: 0, data_hash: held.hash(),+ data_generation: 7, have_frames: 1,+ };+ for (from, frames) in [(1, vec![vec![2; 4]]), (2, vec![])] {+ *host.link.image.borrow_mut() = Some(Arc::new(ImageData::with_data_and_hash(+ ImageDataType::AnimRgba8 {+ width: 1, height: 1,+ durations: vec![std::time::Duration::from_millis(40); 2],+ frames, hashes: vec![first_hash, [2; 32]],+ }, held.hash(),+ )));+ host.link.image_frames_from.set(from);+ let fetched = spin_on(crate::hydrate::fetch_image(&*host, Some(held.clone()), request.clone())).unwrap();+ assert!(Arc::ptr_eq(&held, &fetched));+ assert_eq!(crate::images::frame_count(&held.data()), 2);+ }+ let bad = Arc::new(ImageData::with_data_and_hash(+ ImageDataType::Rgba8 { width: 512, height: 511, data: vec![0; 4], hash: [0; 32] },+ held.hash(),+ ));+ *host.link.image.borrow_mut() = Some(bad);+ host.link.image_frames_from.set(0);+ assert!(spin_on(crate::hydrate::fetch_image(&*host, Some(held.clone()), request)).is_none());+ assert!(held.data().is_well_formed());+ }+/// R1: `prime_frontend_geometry` fetches through the same lock it/// holds. It must neither deadlock nor report ready before the rows/// arrived, and report ready once they have.diff --git a/wezterm-cell/src/image.rs b/wezterm-cell/src/image.rsindex 9923028f..3d487367 100644--- a/wezterm-cell/src/image.rs+++ b/wezterm-cell/src/image.rs@@ -306,6 +306,54 @@ pub const CONTENT_HASH_MAX: usize = 1024 * 1024;const NONCE_KEY_MARKER: [u8; 8] = [0x54, 0x54, 0x4e, 0x43, 0x9d, 0x1b, 0x7a, 0xe4];impl ImageDataType {+ /// Whether the pixel buffers match the dimensions they claim. A value+ /// built by this crate always does; one that arrived over a wire was+ /// built field by field, so `width * height * 4` is a claim until it+ /// is checked, and a renderer that takes it as a buffer length reads+ /// past the buffer.+ pub fn is_well_formed(&self) -> bool {+ self.is_well_formed_tail(0)+ }++ /// Wire animation deltas carry only frames from `frames_from` onward,+ /// but retain the durations and hashes for the entire animation.+ pub fn is_well_formed_tail(&self, frames_from: u32) -> bool {+ fn frame_len(width: u32, height: u32) -> Option<usize> {+ if width == 0 || height == 0 {+ return None;+ }+ (width as usize)+ .checked_mul(height as usize)?+ .checked_mul(4)+ }+ match self {+ Self::EncodedFile(_) => frames_from == 0,+ #[cfg(feature = "std")]+ Self::EncodedLease(_) => frames_from == 0,+ Self::Rgba8 {+ data,+ width,+ height,+ ..+ } => frames_from == 0 && frame_len(*width, *height) == Some(data.len()),+ Self::AnimRgba8 {+ width,+ height,+ durations,+ frames,+ hashes,+ } => {+ !hashes.is_empty()+ && frames.len().checked_add(frames_from as usize) == Some(hashes.len())+ && hashes.len() == durations.len()+ && match frame_len(*width, *height) {+ Some(len) => frames.iter().all(|frame| frame.len() == len),+ None => false,+ }+ }+ }+ }+pub fn new_single_frame(width: u32, height: u32, data: Vec<u8>) -> Self {let hash = Self::content_key(&data);Self::new_single_frame_with_hash(width, height, data, hash)diff --git a/wezterm-escape-parser/src/apc.rs b/wezterm-escape-parser/src/apc.rsindex 8c8d6fb2..9b07952e 100644--- a/wezterm-escape-parser/src/apc.rs+++ b/wezterm-escape-parser/src/apc.rs@@ -211,6 +211,11 @@ impl KittyImageData {/// chunk accumulation rules.#[cfg(feature = "kitty-shm")]pub fn materialize_external_source(&mut self) {+ self.materialize_external_source_capped(MAX_IMAGE_DATA_BYTES);+ }++ #[cfg(feature = "kitty-shm")]+ fn materialize_external_source_capped(&mut self, cap: u64) {if !matches!(self,Self::File { .. } | Self::TemporaryFile { .. } | Self::SharedMem { .. }@@ -219,7 +224,7 @@ impl KittyImageData {}let source = core::mem::replace(self, Self::DirectBin(Vec::new()));- *self = match source.load_data() {+ *self = match source.load_data_capped(cap) {Ok(data) => Self::DirectBin(data),Err(err) => Self::MaterializedError {kind: err.kind(),@@ -234,6 +239,11 @@ impl KittyImageData {/// of the read operaiton.#[cfg(feature = "kitty-shm")]pub fn load_data(self) -> std::io::Result<Vec<u8>> {+ self.load_data_capped(MAX_IMAGE_DATA_BYTES)+ }++ #[cfg(feature = "kitty-shm")]+ fn load_data_capped(self, cap: u64) -> std::io::Result<Vec<u8>> {match self {Self::Direct(data) => base64_decode(data).or_else(|err| {Err(std::io::Error::new(@@ -246,7 +256,7 @@ impl KittyImageData {path,data_offset,data_size,- } => read_from_file(&path, data_offset, data_size),+ } => read_from_file_capped(&path, data_offset, data_size, cap),Self::TemporaryFile {path,data_offset,@@ -255,7 +265,7 @@ impl KittyImageData {// Read first, but clean up no matter how the read went: an// early error return here (a refused oversized file included)// would leave the temporary file behind on disk.- let result = read_from_file(&path, data_offset, data_size);+ let result = read_from_file_capped(&path, data_offset, data_size, cap);remove_temporary_file(&path);result}@@ -263,7 +273,7 @@ impl KittyImageData {name,data_offset,data_size,- } => read_shared_memory_data(&name, data_offset, data_size),+ } => read_shared_memory_data(&name, data_offset, data_size, cap),Self::MaterializedError { kind, message } => Err(std::io::Error::new(kind, message)),}}@@ -361,18 +371,20 @@ impl KittyImageData {}/// Materialize the external kitty payloads of one flush, newest first.-/// Once `budget` bytes have been read, an older payload is discarded unread-/// if -- and only if -- a newer transmit in the same flush carries the same-/// image id (`i=`): that older picture is replaced before anything can be-/// drawn from it. A parser that fell behind a frame stream can find-/// hundreds of frame escapes in a single read; reading all of them holds-/// gigabytes for pictures the next frame overwrites, and the frames a-/// viewer will actually see are the last ones in the batch.+/// Once `budget` bytes have been read, every older payload is discarded+/// unread. A parser that fell behind a frame stream can find hundreds of+/// frame escapes in a single read; reading all of them holds gigabytes for+/// pictures the next frame overwrites, and the frames a viewer will+/// actually see are the last ones in the batch. Newest first is what keeps+/// those.///-/// Anything not superseded that way -- distinct ids, id-less transmits, a-/// gallery of separate pictures, queries, animation frames -- is read even-/// past the budget: the budget bounds the waste, never the protocol.-/// Returns (bytes materialized, actions discarded).+/// The budget is a ceiling on what one flush can hold, not only a filter+/// for superseded frames: a batch of distinct pictures past it is also cut,+/// because the process hosting the pane has to survive whatever a program+/// prints, and 60 bytes of escapes can name gigabytes of shared memory. A+/// discarded transmit is answered with an error, so a client counting+/// replies is not left waiting. Returns (bytes materialized, actions+/// discarded).#[cfg(feature = "kitty-shm")]pub fn materialize_kitty_actions_newest_first(actions: &mut [crate::Action],@@ -389,11 +401,17 @@ pub fn materialize_kitty_actions_newest_first(let replaces_id = image.replacing_transmit_image_id();if image.has_external_data_source() {let superseded = replaces_id.map_or(false, |id| newer_ids.contains(&id));- if remaining == 0 && superseded {- image.discard_data_sources("superseded by a newer frame in the same batch");+ if remaining == 0 {+ image.discard_data_sources(if superseded {+ "superseded by a newer frame in the same batch"+ } else {+ "over the budget for external payloads in one flush"+ });discarded += 1;} else {- image.materialize_data_sources();+ if !image.materialize_data_sources_capped(remaining as u64) {+ discarded += 1;+ }let len = image.materialized_len();materialized += len;remaining = remaining.saturating_sub(len);@@ -462,15 +480,6 @@ fn open_regular_file(path: &str) -> std::io::Result<(std::fs::File, u64)> {Ok((f, metadata.len()))}-#[cfg(feature = "kitty-shm")]-fn read_from_file(- path: &str,- data_offset: Option<u32>,- data_size: Option<u32>,-) -> std::io::Result<Vec<u8>> {- read_from_file_capped(path, data_offset, data_size, MAX_IMAGE_DATA_BYTES)-}-/// The cap is a parameter so the tests can exercise it without a/// hundred-megabyte fixture.#[cfg(feature = "kitty-shm")]@@ -563,6 +572,7 @@ fn read_shared_memory_data(name: &str,data_offset: Option<u32>,data_size: Option<u32>,+ cap: u64,) -> std::result::Result<std::vec::Vec<u8>, std::io::Error> {use nix::sys::mman::{shm_open, shm_unlink};use std::fs::File;@@ -605,11 +615,11 @@ fn read_shared_memory_data(read_exactly(&mut f,len,- MAX_IMAGE_DATA_BYTES,+ cap,available.map(|available| available.min(u64::from(len))),)?} else {- read_to_end_capped(&mut f, MAX_IMAGE_DATA_BYTES, available)?+ read_to_end_capped(&mut f, cap, available)?};Ok(data)@@ -628,6 +638,7 @@ fn read_shared_memory_data(_name: &str,_data_offset: Option<u32>,_data_size: Option<u32>,+ _cap: u64,) -> std::result::Result<std::vec::Vec<u8>, std::io::Error> {Err(std::io::ErrorKind::Unsupported.into())}@@ -678,6 +689,7 @@ mod win {name: &str,data_offset: Option<u32>,data_size: Option<u32>,+ cap: u64,) -> std::result::Result<std::vec::Vec<u8>, std::io::Error> {let wide_name = wide_string(&name);@@ -738,6 +750,9 @@ mod win {if let Some(val) = data_size {size = size.min(val as usize);}+ if size as u64 > cap {+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "shared memory image exceeds the byte limit"));+ }let buf_slice = unsafe { std::slice::from_raw_parts(shm.buf.add(offset), size) };let data = buf_slice.to_vec();@@ -1480,6 +1495,20 @@ impl KittyImage {}}+ #[cfg(feature = "kitty-shm")]+ fn materialize_data_sources_capped(&mut self, cap: u64) -> bool {+ match self {+ Self::TransmitData { transmit, .. }+ | Self::TransmitDataAndDisplay { transmit, .. }+ | Self::Query { transmit, .. }+ | Self::TransmitFrame { transmit, .. } => {+ transmit.data.materialize_external_source_capped(cap.min(MAX_IMAGE_DATA_BYTES));+ !matches!(transmit.data, KittyImageData::MaterializedError { .. })+ }+ _ => true,+ }+ }+pub fn verbosity(&self) -> KittyImageVerbosity {match self {Self::TransmitData { verbosity, .. } => *verbosity,@@ -2009,9 +2038,9 @@ mod temp_file_test {actions.push(temp_file_transmit(&file, Some(1)));}- // 150 bytes: the newest two frames (100 each) are read, the oldest+ // 200 bytes: the newest two frames (100 each) are read, the oldest// is discarded without a read -- but its temporary file still goes.- let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 150);+ let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 200);assert_eq!((bytes, discarded), (200, 1));for file in &files {assert!(!file.exists(), "every temporary file is unlinked");@@ -2053,10 +2082,9 @@ mod temp_file_test {}#[test]- fn a_gallery_of_distinct_pictures_is_read_past_the_budget() {+ fn a_gallery_of_distinct_pictures_is_cut_at_the_budget_newest_first() {// Three separate pictures -- two ids and one id-less -- coalesced- // into one flush. None replaces another, so the budget must not- // cost the viewer any of them.+ // into one flush. Within the budget every one of them is read.let dir = ScratchDir::in_temp("gallery");let files: Vec<_> = (0..3).map(|i| dir.file(&format!("pic-{i}.rgba"), &[i as u8; 100]))@@ -2066,17 +2094,37 @@ mod temp_file_test {temp_file_transmit(&files[1], Some(2)),temp_file_transmit(&files[2], None),];- let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 150);+ let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 300);assert_eq!((bytes, discarded), (300, 0));for (i, action) in actions.iter().enumerate() {assert_eq!(transmit_payload(action).unwrap(), vec![i as u8; 100]);}++ // Past it the oldest are cut, distinct or not: the budget is the+ // ceiling on what one flush may hold, and a cut transmit answers+ // with an error rather than silence.+ let files: Vec<_> = (0..3)+ .map(|i| dir.file(&format!("big-{i}.rgba"), &[i as u8; 100]))+ .collect();+ let mut actions = vec![+ temp_file_transmit(&files[0], Some(1)),+ temp_file_transmit(&files[1], Some(2)),+ temp_file_transmit(&files[2], None),+ ];+ let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 150);+ assert_eq!((bytes, discarded), (100, 2));+ assert_eq!(transmit_payload(&actions[2]).unwrap(), vec![2u8; 100]);+ assert_eq!(transmit_payload(&actions[1]).unwrap_err().kind(), std::io::ErrorKind::InvalidData);+ assert_eq!(+ transmit_payload(&actions[0]).unwrap_err().kind(),+ std::io::ErrorKind::InvalidData+ );}#[test]fn only_a_newer_transmit_of_the_same_id_supersedes() {- // id 1 twice with id 2 in between: over budget, the old id-1 frame- // goes and the id-2 picture stays, whichever order they arrived in.+ // id 1 twice with id 2 in between: the budget runs out after the+ // two newest, and the old id-1 frame is the one that goes.let dir = ScratchDir::in_temp("mixed-ids");let files: Vec<_> = (0..3).map(|i| dir.file(&format!("pic-{i}.rgba"), &[i as u8; 100]))@@ -2086,7 +2134,7 @@ mod temp_file_test {temp_file_transmit(&files[1], Some(2)),temp_file_transmit(&files[2], Some(1)),];- let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 100);+ let (bytes, discarded) = materialize_kitty_actions_newest_first(&mut actions, 200);assert_eq!((bytes, discarded), (200, 1));assert_eq!(transmit_payload(&actions[2]).unwrap(), vec![2u8; 100]);assert_eq!(transmit_payload(&actions[1]).unwrap(), vec![1u8; 100]);diff --git a/wezterm-surface/src/line/clusterline.rs b/wezterm-surface/src/line/clusterline.rsindex 13326611..2ca71750 100644--- a/wezterm-surface/src/line/clusterline.rs+++ b/wezterm-surface/src/line/clusterline.rs@@ -23,14 +23,13 @@ struct Cluster {/// Stores line data as a contiguous string and a series of/// clusters of attribute data describing attributed ranges/// within the line-#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]+#[cfg_attr(feature = "use_serde", derive(Serialize))]#[derive(Debug, Clone, PartialEq)]pub(crate) struct ClusteredLine {pub text: String,#[cfg_attr(feature = "use_serde",serde(- deserialize_with = "deserialize_bitset",serialize_with = "serialize_bitset"))]@@ -42,20 +41,36 @@ pub(crate) struct ClusteredLine {}#[cfg(feature = "use_serde")]-fn deserialize_bitset<'de, D>(deserializer: D) -> Result<Option<Box<FixedBitSet>>, D::Error>-where- D: Deserializer<'de>,-{- let wide_indices = <Vec<usize>>::deserialize(deserializer)?;- if wide_indices.is_empty() {- Ok(None)- } else {- let max_idx = wide_indices.iter().max().unwrap_or(&1);- let mut bitset = FixedBitSet::with_capacity(max_idx + 1);- for idx in wide_indices {- bitset.set(idx, true);+impl<'de> Deserialize<'de> for ClusteredLine {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ // Keep the existing field order and wire representation, but defer+ // sparse-bitset expansion until its indices can be checked against+ // the text. Each UTF-8 byte can contribute at most two cell columns.+ #[derive(Deserialize)]+ struct Wire {+ text: String,+ is_double_wide: Vec<usize>,+ clusters: Vec<Cluster>,+ len: u32,+ last_cell_width: Option<NonZeroU8>,}- Ok(Some(Box::new(bitset)))+ let wire = Wire::deserialize(deserializer)?;+ let is_double_wide = if let Some(&max_idx) = wire.is_double_wide.iter().max() {+ if max_idx >= wire.text.len().saturating_mul(2) {+ return Err(serde::de::Error::custom("wide-cell index exceeds line text"));+ }+ let mut bits = FixedBitSet::with_capacity(max_idx + 1);+ for idx in wire.is_double_wide {+ bits.set(idx, true);+ }+ Some(Box::new(bits))+ } else {+ None+ };+ Ok(Self {+ text: wire.text, is_double_wide, clusters: wire.clusters,+ len: wire.len, last_cell_width: wire.last_cell_width,+ })}}@@ -101,7 +116,9 @@ impl ClusteredLine {// would keep up to 60% slack alive in scrollback. len() is a width// sum, which zero-width cells can overshoot; the shrink is a no-op// in the exact case and trims the rare doubled buffer otherwise.- let mut cells = Vec::with_capacity(self.len());+ // len() is a sum of widths that arrive off the wire; reserve for a+ // plausible line, and let a wider one grow as it is filled.+ let mut cells = Vec::with_capacity(self.len().min(4096));for c in self.iter() {cells.push(c.as_cell());