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
feat(mux-server): share a pane with other accounts on this machine
RoversX968af8245e14
diff --git a/wezterm-mux-server-impl/Cargo.toml b/wezterm-mux-server-impl/Cargo.tomlindex d1f3f105..7020fbdd 100644--- a/wezterm-mux-server-impl/Cargo.toml+++ b/wezterm-mux-server-impl/Cargo.toml@@ -55,7 +55,7 @@ wezterm-ssh.workspace = true[target."cfg(unix)".dependencies]passfd.workspace = true-nix = { workspace = true, features = ["socket"] }+nix = { workspace = true, features = ["socket", "user"] }rustix = { version = "1.1.2", features = ["net", "termios", "fs", "process", "event"] }[target.'cfg(target_os = "macos")'.dependencies]diff --git a/wezterm-mux-server-impl/src/dispatch.rs b/wezterm-mux-server-impl/src/dispatch.rsindex a5fa3185..e6ad0ff9 100644--- a/wezterm-mux-server-impl/src/dispatch.rs+++ b/wezterm-mux-server-impl/src/dispatch.rs@@ -194,7 +194,7 @@ where{let local = match peer {ConnectionPeer::Local => LocalSocket::of(&stream),- ConnectionPeer::Tls | ConnectionPeer::Web(_) => None,+ ConnectionPeer::Tls | ConnectionPeer::Web(_) | ConnectionPeer::Share(_) => None,};let stream = smol::Async::new(stream)?;process_stream_on(stream, peer, local).await@@ -322,8 +322,17 @@ async fn process_async_with_peer<S: ConnectionStream>(log::trace!("process_async called");let revoked = match &peer {ConnectionPeer::Web(web) => Some(web.revoked.clone()),+ ConnectionPeer::Share(share) => Some(share.dropped.clone()),ConnectionPeer::Local | ConnectionPeer::Tls => None,};+ let withdrawn = match &peer {+ ConnectionPeer::Share(_) => "the viewer's share ended, or the viewer was removed",+ _ => "the client's web token was revoked",+ };+ // A viewer hears of nothing but the pane it watches: the rest of the+ // owner's mux -- other panes, windows, the tree, the clipboard -- is+ // not turned into anything for it at all.+ let share_viewer = matches!(peer, ConnectionPeer::Share(_));let mut client_link = codec::Link::Network;let (item_tx, item_rx) = smol::channel::unbounded::<Item>();@@ -358,10 +367,18 @@ async fn process_async_with_peer<S: ConnectionStream>(// it waits on a busy pane's terminal.let mux = Mux::get();let tx = item_tx.clone();+ let watched = handler.share_pane();mux.subscribe(move |n| {if tx.is_closed() {return false;}+ // A viewer's notifications are sorted here, on whatever thread+ // notified, so that none for another pane costs a hop to the+ // main thread: until it joins a share, it hears of nothing.+ if share_viewer && !viewer_hears(&n, watched.load(std::sync::atomic::Ordering::Relaxed))+ {+ return true;+ }log::trace!("notification queued for the connection: {n:?}");let tx = tx.clone();promise::spawn::spawn_into_main_thread(async move {@@ -395,7 +412,10 @@ async fn process_async_with_peer<S: ConnectionStream>(// order and a busy pane keeps the queue arm ready on every turn, so// a revocation that only lived in the race could wait forever.if admission_is_withdrawn(&revoked) {- log::warn!("the client's web token was revoked; dropping the connection");+ log::warn!("{withdrawn}; dropping the connection");+ if share_viewer {+ say_why(&mut stream, &item_rx, client_link).await;+ }return Ok(());}let rx_msg = item_rx.recv();@@ -471,7 +491,16 @@ async fn process_async_with_peer<S: ConnectionStream>(stream: &mut stream,bytes: &moved,};- Read::Decoded(Pdu::decode_async(&mut counted, None).await)+ Read::Decoded(if share_viewer {+ Pdu::decode_async_bounded(+ &mut counted,+ None,+ VIEWER_PAYLOAD_LIMIT,+ )+ .await+ } else {+ Pdu::decode_async(&mut counted, None).await+ })},async {stalled(&moved, READ_STALL_LIMIT, true).await;@@ -530,7 +559,10 @@ async fn process_async_with_peer<S: ConnectionStream>(}Ok(Item::LivenessTick) => unreachable!("handled above"),Ok(Item::Shutdown) => {- log::warn!("the client's web token was revoked; dropping the connection");+ log::warn!("{withdrawn}; dropping the connection");+ if share_viewer {+ say_why(&mut stream, &item_rx, client_link).await;+ }return Ok(());}Ok(Item::WritePdu(decoded)) => {@@ -584,7 +616,10 @@ async fn process_async_with_peer<S: ConnectionStream>(return Ok(());}Err(WriteFailure::Revoked) => {- log::warn!("the client's web token was revoked; dropping the connection");+ log::warn!("{withdrawn}; dropping the connection");+ if share_viewer {+ say_why(&mut stream, &item_rx, client_link).await;+ }return Ok(());}Err(WriteFailure::Encode(err)) => {@@ -608,6 +643,16 @@ async fn process_async_with_peer<S: ConnectionStream>(// A connection subscribed to events reads no pane contents:// output costs it nothing, and an alert goes straight out// rather than waiting for the pane's parser.+ // A viewer hears only of the pane it may read, and of none of+ // what a program there says to its own user's desktop.+ Ok(Item::Notif(+ MuxNotification::PaneOutput(pane_id)+ | MuxNotification::Alert { pane_id, .. }+ | MuxNotification::PaneRemoved(pane_id)+ | MuxNotification::PaneExited { pane_id, .. },+ )) if handler.is_share_viewer() && !handler.share_may_read(pane_id) => {}+ Ok(Item::Notif(MuxNotification::Alert { alert, .. }))+ if handler.is_share_viewer() && !viewer_sees_alert(&alert) => {}Ok(Item::Notif(MuxNotification::PaneOutput(_))) if handler.events_subscribed => {}Ok(Item::Notif(MuxNotification::Alert { pane_id, alert }))if handler.events_subscribed =>@@ -794,6 +839,71 @@ async fn admission_withdrawn(revoked: &Option<smol::channel::Receiver<()>>) {}}+/// Whether a notification concerns a viewer on the share socket watching+/// `pane`: that pane's output, alerts and end.+fn viewer_hears(n: &MuxNotification, pane: usize) -> bool {+ match n {+ MuxNotification::PaneOutput(pane_id)+ | MuxNotification::Alert { pane_id, .. }+ | MuxNotification::PaneRemoved(pane_id)+ | MuxNotification::PaneExited { pane_id, .. } => *pane_id == pane,+ _ => false,+ }+}++/// The most a viewer on the share socket sends in one request: a paste,+/// at its largest. Nothing it may send needs compression.+const VIEWER_PAYLOAD_LIMIT: usize = 1024 * 1024;++/// What of a shared pane's alerts reaches a viewer: what changes how the+/// pane looks. A desktop notification, a user variable or a bell is meant+/// for the owner.+fn viewer_sees_alert(alert: &wezterm_term::Alert) -> bool {+ use wezterm_term::Alert;+ matches!(+ alert,+ Alert::WindowTitleChanged(_)+ | Alert::TabTitleChanged(_)+ | Alert::IconTitleChanged(_)+ | Alert::PaletteChanged+ | Alert::CurrentWorkingDirectoryChanged+ )+}++/// A viewer dropped because its share ended or it was removed: the share+/// queued the reason just before the drop, and it is written out first,+/// within a second, so the viewer can say why rather than just stop.+async fn say_why<S: ConnectionStream>(+ stream: &mut S,+ items: &smol::channel::Receiver<Item>,+ link: codec::Link,+) {+ while let Ok(item) = items.try_recv() {+ let Item::WritePdu(decoded) = item else {+ continue;+ };+ if !matches!(decoded.pdu, Pdu::ShareStateChanged(_)) {+ continue;+ }+ let _ = smol::future::or(+ async {+ if decoded+ .pdu+ .encode_async_over(&mut *stream, decoded.serial, link)+ .await+ .is_ok()+ {+ let _ = stream.flush().await;+ }+ },+ async {+ smol::Timer::after(Duration::from_secs(1)).await;+ },+ )+ .await;+ }+}+/// What the connection loop needs for a mux notification, prepared on the/// main thread. Pane output, alerts, panes coming and going and programs/// ending need the handler's own state and go through as they are;diff --git a/wezterm-mux-server-impl/src/lib.rs b/wezterm-mux-server-impl/src/lib.rsindex 1c187953..c1d40bc5 100644--- a/wezterm-mux-server-impl/src/lib.rs+++ b/wezterm-mux-server-impl/src/lib.rs@@ -18,6 +18,7 @@ mod plugin_relay;mod private_file;mod sent_images;pub mod sessionhandler;+pub mod share;pub mod thinkterm_access;pub mod thinkterm_layout;pub mod thinkterm_session;diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rsindex 31181e7c..30d2c392 100644--- a/wezterm-mux-server-impl/src/sessionhandler.rs+++ b/wezterm-mux-server-impl/src/sessionhandler.rs@@ -124,6 +124,9 @@ pub(crate) struct PerPane {/// The connection subscribed to events: a push carries the pane's/// alerts and nothing of what it shows.events_only: bool,+ /// The connection is a viewer of a shared pane: a push reads its rows+ /// with the screen they are on (see `Pane::get_screen_lines`).+ viewer: bool,}/// What may wait for one pane from one connection before further input is@@ -132,6 +135,10 @@ pub(crate) struct PerPane {/// pastes and `cli send-text` do not pass through it.const INPUT_QUEUE_LIMIT: usize = 8 * 1024 * 1024;+/// A viewer's coalesced wheel event is replayed on the main thread, so+/// its small wire representation must not ask for unbounded work.+const SHARE_WHEEL_NOTCH_LIMIT: usize = 256;+/// One piece of terminal input a client sent for a pane.enum PaneInput {Key {@@ -188,6 +195,8 @@ struct InputSource {client_id: Option<Arc<ClientId>>,registration: Option<ClientRegistrationId>,palette_session_id: Option<PaletteSessionId>,+ /// A viewer on the share socket: its share and its place in it.+ share: Option<ShareWatch>,}impl PerPane {@@ -370,12 +379,15 @@ fn select_dirty_lines(/// Read `pane` against what was `last` sent: None when nothing changed and/// nothing forces a push. Takes the pane's terminal lock, several times;-/// no `PerPane` lock may be held by the caller.+/// no `PerPane` lock may be held by the caller. A `viewer`'s rows are read+/// with the screen they are on: the bounds read here before them may be+/// of the other screen by then.fn read_pane_changes(pane: &Arc<dyn Pane>,last: &LastSent,force_with_input_serial: Option<InputSerial>,scene_seqno: u64,+ viewer: bool,) -> Option<PaneReading> {let mut changed = false;let mouse_grabbed = pane.is_mouse_grabbed();@@ -430,17 +442,25 @@ fn read_pane_changes(// Acknowledge its terminal sequence without copying unchanged rows.Vec::new()} else {+ let read = |lines| {+ if viewer {+ pane.get_screen_lines(lines)+ } else {+ pane.get_lines(lines)+ }+ };let viewport_range =dims.physical_top..dims.physical_top + dims.viewport_rows as StableRowIndex;- let (first_line, lines) = pane.get_lines(viewport_range);+ let (first_line, lines) = read(viewport_range);let mut bonus_lines = select_dirty_lines(first_line, lines, &mut all_dirty_lines);// Always send the cursor's row with ordinary changes, as that tends- // to be the busiest row.- let (cursor_line_idx, mut lines) = pane.get_lines(cursor_position.y..cursor_position.y + 1);- let mut cursor_line = lines.remove(0);- cursor_line.compress_for_scrollback();- bonus_lines.push((cursor_line_idx, cursor_line));+ // to be the busiest row. A viewer's may have left the screen.+ let (cursor_line_idx, lines) = read(cursor_position.y..cursor_position.y + 1);+ if let Some(mut cursor_line) = lines.into_iter().next() {+ cursor_line.compress_for_scrollback();+ bonus_lines.push((cursor_line_idx, cursor_line));+ }bonus_lines};@@ -708,13 +728,25 @@ fn apply_pane_input(pane.erase_scrollback(erase_mode);return Ok(Pdu::UnitResponse(UnitResponse {}));}- claim_viewport_for_pane(- &mux,- source.client_id.as_ref(),- source.registration,- pane.pane_id(),- )?;- activate_client_palette(&mux, pane, source.palette_session_id)?;+ match source.share {+ // A viewer types only while the owner lets it -- asked again now,+ // since the wait for the pane may have outlasted the grant -- and+ // is none of the owner's frontends: it claims no layout, sizes+ // nothing, and brings no palette.+ Some(watch) => anyhow::ensure!(+ crate::share::may_type(watch.viewer_id, watch.share_id, pane.pane_id()),+ "the owner has taken typing back"+ ),+ None => {+ claim_viewport_for_pane(+ &mux,+ source.client_id.as_ref(),+ source.registration,+ pane.pane_id(),+ )?;+ activate_client_palette(&mux, pane, source.palette_session_id)?;+ }+ }let input_serial = match input {PaneInput::Key {event,@@ -730,29 +762,9 @@ fn apply_pane_input(None}PaneInput::Mouse(event) => {- // The client coalesces rapid wheel motion into a single- // event with an accumulated amount, but the terminal- // emits one report per event regardless of the amount;- // replay it per notch so mouse-mode apps scroll the- // full distance.- use wezterm_term::MouseButton as MB;- let notches = match event.button {- MB::WheelUp(n) if n > 1 => Some((MB::WheelUp(1), n)),- MB::WheelDown(n) if n > 1 => Some((MB::WheelDown(1), n)),- MB::WheelLeft(n) if n > 1 => Some((MB::WheelLeft(1), n)),- MB::WheelRight(n) if n > 1 => Some((MB::WheelRight(1), n)),- _ => None,- };- match notches {- Some((notch, n)) => {- let mut single = event;- single.button = notch;- for _ in 0..n {- pane.mouse_event(single.clone())?;- }- }- None => pane.mouse_event(event)?,- }+ apply_mouse_input(pane.pane_id(), source.share, event, |event| {+ pane.mouse_event(event)+ })?;None}PaneInput::Write(data) => {@@ -775,6 +787,59 @@ fn apply_pane_input(Ok(Pdu::UnitResponse(UnitResponse {}))}+fn validate_share_mouse_input(event: &wezterm_term::input::MouseEvent) -> anyhow::Result<()> {+ use wezterm_term::MouseButton as MB;+ if let MB::WheelUp(n) | MB::WheelDown(n) | MB::WheelLeft(n) | MB::WheelRight(n) = event.button {+ anyhow::ensure!(+ n <= SHARE_WHEEL_NOTCH_LIMIT,+ "a shared pane accepts at most {SHARE_WHEEL_NOTCH_LIMIT} wheel notches per event"+ );+ }+ Ok(())+}++fn apply_mouse_input(+ pane_id: PaneId,+ share: Option<ShareWatch>,+ event: wezterm_term::input::MouseEvent,+ mut send: impl FnMut(wezterm_term::input::MouseEvent) -> anyhow::Result<()>,+) -> anyhow::Result<()> {+ if share.is_some() {+ validate_share_mouse_input(&event)?;+ }+ let mut send = |event| {+ if let Some(watch) = share {+ anyhow::ensure!(+ crate::share::may_type(watch.viewer_id, watch.share_id, pane_id),+ "the owner has taken typing back"+ );+ }+ send(event)+ };+ // The client coalesces rapid wheel motion into a single event, but+ // the terminal emits one report per event regardless of the amount.+ // Replay each notch, checking the viewer's grant throughout.+ use wezterm_term::MouseButton as MB;+ let notches = match event.button {+ MB::WheelUp(n) if n > 1 => Some((MB::WheelUp(1), n)),+ MB::WheelDown(n) if n > 1 => Some((MB::WheelDown(1), n)),+ MB::WheelLeft(n) if n > 1 => Some((MB::WheelLeft(1), n)),+ MB::WheelRight(n) if n > 1 => Some((MB::WheelRight(1), n)),+ _ => None,+ };+ match notches {+ Some((notch, n)) => {+ let mut single = event;+ single.button = notch;+ for _ in 0..n {+ send(single)?;+ }+ Ok(())+ }+ None => send(event),+ }+}+fn relative_scene_seqno(selections: &[wezterm_term::KittyFrameSelection]) -> u64 {selections.iter().flat_map(|image| &image.relative_placements).map(|placement| placement.source_seqno).max().unwrap_or(0)@@ -803,7 +868,7 @@ fn maybe_push_pane_changes(// palette from taking over client rendering. Send it before line changes// so a real application override is installed before those lines paint.let application_palette = pane.palette_override();- let (needs_palette, last, frame_control, frame_revision, mut scene_seqno) = {+ let (needs_palette, last, frame_control, frame_revision, mut scene_seqno, viewer) = {let per_pane = per_pane.lock().unwrap();(per_pane.needs_application_palette(&application_palette),@@ -811,6 +876,7 @@ fn maybe_push_pane_changes(per_pane.frame_control,per_pane.frame_revision,per_pane.scene_seqno,+ per_pane.viewer,)};if needs_palette {@@ -841,7 +907,7 @@ fn maybe_push_pane_changes(per_pane.scene_seqno = scene_seqno;}}- let reading = read_pane_changes(pane, &last, force_with_input_serial, scene_seqno);+ let reading = read_pane_changes(pane, &last, force_with_input_serial, scene_seqno, viewer);let mut per_pane = per_pane.lock().unwrap();if let Some(reading) = reading {let resp = per_pane.commit_changes(pane.pane_id(), reading);@@ -1088,6 +1154,9 @@ pub enum ConnectionPeer {/// is not a thing to be able to arrange from off it.Tls,Web(WebPeer),+ /// The share socket: another account on this machine, as the kernel+ /// named it, watching a pane shared with it. See `crate::share`.+ Share(crate::share::SharePeer),}fn peer_may_import_sessions(peer: &ConnectionPeer) -> bool {@@ -1173,6 +1242,40 @@ fn web_peer_may_send(pdu: &Pdu) -> bool {)}+/// What a viewer on the share socket may ask for: to see what is shared+/// with it, to join one share, to read that pane's rows, and to type into+/// it while its owner lets it. Which pane, and whether typing is allowed+/// now, is checked again per request (`SessionHandler::share_gate`). The+/// list names what is allowed, so a request added later is refused here+/// until someone decides it belongs.+fn share_peer_may_send(pdu: &Pdu) -> bool {+ matches!(+ pdu,+ Pdu::Ping(_)+ | Pdu::Pong(_)+ | Pdu::GetCodecVersion(_)+ | Pdu::SetClientId(_)+ | Pdu::ShareIncoming(_)+ | Pdu::ShareJoin(_)+ | Pdu::ShareRequestControl(_)+ | Pdu::ShareReleaseControl(_)+ | Pdu::GetPaneRenderChanges(_)+ | Pdu::GetPaneRenderableDimensions(_)+ | Pdu::GetLines(_)+ | Pdu::WriteToPane(_)+ | Pdu::SendKeyDown(_)+ | Pdu::SendMouseEvent(_)+ | Pdu::SendPaste(_)+ )+}++/// The share a viewer's connection has joined.+#[derive(Debug, Clone, Copy)]+struct ShareWatch {+ share_id: u64,+ viewer_id: u64,+}+pub struct SessionHandler {to_write_tx: PduSender,peer: ConnectionPeer,@@ -1188,10 +1291,30 @@ pub struct SessionHandler {/// The client sent `SubscribeEvents`: it hears of panes appearing,/// and its pane pushes carry alerts only.pub(crate) events_subscribed: bool,+ /// On the share socket, once the viewer has joined a share.+ share_watch: Option<ShareWatch>,+ /// The pane a viewer watches, `NO_PANE` until it joins: read by the+ /// connection's notification filter, which runs on whatever thread+ /// notifies, without a lock.+ share_pane: Arc<std::sync::atomic::AtomicUsize>,+ /// A viewer's ask after what is shared with it is being answered.+ share_asking: Arc<std::sync::atomic::AtomicBool>,+ /// The person's desktop, once it shared a pane here: what it shared+ /// ends when this connection does.+ sharer: Option<crate::share::Sharer>,}+/// `SessionHandler::share_pane` before the viewer joins a share.+pub(crate) const NO_PANE: usize = usize::MAX;+impl Drop for SessionHandler {fn drop(&mut self) {+ if let Some(watch) = self.share_watch.take() {+ crate::share::leave(watch.viewer_id, watch.share_id);+ }+ if let Some(sharer) = self.sharer.take() {+ sharer.left();+ }for pane in self.per_pane.values() {pane.lock().unwrap().set_frame_control(false);}@@ -1222,7 +1345,68 @@ impl SessionHandler {proxy_client_id: None,plugin_pipe: None,events_subscribed: false,+ share_watch: None,+ share_pane: Arc::new(std::sync::atomic::AtomicUsize::new(NO_PANE)),+ share_asking: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ sharer: None,+ }+ }++ /// The pane this connection's viewer watches, for the notification+ /// filter set up before any request is read.+ pub(crate) fn share_pane(&self) -> Arc<std::sync::atomic::AtomicUsize> {+ Arc::clone(&self.share_pane)+ }++ /// Whether this connection is a viewer on the share socket.+ pub(crate) fn is_share_viewer(&self) -> bool {+ matches!(self.peer, ConnectionPeer::Share(_))+ }++ /// Whether this viewer may hear about `pane_id`: the pane of the share+ /// it joined. A viewer removed from it is dropped with its connection.+ pub(crate) fn share_may_read(&self, pane_id: PaneId) -> bool {+ self.share_pane.load(std::sync::atomic::Ordering::Relaxed) == pane_id+ }++ /// For a viewer: refuse what it may not read or type.+ fn share_gate(&self, pdu: &Pdu) -> anyhow::Result<()> {+ let (pane_id, typing) = match pdu {+ Pdu::GetPaneRenderChanges(req) => (req.pane_id, false),+ Pdu::GetPaneRenderableDimensions(req) => (req.pane_id, false),+ Pdu::GetLines(req) => (req.pane_id, false),+ Pdu::WriteToPane(req) => (req.pane_id, true),+ Pdu::SendKeyDown(req) => (req.pane_id, true),+ Pdu::SendMouseEvent(req) => {+ validate_share_mouse_input(&req.event)?;+ (req.pane_id, true)+ }+ Pdu::SendPaste(req) => (req.pane_id, true),+ _ => return Ok(()),+ };+ let watch = self+ .share_watch+ .ok_or_else(|| anyhow!("join a share before reading its pane"))?;+ if typing {+ anyhow::ensure!(+ crate::share::may_type(watch.viewer_id, watch.share_id, pane_id),+ "you can only watch this pane; ask its owner to let you type"+ );+ return Ok(());}+ crate::share::may_read(watch.viewer_id, watch.share_id, pane_id)+ .ok_or_else(|| anyhow!("pane {pane_id} is not shared with you"))?;+ Ok(())+ }++ /// Whether the rows this connection reads of `pane_id` are cut to its+ /// screen: a viewer of a share made without its history.+ /// Whether a viewer reads only the screen of `pane_id`: unless its share+ /// gives it the history, which one it has just left no longer does.+ fn screen_only(&self, pane_id: PaneId) -> bool {+ self.share_watch.is_some_and(|watch| {+ crate::share::may_read(watch.viewer_id, watch.share_id, pane_id) != Some(true)+ })}/// The pid of the client registered on this connection, when it@@ -1297,9 +1481,11 @@ impl SessionHandler {pub(crate) fn per_pane(&mut self, pane_id: PaneId) -> Arc<Mutex<PerPane>> {let events_only = self.events_subscribed;+ let viewer = self.is_share_viewer();Arc::clone(self.per_pane.entry(pane_id).or_insert_with(|| {Arc::new(Mutex::new(PerPane {events_only,+ viewer,..PerPane::default()}))}))@@ -1344,6 +1530,7 @@ impl SessionHandler {client_id: self.client_id.clone(),registration: self.client_registration,palette_session_id: self.palette_session_id,+ share: self.share_watch,};spawn_into_main_thread(drain_pane_inputs(pane_id,@@ -1405,6 +1592,20 @@ impl SessionHandler {return;}+ if self.is_share_viewer() {+ if !share_peer_may_send(&decoded.pdu) {+ send_response(Err(anyhow!(+ "{} is not available to a viewer of a shared pane",+ decoded.pdu.pdu_name()+ )));+ return;+ }+ if let Err(err) = self.share_gate(&decoded.pdu) {+ send_response(Err(err));+ return;+ }+ }+if requires_existing_frontend_access(&decoded.pdu) {if let Err(err) = require_registered_frontend_access(&Mux::get(),@@ -1445,6 +1646,12 @@ impl SessionHandler {}).detach();}+ // A viewer is not one of the owner's frontends: it is not+ // registered, so it holds no lease and sizes nothing, and it+ // is not told the owner's frontend state or palette.+ Pdu::SetClientId(_) if self.is_share_viewer() => {+ send_response(Ok(Pdu::UnitResponse(UnitResponse {})));+ }Pdu::SetClientId(SetClientId {mut client_id,is_proxy,@@ -2500,6 +2707,14 @@ impl SessionHandler {Pdu::GetLines(GetLines { pane_id, lines }) => {let per_pane = self.per_pane(pane_id);let sender = self.to_write_tx.clone();+ let screen_only = self.screen_only(pane_id);+ // A viewer's ask is held to what a viewer needs: each row+ // once, and not without end (see `share::viewer_rows`).+ let lines = if self.is_share_viewer() {+ crate::share::viewer_rows(lines)+ } else {+ lines+ };spawn_into_main_thread(async move {// Read once the pane can be read without waiting, like// a push: the client asks again for rows it does not@@ -2533,7 +2748,17 @@ impl SessionHandler {if range.start > range.end {continue;}- let (first_row, lines) = pane.get_lines(range);+ // A viewer without the history gets what is+ // on the screen as the rows are read: rows+ // are numbered afresh on the alternate+ // screen and move when the pane is+ // reflowed, so no row number marks where+ // the share began.+ let (first_row, lines) = if screen_only {+ pane.get_screen_lines(range)+ } else {+ pane.get_lines(range)+ };for (idx, mut line) in lines.into_iter().enumerate() {let stable_row = first_row + idx as StableRowIndex;line.compress_for_scrollback();@@ -2680,6 +2905,17 @@ impl SessionHandler {.detach();}+ // Where the owner's executable and config live is nothing a+ // viewer needs.+ Pdu::GetCodecVersion(_) if self.is_share_viewer() => {+ send_response(Ok(Pdu::GetCodecVersionResponse(GetCodecVersionResponse {+ codec_vers: CODEC_VERSION,+ version_string: config::wezterm_version().to_owned(),+ server_id: Mux::get().runtime_server_id().to_string(),+ executable_path: std::path::PathBuf::new(),+ config_file_path: None,+ })))+ }Pdu::GetCodecVersion(_) => {match std::env::current_exe().context("resolving current_exe") {Err(err) => send_response(Err(err)),@@ -2960,6 +3196,188 @@ impl SessionHandler {.detach();}+ // The owner's side. Not on the web or viewer allowlists, so+ // only this machine's own clients and mTLS reach these.+ // The accounts and groups it names are looked up, maybe in a+ // directory slow to answer: on a thread of its own, not the main+ // one every pane goes through.+ Pdu::ShareStart(request) => {+ let sender = self.to_write_tx.clone();+ let sharer = self.sharer.get_or_insert_with(Default::default).clone();+ let spawned = std::thread::Builder::new()+ .name("share-start".into())+ .spawn(move || {+ let pdu = match crate::share::start(request, sharer) {+ Ok(info) => Pdu::ShareListResponse(ShareListResponse {+ shares: vec![info],+ }),+ Err(err) => Pdu::ErrorResponse(ErrorResponse {+ reason: format!("Error: {err:#}"),+ }),+ };+ let _ = sender.send(DecodedPdu { serial, pdu });+ });+ if let Err(err) = spawned {+ send_response(Err(anyhow!("cannot start sharing: {err:#}")));+ }+ }+ Pdu::ShareList(_) => send_response(Ok(Pdu::ShareListResponse(ShareListResponse {+ shares: crate::share::list(),+ }))),+ Pdu::ShareStop(ShareStop { share_id }) => send_response(+ crate::share::stop(share_id).map(|()| Pdu::UnitResponse(UnitResponse {})),+ ),+ Pdu::ShareKick(ShareKick {+ share_id,+ viewer_id,+ }) => send_response(+ crate::share::kick(share_id, viewer_id)+ .map(|()| Pdu::UnitResponse(UnitResponse {})),+ ),+ Pdu::ShareGrant(ShareGrant {+ share_id,+ viewer_id,+ for_secs,+ from_desktop,+ }) => send_response(+ crate::share::grant(share_id, viewer_id, for_secs, from_desktop)+ .map(|()| Pdu::UnitResponse(UnitResponse {})),+ ),+ Pdu::ShareRevoke(ShareRevoke { share_id }) => send_response(+ crate::share::revoke(share_id).map(|()| Pdu::UnitResponse(UnitResponse {})),+ ),+ // Looked up off the main thread: the directory service may be+ // slow to answer.+ Pdu::ShareCandidates(_) => {+ let sender = self.to_write_tx.clone();+ let spawned = std::thread::Builder::new()+ .name("share-candidates".into())+ .spawn(move || {+ let _ = sender.send(DecodedPdu {+ serial,+ pdu: Pdu::ShareCandidatesResponse(+ crate::share::candidates_to_share_with(),+ ),+ });+ });+ if let Err(err) = spawned {+ send_response(Err(anyhow!("cannot list the accounts here: {err:#}")));+ }+ }+ Pdu::ShareDeny(ShareDeny {+ share_id,+ viewer_id,+ }) => send_response(+ crate::share::deny(share_id, viewer_id)+ .map(|()| Pdu::UnitResponse(UnitResponse {})),+ ),++ // What other accounts here share with ours. Each of their+ // servers is asked in turn, which may take a few seconds when+ // one does not answer: done on a thread of its own.+ Pdu::ShareDiscover(_) => {+ let sender = self.to_write_tx.clone();+ let spawned = std::thread::Builder::new()+ .name("share-discover".into())+ .spawn(move || {+ let incoming = smol::block_on(wezterm_client::share::incoming());+ let owners = incoming+ .found+ .into_iter()+ .map(|(_, response)| response)+ .collect();+ let watch_program = std::env::current_exe()+ .ok()+ .and_then(|exe| exe.parent().map(|dir| dir.join("thinkterm")))+ .filter(|program| program.exists());+ let _ = sender.send(DecodedPdu {+ serial,+ pdu: Pdu::ShareDiscoverResponse(ShareDiscoverResponse {+ owners,+ other_version: incoming.other_version,+ watch_program,+ }),+ });+ });+ if let Err(err) = spawned {+ send_response(Err(anyhow!("cannot look for shared panes: {err:#}")));+ }+ }++ // The viewer's side, on the share socket only: who the viewer+ // is comes from there.+ // A group is looked up to answer, maybe in a directory slow to+ // answer: on a thread of its own, one at a time, so that no+ // viewer holds up the threads every connection shares.+ Pdu::ShareIncoming(_) => {+ let ConnectionPeer::Share(peer) = &self.peer else {+ send_response(Err(anyhow!("ask for shared panes on the share socket")));+ return;+ };+ if self.share_asking.swap(true, std::sync::atomic::Ordering::SeqCst) {+ send_response(Err(anyhow!("still answering the last ask")));+ return;+ }+ let peer = peer.clone();+ let asking = Arc::clone(&self.share_asking);+ let sender = self.to_write_tx.clone();+ let spawned = std::thread::Builder::new()+ .name("share-incoming".into())+ .spawn(move || {+ let response = crate::share::incoming(&peer);+ asking.store(false, std::sync::atomic::Ordering::SeqCst);+ let _ = sender.send(DecodedPdu {+ serial,+ pdu: Pdu::ShareIncomingResponse(response),+ });+ });+ if let Err(err) = spawned {+ self.share_asking+ .store(false, std::sync::atomic::Ordering::SeqCst);+ send_response(Err(anyhow!("cannot look for shared panes: {err:#}")));+ }+ }+ Pdu::ShareJoin(ShareJoin { share_id }) => {+ let ConnectionPeer::Share(peer) = &self.peer else {+ send_response(Err(anyhow!("join a share on the share socket")));+ return;+ };+ if self.share_watch.is_some() {+ send_response(Err(anyhow!("this connection already watches a share")));+ return;+ }+ match crate::share::join(peer, share_id, self.to_write_tx.clone()) {+ Ok(joined) => {+ self.share_watch = Some(ShareWatch {+ share_id,+ viewer_id: joined.viewer_id,+ });+ self.share_pane+ .store(joined.pane_id, std::sync::atomic::Ordering::Relaxed);+ send_response(Ok(Pdu::ShareJoinResponse(joined)));+ }+ Err(err) => send_response(Err(err)),+ }+ }+ Pdu::ShareRequestControl(ShareRequestControl { share_id }) => {+ let result = match self.share_watch {+ Some(watch) if watch.share_id == share_id => {+ crate::share::request_control(watch.viewer_id, share_id)+ }+ _ => Err(anyhow!("you are not watching share {share_id}")),+ };+ send_response(result.map(|()| Pdu::UnitResponse(UnitResponse {})));+ }+ Pdu::ShareReleaseControl(ShareReleaseControl { share_id }) => {+ let result = match self.share_watch {+ Some(watch) if watch.share_id == share_id => {+ crate::share::release_control(watch.viewer_id, share_id)+ }+ _ => Err(anyhow!("you are not watching share {share_id}")),+ };+ send_response(result.map(|()| Pdu::UnitResponse(UnitResponse {})));+ }+Pdu::Invalid { .. } => send_response(Err(anyhow!("invalid PDU {:?}", decoded.pdu))),// The answer to this connection's liveness probe. Arriving at// all is the answer; there is nothing to reply, and replying@@ -3014,6 +3432,12 @@ impl SessionHandler {| Pdu::EnsureThinkTermThreadResponse { .. }| Pdu::ClientViewportState { .. }| Pdu::FrontendAccessState { .. }+ | Pdu::ShareListResponse { .. }+ | Pdu::ShareIncomingResponse { .. }+ | Pdu::ShareJoinResponse { .. }+ | Pdu::ShareStateChanged { .. }+ | Pdu::ShareDiscoverResponse { .. }+ | Pdu::ShareCandidatesResponse { .. }| Pdu::ErrorResponse { .. } => {send_response(Err(anyhow!("expected a request, got {:?}", decoded.pdu)))}@@ -3401,6 +3825,222 @@ mod tests {use wezterm_term::color::ColorPalette;use wezterm_term::TerminalSize;+ fn mouse_input(+ kind: wezterm_term::MouseEventKind,+ button: wezterm_term::MouseButton,+ ) -> wezterm_term::MouseEvent {+ wezterm_term::MouseEvent {+ kind,+ x: 3,+ y: 4,+ x_pixel_offset: 1,+ y_pixel_offset: 2,+ button,+ modifiers: termwiz::input::Modifiers::SHIFT,+ }+ }++ fn typing_viewer(sender: super::PduSender) -> super::SessionHandler {+ let peer = crate::share::SharePeer::new(u32::MAX - 1, "viewer".into(), u32::MAX - 1);+ let (share_id, viewer_id) = crate::share::share_for_test(7, false, &peer);+ let mut handler =+ super::SessionHandler::for_peer(sender, super::ConnectionPeer::Share(peer));+ handler.share_watch = Some(super::ShareWatch {+ share_id,+ viewer_id,+ });+ handler+ .share_pane+ .store(7, std::sync::atomic::Ordering::Relaxed);+ crate::share::grant_for_test(share_id, viewer_id);+ handler+ }++ #[test]+ fn a_viewers_wheel_count_is_bounded_before_queueing_and_replay() {+ use super::{apply_mouse_input, PduSender, SHARE_WHEEL_NOTCH_LIMIT};+ use std::sync::Mutex;+ use wezterm_term::{MouseButton as MB, MouseEventKind as MK};++ let sent = Arc::new(Mutex::new(Vec::new()));+ let sink = Arc::clone(&sent);+ let mut handler = typing_viewer(PduSender::new(move |pdu| {+ sink.lock().unwrap().push(pdu);+ Ok(())+ }));+ for kind in [MK::Press, MK::Release, MK::Move] {+ for wheel in [+ MB::WheelUp as fn(usize) -> MB,+ MB::WheelDown,+ MB::WheelLeft,+ MB::WheelRight,+ ] {+ for count in [+ 0,+ 1,+ 2,+ SHARE_WHEEL_NOTCH_LIMIT,+ SHARE_WHEEL_NOTCH_LIMIT + 1,+ usize::MAX,+ ] {+ let event = mouse_input(kind, wheel(count));+ let request = Pdu::SendMouseEvent(codec::SendMouseEvent { pane_id: 7, event });+ let mut wire = Vec::new();+ request.encode(&mut wire, 19).unwrap();+ let decoded = Pdu::decode(&wire[..]).unwrap();+ assert_eq!(decoded.pdu, request);+ let mut applied = Vec::new();+ let replay = apply_mouse_input(7, handler.share_watch, event, |event| {+ anyhow::ensure!(+ applied.len() <= SHARE_WHEEL_NOTCH_LIMIT,+ "stop a regressed replay before the test exhausts memory"+ );+ applied.push(event);+ Ok(())+ });+ if count > SHARE_WHEEL_NOTCH_LIMIT {+ assert!(replay.is_err());+ assert!(applied.is_empty(), "no partial replay of an invalid count");+ handler.process_one(decoded);+ let response = sent.lock().unwrap().pop().unwrap();+ assert_eq!(response.serial, 19);+ assert!(matches!(response.pdu, Pdu::ErrorResponse(ref err)+ if err.reason.contains("at most 256 wheel notches")));+ assert!(+ handler.per_pane.is_empty(),+ "refused before creating a queue"+ );+ } else {+ handler.share_gate(&decoded.pdu).unwrap();+ replay.unwrap();+ let expected = mouse_input(kind, wheel(if count > 1 { 1 } else { count }));+ assert_eq!(applied, vec![expected; count.max(1)]);+ }+ }+ }+ }+ }++ #[test]+ fn mouse_replay_preserves_nonwheel_events_and_nonviewer_counts() {+ use super::{apply_mouse_input, PduSender, SHARE_WHEEL_NOTCH_LIMIT};+ use wezterm_term::{MouseButton as MB, MouseEventKind as MK};++ let handler = typing_viewer(PduSender::new(|_| Ok(())));+ for kind in [MK::Press, MK::Release, MK::Move] {+ for button in [MB::Left, MB::Middle, MB::Right, MB::None] {+ let event = mouse_input(kind, button);+ for share in [None, handler.share_watch] {+ let mut applied = Vec::new();+ apply_mouse_input(7, share, event, |event| {+ applied.push(event);+ Ok(())+ })+ .unwrap();+ assert_eq!(applied, vec![event]);+ }+ }+ }+ let count = SHARE_WHEEL_NOTCH_LIMIT + 1;+ let mut applied = Vec::new();+ apply_mouse_input(+ 7,+ None,+ mouse_input(MK::Press, MB::WheelUp(count)),+ |event| {+ applied.push(event);+ Ok(())+ },+ )+ .unwrap();+ assert_eq!(applied, vec![mouse_input(MK::Press, MB::WheelUp(1)); count]);+ }++ #[test]+ fn a_viewers_wheel_replay_stops_when_typing_is_revoked() {+ use super::{apply_mouse_input, PduSender};+ use wezterm_term::{MouseButton as MB, MouseEventKind as MK};++ let handler = typing_viewer(PduSender::new(|_| Ok(())));+ let watch = handler.share_watch.unwrap();+ let event = mouse_input(MK::Press, MB::WheelDown(4));+ let request = Pdu::SendMouseEvent(codec::SendMouseEvent { pane_id: 7, event });+ handler.share_gate(&request).unwrap();+ let mut applied = 0;+ let err = apply_mouse_input(7, Some(watch), event, |_| {+ applied += 1;+ if applied == 2 {+ crate::share::revoke(watch.share_id)?;+ }+ Ok(())+ })+ .unwrap_err();+ assert!(err.to_string().contains("taken typing back"));+ assert_eq!(applied, 2);+ assert!(handler.share_gate(&request).is_err());+ assert!(apply_mouse_input(7, Some(watch), event, |_| {+ panic!("input revoked while queued must not be applied")+ })+ .is_err());+ }++ // A single range is what a viewer asks for here.+ #[allow(clippy::single_range_in_vec_init)]+ #[test]+ fn a_viewer_reads_only_its_pane_and_types_only_when_let() {+ use codec::{GetLines, GetPaneRenderChanges, SendPaste};+ let peer = crate::share::SharePeer::new(u32::MAX - 1, "viewer".into(), u32::MAX - 1);+ let (share_id, viewer_id) = crate::share::share_for_test(7, false, &peer);+ let mut handler = super::SessionHandler::for_peer(+ super::PduSender::new(|_| Ok(())),+ super::ConnectionPeer::Share(peer),+ );++ // Before joining, nothing of any pane.+ let lines = Pdu::GetLines(GetLines {+ pane_id: 7,+ lines: vec![0..200],+ });+ assert!(handler.share_gate(&lines).is_err());+ assert!(!handler.share_may_read(7));++ handler.share_watch = Some(super::ShareWatch {+ share_id,+ viewer_id,+ });+ handler+ .share_pane+ .store(7, std::sync::atomic::Ordering::Relaxed);+ // Its pane, cut to the screen when the rows are read.+ handler.share_gate(&lines).unwrap();+ assert!(handler.screen_only(7));+ // Another pane is not shared with it.+ let other = Pdu::GetPaneRenderChanges(GetPaneRenderChanges { pane_id: 8 });+ assert!(handler.share_gate(&other).is_err());+ assert!(handler.share_may_read(7));+ assert!(!handler.share_may_read(8));++ // Typing waits for the owner.+ let paste = Pdu::SendPaste(SendPaste {+ pane_id: 7,+ data: "rm -rf ~\n".into(),+ });+ assert!(handler.share_gate(&paste).is_err());+ crate::share::grant_for_test(share_id, viewer_id);+ handler.share_gate(&paste).unwrap();++ // Nothing off the list gets as far as the gate.+ assert!(!super::share_peer_may_send(&Pdu::KillPane(codec::KillPane { pane_id: 7 })));+ assert!(!super::share_peer_may_send(&Pdu::ListPanes(codec::ListPanes {})));+ assert!(!super::share_peer_may_send(&Pdu::GetTlsCreds(codec::GetTlsCreds {})));+ assert!(!super::share_peer_may_send(&Pdu::ShareList(codec::ShareList {})));+ assert!(super::share_peer_may_send(&Pdu::ShareJoin(codec::ShareJoin { share_id })));++ // Leaving takes the viewer out of the share.+ drop(handler);+ assert_eq!(crate::share::may_read(viewer_id, share_id, 7), None);+ }+#[test]fn only_a_client_registered_on_the_socket_itself_is_direct() {let id = |pid| ClientId {diff --git a/wezterm-mux-server-impl/src/share.rs b/wezterm-mux-server-impl/src/share.rsnew file mode 100644index 00000000..95dc9ca8--- /dev/null+++ b/wezterm-mux-server-impl/src/share.rs@@ -0,0 +1,1565 @@+//! Sharing a pane with other accounts on this machine.+//!+//! A share names one pane and who may see it: accounts, or every account+//! in a group. While any share exists the server listens on a second+//! socket, `/tmp/thinkterm-share-<uid>/share.sock`, which every account on+//! the machine can reach. Who is at the other end of a connection there is+//! read from the socket itself, so nothing the client says about itself is+//! believed, and a connection from an account no share is for is closed+//! as soon as it is made. A viewer may read the shared pane's rows and+//! nothing else, and may type into it only while the owner lets it, one+//! viewer at a time. With no share there is no socket, no thread and no+//! work.+//!+//! The pane's rows reach a viewer the way they reach any client: one more+//! connection the server pushes changes to. Nothing here touches the+//! pane's output path.++use crate::sessionhandler::PduSender;+use anyhow::anyhow;+#[cfg(unix)]+use anyhow::Context as _;+use codec::{+ DecodedPdu, IncomingShare, Pdu, ShareAudience, ShareController, ShareIncomingResponse,+ ShareInfo, ShareJoinResponse, ShareStart, ShareStateChanged, ShareViewer,+};+use mux::pane::PaneId;+use mux::Mux;+use std::collections::{BTreeMap, HashMap, HashSet};+use std::io::Write as _;+use std::ops::Range;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant, SystemTime};+use wezterm_term::StableRowIndex;++/// Shares one server holds at once.+const MAX_SHARES: usize = 32;+/// Viewers of one share at once.+pub const MAX_VIEWERS: usize = 20;+/// Viewers of one share from the same account at once.+const MAX_VIEWERS_PER_ACCOUNT: usize = 3;+/// Connections on the share socket at once, and from one account.+const MAX_CONNECTIONS: usize = 64;+const MAX_CONNECTIONS_PER_ACCOUNT: usize = 4;+/// Accounts and groups one share may name.+const MAX_AUDIENCE: usize = 64;+/// The longest a right to type may be given for.+const MAX_DURATION: Duration = Duration::from_secs(30 * 24 * 60 * 60);+/// The longest a share lasts, in seconds: one forgotten about ends.+const SHARE_FOR_AT_MOST: u64 = 30 * 60;+/// Rows one viewer may read in one ask: screens of several hundred rows,+/// more than a viewer asks for at once, and no more than that.+const MAX_ROWS_PER_ASK: StableRowIndex = 2000;+/// A viewer asking to type again this soon is not heard again.+const ASK_AGAIN_AFTER: Duration = Duration::from_secs(5);+/// How often expiries, lapsed typing rights and closed panes are noticed.+const TICK: Duration = Duration::from_secs(2);+/// The audit log is started afresh past this, keeping one older file.+const LOG_LIMIT: u64 = 1024 * 1024;++/// A connection on the share socket, as the kernel identified it.+#[derive(Debug, Clone)]+pub struct SharePeer {+ pub uid: u32,+ pub name: String,+ /// The account's primary group, which a group share also admits.+ pub gid: u32,+ /// Closed to drop the connection: when its viewer is removed, or its+ /// share ends.+ pub dropped: smol::channel::Receiver<()>,+ dropper: smol::channel::Sender<()>,+}++impl SharePeer {+ pub fn new(uid: u32, name: String, gid: u32) -> Self {+ let (dropper, dropped) = smol::channel::bounded(1);+ Self {+ uid,+ name,+ gid,+ dropped,+ dropper,+ }+ }+}++struct Viewer {+ name: String,+ uid: u32,+ since: SystemTime,+ sender: PduSender,+ dropper: smol::channel::Sender<()>,+ /// When it last asked to type.+ asked: Option<Instant>,+}++struct Controller {+ viewer_id: u64,+ until: Option<SystemTime>,+}++/// The connection a person shared panes from: their desktop's, to this+/// server. What it shared ends when it closes -- ThinkTerm quit, or lost+/// its way here -- so nobody goes on watching or typing once they have+/// gone.+#[derive(Clone)]+pub struct Sharer {+ connected: Arc<AtomicBool>,+}++/// A connection still open.+impl Default for Sharer {+ fn default() -> Self {+ Self {+ connected: Arc::new(AtomicBool::new(true)),+ }+ }+}++impl Sharer {+ /// Its connection closed: end what it shared.+ pub fn left(&self) {+ self.connected.store(false, Ordering::SeqCst);+ let mut registry = REGISTRY.lock().unwrap();+ let shared: Vec<u64> = registry+ .shares+ .iter()+ .filter(|(_, share)| Arc::ptr_eq(&share.sharer.connected, &self.connected))+ .map(|(id, _)| *id)+ .collect();+ for share_id in shared {+ let _ = registry.end(share_id, "owner left", codec::share_end::STOPPED);+ }+ }++ fn is_connected(&self) -> bool {+ self.connected.load(Ordering::SeqCst)+ }+}++struct Share {+ pane_id: PaneId,+ /// Where it was started; it ends with that.+ sharer: Sharer,+ audience: Vec<ShareAudience>,+ /// Whether viewers may read the pane's history, or only its screen.+ history: bool,+ started: SystemTime,+ expires: Option<SystemTime>,+ viewers: BTreeMap<u64, Viewer>,+ controller: Option<Controller>,+ /// Viewers asking to type, oldest first.+ requests: Vec<u64>,+ /// Accounts the owner removed, which may not come back to this share.+ removed: HashSet<u32>,+}++#[derive(Default)]+struct Registry {+ shares: BTreeMap<u64, Share>,+ next_share_id: u64,+ next_viewer_id: u64,+ #[cfg(unix)]+ listener: Option<listener::Listener>,+ ticking: bool,+}++lazy_static::lazy_static! {+ static ref REGISTRY: Mutex<Registry> = Mutex::new(Registry::default());+ /// Connections open on the share socket, by account.+ static ref CONNECTIONS: Mutex<HashMap<u32, usize>> = Mutex::new(HashMap::new());+}++fn unix_secs(time: SystemTime) -> u64 {+ time.duration_since(SystemTime::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+}++/// `secs` from now, for a share or a right to type; refused past+/// `MAX_DURATION`.+fn after(secs: u64) -> anyhow::Result<SystemTime> {+ let span = Duration::from_secs(secs);+ anyhow::ensure!(+ span <= MAX_DURATION,+ "at most {} days at a time",+ MAX_DURATION.as_secs() / 86400+ );+ SystemTime::now()+ .checked_add(span)+ .ok_or_else(|| anyhow!("{secs} seconds from now is past what this clock can say"))+}++/// Whether an account name, or a group name, can be looked up as given:+/// the characters accounts are made of, nothing a path or a shell would+/// read otherwise.+#[cfg_attr(not(unix), allow(dead_code))]+fn plausible_name(name: &str) -> bool {+ !name.is_empty()+ && name.len() <= 64+ && name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '$' | '@'))+}++/// Whether `peer` is one of the accounts `audience` names. The owner always+/// is: sharing with yourself is how a second screen watches. A group is+/// looked up at each check, so an account added to it while the share runs+/// is let in and one taken out is kept out; the lookup may be slow (a+/// directory server), so no lock is held across it.+fn admitted(audience: &[ShareAudience], peer: &SharePeer) -> bool {+ if peer.uid == own_uid() {+ return true;+ }+ audience.iter().any(|who| match who {+ ShareAudience::User(name) => *name == peer.name,+ ShareAudience::Group(group) => group_has(group, peer),+ })+}++impl Share {+ fn info(&self, share_id: u64) -> ShareInfo {+ let viewer = |viewer_id: u64| {+ self.viewers.get(&viewer_id).map(|v| ShareViewer {+ viewer_id,+ name: v.name.clone(),+ since: unix_secs(v.since),+ })+ };+ ShareInfo {+ share_id,+ pane_id: self.pane_id,+ audience: self.audience.clone(),+ history: self.history,+ started: unix_secs(self.started),+ expires: self.expires.map(unix_secs),+ viewers: self.viewers.keys().filter_map(|id| viewer(*id)).collect(),+ controller: self.controller.as_ref().and_then(|c| {+ self.viewers.get(&c.viewer_id).map(|v| ShareController {+ viewer_id: c.viewer_id,+ name: v.name.clone(),+ until: c.until.map(unix_secs),+ })+ }),+ requests: self.requests.iter().filter_map(|id| viewer(*id)).collect(),+ }+ }++ fn controller_name(&self) -> Option<String> {+ self.controller+ .as_ref()+ .and_then(|c| self.viewers.get(&c.viewer_id))+ .map(|v| v.name.clone())+ }++ fn is_controller(&self, viewer_id: u64) -> bool {+ self.controller+ .as_ref()+ .is_some_and(|c| c.viewer_id == viewer_id)+ }++ /// Tell every viewer where typing stands now.+ fn announce(&self, share_id: u64) {+ let controller = self.controller_name();+ for (viewer_id, viewer) in &self.viewers {+ let state = ShareStateChanged {+ share_id,+ controlling: self.is_controller(*viewer_id),+ requested: self.requests.contains(viewer_id),+ controller: controller.clone(),+ ended: None,+ };+ push(&viewer.sender, state);+ }+ }+}++fn push(sender: &PduSender, state: ShareStateChanged) {+ let _ = sender.send(DecodedPdu {+ serial: 0,+ pdu: Pdu::ShareStateChanged(state),+ });+}++/// End a viewer's watch: say why, then drop its connection.+fn dismiss(share_id: u64, viewer: Viewer, reason: &str) {+ push(+ &viewer.sender,+ ShareStateChanged {+ share_id,+ controlling: false,+ requested: false,+ controller: None,+ ended: Some(reason.to_string()),+ },+ );+ viewer.dropper.close();+}++#[cfg(unix)]+fn own_uid() -> u32 {+ nix::unistd::geteuid().as_raw()+}++#[cfg(not(unix))]+fn own_uid() -> u32 {+ u32::MAX+}++/// The account this server runs as.+pub fn own_name() -> String {+ #[cfg(unix)]+ {+ if let Ok(Some(user)) = nix::unistd::User::from_uid(nix::unistd::geteuid()) {+ return user.name;+ }+ }+ std::env::var("USER").unwrap_or_default()+}++#[cfg(unix)]+fn group_has(group: &str, peer: &SharePeer) -> bool {+ match nix::unistd::Group::from_name(group) {+ Ok(Some(group)) => group.gid.as_raw() == peer.gid || group.mem.contains(&peer.name),+ _ => false,+ }+}++#[cfg(not(unix))]+fn group_has(_group: &str, _peer: &SharePeer) -> bool {+ false+}++/// `who`, as the machine spells it: a lookup may take another case, or+/// another of an account's names (macOS does), and a viewer is told+/// apart by the name the machine gives it.+#[cfg(unix)]+fn check_audience(who: &ShareAudience) -> anyhow::Result<ShareAudience> {+ Ok(match who {+ ShareAudience::User(name) => {+ anyhow::ensure!(plausible_name(name), "`{name}` is not an account name");+ let user = nix::unistd::User::from_name(name)+ .with_context(|| format!("looking up the account `{name}`"))?+ .ok_or_else(|| anyhow!("there is no account `{name}` on this machine"))?;+ ShareAudience::User(user.name)+ }+ ShareAudience::Group(name) => {+ anyhow::ensure!(plausible_name(name), "`{name}` is not a group name");+ let group = nix::unistd::Group::from_name(name)+ .with_context(|| format!("looking up the group `{name}`"))?+ .ok_or_else(|| anyhow!("there is no group `{name}` on this machine"))?;+ ShareAudience::Group(group.name)+ }+ })+}++#[cfg(not(unix))]+fn check_audience(_who: &ShareAudience) -> anyhow::Result<ShareAudience> {+ anyhow::bail!("sharing terminals is not supported on Windows yet")+}++/// How long a share asked to last `expires_in_secs` lasts: half an hour+/// at most.+fn share_for(expires_in_secs: Option<u64>) -> u64 {+ expires_in_secs.map_or(SHARE_FOR_AT_MOST, |secs| secs.min(SHARE_FOR_AT_MOST))+}++/// Start a share, for as long as `sharer` stays. Runs on a thread of its+/// own: the accounts it names are looked up, maybe in a directory slow to+/// answer.+pub fn start(request: ShareStart, sharer: Sharer) -> anyhow::Result<ShareInfo> {+ // What other accounts see is a person's to decide: a program in a pane+ // -- an agent -- cannot share it.+ anyhow::ensure!(+ request.from_desktop,+ "a pane is shared from the share button in ThinkTerm"+ );+ anyhow::ensure!(+ !request.audience.is_empty(),+ "say who the pane is for: an account, or a group"+ );+ anyhow::ensure!(+ request.audience.len() <= MAX_AUDIENCE,+ "a share names at most {MAX_AUDIENCE} accounts and groups"+ );+ let mut audience = vec![];+ for who in &request.audience {+ let who = check_audience(who)?;+ if !audience.contains(&who) {+ audience.push(who);+ }+ }+ anyhow::ensure!(+ Mux::get().get_pane(request.pane_id).is_some(),+ "no such pane {}",+ request.pane_id+ );+ let expires = after(share_for(request.expires_in_secs))?;+ let share = Share {+ pane_id: request.pane_id,+ sharer,+ audience,+ // Only what is on the pane's screen: what came before is not+ // shared, whatever the request says.+ history: false,+ started: SystemTime::now(),+ expires: Some(expires),+ viewers: BTreeMap::new(),+ controller: None,+ requests: vec![],+ removed: HashSet::new(),+ };++ let mut registry = REGISTRY.lock().unwrap();+ // Asked for, then gone while the accounts were looked up: under the+ // lock its leaving takes, so the share is never left behind.+ anyhow::ensure!(+ share.sharer.is_connected(),+ "the window that asked to share has gone"+ );+ // A pane is shared once: one panel shows its share, and stopping that+ // leaves nobody watching through another.+ if let Some(share_id) = registry.share_of(request.pane_id) {+ anyhow::bail!(+ "pane {} is already shared (share {share_id}); stop that share first",+ request.pane_id+ );+ }+ anyhow::ensure!(+ registry.shares.len() < MAX_SHARES,+ "this server already holds {MAX_SHARES} shares; stop one first"+ );+ registry.ensure_listener()?;+ registry.next_share_id += 1;+ let share_id = registry.next_share_id;+ let info = share.info(share_id);+ audit(+ "started",+ share_id,+ share.pane_id,+ None,+ &serde_json::json!({+ "audience": share.audience.iter().map(ToString::to_string).collect::<Vec<_>>(),+ "history": share.history,+ "expires": share.expires.map(unix_secs),+ }),+ );+ registry.shares.insert(share_id, share);+ registry.ensure_ticking();+ Ok(info)+}++pub fn list() -> Vec<ShareInfo> {+ let registry = REGISTRY.lock().unwrap();+ registry+ .shares+ .iter()+ .map(|(id, share)| share.info(*id))+ .collect()+}++pub fn stop(share_id: u64) -> anyhow::Result<()> {+ let mut registry = REGISTRY.lock().unwrap();+ registry.end(share_id, "stopped", codec::share_end::STOPPED)+}++/// Drop a viewer, and keep its account out of this share from now on.+pub fn kick(share_id: u64, viewer_id: u64) -> anyhow::Result<()> {+ let mut registry = REGISTRY.lock().unwrap();+ let share = registry.share_mut(share_id)?;+ let viewer = share+ .viewers+ .remove(&viewer_id)+ .ok_or_else(|| anyhow!("no viewer {viewer_id} in share {share_id}"))?;+ if viewer.uid != own_uid() {+ share.removed.insert(viewer.uid);+ }+ // The account's other connections to this share go with it.+ let same_account: Vec<u64> = share+ .viewers+ .iter()+ .filter(|(_, v)| v.uid == viewer.uid && viewer.uid != own_uid())+ .map(|(id, _)| *id)+ .collect();+ let mut dropped = vec![(viewer_id, viewer)];+ for id in same_account {+ if let Some(other) = share.viewers.remove(&id) {+ dropped.push((id, other));+ }+ }+ let mut had_control = false;+ for (id, viewer) in dropped {+ had_control |= share.is_controller(id);+ share.requests.retain(|asking| *asking != id);+ audit(+ "removed",+ share_id,+ share.pane_id,+ Some(&viewer.name),+ &serde_json::json!({}),+ );+ dismiss(share_id, viewer, codec::share_end::REMOVED);+ }+ if had_control {+ share.controller = None;+ share.announce(share_id);+ }+ Ok(())+}++/// Let a viewer type. A person decides that too: only the desktop's+/// share panel asks.+pub fn grant(+ share_id: u64,+ viewer_id: u64,+ for_secs: Option<u64>,+ from_desktop: bool,+) -> anyhow::Result<()> {+ anyhow::ensure!(+ from_desktop,+ "a viewer is let type from the share panel in ThinkTerm"+ );+ let until = for_secs.map(after).transpose()?;+ let mut registry = REGISTRY.lock().unwrap();+ let share = registry.share_mut(share_id)?;+ let name = share+ .viewers+ .get(&viewer_id)+ .map(|v| v.name.clone())+ .ok_or_else(|| anyhow!("no viewer {viewer_id} in share {share_id}"))?;+ share.controller = Some(Controller { viewer_id, until });+ share.requests.retain(|id| *id != viewer_id);+ audit(+ "may type",+ share_id,+ share.pane_id,+ Some(&name),+ &serde_json::json!({ "for_secs": for_secs }),+ );+ share.announce(share_id);+ Ok(())+}++/// Turn down a request to type; the viewer goes on watching.+pub fn deny(share_id: u64, viewer_id: u64) -> anyhow::Result<()> {+ let mut registry = REGISTRY.lock().unwrap();+ let share = registry.share_mut(share_id)?;+ if share.requests.contains(&viewer_id) {+ share.requests.retain(|id| *id != viewer_id);+ let name = share.viewers.get(&viewer_id).map(|v| v.name.clone());+ audit(+ "turned down",+ share_id,+ share.pane_id,+ name.as_deref(),+ &serde_json::json!({}),+ );+ share.announce(share_id);+ }+ Ok(())+}++pub fn revoke(share_id: u64) -> anyhow::Result<()> {+ let mut registry = REGISTRY.lock().unwrap();+ let share = registry.share_mut(share_id)?;+ if let Some(controller) = share.controller.take() {+ let name = share+ .viewers+ .get(&controller.viewer_id)+ .map(|v| v.name.clone());+ audit(+ "typing taken back",+ share_id,+ share.pane_id,+ name.as_deref(),+ &serde_json::json!({}),+ );+ share.announce(share_id);+ }+ Ok(())+}++/// What a share looks like before deciding whether a peer may see it.+struct Candidate {+ share_id: u64,+ pane_id: PaneId,+ audience: Vec<ShareAudience>,+ history: bool,+ started: SystemTime,+ controller: Option<String>,+}++/// The shares `peer` might see: copied out, so that whether it may is+/// decided with no lock held.+fn candidates(peer: &SharePeer) -> Vec<Candidate> {+ let registry = REGISTRY.lock().unwrap();+ registry+ .shares+ .iter()+ .filter(|(_, share)| !share.removed.contains(&peer.uid))+ .map(|(id, share)| Candidate {+ share_id: *id,+ pane_id: share.pane_id,+ audience: share.audience.clone(),+ history: share.history,+ started: share.started,+ controller: share.controller_name(),+ })+ .collect()+}++/// At most this many accounts, and as many groups, are offered to pick+/// from.+const MAX_CANDIDATES: usize = 500;++/// The accounts and groups of this machine a pane can be shared with:+/// people's, not the system's own.+pub fn candidates_to_share_with() -> codec::ShareCandidatesResponse {+ let (mut accounts, mut groups) = people_and_groups();+ accounts.sort();+ accounts.dedup();+ accounts.truncate(MAX_CANDIDATES);+ groups.sort();+ groups.dedup();+ groups.truncate(MAX_CANDIDATES);+ let me = own_name();+ if !me.is_empty() && !accounts.contains(&me) {+ accounts.insert(0, me.clone());+ }+ codec::ShareCandidatesResponse {+ me,+ accounts,+ groups,+ }+}++/// From `/etc/passwd` and `/etc/group`: accounts from uid 1000, with a+/// shell to log in with, and groups from gid 1000. Accounts a directory+/// service holds are not listed there, and are not offered.+#[cfg(all(unix, not(target_os = "macos")))]+fn people_and_groups() -> (Vec<String>, Vec<String>) {+ let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default();+ let accounts = read("/etc/passwd")+ .lines()+ .filter_map(|line| {+ let fields: Vec<&str> = line.split(':').collect();+ let uid: u32 = fields.get(2)?.parse().ok()?;+ let shell = fields.get(6).copied().unwrap_or("");+ let logs_in = !shell.ends_with("nologin") && !shell.ends_with("false");+ (uid >= 1000 && uid != 65534 && logs_in).then(|| fields[0].to_string())+ })+ .collect();+ let groups = read("/etc/group")+ .lines()+ .filter_map(|line| {+ let fields: Vec<&str> = line.split(':').collect();+ let gid: u32 = fields.get(2)?.parse().ok()?;+ (gid >= 1000 && gid != 65534).then(|| fields[0].to_string())+ })+ .collect();+ (accounts, groups)+}++/// From the directory service: accounts and groups from id 500, without+/// the system's own: names starting with an underscore, and the groups+/// macOS makes for its sharing services (`com.apple.sharepoint.group.1`).+#[cfg(target_os = "macos")]+fn people_and_groups() -> (Vec<String>, Vec<String>) {+ let list = |kind: &str, id: &str| -> Vec<String> {+ let output = std::process::Command::new("/usr/bin/dscl")+ .args([".", "-list", kind, id])+ .output();+ let Ok(output) = output else {+ return vec![];+ };+ String::from_utf8_lossy(&output.stdout)+ .lines()+ .filter_map(|line| {+ let mut words = line.split_whitespace();+ let name = words.next()?;+ let id: i64 = words.next()?.parse().ok()?;+ let system = name.starts_with('_') || name.starts_with("com.apple.");+ (id >= 500 && !system).then(|| name.to_string())+ })+ .collect()+ };+ (+ list("/Users", "UniqueID"),+ list("/Groups", "PrimaryGroupID"),+ )+}++#[cfg(not(unix))]+fn people_and_groups() -> (Vec<String>, Vec<String>) {+ (vec![], vec![])+}++/// Whether any share is for `peer`: a connection from an account none is+/// for is closed at once.+pub fn admits_anywhere(peer: &SharePeer) -> bool {+ candidates(peer)+ .iter()+ .any(|share| admitted(&share.audience, peer))+}++/// The shares `peer` may watch, with their titles read without waiting+/// on the panes.+pub fn incoming(peer: &SharePeer) -> ShareIncomingResponse {+ let mux = Mux::get();+ ShareIncomingResponse {+ owner: own_name(),+ shares: candidates(peer)+ .into_iter()+ .filter(|share| admitted(&share.audience, peer))+ .map(|share| IncomingShare {+ share_id: share.share_id,+ pane_id: share.pane_id,+ title: mux+ .get_pane(share.pane_id)+ .map(|pane| pane.summary_without_waiting().title)+ .unwrap_or_default(),+ history: share.history,+ started: unix_secs(share.started),+ controller: share.controller,+ })+ .collect(),+ }+}++/// Start `peer` watching a share. `sender` carries what the server tells+/// the viewer later; the connection ends when its share or its place in it+/// does.+pub fn join(+ peer: &SharePeer,+ share_id: u64,+ sender: PduSender,+) -> anyhow::Result<ShareJoinResponse> {+ let not_here = || anyhow!("no share {share_id} for you here");+ let audience = candidates(peer)+ .into_iter()+ .find(|share| share.share_id == share_id)+ .map(|share| share.audience)+ .ok_or_else(not_here)?;+ anyhow::ensure!(admitted(&audience, peer), not_here());++ let mut registry = REGISTRY.lock().unwrap();+ registry.next_viewer_id += 1;+ let viewer_id = registry.next_viewer_id;+ let share = registry+ .shares+ .get_mut(&share_id)+ .filter(|share| !share.removed.contains(&peer.uid))+ .ok_or_else(not_here)?;+ anyhow::ensure!(+ share.viewers.len() < MAX_VIEWERS,+ "share {share_id} already has {MAX_VIEWERS} viewers"+ );+ let from_account = share.viewers.values().filter(|v| v.uid == peer.uid).count();+ anyhow::ensure!(+ from_account < MAX_VIEWERS_PER_ACCOUNT,+ "you already watch share {share_id} {MAX_VIEWERS_PER_ACCOUNT} times"+ );+ share.viewers.insert(+ viewer_id,+ Viewer {+ name: peer.name.clone(),+ uid: peer.uid,+ since: SystemTime::now(),+ sender,+ dropper: peer.dropper.clone(),+ asked: None,+ },+ );+ audit(+ "joined",+ share_id,+ share.pane_id,+ Some(&peer.name),+ &serde_json::json!({}),+ );+ let response = ShareJoinResponse {+ share_id,+ pane_id: share.pane_id,+ viewer_id,+ history: share.history,+ };+ // Who types now, so a viewer arriving mid-way knows.+ share.announce(share_id);+ Ok(response)+}++/// A viewer asks to type. Asking again within `ASK_AGAIN_AFTER` is not+/// heard: one request is enough for the owner to see.+pub fn request_control(viewer_id: u64, share_id: u64) -> anyhow::Result<()> {+ let mut registry = REGISTRY.lock().unwrap();+ let share = registry.share_of_viewer(share_id, viewer_id)?;+ if share.is_controller(viewer_id) || share.requests.contains(&viewer_id) {+ return Ok(());+ }+ let Some(viewer) = share.viewers.get_mut(&viewer_id) else {+ return Ok(());+ };+ if viewer+ .asked+ .is_some_and(|at| at.elapsed() < ASK_AGAIN_AFTER)+ {+ return Ok(());+ }+ viewer.asked = Some(Instant::now());+ let name = viewer.name.clone();+ share.requests.push(viewer_id);+ audit(+ "asked to type",+ share_id,+ share.pane_id,+ Some(&name),+ &serde_json::json!({}),+ );+ share.announce(share_id);+ Ok(())+}++pub fn release_control(viewer_id: u64, share_id: u64) -> anyhow::Result<()> {+ let mut registry = REGISTRY.lock().unwrap();+ let share = registry.share_of_viewer(share_id, viewer_id)?;+ let controlling = share.is_controller(viewer_id);+ let requested = share.requests.contains(&viewer_id);+ if controlling {+ share.controller = None;+ let name = share.viewers.get(&viewer_id).map(|v| v.name.clone());+ audit(+ "gave typing back",+ share_id,+ share.pane_id,+ name.as_deref(),+ &serde_json::json!({}),+ );+ }+ share.requests.retain(|id| *id != viewer_id);+ if controlling || requested {+ share.announce(share_id);+ }+ Ok(())+}++/// A viewer's connection closed.+pub fn leave(viewer_id: u64, share_id: u64) {+ let mut registry = REGISTRY.lock().unwrap();+ let Some(share) = registry.shares.get_mut(&share_id) else {+ return;+ };+ let Some(viewer) = share.viewers.remove(&viewer_id) else {+ return;+ };+ let had_control = share.is_controller(viewer_id);+ if had_control {+ share.controller = None;+ }+ share.requests.retain(|id| *id != viewer_id);+ audit(+ "left",+ share_id,+ share.pane_id,+ Some(&viewer.name),+ &serde_json::json!({}),+ );+ if had_control {+ share.announce(share_id);+ }+}++/// Whether a viewer may read `pane_id`, and if so whether its history:+/// `Some(true)` for the whole pane, `Some(false)` for its screen only.+pub fn may_read(viewer_id: u64, share_id: u64, pane_id: PaneId) -> Option<bool> {+ let registry = REGISTRY.lock().unwrap();+ let share = registry.shares.get(&share_id)?;+ (share.pane_id == pane_id && share.viewers.contains_key(&viewer_id)).then_some(share.history)+}++/// Whether a viewer may type into `pane_id` now.+pub fn may_type(viewer_id: u64, share_id: u64, pane_id: PaneId) -> bool {+ let registry = REGISTRY.lock().unwrap();+ registry.shares.get(&share_id).is_some_and(|share| {+ share.pane_id == pane_id+ && share.controller.as_ref().is_some_and(|c| {+ c.viewer_id == viewer_id && c.until.is_none_or(|until| SystemTime::now() < until)+ })+ })+}++/// The rows a viewer asked for, as few ranges as hold them: overlapping+/// ones merged, and the earliest `MAX_ROWS_PER_ASK` rows of them. Asking+/// for the same rows over and over, or for all of a long history at once,+/// makes no work beyond that.+pub fn viewer_rows(mut ranges: Vec<Range<StableRowIndex>>) -> Vec<Range<StableRowIndex>> {+ ranges.retain(|range| range.start < range.end);+ ranges.sort_by_key(|range| range.start);+ let mut merged: Vec<Range<StableRowIndex>> = vec![];+ for range in ranges {+ match merged.last_mut() {+ Some(last) if range.start <= last.end => last.end = last.end.max(range.end),+ _ => merged.push(range),+ }+ }+ let mut left = MAX_ROWS_PER_ASK;+ let mut rows = vec![];+ for range in merged {+ if left == 0 {+ break;+ }+ let take = range.end.saturating_sub(range.start).min(left);+ rows.push(range.start..range.start + take);+ left -= take;+ }+ rows+}++/// A place among the connections on the share socket, given back when the+/// connection ends.+pub struct ConnectionSlot {+ uid: u32,+}++impl ConnectionSlot {+ /// A place for one more connection from `uid`, if the socket has room+ /// for it.+ pub fn take(uid: u32) -> Option<Self> {+ let mut open = CONNECTIONS.lock().unwrap();+ let total: usize = open.values().sum();+ let mine = open.get(&uid).copied().unwrap_or(0);+ if total >= MAX_CONNECTIONS || mine >= MAX_CONNECTIONS_PER_ACCOUNT {+ return None;+ }+ open.insert(uid, mine + 1);+ Some(Self { uid })+ }+}++impl Drop for ConnectionSlot {+ fn drop(&mut self) {+ let mut open = CONNECTIONS.lock().unwrap();+ if let Some(count) = open.get_mut(&self.uid) {+ *count = count.saturating_sub(1);+ if *count == 0 {+ open.remove(&self.uid);+ }+ }+ }+}++impl Registry {+ fn share_mut(&mut self, share_id: u64) -> anyhow::Result<&mut Share> {+ self.shares+ .get_mut(&share_id)+ .ok_or_else(|| anyhow!("no share {share_id}"))+ }++ /// The share of `pane_id`, while it has one.+ fn share_of(&self, pane_id: PaneId) -> Option<u64> {+ self.shares+ .iter()+ .find(|(_, share)| share.pane_id == pane_id)+ .map(|(share_id, _)| *share_id)+ }++ fn share_of_viewer(&mut self, share_id: u64, viewer_id: u64) -> anyhow::Result<&mut Share> {+ self.shares+ .get_mut(&share_id)+ .filter(|share| share.viewers.contains_key(&viewer_id))+ .ok_or_else(|| anyhow!("you are not watching share {share_id}"))+ }++ /// End a share: `event` for the log, `reason` for its viewers.+ fn end(&mut self, share_id: u64, event: &str, reason: &str) -> anyhow::Result<()> {+ let share = self+ .shares+ .remove(&share_id)+ .ok_or_else(|| anyhow!("no share {share_id}"))?;+ audit(event, share_id, share.pane_id, None, &serde_json::json!({}));+ for (_, viewer) in share.viewers {+ dismiss(share_id, viewer, reason);+ }+ if self.shares.is_empty() {+ self.close_listener();+ }+ Ok(())+ }++ #[cfg(unix)]+ fn ensure_listener(&mut self) -> anyhow::Result<()> {+ if self.listener.is_none() {+ self.listener = Some(listener::Listener::open()?);+ }+ Ok(())+ }++ #[cfg(not(unix))]+ fn ensure_listener(&mut self) -> anyhow::Result<()> {+ anyhow::bail!("sharing terminals is not supported on Windows yet")+ }++ /// Closed here and now, the socket gone before the lock is let go: a+ /// share started next opens a socket of its own where this one was.+ fn close_listener(&mut self) {+ #[cfg(unix)]+ if let Some(listener) = self.listener.take() {+ listener.close();+ }+ }++ /// One thread notices what lapses with time, while there is anything+ /// to notice; it ends with the last share.+ fn ensure_ticking(&mut self) {+ if self.ticking {+ return;+ }+ self.ticking = true;+ let spawned = std::thread::Builder::new()+ .name("share-tick".into())+ .spawn(|| loop {+ std::thread::sleep(TICK);+ if !tick() {+ break;+ }+ });+ if let Err(err) = spawned {+ log::error!("cannot start the thread that ends lapsed shares: {err:#}");+ self.ticking = false;+ }+ }+}++/// End what has lapsed. False once there is nothing left to watch over,+/// which ends the thread.+fn tick() -> bool {+ let mux = Mux::try_get();+ let mut registry = REGISTRY.lock().unwrap();+ let now = SystemTime::now();+ let lapsed: Vec<(u64, &'static str, &'static str)> = registry+ .shares+ .iter()+ .filter_map(|(id, share)| {+ let pane_gone = mux+ .as_ref()+ .is_some_and(|mux| mux.get_pane(share.pane_id).is_none());+ if pane_gone {+ Some((*id, "pane closed", codec::share_end::CLOSED))+ } else if share.expires.is_some_and(|at| at <= now) {+ Some((*id, "expired", codec::share_end::EXPIRED))+ } else {+ None+ }+ })+ .collect();+ for (share_id, event, reason) in lapsed {+ let _ = registry.end(share_id, event, reason);+ }+ for (share_id, share) in registry.shares.iter_mut() {+ let lapsed = share+ .controller+ .as_ref()+ .and_then(|c| c.until)+ .is_some_and(|until| until <= now);+ if lapsed {+ share.controller = None;+ audit(+ "typing lapsed",+ *share_id,+ share.pane_id,+ None,+ &serde_json::json!({}),+ );+ share.announce(*share_id);+ }+ }+ if registry.shares.is_empty() {+ registry.ticking = false;+ return false;+ }+ true+}++/// The server is going away: end every share, telling its viewers, and+/// take the socket down so nobody finds it left behind.+pub fn shut_down() {+ let mut registry = REGISTRY.lock().unwrap();+ let ids: Vec<u64> = registry.shares.keys().copied().collect();+ for share_id in ids {+ let _ = registry.end(share_id, "server stopped", codec::share_end::STOPPED);+ }+ // The last share's end took the socket down; this is for one that+ // outlived its shares.+ registry.close_listener();+}++pub fn log_path() -> PathBuf {+ config::DATA_DIR.join("share-log.jsonl")+}++/// One line in the share log: who came and went, and who could type.+/// Tests leave the log alone: it is in the data directory of whoever runs+/// them.+fn audit(+ event: &str,+ share_id: u64,+ pane_id: PaneId,+ who: Option<&str>,+ detail: &serde_json::Value,+) {+ if cfg!(test) {+ return;+ }+ let line = serde_json::json!({+ "time": unix_secs(SystemTime::now()),+ "event": event,+ "share": share_id,+ "pane": pane_id,+ "who": who,+ "detail": detail,+ });+ if let Err(err) = append_log(&log_path(), &line.to_string()) {+ log::warn!("cannot write the share log: {err:#}");+ }+}++fn append_log(path: &Path, line: &str) -> anyhow::Result<()> {+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)?;+ }+ if std::fs::metadata(path).is_ok_and(|meta| meta.len() > LOG_LIMIT) {+ let older = path.with_extension("1.jsonl");+ std::fs::rename(path, older)?;+ }+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)?;+ writeln!(file, "{line}")?;+ Ok(())+}++#[cfg(unix)]+mod listener {+ use super::*;+ use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _, PermissionsExt as _};+ use wezterm_uds::{UnixListener, UnixStream};++ pub struct Listener {+ path: PathBuf,+ closing: Arc<AtomicBool>,+ }++ /// Make the directory the socket goes in: ours, a real directory, and+ /// writable by nobody else, so nobody else can put a socket of their+ /// own where viewers look for ours. Others may pass through it, which+ /// is all a connect needs.+ pub fn prepare_dir(dir: &Path, uid: u32) -> anyhow::Result<()> {+ match std::fs::symlink_metadata(dir) {+ Ok(meta) => {+ anyhow::ensure!(+ meta.file_type().is_dir(),+ "{} is not a directory; remove it to share panes",+ dir.display()+ );+ anyhow::ensure!(+ meta.uid() == uid,+ "{} belongs to another account; an administrator has to remove it \+ before panes can be shared",+ dir.display()+ );+ }+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {+ std::fs::DirBuilder::new()+ .mode(0o711)+ .create(dir)+ .with_context(|| format!("creating {}", dir.display()))?;+ }+ Err(err) => return Err(err).with_context(|| format!("checking {}", dir.display())),+ }+ // Whatever the umask left, or a mode someone changed since.+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o711))+ .with_context(|| format!("setting the mode of {}", dir.display()))?;+ Ok(())+ }++ impl Listener {+ pub fn open() -> anyhow::Result<Self> {+ let uid = own_uid();+ let dir = codec::share_socket_dir(uid);+ prepare_dir(&dir, uid)?;+ let path = dir.join(codec::SHARE_SOCKET_NAME);+ // One server per account shares: a second one -- a test server+ // beside the usual one, say -- would take the viewers' socket+ // away from the first.+ anyhow::ensure!(+ !crate::local::someone_listens(&path),+ "another ThinkTerm server of this account already shares panes from {}; \+ stop its shares first",+ path.display()+ );+ crate::local::claim_socket_path(&path)?;+ let listener = UnixListener::bind(&path)+ .with_context(|| format!("listening on {}", path.display()))?;+ // Any account may connect; who did is read from the socket.+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o666))+ .with_context(|| format!("setting the mode of {}", path.display()))?;+ let closing = Arc::new(AtomicBool::new(false));+ {+ let closing = Arc::clone(&closing);+ std::thread::Builder::new()+ .name("share-accept".into())+ .spawn(move || accept_loop(listener, closing))+ .context("starting the share listener")?;+ }+ log::info!("sharing panes on {}", path.display());+ Ok(Self { path, closing })+ }++ /// Stop accepting and remove the socket, before this returns. The+ /// accept loop is woken with a connection of our own, which it+ /// drops on seeing why. That connection does not wait for room:+ /// the loop may itself be waiting for the registry, held by whoever+ /// closes. The directory stays: removed, another account could make+ /// one of the same name, and a viewer that had looked at ours would+ /// connect to theirs.+ pub fn close(self) {+ self.closing.store(true, Ordering::SeqCst);+ match UnixStream::connect_without_waiting(&self.path) {+ Ok(_) => {}+ // No room: the loop has others to accept first, and sees+ // why on the next of them.+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {}+ Err(err) => log::warn!("cannot wake the share listener to close it: {err:#}"),+ }+ let _ = std::fs::remove_file(&self.path);+ log::info!("no longer sharing panes on {}", self.path.display());+ }+ }++ fn accept_loop(listener: UnixListener, closing: Arc<AtomicBool>) {+ loop {+ let accepted = listener.accept();+ if closing.load(Ordering::SeqCst) {+ break;+ }+ let stream = match accepted {+ Ok((stream, _)) => stream,+ Err(err) => {+ // Out of descriptors, say: wait a moment and go on, for+ // as long as a share wants the socket.+ log::warn!("share listener: accept failed: {err:#}");+ std::thread::sleep(Duration::from_millis(200));+ continue;+ }+ };+ let peer = match identify(&stream) {+ Ok(peer) => peer,+ Err(err) => {+ log::warn!("share listener: refusing a connection: {err:#}");+ continue;+ }+ };+ // Nothing is decoded, nor any notification subscribed, for an+ // account no share is for.+ if !admits_anywhere(&peer) {+ log::debug!("share listener: no share is for uid {}", peer.uid);+ continue;+ }+ let Some(slot) = ConnectionSlot::take(peer.uid) else {+ log::warn!(+ "share listener: too many connections; refusing uid {}",+ peer.uid+ );+ continue;+ };+ crate::connections::spawn(async move {+ let _slot = slot;+ if let Err(err) = crate::dispatch::process(+ stream,+ crate::sessionhandler::ConnectionPeer::Share(peer),+ )+ .await+ {+ log::debug!("share connection: {err:#}");+ }+ });+ }+ }++ /// The account at the other end, as the kernel reports it.+ fn identify(stream: &UnixStream) -> anyhow::Result<SharePeer> {+ let uid = peer_uid(stream)?;+ let user = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))+ .context("looking up the connecting account")?+ .ok_or_else(|| anyhow!("uid {uid} has no account"))?;+ Ok(SharePeer::new(uid, user.name, user.gid.as_raw()))+ }++ #[cfg(any(target_os = "linux", target_os = "android"))]+ fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {+ use nix::sys::socket::{getsockopt, sockopt};+ Ok(getsockopt(stream, sockopt::PeerCredentials)+ .context("reading the peer's credentials")?+ .uid())+ }++ #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]+ fn peer_uid(stream: &UnixStream) -> anyhow::Result<u32> {+ use nix::sys::socket::{getsockopt, sockopt};+ Ok(getsockopt(stream, sockopt::LocalPeerCred)+ .context("reading the peer's credentials")?+ .uid())+ }++ #[cfg(not(any(+ target_os = "linux",+ target_os = "android",+ target_os = "macos",+ target_os = "ios",+ target_os = "freebsd"+ )))]+ fn peer_uid(_stream: &UnixStream) -> anyhow::Result<u32> {+ anyhow::bail!("this system does not say who is at the other end of a socket")+ }+}++#[cfg(unix)]+pub use listener::prepare_dir;++/// A share of `pane_id` with one viewer in it, put in place without a mux,+/// for tests of what a viewer may do. Returns the share and the viewer.+#[cfg(test)]+pub(crate) fn share_for_test(pane_id: PaneId, history: bool, peer: &SharePeer) -> (u64, u64) {+ let mut registry = REGISTRY.lock().unwrap();+ registry.next_share_id += 1;+ let share_id = registry.next_share_id;+ registry.next_viewer_id += 1;+ let viewer_id = registry.next_viewer_id;+ let mut viewers = BTreeMap::new();+ viewers.insert(+ viewer_id,+ Viewer {+ name: peer.name.clone(),+ uid: peer.uid,+ since: SystemTime::now(),+ sender: PduSender::new(|_| Ok(())),+ dropper: peer.dropper.clone(),+ asked: None,+ },+ );+ registry.shares.insert(+ share_id,+ Share {+ pane_id,+ sharer: Sharer::default(),+ audience: vec![ShareAudience::User(peer.name.clone())],+ history,+ started: SystemTime::now(),+ expires: None,+ viewers,+ controller: None,+ requests: vec![],+ removed: HashSet::new(),+ },+ );+ (share_id, viewer_id)+}++/// Let `viewer_id` type in a share made by `share_for_test`.+#[cfg(test)]+pub(crate) fn grant_for_test(share_id: u64, viewer_id: u64) {+ let mut registry = REGISTRY.lock().unwrap();+ registry.shares.get_mut(&share_id).unwrap().controller = Some(Controller {+ viewer_id,+ until: None,+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ // Single ranges and an empty one are what is being asked about.+ #[allow(clippy::single_range_in_vec_init, clippy::reversed_empty_ranges)]+ #[test]+ fn a_viewer_asks_for_rows_once_and_not_too_many() {+ // The same screen asked for again and again is read once.+ let asked: Vec<_> = std::iter::repeat_n(100..124, 100_000).collect();+ assert_eq!(viewer_rows(asked), vec![100..124]);+ // Overlapping and touching ranges merge; empty and backward ones+ // go.+ #[allow(clippy::reversed_empty_ranges)]+ let asked = vec![10..20, 0..5, 15..30, 30..31, 50..50, 60..55];+ assert_eq!(viewer_rows(asked), vec![0..5, 10..31]);+ // All of a long history is cut to the limit, earliest first.+ assert_eq!(viewer_rows(vec![0..1_000_000]), vec![0..MAX_ROWS_PER_ASK]);+ assert_eq!(+ viewer_rows(vec![0..1500, 5000..6000]),+ vec![0..1500, 5000..5000 + MAX_ROWS_PER_ASK - 1500]+ );+ }++ #[test]+ fn names_are_plain() {+ assert!(plausible_name("fox"));+ assert!(plausible_name("team-3"));+ assert!(plausible_name("svc$"));+ // As a directory service names its accounts.+ assert!(plausible_name("[email protected]"));+ assert!(!plausible_name(""));+ assert!(!plausible_name("../etc"));+ assert!(!plausible_name("a b"));+ assert!(!plausible_name(&"x".repeat(65)));+ }++ #[test]+ fn durations_are_bounded() {+ assert!(after(60).is_ok());+ assert!(after(MAX_DURATION.as_secs() + 1).is_err());+ assert!(after(u64::MAX).is_err());+ }++ #[test]+ fn the_log_starts_afresh_past_its_limit() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("share-log.jsonl");+ append_log(&path, "first").unwrap();+ std::fs::write(&path, vec![b'x'; (LOG_LIMIT + 1) as usize]).unwrap();+ append_log(&path, "second").unwrap();+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "second\n");+ assert!(path.with_extension("1.jsonl").exists());+ }++ #[cfg(unix)]+ #[test]+ fn the_socket_directory_must_be_ours() {+ use std::os::unix::fs::PermissionsExt as _;+ let base = tempfile::tempdir().unwrap();+ let dir = base.path().join("share");+ prepare_dir(&dir, own_uid()).unwrap();+ let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode, 0o711);+ // Someone else's directory is refused.+ let err = prepare_dir(&dir, own_uid() + 1).unwrap_err();+ assert!(err.to_string().contains("another account"), "{}", err);+ // So is a symlink standing in for one.+ let link = base.path().join("link");+ std::os::unix::fs::symlink(&dir, &link).unwrap();+ assert!(prepare_dir(&link, own_uid()).is_err());+ }++ #[test]+ fn the_owner_and_the_named_are_admitted() {+ let audience = vec![ShareAudience::User("someone-else".into())];+ let me = SharePeer::new(own_uid(), "me".into(), 0);+ assert!(admitted(&audience, &me));+ let named = SharePeer::new(own_uid().wrapping_add(1), "someone-else".into(), 12345);+ assert!(admitted(&audience, &named));+ let stranger = SharePeer::new(own_uid().wrapping_add(2), "stranger".into(), 12345);+ assert!(!admitted(&audience, &stranger));+ }++ #[test]+ fn a_removed_account_cannot_come_back() {+ let peer = SharePeer::new(own_uid().wrapping_add(3), "removed-viewer".into(), 12345);+ let (share_id, viewer_id) = share_for_test(1, false, &peer);+ kick(share_id, viewer_id).unwrap();+ let err = join(&peer, share_id, PduSender::new(|_| Ok(()))).unwrap_err();+ assert!(err.to_string().contains("no share"), "{}", err);+ assert!(+ !admits_anywhere(&peer) || candidates(&peer).iter().all(|s| s.share_id != share_id)+ );+ let _ = stop(share_id);+ }++ #[test]+ fn asking_again_at_once_is_not_heard() {+ let peer = SharePeer::new(own_uid().wrapping_add(4), "asker".into(), 12345);+ let (share_id, viewer_id) = share_for_test(2, false, &peer);+ request_control(viewer_id, share_id).unwrap();+ release_control(viewer_id, share_id).unwrap();+ request_control(viewer_id, share_id).unwrap();+ let info = list().into_iter().find(|s| s.share_id == share_id).unwrap();+ assert!(info.requests.is_empty(), "{:?}", info.requests);+ let _ = stop(share_id);+ }++ #[test]+ fn a_pane_has_one_share_at_a_time() {+ let peer = SharePeer::new(own_uid().wrapping_add(6), "one-share".into(), 12345);+ let (share_id, _) = share_for_test(3, false, &peer);+ // What `start` refuses a second share of the pane on.+ assert_eq!(REGISTRY.lock().unwrap().share_of(3), Some(share_id));+ stop(share_id).unwrap();+ assert_eq!(REGISTRY.lock().unwrap().share_of(3), None);+ }++ #[test]+ fn only_a_person_at_the_desktop_shares_or_lets_type() {+ let asked_by_a_program = ShareStart {+ pane_id: 3,+ audience: vec![ShareAudience::User(own_name())],+ history: false,+ expires_in_secs: None,+ from_desktop: false,+ };+ let err = start(asked_by_a_program, Sharer::default()).unwrap_err();+ assert!(err.to_string().contains("share button"), "{:#}", err);+ let err = grant(1, 1, None, false).unwrap_err();+ assert!(err.to_string().contains("share panel"), "{:#}", err);+ }++ #[test]+ fn a_share_lasts_half_an_hour_at_most() {+ assert_eq!(share_for(None), 30 * 60);+ assert_eq!(share_for(Some(15 * 60)), 15 * 60);+ assert_eq!(share_for(Some(2 * 60 * 60)), 30 * 60);+ }++ #[test]+ fn shares_end_when_the_desktop_that_started_them_leaves() {+ let peer = SharePeer::new(own_uid().wrapping_add(7), "left-behind".into(), 12345);+ let sharer = Sharer::default();+ let (left, viewer_id) = share_for_test(7, false, &peer);+ grant_for_test(left, viewer_id);+ REGISTRY.lock().unwrap().shares.get_mut(&left).unwrap().sharer = sharer.clone();+ let (kept, _) = share_for_test(8, false, &peer);+ sharer.left();+ assert!(!sharer.is_connected());+ let shares: Vec<u64> = list().iter().map(|s| s.share_id).collect();+ assert!(!shares.contains(&left), "{:?}", shares);+ assert!(!may_type(viewer_id, left, 7));+ assert!(shares.contains(&kept), "{:?}", shares);+ stop(kept).unwrap();+ }++ #[cfg(unix)]+ #[test]+ fn an_account_is_kept_as_the_machine_spells_it() {+ let me = own_name();+ assert_eq!(+ check_audience(&ShareAudience::User(me.clone())).unwrap(),+ ShareAudience::User(me.clone())+ );+ // macOS finds an account in whatever case it is typed; the share+ // names it as a viewer's connection will be named.+ #[cfg(target_os = "macos")]+ assert_eq!(+ check_audience(&ShareAudience::User(me.to_uppercase())).unwrap(),+ ShareAudience::User(me)+ );+ }++ #[test]+ fn connections_are_capped_per_account() {+ let uid = own_uid().wrapping_add(5);+ let slots: Vec<_> = (0..MAX_CONNECTIONS_PER_ACCOUNT)+ .map(|_| ConnectionSlot::take(uid).unwrap())+ .collect();+ assert!(ConnectionSlot::take(uid).is_none());+ drop(slots);+ assert!(ConnectionSlot::take(uid).is_some());+ }+}diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex e5068f38..cb9d521b 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -748,6 +748,7 @@ fn install_shutdown_signal_handler() -> anyhow::Result<()> {log::error!("flushing ThinkTerm layouts before shutdown: {err:#}");}wezterm_mux_server_impl::thinkterm_layout::keep_pane_output();+ wezterm_mux_server_impl::share::shut_down();std::process::exit(0);}).detach();@@ -1107,6 +1108,7 @@ mod windows_daemon {log::error!("flushing ThinkTerm layouts before shutdown: {err:#}");}wezterm_mux_server_impl::thinkterm_layout::keep_pane_output();+ wezterm_mux_server_impl::share::shut_down();std::process::exit(0);}).detach();