//! Display-only client transport. No terminal parser, PTY, or shell lives here. use crate::protocol::{self, ClientMessage, ServerMessage, SessionTarget, Snapshot, SshOptions}; use anyhow::{Context, Result, bail}; use std::{ collections::{HashSet, VecDeque}, io::{self, Read, Write}, net::Shutdown, os::{fd::OwnedFd, unix::net::UnixStream}, path::{Path, PathBuf}, process::{Child, ChildStderr, Command, Stdio}, sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, mpsc, }, thread, time::{Duration, Instant}, }; #[derive(Default)] pub struct Update { pub snapshot: Option>, pub clipboard: VecDeque, pub error: Option, pub disconnected: bool, } pub struct Updates { signal: async_channel::Receiver<()>, pending: Arc>, } impl Updates { pub fn recv_blocking(&self) -> Option { self.signal.recv_blocking().ok()?; Some(std::mem::take(&mut *self.pending.lock().unwrap())) } pub async fn recv(&self) -> Option { self.signal.recv().await.ok()?; Some(std::mem::take(&mut *self.pending.lock().unwrap())) } } #[derive(Clone)] pub struct Client(Arc); struct Connection { launcher_socket: PathBuf, remote: Option, commands: mpsc::Sender, socket: Option, ssh: Mutex>, } impl Drop for Connection { fn drop(&mut self) { // Detach closes this transport, never a server-owned PTY. if let Some(socket) = &self.socket { let _ = socket.shutdown(Shutdown::Both); } if let Some(mut child) = self.ssh.lock().unwrap().take() { let _ = child.kill(); let _ = child.wait(); } } } impl SshOptions { pub fn from_env() -> Self { Self { executable: std::env::var("PSYTERM_REMOTE_BIN").ok(), agent_socket: std::env::var_os("SSH_AUTH_SOCK").map(PathBuf::from), } } } pub fn validate_destination(destination: &str) -> Result<()> { if destination.is_empty() || destination.len() > 1024 || destination.starts_with('-') || destination .chars() .any(|c| c.is_control() || c.is_whitespace()) { bail!("invalid SSH destination"); } Ok(()) } impl Client { pub fn connect( launcher_socket: &Path, remote: Option<&str>, session: SessionTarget, ) -> Result<(Self, Updates)> { Self::connect_with( launcher_socket, remote, session, SshOptions::from_env(), None, ) } pub fn connect_remote( launcher_socket: &Path, destination: &str, session: SessionTarget, ssh: SshOptions, cancelled: Arc, ) -> Result<(Self, Updates)> { Self::connect_with( launcher_socket, Some(destination), session, ssh, Some(cancelled), ) } fn connect_with( launcher_socket: &Path, remote: Option<&str>, session: SessionTarget, options: SshOptions, cancelled: Option>, ) -> Result<(Self, Updates)> { let (mut reader, mut writer, socket, mut ssh): (_, Box, _, _) = if let Some(remote) = remote { validate_destination(remote)?; let executable = options.executable.as_deref().unwrap_or("psyterm"); let attach = if matches!(session, SessionTarget::Attach(_)) { " --attach" } else { "" }; let remote_command = format!("exec {} --bridge{attach}", shell_quote(executable)); let mut ssh_command = Command::new("ssh"); if let Some(socket) = options.agent_socket { ssh_command.env("SSH_AUTH_SOCK", socket); } else { ssh_command.env_remove("SSH_AUTH_SOCK"); } // A socketpair allows a bounded, cancellable greeting even when the // SSH connection succeeds but the remote bridge stalls. let (reader, stdout) = UnixStream::pair()?; let mut child = ssh_command .args([ "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--", remote, &remote_command, ]) .stdin(Stdio::piped()) .stdout(Stdio::from(OwnedFd::from(stdout))) .stderr(Stdio::piped()) .spawn() .context("start SSH terminal transport")?; let writer = Box::new(child.stdin.take().unwrap()) as Box; (reader, writer, None, Some(child)) } else { let stream = UnixStream::connect(launcher_socket).context("connect to psyTerm server")?; crate::launcher::verify_peer(&stream)?; ( stream.try_clone()?, Box::new(stream.try_clone()?) as Box, Some(stream), None, ) }; let stderr = ssh.as_mut().and_then(|child| child.stderr.take()); let (commands, receive) = mpsc::channel(); let (signal, notifications) = async_channel::bounded(1); let pending = Arc::new(Mutex::new(Update::default())); let connection = Self(Arc::new(Connection { launcher_socket: launcher_socket.to_owned(), remote: remote.map(str::to_owned), commands, socket, ssh: Mutex::new(ssh), })); let diagnostic = stderr.map(ssh_diagnostics).transpose()?; reader.set_read_timeout(Some(Duration::from_millis(150)))?; let mut greeting = GreetingReader { reader: &mut reader, deadline: Instant::now() + Duration::from_secs(if remote.is_some() { 30 } else { 5 }), cancelled: cancelled.as_deref(), }; if let Err(error) = greet(&mut greeting, &mut writer, session) { drop(connection); if let Some(detail) = diagnostic .and_then(|rx| rx.recv_timeout(Duration::from_millis(150)).ok()) .filter(|s| !s.is_empty()) { bail!("{error:#}: {detail}"); } return Err(error); } reader.set_read_timeout(None)?; let errors = pending.clone(); let notify = signal.clone(); thread::Builder::new() .name("psyterm-client-writer".into()) .spawn(move || { let mut writer = writer; while let Ok(message) = receive.recv() { if let Err(error) = protocol::write_message(&mut writer, &message) { errors.lock().unwrap().error = Some(format!("Connection lost: {error:#}")); let _ = notify.try_send(()); break; } } })?; let incoming = pending.clone(); thread::Builder::new() .name("psyterm-client-reader".into()) .spawn(move || { let mut reader = reader; loop { let message = protocol::read_message::(&mut reader); let mut update = incoming.lock().unwrap(); match message { Ok(ServerMessage::Snapshot(snapshot)) => { if let Err(error) = validate_snapshot(&snapshot) { update.disconnected = true; update.error = Some(error.to_string()); let _ = signal.try_send(()); break; } // A slow window never accumulates a queue of obsolete frames. update.snapshot = Some(Arc::new(snapshot)); } Ok(ServerMessage::Clipboard(text)) => { if update.clipboard.len() < 16 { update.clipboard.push_back(text); } } Ok(ServerMessage::Error(error)) => update.error = Some(error), Ok(ServerMessage::Closing) => { update.disconnected = true; update.error = Some("Server stopped. Shell sessions have ended.".into()); let _ = signal.try_send(()); break; } Ok(ServerMessage::Pong) => {} Ok(_) => { update.error = Some("Unexpected server response after session handshake".into()); } Err(error) => { update.disconnected = true; update.error = Some(format!( "Disconnected — sessions remain on the server. {error:#}" )); let _ = signal.try_send(()); break; } } drop(update); let _ = signal.try_send(()); } })?; Ok(( connection, Updates { signal: notifications, pending, }, )) } pub fn remote(&self) -> Option<&str> { self.0.remote.as_deref() } /// Launch through the local daemon even when this terminal connects over SSH. pub fn open_window(&self, remote: Option, cwd: Option) -> Result<()> { crate::launcher::control( &self.0.launcher_socket, ClientMessage::OpenWindow { target: remote, session: SessionTarget::New { cwd }, }, )?; Ok(()) } pub fn send(&self, message: ClientMessage) -> Result<()> { self.0 .commands .send(message) .context("server transport is closed") } pub fn input(&self, pane: u64, bytes: Vec) -> Result<()> { for chunk in bytes.chunks(64 * 1024) { self.send(ClientMessage::Input { pane, bytes: chunk.to_vec(), })?; } Ok(()) } } /// Drain SSH stderr throughout the connection. Keep a bounded tail to explain /// startup failures in the invoking window as well as in the daemon log. fn ssh_diagnostics(mut stderr: ChildStderr) -> io::Result> { let (tx, rx) = mpsc::channel(); thread::Builder::new() .name("psyterm-ssh-stderr".into()) .spawn(move || { let mut tail = Vec::new(); let mut buf = [0; 1024]; while let Ok(n) = stderr.read(&mut buf) { if n == 0 { break; } let _ = io::stderr().write_all(&buf[..n]); tail.extend_from_slice(&buf[..n]); tail.drain(..tail.len().saturating_sub(1024)); } let detail = String::from_utf8_lossy(&tail); let _ = tx.send( detail .trim() .lines() .next_back() .unwrap_or_default() .to_owned(), ); })?; Ok(rx) } struct GreetingReader<'a> { reader: &'a mut UnixStream, deadline: Instant, cancelled: Option<&'a AtomicBool>, } impl GreetingReader<'_> { fn check(&self) -> io::Result<()> { if self .cancelled .is_some_and(|flag| flag.load(Ordering::Acquire)) { return Err(io::Error::new( io::ErrorKind::ConnectionAborted, "connection cancelled", )); } if Instant::now() >= self.deadline { return Err(io::Error::new( io::ErrorKind::TimedOut, "timed out waiting for the psyTerm server", )); } Ok(()) } } impl Read for GreetingReader<'_> { fn read(&mut self, buffer: &mut [u8]) -> io::Result { loop { self.check()?; match self.reader.read(buffer) { Err(e) if matches!( e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock ) => {} result => return result, } } } } fn greet( reader: &mut GreetingReader<'_>, writer: &mut impl Write, session: SessionTarget, ) -> Result<()> { reader.check()?; protocol::write_message( writer, &ClientMessage::Hello { version: protocol::VERSION, }, )?; match protocol::read_message::(reader)? { ServerMessage::Hello { version, .. } if version == protocol::VERSION => {} ServerMessage::Error(error) => bail!("{error}"), _ => bail!("server protocol differs from this client"), } reader.check()?; protocol::write_message(writer, &ClientMessage::Connect(session))?; match protocol::read_message::(reader)? { ServerMessage::Connected { .. } => Ok(()), ServerMessage::Error(error) => bail!("{error}"), _ => bail!("server did not acknowledge the session"), } } fn shell_quote(value: &str) -> String { format!("'{}'", value.replace('\'', "'\\''")) } pub(crate) fn validate_snapshot(snapshot: &Snapshot) -> Result<()> { if snapshot.tabs.len() > 256 || snapshot.lineage.len() > 256 || snapshot.panes.len() > 64 { bail!("Server layout exceeds client limits"); } let mut tab_ids = HashSet::new(); let mut pane_ids = HashSet::new(); let mut expanded = HashSet::new(); for tab in &snapshot.tabs { if !tab_ids.insert(tab.id) { bail!("Server sent a duplicate tab ID"); } if tab.is_connecting() { continue; } let ordered = tab.stacks.iter().flat_map(|s| s.panes.iter().map(|p| p.id)); if tab.panes.is_empty() || tab.panes.len() > 64 || !tab.panes.iter().all(|id| pane_ids.insert(*id)) || ordered.ne(tab.panes.iter().copied()) || !tab.stacks.iter().any(|s| s.active_pane == tab.active_pane) { bail!("Server sent an invalid tab layout"); } for stack in &tab.stacks { if !stack.panes.iter().any(|p| p.id == stack.active_pane) { bail!("Server sent an invalid pane stack"); } if tab.id == snapshot.active_tab { expanded.insert(stack.active_pane); } } } if !(tab_ids.contains(&snapshot.active_tab) || (tab_ids.is_empty() && snapshot.active_tab == 0)) { bail!("Server sent an invalid active tab"); } for pane in &snapshot.panes { let count = usize::from(pane.columns) * usize::from(pane.lines); if !expanded.remove(&pane.id) || pane.columns < 2 || pane.lines == 0 || count > 1_000_000 || pane.cells.len() != count || pane.selected.len() != count || pane.colors.len() > alacritty_terminal::term::color::COUNT { bail!("Server sent an invalid terminal grid"); } } Ok(()) } /// SSH starts this command on the remote host. Only framed protocol bytes use stdout. pub fn bridge(socket: &Path, attach: bool) -> Result<()> { if attach { crate::launcher::require_server(socket)?; } else { crate::launcher::ensure_server(socket)?; } let stream = UnixStream::connect(socket)?; let mut output = stream.try_clone()?; let copy_input = thread::spawn(move || { let result = copy_and_flush(&mut std::io::stdin().lock(), &mut output); let _ = output.shutdown(Shutdown::Write); result }); let mut input = stream; copy_and_flush(&mut input, &mut std::io::stdout().lock())?; // Don't wait indefinitely for stdin after a remote server disconnects. drop(copy_input); Ok(()) } // stdout is line-buffered even over SSH. Flush each binary chunk; waiting for a // newline or EOF can withhold a frame tail and deadlock an otherwise idle GUI. fn copy_and_flush(reader: &mut impl Read, writer: &mut impl Write) -> std::io::Result<()> { let mut buffer = [0u8; 64 * 1024]; loop { let count = match reader.read(&mut buffer) { Ok(0) => return Ok(()), Ok(count) => count, Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, Err(error) => return Err(error), }; writer.write_all(&buffer[..count])?; writer.flush()?; } } #[cfg(test)] mod tests { use super::*; #[test] fn binary_bridge_flushes_without_newlines() { struct Output { bytes: Vec, flushes: usize, } impl Write for Output { fn write(&mut self, bytes: &[u8]) -> std::io::Result { self.bytes.extend_from_slice(bytes); Ok(bytes.len()) } fn flush(&mut self) -> std::io::Result<()> { self.flushes += 1; Ok(()) } } let mut output = Output { bytes: Vec::new(), flushes: 0, }; copy_and_flush(&mut b"binary-without-newlines".as_slice(), &mut output).unwrap(); assert_eq!(output.bytes, b"binary-without-newlines"); assert!(output.flushes > 0); } #[test] fn stalled_bridge_can_be_cancelled_during_a_partial_greeting() { let (mut socket, mut peer) = UnixStream::pair().unwrap(); socket .set_read_timeout(Some(Duration::from_millis(15))) .unwrap(); let cancelled = AtomicBool::new(false); thread::scope(|threads| { let (ready, start) = mpsc::channel(); let (done, wait) = mpsc::channel::<()>(); let flag = &cancelled; threads.spawn(move || { peer.write_all(&[8, 0]).unwrap(); start.recv().unwrap(); flag.store(true, Ordering::Release); // Keep the peer open until the reader notices cancellation. let _ = wait.recv(); }); let mut greeting = GreetingReader { reader: &mut socket, deadline: Instant::now() + Duration::from_secs(5), cancelled: Some(&cancelled), }; let mut header = [0; 4]; greeting.read_exact(&mut header[..2]).unwrap(); ready.send(()).unwrap(); assert_eq!( greeting.read_exact(&mut header[2..]).unwrap_err().kind(), io::ErrorKind::ConnectionAborted ); drop(done); }); } #[test] fn remote_binary_paths_are_shell_quoted() { assert_eq!(shell_quote("/tmp/a'b; x"), "'/tmp/a'\\''b; x'"); } }