Compare commits

...

10 Commits

Author SHA1 Message Date
DuProcess 039dc641b3 Fix resumed copy truncation
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-09 19:10:17 -04:00
DuProcess 4c9e31fd16 Harden alternate screen tracking
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 20:37:16 -04:00
DuProcess c1c672b188 Bump release candidate to rc8
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 15:34:49 -04:00
DuProcess a23f610f20 Keep generated sessions alive across updates 2026-07-07 15:34:24 -04:00
DuProcess ff2b7fff2b Bump release candidate to rc7
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 14:58:13 -04:00
DuProcess f4879090f6 Keep terminal focus reports local 2026-07-07 14:57:53 -04:00
DuProcess 37ec9fc520 Bump release candidate to rc6
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 12:01:03 -04:00
DuProcess f3c7ec225d Repaint terminal after idle tab return 2026-07-07 12:00:40 -04:00
DuProcess d3c40a06ac Bump release candidate to rc5
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 11:49:41 -04:00
DuProcess 6b12b3dfe0 Harden terminal reconnect packet handling 2026-07-07 11:48:59 -04:00
7 changed files with 725 additions and 79 deletions
Generated
+1 -1
View File
@@ -436,7 +436,7 @@ dependencies = [
[[package]]
name = "dosh"
version = "1.0.0-rc4"
version = "1.0.0-rc10"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "dosh"
version = "1.0.0-rc4"
version = "1.0.0-rc10"
edition = "2024"
license = "MIT"
+332 -29
View File
@@ -66,6 +66,8 @@ const STARTUP_INPUT_HOLD: Duration = Duration::from_millis(750);
const POST_SUBMIT_ALL_INPUT_HOLD: Duration = Duration::from_millis(120);
const STALE_TERMINAL_INPUT_AFTER: Duration = Duration::from_secs(2);
const POST_RECONNECT_STALE_INPUT_GRACE: Duration = Duration::from_secs(2);
const FOCUS_REPAINT_COOLDOWN: Duration = Duration::from_secs(1);
const ALT_SCREEN_IDLE_REPAINT_AFTER: Duration = Duration::from_secs(15);
/// Sentinel `target_host` the server uses on a server-initiated `StreamOpen` that
/// represents an SSH-agent connection (rather than a TCP target). The client
@@ -2496,11 +2498,15 @@ fn download_file(
0
};
let mut file = if offset > 0 {
fs::OpenOptions::new()
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.append(true)
.open(local)
.with_context(|| format!("open {}", local.display()))?
.with_context(|| format!("open {}", local.display()))?;
file.set_len(offset)
.with_context(|| format!("truncate {}", local.display()))?;
file
} else {
fs::OpenOptions::new()
.create(true)
@@ -4334,10 +4340,14 @@ async fn run_terminal(
let mut startup_input_hold_until: Option<Instant> = None;
let mut startup_gate_mode = StartupGateMode::HoldControl;
let mut stale_terminal_input_suppress_until: Option<Instant> = None;
let mut last_terminal_frame_at = Instant::now();
let mut last_focus_repaint_at = Instant::now() - FOCUS_REPAINT_COOLDOWN;
let mut last_idle_repaint_attempt_at = Instant::now() - ALT_SCREEN_IDLE_REPAINT_AFTER;
if let Some(frame) = first_frame {
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
}
if frame.closed {
return Ok(());
@@ -4395,6 +4405,46 @@ async fn run_terminal(
if input_matches_escape(&bytes, escape_key.as_deref()) {
break;
}
let saw_focus_in = input_contains_focus_in(&bytes);
if !forward_only
&& saw_focus_in
&& last_focus_repaint_at.elapsed() >= FOCUS_REPAINT_COOLDOWN
{
last_focus_repaint_at = Instant::now();
if let Some(frame) = reconnect(
&socket,
&mut cred,
&mut send_seq,
last_size,
&mut frame_buffer,
&mut predictor,
)
.await?
{
refresh_live_addr(&mut addr, &cred)?;
arm_stale_terminal_input_suppression(
&mut stale_terminal_input_suppress_until,
);
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
last_packet_at = Instant::now();
flush_pending_user_input(
&socket,
addr,
&cred,
&mut send_seq,
&mut predictor,
&mut pending_user_input,
&mut pending_user_input_bytes,
)
.await?;
}
}
bytes = strip_terminal_focus_reports(&bytes);
if bytes.is_empty() {
continue;
}
if should_strip_stale_terminal_reports(
last_packet_at.elapsed(),
stale_terminal_input_suppress_until,
@@ -4508,6 +4558,7 @@ async fn run_terminal(
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
}
last_packet_at = Instant::now();
flush_pending_user_input(
@@ -4570,6 +4621,7 @@ async fn run_terminal(
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
}
last_packet_at = Instant::now();
flush_pending_user_input(
@@ -4623,6 +4675,7 @@ async fn run_terminal(
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
}
last_packet_at = Instant::now();
flush_pending_user_input(
@@ -4648,6 +4701,7 @@ async fn run_terminal(
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
flush_startup_input_if_ready(
&socket,
addr,
@@ -4747,6 +4801,7 @@ async fn run_terminal(
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
}
last_packet_at = Instant::now();
flush_pending_user_input(
@@ -5142,6 +5197,7 @@ async fn run_terminal(
if !forward_only {
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
}
last_packet_at = Instant::now();
flush_pending_user_input(
@@ -5183,6 +5239,44 @@ async fn run_terminal(
(&mut startup_input_hold_until, &mut startup_gate_mode),
)
.await?;
let now = Instant::now();
if should_repaint_idle_alternate_screen(
predictor.alternate_screen,
last_terminal_frame_at,
last_idle_repaint_attempt_at,
now,
) {
last_idle_repaint_attempt_at = now;
if let Some(frame) = reconnect(
&socket,
&mut cred,
&mut send_seq,
last_size,
&mut frame_buffer,
&mut predictor,
)
.await?
{
refresh_live_addr(&mut addr, &cred)?;
arm_stale_terminal_input_suppression(
&mut stale_terminal_input_suppress_until,
);
render_frame(&frame)?;
predictor.observe_output(&frame.bytes);
last_terminal_frame_at = Instant::now();
last_packet_at = Instant::now();
flush_pending_user_input(
&socket,
addr,
&cred,
&mut send_seq,
&mut predictor,
&mut pending_user_input,
&mut pending_user_input_bytes,
)
.await?;
}
}
}
// Refresh / clear the non-destructive disconnect status line based
// on how long the link has been silent (recomputed after any
@@ -5552,6 +5646,41 @@ fn should_strip_stale_terminal_reports(
|| suppress_until.is_some_and(|deadline| Instant::now() < deadline)
}
fn input_contains_focus_in(bytes: &[u8]) -> bool {
contains_bytes(bytes, b"\x1b[I") || contains_bytes(bytes, b"\x9bI")
}
fn strip_terminal_focus_reports(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len());
let mut offset = 0;
while offset < bytes.len() {
match bytes.get(offset..) {
Some([0x1b, b'[', b'I' | b'O', ..]) => {
offset += 3;
}
Some([0x9b, b'I' | b'O', ..]) => {
offset += 2;
}
_ => {
out.push(bytes[offset]);
offset += 1;
}
}
}
out
}
fn should_repaint_idle_alternate_screen(
alternate_screen: bool,
last_terminal_frame_at: Instant,
last_attempt_at: Instant,
now: Instant,
) -> bool {
alternate_screen
&& now.duration_since(last_terminal_frame_at) >= ALT_SCREEN_IDLE_REPAINT_AFTER
&& now.duration_since(last_attempt_at) >= ALT_SCREEN_IDLE_REPAINT_AFTER
}
fn arm_stale_terminal_input_suppression(suppress_until: &mut Option<Instant>) {
*suppress_until = Some(Instant::now() + POST_RECONNECT_STALE_INPUT_GRACE);
}
@@ -5679,19 +5808,21 @@ fn stale_mouse_report_maybe_incomplete(bytes: &[u8], offset: usize) -> bool {
[0x1b] | [0x1b, b'['] | [0x1b, b'[', b'<'] => true,
[0x1b, b'[', b'M', ..] if rest.len() < 6 => true,
[0x1b, b'[', b'<', params @ ..] | [0x1b, b'[', params @ ..]
if params_are_mouse_prefix(params) =>
if params_are_mouse_prefix(params, 2) =>
{
true
}
[0x9b] | [0x9b, b'<'] => true,
[0x9b, b'M', ..] if rest.len() < 5 => true,
[0x9b, b'<', params @ ..] | [0x9b, params @ ..] if params_are_mouse_prefix(params) => true,
params if params_are_mouse_prefix(params) => true,
[0x9b, b'<', params @ ..] | [0x9b, params @ ..] if params_are_mouse_prefix(params, 2) => {
true
}
params if params_are_mouse_prefix(params, 2) => true,
_ => false,
}
}
fn params_are_mouse_prefix(params: &[u8]) -> bool {
fn params_are_mouse_prefix(params: &[u8], min_semicolons: usize) -> bool {
let mut semicolons = 0usize;
let mut saw_digit = false;
for byte in params {
@@ -5701,7 +5832,7 @@ fn params_are_mouse_prefix(params: &[u8]) -> bool {
_ => return false,
}
}
saw_digit && semicolons >= 1
saw_digit && semicolons >= min_semicolons
}
async fn flush_startup_input_if_ready(
@@ -6169,6 +6300,60 @@ const FLAG_TRIGGER_LOW_MS: f64 = 50.0;
/// (covers a sudden latency spike on the very first slow keystroke).
const GLITCH_FORCE_MS: u128 = 250;
/// Enough recent bytes to join a CSI private-mode sequence split across frames
/// without retaining arbitrary terminal output.
const TERMINAL_OUTPUT_PARSE_TAIL: usize = 64;
fn alternate_screen_after_output(mut active: bool, bytes: &[u8]) -> bool {
let mut offset = 0usize;
while offset < bytes.len() {
let Some((next, transition)) = terminal_private_mode_transition(bytes, offset) else {
offset += 1;
continue;
};
if let Some(enable) = transition {
active = enable;
}
offset = next.max(offset + 1);
}
active
}
fn terminal_private_mode_transition(bytes: &[u8], offset: usize) -> Option<(usize, Option<bool>)> {
let mut cursor = offset;
match bytes.get(cursor).copied()? {
0x1b if bytes.get(cursor + 1) == Some(&b'[') => cursor += 2,
0x9b => cursor += 1,
_ => return None,
}
if bytes.get(cursor) != Some(&b'?') {
return None;
}
cursor += 1;
let params_start = cursor;
while let Some(byte) = bytes.get(cursor).copied() {
match byte {
b'0'..=b'9' | b';' | b':' => cursor += 1,
b'h' | b'l' => {
let params = &bytes[params_start..cursor];
let touches_alt = terminal_private_params_include_alt_screen(params);
return Some((cursor + 1, touches_alt.then_some(byte == b'h')));
}
0x40..=0x7e => return Some((cursor + 1, None)),
_ => return None,
}
}
None
}
fn terminal_private_params_include_alt_screen(params: &[u8]) -> bool {
params
.split(|byte| matches!(byte, b';' | b':'))
.any(|param| matches!(param, b"47" | b"1047" | b"1049"))
}
/// One speculatively-echoed character on the current line.
#[derive(Clone, Debug)]
struct PredictedCell {
@@ -6186,6 +6371,9 @@ struct Predictor {
/// as vim/htop); we never speculate there because we cannot model arbitrary
/// cursor addressing safely.
alternate_screen: bool,
/// Tail of recent terminal output, retained so alternate-screen transitions
/// split across UDP frames are still detected.
output_parse_tail: Vec<u8>,
/// Predicted cells for the current line, left-to-right starting at the
/// column where the cursor sat when this run of predictions began.
@@ -6232,6 +6420,7 @@ impl Predictor {
mode,
enabled: enabled && mode != PredictMode::Off,
alternate_screen: false,
output_parse_tail: Vec::new(),
cells: Vec::new(),
cursor: 0,
epoch: 1,
@@ -6254,6 +6443,7 @@ impl Predictor {
self.epoch += 1;
self.confirmed_epoch = self.epoch - 1;
self.alternate_screen = false;
self.output_parse_tail.clear();
self.oldest_pending_at = None;
}
@@ -6410,20 +6600,20 @@ impl Predictor {
/// and confirms outstanding predictions: a fresh frame means the server has
/// re-rendered the line, so our speculative glyphs are superseded and erased.
fn observe_output(&mut self, bytes: &[u8]) {
if contains_bytes(bytes, b"\x1b[?1049h")
|| contains_bytes(bytes, b"\x1b[?1047h")
|| contains_bytes(bytes, b"\x1b[?47h")
{
self.alternate_screen = true;
let _ = self.discard_all();
}
if contains_bytes(bytes, b"\x1b[?1049l")
|| contains_bytes(bytes, b"\x1b[?1047l")
|| contains_bytes(bytes, b"\x1b[?47l")
{
self.alternate_screen = false;
let mut parse = Vec::with_capacity(self.output_parse_tail.len() + bytes.len());
parse.extend_from_slice(&self.output_parse_tail);
parse.extend_from_slice(bytes);
let before = self.alternate_screen;
self.alternate_screen = alternate_screen_after_output(self.alternate_screen, &parse);
if self.alternate_screen != before {
let _ = self.discard_all();
}
self.output_parse_tail.clear();
let keep = parse.len().min(TERMINAL_OUTPUT_PARSE_TAIL);
self.output_parse_tail
.extend_from_slice(&parse[parse.len().saturating_sub(keep)..]);
}
/// Sample SRTT from a newly arrived frame and confirm/clear outstanding
@@ -7217,10 +7407,13 @@ const TERMINAL_CLEANUP: &[u8] = concat!(
"\x1b[?1002l",
"\x1b[?1001l",
"\x1b[?1000l",
"\x1b[?1004l",
"\x1b[?1015l",
"\x1b[?1006l",
"\x1b[?1005l",
"\x1b[?2004l",
"\x1b[?47l",
"\x1b[?1047l",
"\x1b[?1049l"
)
.as_bytes();
@@ -7228,11 +7421,12 @@ const TERMINAL_CLEANUP: &[u8] = concat!(
#[cfg(test)]
mod tests {
use super::{
CachedCredential, DisconnectStatus, DynamicForward, FRAME_GAP_RESYNC_AFTER_MS, FrameBuffer,
LocalForward, MAX_PENDING_USER_INPUT_BYTES, POST_SUBMIT_ALL_INPUT_HOLD, PendingStreamOpen,
PredictMode, Predictor, RESTART_STATUS_SCRIPT, RemoteForward, STARTUP_INPUT_HOLD,
SshConfig, StartupGateMode, StatusAction, auth_allows, cache_key, cache_server_prefix,
clear_cached_credentials, ensure_tui_safe_status_overlay, input_matches_escape,
ALT_SCREEN_IDLE_REPAINT_AFTER, CachedCredential, DisconnectStatus, DynamicForward,
FRAME_GAP_RESYNC_AFTER_MS, FrameBuffer, LocalForward, MAX_PENDING_USER_INPUT_BYTES,
POST_SUBMIT_ALL_INPUT_HOLD, PendingStreamOpen, PredictMode, Predictor,
RESTART_STATUS_SCRIPT, RemoteForward, STARTUP_INPUT_HOLD, SshConfig, StartupGateMode,
StatusAction, auth_allows, cache_key, cache_server_prefix, clear_cached_credentials,
ensure_tui_safe_status_overlay, input_contains_focus_in, input_matches_escape,
is_local_status_target, is_resume_response_for_client, latest_release_download_url,
load_first_native_identity_with_prompt, parse_dynamic_forward, parse_escape_key,
parse_local_forward, parse_remote_forward, parse_ssh_config, post_submit_hold_duration,
@@ -7241,10 +7435,12 @@ mod tests {
render_status_clear, render_status_overlay, requested_env, resolved_startup_command,
retransmit_stream_opens, rewrite_forward_command, selected_predict_mode, selected_udp_host,
server_version_mismatch, should_flush_terminal_input_after_contact,
should_hold_during_startup_gate, should_hold_post_submit_input, split_after_command_submit,
ssh_destination_host, ssh_username, ssh_with_user, startup_command, status_ssh_target,
strip_stale_mouse_reports, toml_bare_key_or_quoted, update_check_requested,
update_version_status, upsert_managed_block, valid_forward_host, vscode_safe_alias,
should_hold_during_startup_gate, should_hold_post_submit_input,
should_repaint_idle_alternate_screen, split_after_command_submit, ssh_destination_host,
ssh_username, ssh_with_user, startup_command, status_ssh_target, strip_stale_mouse_reports,
strip_terminal_focus_reports, terminal_private_mode_transition, toml_bare_key_or_quoted,
update_check_requested, update_version_status, upsert_managed_block, valid_forward_host,
vscode_safe_alias,
};
use dosh::config::{ClientConfig, CommandExtension, HostConfig};
use dosh::native::EnvVar;
@@ -7253,7 +7449,7 @@ mod tests {
use ed25519_dalek::{SigningKey, VerifyingKey};
use std::collections::{HashMap, VecDeque};
use std::fs;
use std::time::Duration;
use std::time::{Duration, Instant};
fn test_args(server: &str, command: &[&str]) -> super::Args {
super::Args {
@@ -7763,6 +7959,61 @@ mod tests {
assert!(!predictor.alternate_screen);
}
#[test]
fn predictor_tracks_legacy_and_combined_alternate_screen_modes() {
let mut predictor = Predictor::new(true);
predictor.observe_output(b"\x1b[?1000;1006;1049h");
assert!(predictor.alternate_screen);
predictor.observe_output(b"\x1b[?1006;1000l");
assert!(
predictor.alternate_screen,
"leaving mouse modes must not imply leaving alternate screen"
);
predictor.observe_output(b"\x1b[?1047l");
assert!(!predictor.alternate_screen);
predictor.observe_output(b"\x1b[?47h");
assert!(predictor.alternate_screen);
predictor.observe_output(b"\x1b[?47l");
assert!(!predictor.alternate_screen);
}
#[test]
fn predictor_tracks_alternate_screen_split_across_frames() {
let mut predictor = Predictor::new(true);
predictor.observe_output(b"\x1b");
assert!(!predictor.alternate_screen);
predictor.observe_output(b"[?");
assert!(!predictor.alternate_screen);
predictor.observe_output(b"10");
assert!(!predictor.alternate_screen);
predictor.observe_output(b"49h");
assert!(predictor.alternate_screen);
predictor.observe_output(b"\x1b");
assert!(predictor.alternate_screen);
predictor.observe_output(b"[?104");
assert!(predictor.alternate_screen);
predictor.observe_output(b"9l");
assert!(!predictor.alternate_screen);
}
#[test]
fn private_mode_parser_ignores_non_alt_modes() {
assert_eq!(
terminal_private_mode_transition(b"\x1b[?1000;1006h", 0),
Some((13, None))
);
assert_eq!(
terminal_private_mode_transition(b"\x1b[?1000;1049h", 0),
Some((13, Some(true)))
);
}
/// Typing printable characters builds an in-order predicted line and the
/// local cursor tracks the end of it.
#[test]
@@ -8529,12 +8780,64 @@ mod tests {
assert_eq!(strip_stale_mouse_reports(b"10m"), b"");
}
#[test]
fn numeric_semicolon_input_survives_stale_filter() {
assert_eq!(strip_stale_mouse_reports(b"123;"), b"123;");
assert_eq!(strip_stale_mouse_reports(b"12;34"), b"12;34");
assert_eq!(strip_stale_mouse_reports(b"echo 1;"), b"echo 1;");
}
#[test]
fn incomplete_three_field_mouse_prefix_is_suppressed() {
assert_eq!(strip_stale_mouse_reports(b"35;152;"), b"");
assert_eq!(strip_stale_mouse_reports(b"\x1b[<35;152;"), b"");
assert_eq!(strip_stale_mouse_reports(b"\x9b35;152;"), b"");
}
#[test]
fn stale_focus_reports_are_stripped_from_pending_input() {
assert_eq!(strip_stale_mouse_reports(b"\x1b[Ihello\x1b[O"), b"hello");
assert_eq!(strip_stale_mouse_reports(b"\x9bIhello\x9bO"), b"hello");
}
#[test]
fn focus_in_reports_trigger_local_repaint_detection() {
assert!(input_contains_focus_in(b"\x1b[I"));
assert!(input_contains_focus_in(b"before\x9bIafter"));
assert!(!input_contains_focus_in(b"\x1b[O"));
assert!(!input_contains_focus_in(b"\x1b[A"));
}
#[test]
fn focus_reports_are_never_forwarded_as_user_input() {
assert_eq!(strip_terminal_focus_reports(b"\x1b[Ihello\x1b[O"), b"hello");
assert_eq!(strip_terminal_focus_reports(b"\x9bIhello\x9bO"), b"hello");
assert_eq!(strip_terminal_focus_reports(b"\x1b[A"), b"\x1b[A");
assert_eq!(
strip_terminal_focus_reports(b"before\x1b[Iafter"),
b"beforeafter"
);
}
#[test]
fn idle_repaint_only_runs_for_stale_alternate_screen() {
let now = Instant::now();
let stale = now - ALT_SCREEN_IDLE_REPAINT_AFTER - Duration::from_secs(1);
let recent = now - Duration::from_secs(1);
assert!(should_repaint_idle_alternate_screen(
true, stale, stale, now
));
assert!(!should_repaint_idle_alternate_screen(
false, stale, stale, now
));
assert!(!should_repaint_idle_alternate_screen(
true, recent, stale, now
));
assert!(!should_repaint_idle_alternate_screen(
true, stale, recent, now
));
}
#[test]
fn non_mouse_escape_input_survives_stale_filter() {
assert_eq!(strip_stale_mouse_reports(b"\x1b[A"), b"\x1b[A");
+118 -27
View File
@@ -52,6 +52,7 @@ const STREAM_INITIAL_WINDOW: usize = 1024 * 1024;
/// have accumulated since the last mirror. Keeps the atomic write off the
/// per-packet hot path while bounding how much fresh output a crash can lose.
const SCREEN_PERSIST_BYTES: usize = 4096;
const IMPLICIT_EMPTY_SESSION_GRACE_SECS: u64 = 300;
/// Sentinel `target_host` sent to the client on a server-initiated `StreamOpen`
/// that carries an SSH-agent connection (the client splices it into its local
@@ -512,15 +513,16 @@ impl ServerState {
Ok(())
}
/// Whether a session named `name` should be backed by a persistent holder.
/// Whether a session should be backed by a persistent holder.
///
/// With persistence enabled, explicitly named sessions get a detached
/// holder. Implicit `term-<millis>-<pid>` sessions are one-off terminals
/// created by `dosh host`; users cannot intentionally reattach to them by
/// name, so persisting them only leaves stale holders that can be
/// accidentally re-adopted after restarts.
fn should_persist_session(&self, name: &str) -> bool {
self.config.persist_sessions && !protocol::is_implicit_session_name(name)
/// With persistence enabled, every interactive session gets a detached holder
/// so an update/restart of `dosh-server` behaves like a transient network
/// break. Named sessions can sit empty for the normal client timeout.
/// Generated one-off sessions are also persisted, but cleanup gives them a
/// shorter empty grace period so invisible abandoned holders do not linger
/// indefinitely.
fn should_persist_session(&self, _name: &str) -> bool {
self.config.persist_sessions
}
/// Spawn (or, in the persistent case, spawn-and-adopt) a PTY for a session.
@@ -608,20 +610,6 @@ impl ServerState {
if self.sessions.contains_key(&name) {
continue;
}
if !self.should_persist_session(&name) {
eprintln!(
"discarding stale implicit persistent session {name} (shell pid {})",
meta.shell_pid
);
persist::request_shutdown(&sessions_dir, &name, None);
if meta.shell_pid > 0 {
let _ = unsafe { libc::kill(meta.shell_pid, libc::SIGHUP) };
let _ = unsafe { libc::kill(meta.shell_pid, libc::SIGTERM) };
std::thread::sleep(Duration::from_millis(50));
let _ = unsafe { libc::kill(meta.shell_pid, libc::SIGKILL) };
}
continue;
}
let (pty, control) = match self.adopt_persistent_pty(&name) {
Ok(pair) => pair,
Err(err) => {
@@ -671,6 +659,7 @@ impl ServerState {
fn insert_client(&mut self, session_name: &str, client_id: [u8; 16], client: ClientState) {
if let Some(session) = self.sessions.get_mut(session_name) {
session.clients.insert(client_id, client);
session.empty_since = None;
self.client_index
.insert(client_id, session_name.to_string());
}
@@ -865,6 +854,7 @@ async fn handle_packet(
| PacketKind::StreamEof
| PacketKind::StreamWindowAdjust
| PacketKind::RekeyAck
| PacketKind::Detach
if find_client_decrypt_key(state, &packet.header).is_err() =>
{
send_reject_to_client(socket, peer, packet.header.conn_id, "unknown client").await
@@ -1734,7 +1724,14 @@ async fn handle_ping(
}
async fn handle_detach(state: &Arc<Mutex<ServerState>>, packet: &protocol::Packet) -> Result<()> {
let (key, _) = find_client_decrypt_key(state, &packet.header)?;
let _ = protocol::decrypt_body(packet, &key, CLIENT_TO_SERVER)?;
let mut locked = state.lock().expect("server state poisoned");
if let Some(client) = locked.client_mut(&packet.header.conn_id) {
if !client.replay.accept(packet.header.seq) {
return Ok(());
}
}
locked.remove_client_everywhere(&packet.header.conn_id);
Ok(())
}
@@ -2670,10 +2667,13 @@ async fn handle_file_request(
let (file, temp_path, written, atomic) = if resume && final_path.exists() {
let mut file = fs::OpenOptions::new()
.read(true)
.write(true)
.append(true)
.open(&final_path)
.with_context(|| format!("open {}", final_path.display()))?;
let written = file.metadata()?.len().min(size);
file.set_len(written)
.with_context(|| format!("truncate {}", final_path.display()))?;
if written > 0 {
let mut prefix = fs::File::open(&final_path)?;
hash_exact_prefix(&mut prefix, written, &mut hasher)?;
@@ -3834,9 +3834,9 @@ fn cleanup_disconnected_clients(state: &Arc<Mutex<ServerState>>) {
.iter()
.filter(|(name, session)| {
!prewarm.contains(name.as_str())
&& session
.empty_since
.is_some_and(|since| now.duration_since(since) >= timeout)
&& session.empty_since.is_some_and(|since| {
now.duration_since(since) >= empty_session_timeout(name, timeout)
})
})
.map(|(name, _)| name.clone())
.collect();
@@ -3855,6 +3855,14 @@ fn cleanup_disconnected_clients(state: &Arc<Mutex<ServerState>>) {
}
}
fn empty_session_timeout(name: &str, configured_timeout: Duration) -> Duration {
if protocol::is_implicit_session_name(name) {
configured_timeout.min(Duration::from_secs(IMPLICIT_EMPTY_SESSION_GRACE_SECS))
} else {
configured_timeout
}
}
/// Select the client key (current or retained previous epoch) matching the
/// packet header's `session_key_id`, so a packet sealed under the pre-rekey key
/// during the grace window still decrypts while an expired/stale epoch is
@@ -3901,7 +3909,7 @@ mod tests {
use super::*;
#[test]
fn persists_named_sessions_when_enabled() {
fn persists_terminal_sessions_when_enabled() {
let (pty_tx, _rx) = mpsc::unbounded_channel();
let config = ServerConfig {
persist_sessions: true,
@@ -3911,7 +3919,7 @@ mod tests {
let state = ServerState::new(config, [0u8; 32], pty_tx);
assert!(state.should_persist_session("default")); // prewarmed
assert!(state.should_persist_session("work")); // explicitly named
assert!(!state.should_persist_session("term-1781470634216-76685")); // one-off terminal
assert!(state.should_persist_session("term-1781470634216-76685")); // one-off update-survivable terminal
}
#[test]
@@ -4066,6 +4074,12 @@ mod tests {
Some((key, "work".to_string()))
);
assert!(state.client_mut(&client_id).is_some());
state.sessions.get_mut("work").unwrap().empty_since = Some(Instant::now());
state.insert_client("work", [7u8; 16], test_client_state([9u8; 32]));
assert!(
state.sessions["work"].empty_since.is_none(),
"reattach must clear empty-since so cleanup cannot reap a live session"
);
// Removing purges both the session map and the index.
assert!(state.remove_client_everywhere(&client_id));
@@ -4105,6 +4119,83 @@ mod tests {
assert!(locked.lookup_client(&client_id).is_none());
}
#[test]
fn implicit_empty_session_timeout_is_bounded_for_update_reconnect() {
let configured = Duration::from_secs(2_592_000);
let implicit = protocol::generate_implicit_session_name();
assert_eq!(
empty_session_timeout(&implicit, configured),
Duration::from_secs(IMPLICIT_EMPTY_SESSION_GRACE_SECS)
);
assert_eq!(
empty_session_timeout("work", configured),
configured,
"named sessions keep the normal long timeout"
);
assert_eq!(
empty_session_timeout(&implicit, Duration::from_secs(1)),
Duration::from_secs(1),
"tests/admins can still configure a shorter timeout"
);
}
#[tokio::test]
async fn forged_plaintext_detach_does_not_remove_client() {
let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
let mut state = ServerState::new(ServerConfig::default(), [0u8; 32], pty_tx);
state
.ensure_session("work", 80, 24, "forward-only", &[])
.unwrap();
let client_id = [21u8; 16];
let session_key = [22u8; 32];
state.insert_client("work", client_id, test_client_state(session_key));
let state = Arc::new(Mutex::new(state));
let mut packet = protocol::decode(
&protocol::encode_plain(PacketKind::Detach, client_id, 1, 0, b"").unwrap(),
)
.unwrap();
packet.header.session_key_id = protocol::session_key_id(&session_key);
assert!(handle_detach(&state, &packet).await.is_err());
let locked = state.lock().unwrap();
assert!(
locked.lookup_client(&client_id).is_some(),
"plaintext detach with a copied key id must not remove a live client"
);
}
#[tokio::test]
async fn authenticated_detach_removes_client() {
let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
let mut state = ServerState::new(ServerConfig::default(), [0u8; 32], pty_tx);
state
.ensure_session("work", 80, 24, "forward-only", &[])
.unwrap();
let client_id = [23u8; 16];
let session_key = [24u8; 32];
state.insert_client("work", client_id, test_client_state(session_key));
let state = Arc::new(Mutex::new(state));
let packet = protocol::decode(
&protocol::encode_encrypted(
PacketKind::Detach,
client_id,
1,
0,
&session_key,
CLIENT_TO_SERVER,
b"",
)
.unwrap(),
)
.unwrap();
handle_detach(&state, &packet).await.unwrap();
let locked = state.lock().unwrap();
assert!(locked.lookup_client(&client_id).is_none());
}
#[tokio::test]
async fn duplicate_stream_open_for_open_stream_resends_ok() {
let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
+1 -1
View File
@@ -280,7 +280,7 @@ pub fn decode(input: &[u8]) -> Result<Packet> {
pub fn decrypt_body(packet: &Packet, key: &[u8; 32], direction: u32) -> Result<Vec<u8>> {
if packet.header.flags & 1 == 0 {
return Ok(packet.body.clone());
bail!("packet body is not encrypted");
}
let nonce = crypto::nonce_from(direction, packet.header.seq);
let aad = packet.header.aad();
+259 -20
View File
@@ -18,7 +18,8 @@ use dosh::crypto;
use dosh::native::{host_public_key, load_or_create_host_key, ssh_ed25519_public_blob, trust_host};
use dosh::protocol::{
self, AttachOk, AttachReject, BootstrapAttachRequest, CLIENT_TO_SERVER, Frame, Input,
PacketKind, Resize, ResumeRequest, SERVER_TO_CLIENT,
PacketKind, Resize, ResumeRequest, SERVER_TO_CLIENT, TicketAttachBody, TicketAttachEnvelope,
TicketAttachOkEnvelope,
};
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
@@ -530,6 +531,75 @@ fn direct_attach_session(
(socket, bootstrap, ok)
}
fn ticket_attach_session(
socket: &UdpSocket,
port: u16,
bootstrap: &dosh::auth::BootstrapResponse,
session: &str,
mode: &str,
) -> AttachOk {
let client_nonce = crypto::random_12();
let request_key = crypto::hkdf32(
&bootstrap.attach_ticket_psk,
&client_nonce,
b"dosh/ticket-attach-request/v1",
)
.unwrap();
let body = protocol::to_body(&TicketAttachBody {
session: session.to_string(),
mode: mode.to_string(),
cols: 80,
rows: 24,
requested_env: Vec::new(),
})
.unwrap();
let ciphertext = crypto::seal(
&request_key,
&client_nonce,
b"dosh-ticket-attach-request-v1",
&body,
)
.unwrap();
let envelope = TicketAttachEnvelope {
ticket: bootstrap.attach_ticket.clone(),
client_nonce,
ciphertext,
};
let packet = protocol::encode_plain(
PacketKind::TicketAttachRequest,
[0u8; 16],
1,
0,
&protocol::to_body(&envelope).unwrap(),
)
.unwrap();
socket
.send_to(&packet, format!("127.0.0.1:{port}"))
.unwrap();
let mut buf = [0u8; 65535];
let (n, _) = socket.recv_from(&mut buf).unwrap();
let packet = protocol::decode(&buf[..n]).unwrap();
assert_eq!(packet.header.kind, PacketKind::AttachOk);
let envelope: TicketAttachOkEnvelope = protocol::from_body(&packet.body).unwrap();
let mut salt = Vec::with_capacity(24);
salt.extend_from_slice(&client_nonce);
salt.extend_from_slice(&envelope.server_nonce);
let response_key = crypto::hkdf32(
&bootstrap.attach_ticket_psk,
&salt,
b"dosh/ticket-attach-ok/v1",
)
.unwrap();
let plain = crypto::open(
&response_key,
&envelope.server_nonce,
b"dosh-ticket-attach-ok-v1",
&envelope.ciphertext,
)
.unwrap();
protocol::from_body(&plain).unwrap()
}
#[allow(clippy::too_many_arguments)]
fn send_encrypted(
socket: &UdpSocket,
@@ -1038,6 +1108,117 @@ fn native_file_copy_recursive_round_trip() {
let _ = server.wait();
}
#[test]
fn native_file_copy_resume_truncates_oversized_destinations() {
let dir = tempfile::tempdir().unwrap();
let port = free_udp_port();
let config = write_server_config(&dir, port);
write_native_client_auth(&dir, &config);
let mut server = start_server(&dir, &config);
let client_bin = env!("CARGO_BIN_EXE_dosh-client");
let local_short = dir.path().join("short.txt");
fs::write(&local_short, b"short\n").unwrap();
let seed_remote = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("exec")
.arg("local")
.arg("printf 'short\\nSTALE' > \"$HOME/resume-upload.txt\"")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
seed_remote.status.success(),
"seed remote failed: stdout={} stderr={}",
String::from_utf8_lossy(&seed_remote.stdout),
String::from_utf8_lossy(&seed_remote.stderr)
);
let resume_upload = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("cp")
.arg("--resume")
.arg(&local_short)
.arg("local:resume-upload.txt")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
resume_upload.status.success(),
"resume upload failed: stdout={} stderr={}",
String::from_utf8_lossy(&resume_upload.stdout),
String::from_utf8_lossy(&resume_upload.stderr)
);
let cat_upload = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("cat")
.arg("local:resume-upload.txt")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
cat_upload.status.success(),
"cat upload failed: stdout={} stderr={}",
String::from_utf8_lossy(&cat_upload.stdout),
String::from_utf8_lossy(&cat_upload.stderr)
);
assert_eq!(String::from_utf8_lossy(&cat_upload.stdout), "short\n");
let seed_download = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("exec")
.arg("local")
.arg("printf 'tiny\\n' > \"$HOME/resume-download.txt\"")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
seed_download.status.success(),
"seed download failed: stdout={} stderr={}",
String::from_utf8_lossy(&seed_download.stdout),
String::from_utf8_lossy(&seed_download.stderr)
);
let local_download = dir.path().join("resume-download-local.txt");
fs::write(&local_download, b"tiny\nSTALE").unwrap();
let resume_download = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("cp")
.arg("--resume")
.arg("local:resume-download.txt")
.arg(&local_download)
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
resume_download.status.success(),
"resume download failed: stdout={} stderr={}",
String::from_utf8_lossy(&resume_download.stdout),
String::from_utf8_lossy(&resume_download.stderr)
);
assert_eq!(fs::read_to_string(&local_download).unwrap(), "tiny\n");
let _ = server.kill();
let _ = server.wait();
}
#[test]
fn native_exec_command_smoke() {
let dir = tempfile::tempdir().unwrap();
@@ -2733,7 +2914,7 @@ fn session_survives_server_restart_same_shell_and_screen() {
}
#[test]
fn implicit_session_does_not_create_restart_holder() {
fn implicit_session_survives_update_restart_via_ticket_reattach() {
let dir = tempfile::tempdir().unwrap();
let sessions_dir = dir.path().join("sessions");
let port = free_udp_port();
@@ -2743,21 +2924,34 @@ fn implicit_session_does_not_create_restart_holder() {
let mut server = start_server(&dir, &config);
let (socket, bootstrap, ok) = direct_attach_session(&config, port, "read-write", &session);
let key = bootstrap.session_key;
type_line(&socket, port, &ok, &key, 2, "cd /tmp\n");
type_line(
&socket,
port,
&ok,
&key,
2,
3,
"export IMPLICIT_MARK=implicit_restart_42\n",
);
let _ = collect_frame_text(&socket, &key, 1000);
type_line(
&socket,
port,
&ok,
&key,
4,
"printf 'IMPLICIT_SCREEN_MARKER\\n'\n",
);
let pre = collect_frame_text(&socket, &key, 1500);
assert!(
pre.contains("IMPLICIT_SCREEN_MARKER"),
"implicit marker missing before restart: {pre:?}"
);
thread::sleep(Duration::from_secs(3));
let shell_pid_before = holder_shell_pid(&sessions_dir, &session);
assert!(
shell_pid_before.is_none(),
"implicit sessions must not get persistent holders when persistence is enabled"
shell_pid_before.is_some(),
"implicit sessions must get temporary holders so active clients survive updates"
);
let _ = server.kill();
@@ -2765,34 +2959,78 @@ fn implicit_session_does_not_create_restart_holder() {
thread::sleep(Duration::from_millis(300));
let mut server = start_server(&dir, &config);
let (socket2, bootstrap2, ok2) = direct_attach_session(&config, port, "read-write", &session);
let key2 = bootstrap2.session_key;
let resume = ResumeRequest {
session: session.clone(),
last_rendered_seq: ok.initial_seq,
cols: 80,
rows: 24,
};
send_encrypted(
&socket,
port,
PacketKind::ResumeRequest,
ok.client_id,
5,
0,
&key,
&protocol::to_body(&resume).unwrap(),
);
let mut buf = [0u8; 65535];
let deadline = std::time::Instant::now() + Duration::from_secs(2);
loop {
assert!(
std::time::Instant::now() < deadline,
"old live resume did not receive unknown-client reject"
);
let (n, _) = socket.recv_from(&mut buf).unwrap();
let packet = protocol::decode(&buf[..n]).unwrap();
if packet.header.kind == PacketKind::Frame {
continue;
}
assert_eq!(packet.header.kind, PacketKind::AttachReject);
assert_eq!(packet.header.conn_id, ok.client_id);
break;
}
let ok2 = ticket_attach_session(&socket, port, &bootstrap, &session, "read-write");
let key2 = ok2.session_key;
let snapshot = String::from_utf8_lossy(&ok2.snapshot).to_string();
type_line(
&socket2,
&socket,
port,
&ok2,
&key2,
2,
"printf 'IMPLICIT_MARK=%s\\n' \"$IMPLICIT_MARK\"\n",
"printf 'IMPLICIT_MARK=%s PWD=%s\\n' \"$IMPLICIT_MARK\" \"$PWD\"\n",
);
let post = collect_frame_text(&socket2, &key2, 2000);
let post = collect_frame_text(&socket, &key2, 2000);
let shell_pid_after = holder_shell_pid(&sessions_dir, &session);
let _ = server.kill();
let _ = server.wait();
kill_holder(&sessions_dir, &session);
assert!(
shell_pid_after.is_none(),
"implicit restart attach must stay ephemeral"
snapshot.contains("IMPLICIT_SCREEN_MARKER"),
"ticket reattach snapshot must repaint the exact pre-update screen, got {snapshot:?}"
);
assert_eq!(
shell_pid_after, shell_pid_before,
"implicit update reconnect must use the same holder shell"
);
assert!(
post.contains("IMPLICIT_MARK=") && !post.contains("implicit_restart_42"),
"implicit session must start fresh after server restart, got {post:?}"
post.contains("IMPLICIT_MARK=implicit_restart_42"),
"implicit session env must survive update reconnect, got {post:?}"
);
assert!(
post.contains("PWD=/tmp"),
"implicit session cwd must survive update reconnect, got {post:?}"
);
}
#[test]
fn startup_discards_legacy_implicit_holders() {
fn startup_readopts_implicit_holders_for_update_reconnect() {
let dir = tempfile::tempdir().unwrap();
let sessions_dir = dir.path().join("sessions");
let port = free_udp_port();
@@ -2812,13 +3050,14 @@ fn startup_discards_legacy_implicit_holders() {
let _ = server.kill();
let _ = server.wait();
assert!(
holder_shell_pid(&sessions_dir, &session).is_none(),
"startup must remove old implicit holder metadata"
holder_shell_pid(&sessions_dir, &session).is_some(),
"startup must keep live implicit holders so active update reconnects can reattach"
);
assert!(
unsafe { libc::kill(shell_pid, 0) } != 0,
"startup must shut down old implicit holder shell"
unsafe { libc::kill(shell_pid, 0) } == 0,
"startup must not shut down a live implicit holder before reconnect grace"
);
kill_holder(&sessions_dir, &session);
}
#[test]
+13
View File
@@ -58,6 +58,19 @@ fn encrypted_packet_round_trips() {
assert_eq!(plain, b"hello");
}
#[test]
fn plaintext_packet_never_decrypts_as_authenticated_body() {
let key = crypto::random_32();
let mut decoded = protocol::decode(
&protocol::encode_plain(PacketKind::Input, crypto::random_16(), 1, 0, b"hello").unwrap(),
)
.unwrap();
decoded.header.session_key_id = protocol::session_key_id(&key);
let err = protocol::decrypt_body(&decoded, &key, CLIENT_TO_SERVER).unwrap_err();
assert!(err.to_string().contains("not encrypted"));
}
#[test]
fn encrypted_packet_rejects_wrong_session_key_id_before_decrypt() {
let key = crypto::random_32();