Files
psyTerm/src/client.rs
T

1087 lines
38 KiB
Rust
Raw Normal View History

//! Display-only client transport. No terminal parser, PTY, or shell lives here.
use crate::protocol::{
self, ClientMessage, RemoteSessionInfo, RemoteWindow, ServerMessage, SessionIdentity,
SessionInfo, SessionRoute, SessionSummary, SessionTarget, Snapshot, SshOptions, TabId,
};
use anyhow::{Context, Result, bail, ensure};
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<Arc<Snapshot>>,
pub clipboard: VecDeque<String>,
pub error: Option<String>,
pub disconnected: bool,
}
pub struct Updates {
signal: async_channel::Receiver<()>,
pending: Arc<Mutex<Update>>,
}
impl Updates {
pub fn recv_blocking(&self) -> Option<Update> {
self.signal.recv_blocking().ok()?;
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
}
pub async fn recv(&self) -> Option<Update> {
self.signal.recv().await.ok()?;
Some(std::mem::take(&mut *self.pending.lock().unwrap()))
}
}
#[derive(Clone)]
pub struct Client {
connection: Arc<Connection>,
remote_session: Option<Arc<RemoteSession>>,
}
struct RemoteSession {
identity: SessionIdentity,
live: AtomicBool,
directory: Mutex<RemoteDirectory>,
}
#[derive(Default)]
struct RemoteDirectory {
sessions: Vec<RemoteSessionInfo>,
requested_at: Option<Instant>,
pending: bool,
}
impl RemoteDirectory {
fn refresh(&mut self, commands: &mpsc::Sender<ClientMessage>) {
// A slow host should have at most one request in flight. Allow retries
// if the peer never answered, and coalesce simultaneous picker queries.
let interval = Duration::from_secs(if self.pending { 30 } else { 1 });
if self
.requested_at
.is_none_or(|last| last.elapsed() >= interval)
&& commands.send(ClientMessage::ListSessions).is_ok()
{
self.requested_at = Some(Instant::now());
self.pending = true;
}
}
fn received(&mut self, sessions: Vec<SessionInfo>) {
self.pending = false;
self.sessions = sessions
.into_iter()
.filter_map(|session| {
// v6's directory describes every tab, but omits the active tab.
let first = session.tabs.first()?;
Some(RemoteSessionInfo {
id: session.id,
summary: SessionSummary::from_tabs(&session.tabs, first.id),
attached: session.attached,
})
})
.collect();
}
}
pub(crate) struct RemoteWindowListing {
pub summary: SessionSummary,
pub sessions: Option<Vec<RemoteSessionInfo>>,
}
/// A direct SSH window has no session on the local daemon. Publish its
/// layout summary separately so local directory I/O never blocks the grid.
struct RemoteListing {
latest: Arc<Mutex<RemoteWindowListing>>,
notify: UnixStream,
}
impl RemoteListing {
fn start(
socket: PathBuf,
target: RemoteWindow,
frame: &Snapshot,
commands: mpsc::Sender<ClientMessage>,
) -> Result<Self> {
let identity = frame.lineage[0]; // Verified in greet().
let latest = Arc::new(Mutex::new(RemoteWindowListing {
summary: SessionSummary::from_tabs(&frame.tabs, frame.active_tab),
sessions: None,
}));
let published = latest.clone();
let (notify, changes) = UnixStream::pair()?;
notify.set_nonblocking(true)?;
thread::Builder::new()
.name("psyterm-remote-listing".into())
.spawn(move || {
if let Err(error) = crate::launcher::publish_remote_window(
&socket,
target,
identity,
changes,
published,
|| {
let _ = commands.send(ClientMessage::ListSessions);
},
) {
log::warn!("Could not list SSH window on local server: {error:#}");
}
})?;
Ok(Self { latest, notify })
}
fn update(&mut self, frame: &Snapshot) {
let summary = SessionSummary::from_tabs(&frame.tabs, frame.active_tab);
let mut latest = self.latest.lock().unwrap();
if summary != latest.summary {
latest.summary = summary;
// If the nonblocking socket is full, the worker is already due to
// wake and will publish the latest summary.
let _ = self.notify.write(&[1]);
}
}
fn update_sessions(&mut self, sessions: &[RemoteSessionInfo]) {
self.latest.lock().unwrap().sessions = Some(sessions.to_vec());
// Publish every answer, including an unchanged or empty host directory.
let _ = self.notify.write(&[1]);
}
}
struct Connection {
launcher_socket: PathBuf,
remote: Option<RemoteWindow>,
commands: mpsc::Sender<ClientMessage>,
socket: Option<UnixStream>,
ssh: Mutex<Option<Child>>,
}
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,
options: SshOptions,
) -> Result<(Self, Updates)> {
Self::connect_with(launcher_socket, remote, session, options, None)
}
pub fn connect_remote(
launcher_socket: &Path,
destination: &str,
session: SessionTarget,
ssh: SshOptions,
cancelled: Arc<AtomicBool>,
) -> 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<Arc<AtomicBool>>,
) -> Result<(Self, Updates)> {
let (session, expected) = match session {
SessionTarget::Remembered(identity) => (
SessionTarget::Attach(Some(identity.session)),
Some(identity),
),
other => (other, None),
};
let (mut reader, mut writer, socket, mut ssh): (_, Box<dyn Write + Send>, _, _) =
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<dyn Write + Send>;
(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<dyn Write + Send>,
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 = Arc::new(Connection {
launcher_socket: launcher_socket.to_owned(),
remote: remote.map(|destination| RemoteWindow {
destination: destination.into(),
ssh: options,
}),
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(),
};
let first_frame = match greet(
&mut greeting,
&mut writer,
session,
remote.is_some(),
expected,
) {
Ok(greeting) => greeting,
Err(error) => {
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);
}
};
let remote_session = first_frame
.as_ref()
.filter(|_| remote.is_some())
.map(|frame| {
Arc::new(RemoteSession {
identity: frame.lineage[0],
live: AtomicBool::new(!frame.tabs.is_empty()),
directory: Mutex::default(),
})
});
// Mounted SSH connections are already listed by their owning daemon.
let listing = if cancelled.is_none()
&& let (Some(target), Some(frame)) = (&connection.remote, &first_frame)
&& !frame.tabs.is_empty()
{
RemoteListing::start(
launcher_socket.to_owned(),
target.clone(),
frame,
connection.commands.clone(),
)
.inspect_err(|error| log::warn!("Could not start SSH window listing: {error:#}"))
.ok()
} else {
None
};
if let Some(frame) = first_frame {
pending.lock().unwrap().snapshot = Some(Arc::new(frame));
let _ = signal.try_send(());
}
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();
let reader_session = remote_session.clone();
thread::Builder::new()
.name("psyterm-client-reader".into())
.spawn(move || {
read_updates(
reader,
&incoming,
signal,
reader_session.as_deref(),
listing,
)
})?;
Ok((
Self {
connection,
remote_session,
},
Updates {
signal: notifications,
pending,
},
))
}
pub fn remote(&self) -> Option<&str> {
self.connection
.remote
.as_ref()
.map(|remote| remote.destination.as_str())
}
pub fn remote_identity(&self) -> Option<SessionIdentity> {
self.remote_session.as_ref().map(|session| session.identity)
}
/// Queue a host-wide lookup on the live SSH bridge and return its latest
/// answer immediately, so listing sessions never stalls the daemon actor.
pub fn remote_directory(&self) -> Vec<RemoteSessionInfo> {
let Some(remote) = &self.remote_session else {
return Vec::new();
};
let mut directory = remote.directory.lock().unwrap();
directory.refresh(&self.connection.commands);
directory.sessions.clone()
}
/// Remember a direct SSH window on its local launcher before detaching it.
pub fn remember_remote_detach(&self) -> Result<()> {
let remote = self
.connection
.remote
.as_ref()
.context("this window is local")?;
let session = self
.remote_session
.as_ref()
.context("missing SSH session identity")?;
if !session.live.load(Ordering::Acquire) {
return Ok(());
}
crate::launcher::control(
&self.connection.launcher_socket,
ClientMessage::RememberDetachedRemote(protocol::DetachedRemote {
destination: remote.destination.clone(),
identity: session.identity,
executable: remote.ssh.executable.clone(),
}),
)?;
Ok(())
}
pub fn session_directory(&self) -> Result<crate::launcher::SessionDirectoryPage> {
crate::launcher::session_directory(&self.connection.launcher_socket)
}
pub fn open_listed_session(
&self,
route: SessionRoute,
workspace: Option<SessionIdentity>,
) -> Result<()> {
let request = match route {
SessionRoute::Remote(identity) => ClientMessage::OpenPeerSession {
identity,
workspace,
},
_ => ClientMessage::OpenListedSession(route),
};
let response = crate::launcher::control(&self.connection.launcher_socket, request)?;
ensure!(
matches!(response, ServerMessage::Pong),
"local daemon did not open the session"
);
Ok(())
}
/// Launch through the local daemon even when this terminal connects over SSH.
pub fn open_window(
&self,
remote_tab: Option<(TabId, String)>,
cwd: Option<String>,
) -> Result<()> {
let request = new_window_request(self.connection.remote.as_ref(), remote_tab, cwd);
if matches!(request, ClientMessage::OpenWindowForRemoteTab { .. }) {
return self.send(request);
}
crate::launcher::control(&self.connection.launcher_socket, request)?;
Ok(())
}
pub fn send(&self, message: ClientMessage) -> Result<()> {
self.connection
.commands
.send(message)
.context("server transport is closed")
}
pub fn input(&self, pane: u64, bytes: Vec<u8>) -> Result<()> {
for chunk in bytes.chunks(64 * 1024) {
self.send(ClientMessage::Input {
pane,
bytes: chunk.to_vec(),
})?;
}
Ok(())
}
}
fn new_window_request(
direct: Option<&RemoteWindow>,
remote_tab: Option<(TabId, String)>,
cwd: Option<String>,
) -> ClientMessage {
match (direct, remote_tab) {
// The local daemon owns the mounted connection, including its SSH options.
(None, Some((tab, _))) => ClientMessage::OpenWindowForRemoteTab {
tab,
cwd,
fallback: SshOptions::from_env(),
},
(None, None) => ClientMessage::OpenWindow {
target: None,
session: SessionTarget::New { cwd },
},
(Some(direct), None) => ClientMessage::OpenRemoteWindow {
target: direct.clone(),
session: SessionTarget::New { cwd },
},
(Some(_), Some((_, destination))) => ClientMessage::OpenRemoteWindow {
target: RemoteWindow::from_env(destination),
session: SessionTarget::New { cwd },
},
}
}
fn read_updates(
mut reader: impl Read,
pending: &Mutex<Update>,
signal: async_channel::Sender<()>,
remote_session: Option<&RemoteSession>,
mut listing: Option<RemoteListing>,
) {
loop {
let message = protocol::read_message::<ServerMessage>(&mut reader);
if let Ok(ServerMessage::Sessions(sessions)) = message {
if let Some(remote) = remote_session {
let mut directory = remote.directory.lock().unwrap();
directory.received(sessions);
if let Some(listing) = &mut listing {
listing.update_sessions(&directory.sessions);
}
}
continue;
}
let mut update = pending.lock().unwrap();
match message {
Ok(ServerMessage::Snapshot(snapshot)) => {
match validate_snapshot(&snapshot) {
Ok(()) => {
if let Some(session) = remote_session {
session
.live
.store(!snapshot.tabs.is_empty(), Ordering::Release);
}
if snapshot.tabs.is_empty() {
listing = None;
} else if let Some(listing) = &mut listing {
listing.update(&snapshot);
}
update.snapshot = Some(Arc::new(snapshot));
}
Err(error) => {
// Older daemons can briefly mix layouts and grids during SSH
// navigation. A complete frame leaves the stream synchronized.
update.error = Some(format!("Discarded workspace update: {error}"));
}
}
}
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) => {
if let Some(session) = remote_session {
session.live.store(false, Ordering::Release);
}
update.disconnected = true;
update.error = Some("Server stopped. Shell sessions have ended.".into());
}
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 disconnected = update.disconnected;
drop(update);
let _ = signal.try_send(());
if disconnected {
break;
}
}
}
/// 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<mpsc::Receiver<String>> {
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<usize> {
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,
from_ssh: bool,
expected: Option<SessionIdentity>,
) -> Result<Option<Snapshot>> {
reader.check()?;
protocol::write_message(
writer,
&ClientMessage::Hello {
version: protocol::VERSION,
},
)?;
match protocol::read_message::<ServerMessage>(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))?;
let session = match protocol::read_message::<ServerMessage>(reader)? {
ServerMessage::Connected { session } => session,
ServerMessage::Error(error) => bail!("{error}"),
_ => bail!("server did not acknowledge the session"),
};
if !from_ssh && expected.is_none() {
return Ok(None);
}
// Session numbers start over after a daemon restart. Check the identity
// before handing a display or an input channel to the attaching client.
let frame = match protocol::read_message::<ServerMessage>(reader)? {
ServerMessage::Snapshot(frame) => frame,
ServerMessage::Error(error) => bail!("{error}"),
_ => bail!("expected initial session snapshot"),
};
validate_snapshot(&frame)?;
let identity = frame.lineage.first().context("missing session identity")?;
ensure!(identity.session == session, "incorrect session identity");
if let Some(expected) = expected {
ensure!(*identity == expected, "the remembered session has ended");
}
Ok(Some(frame))
}
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 ssh_directory_reads_v6_session_lists_alongside_terminal_messages() {
let remote = RemoteSession {
identity: SessionIdentity {
server: [9; 16],
session: 1,
},
live: AtomicBool::new(true),
directory: Mutex::default(),
};
let (commands, sent) = mpsc::channel();
{
let mut directory = remote.directory.lock().unwrap();
directory.refresh(&commands);
directory.refresh(&commands);
}
assert!(matches!(sent.try_recv(), Ok(ClientMessage::ListSessions)));
assert!(sent.try_recv().is_err());
let tab = |id, title: &str| protocol::TabInfo {
id,
title: title.into(),
manual_title: None,
remote: None,
panes: vec![id],
active_pane: id,
stacks: Vec::new(),
};
let (peer, reader) = UnixStream::pair().unwrap();
reader
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let (signal, changes) = async_channel::bounded(1);
let pending = Mutex::new(Update::default());
thread::scope(|scope| {
let mut peer = peer;
scope.spawn(|| read_updates(reader, &pending, signal, Some(&remote), None));
let directory = vec![
SessionInfo {
id: 1,
attached: 1,
tabs: vec![tab(21, "Current")],
},
SessionInfo {
id: 2,
attached: 0,
tabs: vec![tab(31, "Build"), tab(32, "Logs")],
},
];
protocol::write_message(&mut peer, &ServerMessage::Sessions(directory)).unwrap();
protocol::write_message(&mut peer, &ServerMessage::Clipboard("copied".into())).unwrap();
changes.recv_blocking().unwrap();
let mut update = pending.lock().unwrap();
assert!(update.error.is_none());
assert_eq!(update.clipboard.pop_front().as_deref(), Some("copied"));
let list = &remote.directory.lock().unwrap().sessions;
assert_eq!(list.len(), 2);
assert_eq!((list[1].id, list[1].attached), (2, 0));
assert_eq!(list[1].summary.title, "Build");
assert_eq!((list[1].summary.tabs, list[1].summary.panes), (2, 2));
peer.shutdown(Shutdown::Write).unwrap();
});
}
#[test]
fn new_window_routes_local_direct_mounted_and_nested_tabs() {
let direct = RemoteWindow {
destination: "outer".into(),
ssh: SshOptions {
executable: Some("/custom/bin/psyterm".into()),
agent_socket: Some("/custom/agent.sock".into()),
},
};
let request = |host, tab| new_window_request(host, tab, Some("/work".into()));
assert!(matches!(
request(None, None),
ClientMessage::OpenWindow { target: None, .. }
));
assert!(matches!(
request(None, Some((42, "outer".into()))),
ClientMessage::OpenWindowForRemoteTab { tab: 42, .. }
));
let ClientMessage::OpenRemoteWindow { target, session } = request(Some(&direct), None)
else {
panic!("expected direct SSH window")
};
assert!(matches!(session, SessionTarget::New { cwd: Some(cwd) } if cwd == "/work"));
assert_eq!(target.destination, direct.destination);
assert_eq!(target.ssh.executable, direct.ssh.executable);
assert_eq!(target.ssh.agent_socket, direct.ssh.agent_socket);
let ClientMessage::OpenRemoteWindow { target, .. } =
request(Some(&direct), Some((42, "inner".into())))
else {
panic!("expected nested SSH window")
};
assert_eq!(target.destination, "inner");
let fallback = SshOptions::from_env();
assert_eq!(target.ssh.executable, fallback.executable);
assert_eq!(target.ssh.agent_socket, fallback.agent_socket);
}
#[test]
fn invalid_frame_does_not_disconnect_local_or_remote_workspaces() {
let remote = RemoteSession {
identity: SessionIdentity {
server: [1; 16],
session: 1,
},
live: AtomicBool::new(true),
directory: Mutex::default(),
};
for session in [None, Some(&remote)] {
let (client, mut server) = UnixStream::pair().unwrap();
client
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let pending = Mutex::new(Update::default());
let (signal, received) = async_channel::bounded(1);
thread::scope(|threads| {
threads.spawn(|| read_updates(client, &pending, signal, session, None));
let mut send_snapshot = |snapshot| {
protocol::write_message(&mut server, &ServerMessage::Snapshot(snapshot))
.unwrap();
received.recv_blocking().unwrap();
std::mem::take(&mut *pending.lock().unwrap())
};
let frame = Snapshot {
lineage: vec![remote.identity],
revision: 1,
tabs: vec![protocol::TabInfo {
id: 1,
remote: Some("work".into()),
title: "work".into(),
manual_title: None,
panes: Vec::new(),
active_pane: 0,
stacks: Vec::new(),
}],
active_tab: 1,
panes: Vec::new(),
};
assert_eq!(send_snapshot(frame.clone()).snapshot.unwrap().revision, 1);
let skipped = send_snapshot(Snapshot {
revision: 2,
active_tab: 42,
..frame.clone()
});
assert!(skipped.snapshot.is_none());
assert!(skipped.error.unwrap().contains("invalid active tab"));
assert!(!skipped.disconnected);
let resumed = send_snapshot(Snapshot {
revision: 3,
..frame
});
assert_eq!(resumed.snapshot.unwrap().revision, 3);
assert!(!resumed.disconnected);
server.shutdown(Shutdown::Write).unwrap();
received.recv_blocking().unwrap();
assert!(pending.lock().unwrap().disconnected);
});
}
}
#[test]
fn remote_session_can_be_remembered_after_transport_loss_but_not_after_exit() {
let empty = ServerMessage::Snapshot(Snapshot {
revision: 2,
lineage: Vec::new(),
tabs: Vec::new(),
active_tab: 0,
panes: Vec::new(),
});
for (last_message, resumable) in [
(ServerMessage::Pong, true),
(empty, false),
(ServerMessage::Closing, false),
] {
let remote = RemoteSession {
identity: SessionIdentity {
server: [1; 16],
session: 1,
},
live: AtomicBool::new(true),
directory: Mutex::default(),
};
let mut bytes = Vec::new();
protocol::write_message(&mut bytes, &last_message).unwrap();
let (signal, _updates) = async_channel::bounded(1);
read_updates(
bytes.as_slice(),
&Mutex::new(Update::default()),
signal,
Some(&remote),
None,
);
assert_eq!(remote.live.load(Ordering::Acquire), resumable);
}
}
#[test]
fn binary_bridge_flushes_without_newlines() {
struct Output {
bytes: Vec<u8>,
flushes: usize,
}
impl Write for Output {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
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'");
}
}