Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
039dc641b3 | ||
|
|
4c9e31fd16 | ||
|
|
c1c672b188 | ||
|
|
a23f610f20 | ||
|
|
ff2b7fff2b | ||
|
|
f4879090f6 | ||
|
|
37ec9fc520 | ||
|
|
f3c7ec225d | ||
|
|
d3c40a06ac | ||
|
|
6b12b3dfe0 | ||
|
|
b90c34dc17 | ||
|
|
f205e0c128 | ||
|
|
92c94176bd | ||
|
|
4b2e9a62d5 | ||
|
|
689d20f7e7 | ||
|
|
252f081a61 | ||
|
|
b1e8326b0a | ||
|
|
3b4931aa8f | ||
|
|
5c54601cdf | ||
|
|
c085137250 | ||
|
|
237ad52bef |
Generated
+1
-1
@@ -436,7 +436,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dosh"
|
name = "dosh"
|
||||||
version = "0.1.16"
|
version = "1.0.0-rc10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dosh"
|
name = "dosh"
|
||||||
version = "0.1.16"
|
version = "1.0.0-rc10"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: build test fmt clippy release-check install package-release package-release-linux package-release-windows publish-release bench-report bench-local bench-local-json bench-docker-ssh bench-docker-mosh fuzz-smoke fuzz-deep soak-local tui-harness
|
.PHONY: build test fmt clippy release-check 1.0-check reconnect-check hostile-network-check persistence-check package-check install package-release package-release-linux package-release-windows publish-release bench-report bench-local bench-local-json bench-docker-ssh bench-docker-mosh fuzz-smoke fuzz-deep soak-local tui-harness
|
||||||
|
|
||||||
build:
|
build:
|
||||||
cargo build --release
|
cargo build --release
|
||||||
@@ -19,6 +19,25 @@ release-check:
|
|||||||
cargo test
|
cargo test
|
||||||
$(MAKE) tui-harness
|
$(MAKE) tui-harness
|
||||||
|
|
||||||
|
1.0-check: release-check reconnect-check hostile-network-check persistence-check package-check
|
||||||
|
|
||||||
|
reconnect-check:
|
||||||
|
cargo test --test integration_smoke resume_updates_udp_endpoint_for_roaming -- --nocapture
|
||||||
|
DOSH_SOAK_SECONDS=$${DOSH_SOAK_SECONDS:-300} cargo test --test integration_smoke sleep_roaming_soak_30m -- --ignored --nocapture
|
||||||
|
|
||||||
|
hostile-network-check:
|
||||||
|
cargo test --test hostile_network -- --nocapture
|
||||||
|
DOSH_BADNET_SOAK_SECONDS=$${DOSH_BADNET_SOAK_SECONDS:-300} cargo test --test hostile_network bad_network_tui_work_soak_30m -- --ignored --nocapture
|
||||||
|
|
||||||
|
persistence-check:
|
||||||
|
cargo test --test integration_smoke session_survives_server_restart_same_shell_and_screen -- --nocapture
|
||||||
|
cargo test --test integration_smoke multiple_persistent_named_sessions_survive_restart_independently -- --nocapture
|
||||||
|
|
||||||
|
package-check:
|
||||||
|
$(MAKE) package-release-linux
|
||||||
|
$(MAKE) package-release-windows
|
||||||
|
sh scripts/verify-release-artifacts.sh
|
||||||
|
|
||||||
install:
|
install:
|
||||||
sh install.sh --from-current
|
sh install.sh --from-current
|
||||||
|
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ cleanup() {
|
|||||||
kill "$server_pid" 2>/dev/null || true
|
kill "$server_pid" 2>/dev/null || true
|
||||||
wait "$server_pid" 2>/dev/null || true
|
wait "$server_pid" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
|
pkill -f "$server_bin hold --runtime-dir $home/sessions/run" 2>/dev/null || true
|
||||||
rm -rf "$home"
|
rm -rf "$home"
|
||||||
}
|
}
|
||||||
trap cleanup EXIT INT TERM
|
trap cleanup EXIT INT TERM
|
||||||
@@ -86,6 +87,7 @@ scrollback = 5000
|
|||||||
auth_ttl_secs = 30
|
auth_ttl_secs = 30
|
||||||
attach_ticket_ttl_secs = 3600
|
attach_ticket_ttl_secs = 3600
|
||||||
allow_attach_tickets = true
|
allow_attach_tickets = true
|
||||||
|
persist_sessions = false
|
||||||
client_timeout_secs = 60
|
client_timeout_secs = 60
|
||||||
retransmit_window = 256
|
retransmit_window = 256
|
||||||
default_input_mode = "read-write"
|
default_input_mode = "read-write"
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
repo_root="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
version="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | sed -n '1p')"
|
||||||
|
out_dir="${DOSH_PACKAGE_DIR:-target/dosh-release}"
|
||||||
|
|
||||||
|
artifact_version() {
|
||||||
|
artifact="$1"
|
||||||
|
case "$artifact" in
|
||||||
|
*.tar.gz)
|
||||||
|
tar -xOf "$artifact" dosh/VERSION 2>/dev/null | tr -d '\r\n'
|
||||||
|
;;
|
||||||
|
*.zip)
|
||||||
|
unzip -p "$artifact" dosh/VERSION 2>/dev/null | tr -d '\r\n'
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
failed=0
|
||||||
|
for artifact in \
|
||||||
|
"$out_dir/dosh-linux-x86_64.tar.gz" \
|
||||||
|
"$out_dir/dosh-macos-aarch64.tar.gz" \
|
||||||
|
"$out_dir/dosh-windows-x86_64.zip"; do
|
||||||
|
if [ ! -f "$artifact" ]; then
|
||||||
|
echo "missing release artifact: $artifact" >&2
|
||||||
|
failed=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if [ ! -f "$artifact.sha256" ]; then
|
||||||
|
echo "missing release checksum: $artifact.sha256" >&2
|
||||||
|
failed=1
|
||||||
|
fi
|
||||||
|
actual="$(artifact_version "$artifact" || true)"
|
||||||
|
if [ "$actual" != "$version" ]; then
|
||||||
|
echo "artifact version mismatch: $artifact has ${actual:-unknown}, expected $version" >&2
|
||||||
|
failed=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
exit "$failed"
|
||||||
+573
-49
@@ -36,6 +36,7 @@ use dosh::transport::{
|
|||||||
DoshTransport, SessionEvent, SessionRole, SessionTransportConfig, TransportConfig,
|
DoshTransport, SessionEvent, SessionRole, SessionTransportConfig, TransportConfig,
|
||||||
TransportEvent,
|
TransportEvent,
|
||||||
};
|
};
|
||||||
|
use dosh::udp::is_transient_udp_send_error;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
@@ -63,6 +64,10 @@ const STREAM_INITIAL_WINDOW: usize = 1024 * 1024;
|
|||||||
const MAX_PENDING_USER_INPUT_BYTES: usize = 1024 * 1024;
|
const MAX_PENDING_USER_INPUT_BYTES: usize = 1024 * 1024;
|
||||||
const STARTUP_INPUT_HOLD: Duration = Duration::from_millis(750);
|
const STARTUP_INPUT_HOLD: Duration = Duration::from_millis(750);
|
||||||
const POST_SUBMIT_ALL_INPUT_HOLD: Duration = Duration::from_millis(120);
|
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
|
/// Sentinel `target_host` the server uses on a server-initiated `StreamOpen` that
|
||||||
/// represents an SSH-agent connection (rather than a TCP target). The client
|
/// represents an SSH-agent connection (rather than a TCP target). The client
|
||||||
@@ -2493,11 +2498,15 @@ fn download_file(
|
|||||||
0
|
0
|
||||||
};
|
};
|
||||||
let mut file = if offset > 0 {
|
let mut file = if offset > 0 {
|
||||||
fs::OpenOptions::new()
|
let file = fs::OpenOptions::new()
|
||||||
.read(true)
|
.read(true)
|
||||||
|
.write(true)
|
||||||
.append(true)
|
.append(true)
|
||||||
.open(local)
|
.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 {
|
} else {
|
||||||
fs::OpenOptions::new()
|
fs::OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
@@ -3524,6 +3533,14 @@ fn resolve_addr(host: &str, port: u16) -> Result<SocketAddr> {
|
|||||||
.ok_or_else(|| anyhow!("no UDP address resolved for {host}:{port}"))
|
.ok_or_else(|| anyhow!("no UDP address resolved for {host}:{port}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn send_terminal_udp(socket: &UdpSocket, packet: &[u8], addr: SocketAddr) -> Result<bool> {
|
||||||
|
match socket.send_to(packet, addr).await {
|
||||||
|
Ok(_) => Ok(true),
|
||||||
|
Err(err) if is_transient_udp_send_error(&err) => Ok(false),
|
||||||
|
Err(err) => Err(err).with_context(|| format!("send UDP packet to {addr}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
async fn try_native_auth(
|
async fn try_native_auth(
|
||||||
socket: &UdpSocket,
|
socket: &UdpSocket,
|
||||||
@@ -4322,10 +4339,15 @@ async fn run_terminal(
|
|||||||
let mut pending_user_input_bytes = 0usize;
|
let mut pending_user_input_bytes = 0usize;
|
||||||
let mut startup_input_hold_until: Option<Instant> = None;
|
let mut startup_input_hold_until: Option<Instant> = None;
|
||||||
let mut startup_gate_mode = StartupGateMode::HoldControl;
|
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 let Some(frame) = first_frame {
|
||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
}
|
}
|
||||||
if frame.closed {
|
if frame.closed {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -4337,7 +4359,13 @@ async fn run_terminal(
|
|||||||
&& cred.mode != "view-only"
|
&& cred.mode != "view-only"
|
||||||
&& !forward_only
|
&& !forward_only
|
||||||
{
|
{
|
||||||
send_input(&socket, addr, &cred, &mut send_seq, bytes).await?;
|
if !send_input(&socket, addr, &cred, &mut send_seq, bytes.clone()).await? {
|
||||||
|
queue_stale_pending_user_input(
|
||||||
|
&mut pending_user_input,
|
||||||
|
&mut pending_user_input_bytes,
|
||||||
|
bytes,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
startup_input_hold_until = Some(Instant::now() + STARTUP_INPUT_HOLD);
|
startup_input_hold_until = Some(Instant::now() + STARTUP_INPUT_HOLD);
|
||||||
startup_gate_mode = StartupGateMode::HoldAll;
|
startup_gate_mode = StartupGateMode::HoldAll;
|
||||||
}
|
}
|
||||||
@@ -4373,10 +4401,59 @@ async fn run_terminal(
|
|||||||
biased;
|
biased;
|
||||||
stdin_msg = stdin_rx.recv() => {
|
stdin_msg = stdin_rx.recv() => {
|
||||||
match stdin_msg {
|
match stdin_msg {
|
||||||
Some(bytes) => {
|
Some(mut bytes) => {
|
||||||
if input_matches_escape(&bytes, escape_key.as_deref()) {
|
if input_matches_escape(&bytes, escape_key.as_deref()) {
|
||||||
break;
|
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,
|
||||||
|
) {
|
||||||
|
bytes = strip_stale_mouse_reports(&bytes);
|
||||||
|
if bytes.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
if cred.mode != "view-only" && cred.mode != "forward-only" {
|
if cred.mode != "view-only" && cred.mode != "forward-only" {
|
||||||
if let Some(deadline) = startup_input_hold_until {
|
if let Some(deadline) = startup_input_hold_until {
|
||||||
if !predictor.alternate_screen
|
if !predictor.alternate_screen
|
||||||
@@ -4411,8 +4488,15 @@ async fn run_terminal(
|
|||||||
&& let Some((send_now, mut hold_for_later)) =
|
&& let Some((send_now, mut hold_for_later)) =
|
||||||
split_after_command_submit(&bytes)
|
split_after_command_submit(&bytes)
|
||||||
{
|
{
|
||||||
predictor.observe_input(&send_now)?;
|
if send_input(&socket, addr, &cred, &mut send_seq, send_now.clone()).await? {
|
||||||
send_input(&socket, addr, &cred, &mut send_seq, send_now).await?;
|
predictor.observe_input(&send_now)?;
|
||||||
|
} else {
|
||||||
|
queue_stale_pending_user_input(
|
||||||
|
&mut pending_user_input,
|
||||||
|
&mut pending_user_input_bytes,
|
||||||
|
send_now,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
startup_input_hold_until = Some(
|
startup_input_hold_until = Some(
|
||||||
Instant::now()
|
Instant::now()
|
||||||
+ post_submit_hold_duration(&hold_for_later),
|
+ post_submit_hold_duration(&hold_for_later),
|
||||||
@@ -4431,15 +4515,23 @@ async fn run_terminal(
|
|||||||
)?;
|
)?;
|
||||||
continue;
|
continue;
|
||||||
} else if !hold_for_later.is_empty() {
|
} else if !hold_for_later.is_empty() {
|
||||||
predictor.observe_input(&hold_for_later)?;
|
let sent = send_input(
|
||||||
send_input(
|
|
||||||
&socket,
|
&socket,
|
||||||
addr,
|
addr,
|
||||||
&cred,
|
&cred,
|
||||||
&mut send_seq,
|
&mut send_seq,
|
||||||
std::mem::take(&mut hold_for_later),
|
hold_for_later.clone(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
if sent {
|
||||||
|
predictor.observe_input(&hold_for_later)?;
|
||||||
|
} else {
|
||||||
|
queue_stale_pending_user_input(
|
||||||
|
&mut pending_user_input,
|
||||||
|
&mut pending_user_input_bytes,
|
||||||
|
std::mem::take(&mut hold_for_later),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -4460,9 +4552,13 @@ async fn run_terminal(
|
|||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
|
arm_stale_terminal_input_suppression(
|
||||||
|
&mut stale_terminal_input_suppress_until,
|
||||||
|
);
|
||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
}
|
}
|
||||||
last_packet_at = Instant::now();
|
last_packet_at = Instant::now();
|
||||||
flush_pending_user_input(
|
flush_pending_user_input(
|
||||||
@@ -4477,8 +4573,15 @@ async fn run_terminal(
|
|||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
predictor.observe_input(&bytes)?;
|
if send_input(&socket, addr, &cred, &mut send_seq, bytes.clone()).await? {
|
||||||
send_input(&socket, addr, &cred, &mut send_seq, bytes).await?;
|
predictor.observe_input(&bytes)?;
|
||||||
|
} else {
|
||||||
|
queue_stale_pending_user_input(
|
||||||
|
&mut pending_user_input,
|
||||||
|
&mut pending_user_input_bytes,
|
||||||
|
bytes,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4512,9 +4615,13 @@ async fn run_terminal(
|
|||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
|
arm_stale_terminal_input_suppression(
|
||||||
|
&mut stale_terminal_input_suppress_until,
|
||||||
|
);
|
||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
}
|
}
|
||||||
last_packet_at = Instant::now();
|
last_packet_at = Instant::now();
|
||||||
flush_pending_user_input(
|
flush_pending_user_input(
|
||||||
@@ -4562,9 +4669,13 @@ async fn run_terminal(
|
|||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
|
arm_stale_terminal_input_suppression(
|
||||||
|
&mut stale_terminal_input_suppress_until,
|
||||||
|
);
|
||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
}
|
}
|
||||||
last_packet_at = Instant::now();
|
last_packet_at = Instant::now();
|
||||||
flush_pending_user_input(
|
flush_pending_user_input(
|
||||||
@@ -4590,6 +4701,7 @@ async fn run_terminal(
|
|||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
flush_startup_input_if_ready(
|
flush_startup_input_if_ready(
|
||||||
&socket,
|
&socket,
|
||||||
addr,
|
addr,
|
||||||
@@ -4610,6 +4722,22 @@ async fn run_terminal(
|
|||||||
}
|
}
|
||||||
PacketKind::Pong => {
|
PacketKind::Pong => {
|
||||||
last_packet_at = Instant::now();
|
last_packet_at = Instant::now();
|
||||||
|
if should_flush_terminal_input_after_contact(
|
||||||
|
forward_only,
|
||||||
|
&cred.mode,
|
||||||
|
pending_user_input.is_empty(),
|
||||||
|
) {
|
||||||
|
flush_pending_user_input(
|
||||||
|
&socket,
|
||||||
|
addr,
|
||||||
|
&cred,
|
||||||
|
&mut send_seq,
|
||||||
|
&mut predictor,
|
||||||
|
&mut pending_user_input,
|
||||||
|
&mut pending_user_input_bytes,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
PacketKind::Rekey => {
|
PacketKind::Rekey => {
|
||||||
// Server-initiated transport rekey (spec §11). The Rekey is
|
// Server-initiated transport rekey (spec §11). The Rekey is
|
||||||
@@ -4651,7 +4779,7 @@ async fn run_terminal(
|
|||||||
CLIENT_TO_SERVER,
|
CLIENT_TO_SERVER,
|
||||||
b"",
|
b"",
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&ack, addr).await?;
|
let _ = send_terminal_udp(&socket, &ack, addr).await?;
|
||||||
}
|
}
|
||||||
PacketKind::AttachReject => {
|
PacketKind::AttachReject => {
|
||||||
let reject: AttachReject = protocol::from_body(&packet.body)?;
|
let reject: AttachReject = protocol::from_body(&packet.body)?;
|
||||||
@@ -4667,9 +4795,13 @@ async fn run_terminal(
|
|||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
|
arm_stale_terminal_input_suppression(
|
||||||
|
&mut stale_terminal_input_suppress_until,
|
||||||
|
);
|
||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
}
|
}
|
||||||
last_packet_at = Instant::now();
|
last_packet_at = Instant::now();
|
||||||
flush_pending_user_input(
|
flush_pending_user_input(
|
||||||
@@ -5059,9 +5191,13 @@ async fn run_terminal(
|
|||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
refresh_live_addr(&mut addr, &cred)?;
|
refresh_live_addr(&mut addr, &cred)?;
|
||||||
|
arm_stale_terminal_input_suppression(
|
||||||
|
&mut stale_terminal_input_suppress_until,
|
||||||
|
);
|
||||||
if !forward_only {
|
if !forward_only {
|
||||||
render_frame(&frame)?;
|
render_frame(&frame)?;
|
||||||
predictor.observe_output(&frame.bytes);
|
predictor.observe_output(&frame.bytes);
|
||||||
|
last_terminal_frame_at = Instant::now();
|
||||||
}
|
}
|
||||||
last_packet_at = Instant::now();
|
last_packet_at = Instant::now();
|
||||||
flush_pending_user_input(
|
flush_pending_user_input(
|
||||||
@@ -5086,7 +5222,7 @@ async fn run_terminal(
|
|||||||
b"",
|
b"",
|
||||||
)?;
|
)?;
|
||||||
send_seq += 1;
|
send_seq += 1;
|
||||||
socket.send_to(&packet, addr).await?;
|
let _ = send_terminal_udp(&socket, &packet, addr).await?;
|
||||||
}
|
}
|
||||||
// Re-evaluate the prediction display policy on every timer tick so
|
// Re-evaluate the prediction display policy on every timer tick so
|
||||||
// a latency spike (or recovery) flips speculation on/off promptly
|
// a latency spike (or recovery) flips speculation on/off promptly
|
||||||
@@ -5103,6 +5239,44 @@ async fn run_terminal(
|
|||||||
(&mut startup_input_hold_until, &mut startup_gate_mode),
|
(&mut startup_input_hold_until, &mut startup_gate_mode),
|
||||||
)
|
)
|
||||||
.await?;
|
.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
|
// Refresh / clear the non-destructive disconnect status line based
|
||||||
// on how long the link has been silent (recomputed after any
|
// on how long the link has been silent (recomputed after any
|
||||||
@@ -5400,6 +5574,23 @@ fn queue_pending_user_input_with_filter(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn requeue_pending_user_input_front(
|
||||||
|
pending: &mut VecDeque<PendingUserInput>,
|
||||||
|
pending_bytes: &mut usize,
|
||||||
|
input: PendingUserInput,
|
||||||
|
) -> Result<()> {
|
||||||
|
let next = pending_bytes
|
||||||
|
.checked_add(input.bytes.len())
|
||||||
|
.ok_or_else(|| anyhow!("pending input buffer overflow"))?;
|
||||||
|
anyhow::ensure!(
|
||||||
|
next <= MAX_PENDING_USER_INPUT_BYTES,
|
||||||
|
"pending input buffer full while disconnected"
|
||||||
|
);
|
||||||
|
*pending_bytes = next;
|
||||||
|
pending.push_front(input);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
struct PendingUserInput {
|
struct PendingUserInput {
|
||||||
bytes: Vec<u8>,
|
bytes: Vec<u8>,
|
||||||
@@ -5439,6 +5630,61 @@ fn should_hold_during_startup_gate(
|
|||||||
mode == StartupGateMode::HoldAll || already_queued || should_hold_post_submit_input(bytes)
|
mode == StartupGateMode::HoldAll || already_queued || should_hold_post_submit_input(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn should_flush_terminal_input_after_contact(
|
||||||
|
forward_only: bool,
|
||||||
|
mode: &str,
|
||||||
|
pending_empty: bool,
|
||||||
|
) -> bool {
|
||||||
|
!forward_only && !pending_empty && mode != "view-only" && mode != "forward-only"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn should_strip_stale_terminal_reports(
|
||||||
|
silent_for: Duration,
|
||||||
|
suppress_until: Option<Instant>,
|
||||||
|
) -> bool {
|
||||||
|
silent_for >= STALE_TERMINAL_INPUT_AFTER
|
||||||
|
|| 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);
|
||||||
|
}
|
||||||
|
|
||||||
async fn flush_pending_user_input(
|
async fn flush_pending_user_input(
|
||||||
socket: &UdpSocket,
|
socket: &UdpSocket,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
@@ -5462,8 +5708,19 @@ async fn flush_pending_user_input(
|
|||||||
if bytes.is_empty() {
|
if bytes.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
predictor.observe_input(&bytes)?;
|
if send_input(socket, addr, cred, send_seq, bytes.clone()).await? {
|
||||||
send_input(socket, addr, cred, send_seq, bytes).await?;
|
predictor.observe_input(&bytes)?;
|
||||||
|
} else {
|
||||||
|
requeue_pending_user_input_front(
|
||||||
|
pending,
|
||||||
|
pending_bytes,
|
||||||
|
PendingUserInput {
|
||||||
|
bytes,
|
||||||
|
strip_mouse_reports: false,
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -5489,6 +5746,7 @@ fn stale_mouse_report_len(bytes: &[u8], offset: usize) -> Option<usize> {
|
|||||||
match bytes.get(offset).copied()? {
|
match bytes.get(offset).copied()? {
|
||||||
0x1b if bytes.get(offset + 1) == Some(&b'[') => match bytes.get(offset + 2).copied() {
|
0x1b if bytes.get(offset + 1) == Some(&b'[') => match bytes.get(offset + 2).copied() {
|
||||||
Some(b'M') if offset + 6 <= bytes.len() => Some(6),
|
Some(b'M') if offset + 6 <= bytes.len() => Some(6),
|
||||||
|
Some(b'I' | b'O') => Some(3),
|
||||||
Some(b'<') => mouse_report_params_len(bytes, offset + 3, 2).map(|len| len + 3),
|
Some(b'<') => mouse_report_params_len(bytes, offset + 3, 2).map(|len| len + 3),
|
||||||
Some(byte) if byte.is_ascii_digit() => {
|
Some(byte) if byte.is_ascii_digit() => {
|
||||||
mouse_report_params_len(bytes, offset + 2, 2).map(|len| len + 2)
|
mouse_report_params_len(bytes, offset + 2, 2).map(|len| len + 2)
|
||||||
@@ -5497,13 +5755,15 @@ fn stale_mouse_report_len(bytes: &[u8], offset: usize) -> Option<usize> {
|
|||||||
},
|
},
|
||||||
0x9b => match bytes.get(offset + 1).copied() {
|
0x9b => match bytes.get(offset + 1).copied() {
|
||||||
Some(b'M') if offset + 5 <= bytes.len() => Some(5),
|
Some(b'M') if offset + 5 <= bytes.len() => Some(5),
|
||||||
|
Some(b'I' | b'O') => Some(2),
|
||||||
Some(b'<') => mouse_report_params_len(bytes, offset + 2, 2).map(|len| len + 2),
|
Some(b'<') => mouse_report_params_len(bytes, offset + 2, 2).map(|len| len + 2),
|
||||||
Some(byte) if byte.is_ascii_digit() => {
|
Some(byte) if byte.is_ascii_digit() => {
|
||||||
mouse_report_params_len(bytes, offset + 1, 2).map(|len| len + 1)
|
mouse_report_params_len(bytes, offset + 1, 2).map(|len| len + 1)
|
||||||
}
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
},
|
},
|
||||||
byte if byte.is_ascii_digit() => mouse_report_params_len(bytes, offset, 1),
|
byte if byte.is_ascii_digit() => mouse_report_params_len(bytes, offset, 1)
|
||||||
|
.or_else(|| orphan_mouse_suffix_len(bytes, offset)),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5525,6 +5785,21 @@ fn mouse_report_params_len(bytes: &[u8], offset: usize, min_semicolons: usize) -
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn orphan_mouse_suffix_len(bytes: &[u8], offset: usize) -> Option<usize> {
|
||||||
|
if offset != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut cursor = offset;
|
||||||
|
while let Some(byte) = bytes.get(cursor).copied() {
|
||||||
|
match byte {
|
||||||
|
b'0'..=b'9' => cursor += 1,
|
||||||
|
b'M' | b'm' if cursor > offset => return Some(cursor + 1 - offset),
|
||||||
|
_ => return None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn stale_mouse_report_maybe_incomplete(bytes: &[u8], offset: usize) -> bool {
|
fn stale_mouse_report_maybe_incomplete(bytes: &[u8], offset: usize) -> bool {
|
||||||
let Some(rest) = bytes.get(offset..) else {
|
let Some(rest) = bytes.get(offset..) else {
|
||||||
return false;
|
return false;
|
||||||
@@ -5533,19 +5808,21 @@ fn stale_mouse_report_maybe_incomplete(bytes: &[u8], offset: usize) -> bool {
|
|||||||
[0x1b] | [0x1b, b'['] | [0x1b, b'[', b'<'] => true,
|
[0x1b] | [0x1b, b'['] | [0x1b, b'[', b'<'] => true,
|
||||||
[0x1b, b'[', b'M', ..] if rest.len() < 6 => true,
|
[0x1b, b'[', b'M', ..] if rest.len() < 6 => true,
|
||||||
[0x1b, b'[', b'<', params @ ..] | [0x1b, b'[', params @ ..]
|
[0x1b, b'[', b'<', params @ ..] | [0x1b, b'[', params @ ..]
|
||||||
if params_are_mouse_prefix(params) =>
|
if params_are_mouse_prefix(params, 2) =>
|
||||||
{
|
{
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
[0x9b] | [0x9b, b'<'] => true,
|
[0x9b] | [0x9b, b'<'] => true,
|
||||||
[0x9b, b'M', ..] if rest.len() < 5 => true,
|
[0x9b, b'M', ..] if rest.len() < 5 => true,
|
||||||
[0x9b, b'<', params @ ..] | [0x9b, params @ ..] if params_are_mouse_prefix(params) => true,
|
[0x9b, b'<', params @ ..] | [0x9b, params @ ..] if params_are_mouse_prefix(params, 2) => {
|
||||||
params if params_are_mouse_prefix(params) => true,
|
true
|
||||||
|
}
|
||||||
|
params if params_are_mouse_prefix(params, 2) => true,
|
||||||
_ => false,
|
_ => 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 semicolons = 0usize;
|
||||||
let mut saw_digit = false;
|
let mut saw_digit = false;
|
||||||
for byte in params {
|
for byte in params {
|
||||||
@@ -5555,7 +5832,7 @@ fn params_are_mouse_prefix(params: &[u8]) -> bool {
|
|||||||
_ => return false,
|
_ => return false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
saw_digit && semicolons >= 1
|
saw_digit && semicolons >= min_semicolons
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn flush_startup_input_if_ready(
|
async fn flush_startup_input_if_ready(
|
||||||
@@ -5595,7 +5872,7 @@ async fn send_input(
|
|||||||
cred: &CachedCredential,
|
cred: &CachedCredential,
|
||||||
send_seq: &mut u64,
|
send_seq: &mut u64,
|
||||||
bytes: Vec<u8>,
|
bytes: Vec<u8>,
|
||||||
) -> Result<()> {
|
) -> Result<bool> {
|
||||||
let body = protocol::to_body(&Input { bytes })?;
|
let body = protocol::to_body(&Input { bytes })?;
|
||||||
let packet = protocol::encode_encrypted(
|
let packet = protocol::encode_encrypted(
|
||||||
PacketKind::Input,
|
PacketKind::Input,
|
||||||
@@ -5607,8 +5884,7 @@ async fn send_input(
|
|||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
*send_seq += 1;
|
*send_seq += 1;
|
||||||
socket.send_to(&packet, addr).await?;
|
send_terminal_udp(socket, &packet, addr).await
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_stream_open(
|
async fn send_stream_open(
|
||||||
@@ -5951,7 +6227,7 @@ async fn send_stream_packet(
|
|||||||
body,
|
body,
|
||||||
)?;
|
)?;
|
||||||
*send_seq += 1;
|
*send_seq += 1;
|
||||||
socket.send_to(&packet, addr).await?;
|
let _ = send_terminal_udp(socket, &packet, addr).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6024,6 +6300,60 @@ const FLAG_TRIGGER_LOW_MS: f64 = 50.0;
|
|||||||
/// (covers a sudden latency spike on the very first slow keystroke).
|
/// (covers a sudden latency spike on the very first slow keystroke).
|
||||||
const GLITCH_FORCE_MS: u128 = 250;
|
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.
|
/// One speculatively-echoed character on the current line.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
struct PredictedCell {
|
struct PredictedCell {
|
||||||
@@ -6041,6 +6371,9 @@ struct Predictor {
|
|||||||
/// as vim/htop); we never speculate there because we cannot model arbitrary
|
/// as vim/htop); we never speculate there because we cannot model arbitrary
|
||||||
/// cursor addressing safely.
|
/// cursor addressing safely.
|
||||||
alternate_screen: bool,
|
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
|
/// Predicted cells for the current line, left-to-right starting at the
|
||||||
/// column where the cursor sat when this run of predictions began.
|
/// column where the cursor sat when this run of predictions began.
|
||||||
@@ -6087,6 +6420,7 @@ impl Predictor {
|
|||||||
mode,
|
mode,
|
||||||
enabled: enabled && mode != PredictMode::Off,
|
enabled: enabled && mode != PredictMode::Off,
|
||||||
alternate_screen: false,
|
alternate_screen: false,
|
||||||
|
output_parse_tail: Vec::new(),
|
||||||
cells: Vec::new(),
|
cells: Vec::new(),
|
||||||
cursor: 0,
|
cursor: 0,
|
||||||
epoch: 1,
|
epoch: 1,
|
||||||
@@ -6109,6 +6443,7 @@ impl Predictor {
|
|||||||
self.epoch += 1;
|
self.epoch += 1;
|
||||||
self.confirmed_epoch = self.epoch - 1;
|
self.confirmed_epoch = self.epoch - 1;
|
||||||
self.alternate_screen = false;
|
self.alternate_screen = false;
|
||||||
|
self.output_parse_tail.clear();
|
||||||
self.oldest_pending_at = None;
|
self.oldest_pending_at = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6265,20 +6600,20 @@ impl Predictor {
|
|||||||
/// and confirms outstanding predictions: a fresh frame means the server has
|
/// and confirms outstanding predictions: a fresh frame means the server has
|
||||||
/// re-rendered the line, so our speculative glyphs are superseded and erased.
|
/// re-rendered the line, so our speculative glyphs are superseded and erased.
|
||||||
fn observe_output(&mut self, bytes: &[u8]) {
|
fn observe_output(&mut self, bytes: &[u8]) {
|
||||||
if contains_bytes(bytes, b"\x1b[?1049h")
|
let mut parse = Vec::with_capacity(self.output_parse_tail.len() + bytes.len());
|
||||||
|| contains_bytes(bytes, b"\x1b[?1047h")
|
parse.extend_from_slice(&self.output_parse_tail);
|
||||||
|| contains_bytes(bytes, b"\x1b[?47h")
|
parse.extend_from_slice(bytes);
|
||||||
{
|
|
||||||
self.alternate_screen = true;
|
let before = self.alternate_screen;
|
||||||
let _ = self.discard_all();
|
self.alternate_screen = alternate_screen_after_output(self.alternate_screen, &parse);
|
||||||
}
|
if self.alternate_screen != before {
|
||||||
if contains_bytes(bytes, b"\x1b[?1049l")
|
|
||||||
|| contains_bytes(bytes, b"\x1b[?1047l")
|
|
||||||
|| contains_bytes(bytes, b"\x1b[?47l")
|
|
||||||
{
|
|
||||||
self.alternate_screen = false;
|
|
||||||
let _ = self.discard_all();
|
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
|
/// Sample SRTT from a newly arrived frame and confirm/clear outstanding
|
||||||
@@ -6715,7 +7050,7 @@ async fn send_resize(
|
|||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
*send_seq += 1;
|
*send_seq += 1;
|
||||||
socket.send_to(&packet, addr).await?;
|
let _ = send_terminal_udp(socket, &packet, addr).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6735,7 +7070,7 @@ async fn send_ack(
|
|||||||
b"",
|
b"",
|
||||||
)?;
|
)?;
|
||||||
*send_seq += 1;
|
*send_seq += 1;
|
||||||
socket.send_to(&packet, addr).await?;
|
let _ = send_terminal_udp(socket, &packet, addr).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6750,7 +7085,7 @@ async fn detach_once(socket: &UdpSocket, cred: &CachedCredential, seq: u64) -> R
|
|||||||
CLIENT_TO_SERVER,
|
CLIENT_TO_SERVER,
|
||||||
b"",
|
b"",
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&packet, addr).await?;
|
let _ = send_terminal_udp(socket, &packet, addr).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -7072,10 +7407,13 @@ const TERMINAL_CLEANUP: &[u8] = concat!(
|
|||||||
"\x1b[?1002l",
|
"\x1b[?1002l",
|
||||||
"\x1b[?1001l",
|
"\x1b[?1001l",
|
||||||
"\x1b[?1000l",
|
"\x1b[?1000l",
|
||||||
|
"\x1b[?1004l",
|
||||||
"\x1b[?1015l",
|
"\x1b[?1015l",
|
||||||
"\x1b[?1006l",
|
"\x1b[?1006l",
|
||||||
"\x1b[?1005l",
|
"\x1b[?1005l",
|
||||||
"\x1b[?2004l",
|
"\x1b[?2004l",
|
||||||
|
"\x1b[?47l",
|
||||||
|
"\x1b[?1047l",
|
||||||
"\x1b[?1049l"
|
"\x1b[?1049l"
|
||||||
)
|
)
|
||||||
.as_bytes();
|
.as_bytes();
|
||||||
@@ -7083,11 +7421,12 @@ const TERMINAL_CLEANUP: &[u8] = concat!(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
CachedCredential, DisconnectStatus, DynamicForward, FRAME_GAP_RESYNC_AFTER_MS, FrameBuffer,
|
ALT_SCREEN_IDLE_REPAINT_AFTER, CachedCredential, DisconnectStatus, DynamicForward,
|
||||||
LocalForward, MAX_PENDING_USER_INPUT_BYTES, POST_SUBMIT_ALL_INPUT_HOLD, PendingStreamOpen,
|
FRAME_GAP_RESYNC_AFTER_MS, FrameBuffer, LocalForward, MAX_PENDING_USER_INPUT_BYTES,
|
||||||
PredictMode, Predictor, RESTART_STATUS_SCRIPT, RemoteForward, STARTUP_INPUT_HOLD,
|
POST_SUBMIT_ALL_INPUT_HOLD, PendingStreamOpen, PredictMode, Predictor,
|
||||||
SshConfig, StartupGateMode, StatusAction, auth_allows, cache_key, cache_server_prefix,
|
RESTART_STATUS_SCRIPT, RemoteForward, STARTUP_INPUT_HOLD, SshConfig, StartupGateMode,
|
||||||
clear_cached_credentials, ensure_tui_safe_status_overlay, input_matches_escape,
|
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,
|
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,
|
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,
|
parse_local_forward, parse_remote_forward, parse_ssh_config, post_submit_hold_duration,
|
||||||
@@ -7095,19 +7434,22 @@ mod tests {
|
|||||||
release_tag_download_url, release_tag_from_effective_url, release_version_from_tag,
|
release_tag_download_url, release_tag_from_effective_url, release_version_from_tag,
|
||||||
render_status_clear, render_status_overlay, requested_env, resolved_startup_command,
|
render_status_clear, render_status_overlay, requested_env, resolved_startup_command,
|
||||||
retransmit_stream_opens, rewrite_forward_command, selected_predict_mode, selected_udp_host,
|
retransmit_stream_opens, rewrite_forward_command, selected_predict_mode, selected_udp_host,
|
||||||
server_version_mismatch, should_hold_during_startup_gate, should_hold_post_submit_input,
|
server_version_mismatch, should_flush_terminal_input_after_contact,
|
||||||
split_after_command_submit, ssh_destination_host, ssh_username, ssh_with_user,
|
should_hold_during_startup_gate, should_hold_post_submit_input,
|
||||||
startup_command, status_ssh_target, strip_stale_mouse_reports, toml_bare_key_or_quoted,
|
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,
|
update_check_requested, update_version_status, upsert_managed_block, valid_forward_host,
|
||||||
vscode_safe_alias,
|
vscode_safe_alias,
|
||||||
};
|
};
|
||||||
use dosh::config::{ClientConfig, CommandExtension, HostConfig};
|
use dosh::config::{ClientConfig, CommandExtension, HostConfig};
|
||||||
use dosh::native::EnvVar;
|
use dosh::native::EnvVar;
|
||||||
use dosh::protocol::{self, Frame, PacketKind};
|
use dosh::protocol::{self, Frame, PacketKind};
|
||||||
|
use dosh::udp::is_transient_udp_send_error;
|
||||||
use ed25519_dalek::{SigningKey, VerifyingKey};
|
use ed25519_dalek::{SigningKey, VerifyingKey};
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
fn test_args(server: &str, command: &[&str]) -> super::Args {
|
fn test_args(server: &str, command: &[&str]) -> super::Args {
|
||||||
super::Args {
|
super::Args {
|
||||||
@@ -7617,6 +7959,61 @@ mod tests {
|
|||||||
assert!(!predictor.alternate_screen);
|
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
|
/// Typing printable characters builds an in-order predicted line and the
|
||||||
/// local cursor tracks the end of it.
|
/// local cursor tracks the end of it.
|
||||||
#[test]
|
#[test]
|
||||||
@@ -7879,6 +8276,34 @@ mod tests {
|
|||||||
assert_eq!(post_submit_hold_duration(b"x"), POST_SUBMIT_ALL_INPUT_HOLD);
|
assert_eq!(post_submit_hold_duration(b"x"), POST_SUBMIT_ALL_INPUT_HOLD);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn contact_flushes_pending_terminal_input_for_interactive_sessions() {
|
||||||
|
assert!(should_flush_terminal_input_after_contact(
|
||||||
|
false, "normal", false
|
||||||
|
));
|
||||||
|
assert!(should_flush_terminal_input_after_contact(
|
||||||
|
false,
|
||||||
|
"read-write",
|
||||||
|
false
|
||||||
|
));
|
||||||
|
assert!(!should_flush_terminal_input_after_contact(
|
||||||
|
false, "normal", true
|
||||||
|
));
|
||||||
|
assert!(!should_flush_terminal_input_after_contact(
|
||||||
|
true, "normal", false
|
||||||
|
));
|
||||||
|
assert!(!should_flush_terminal_input_after_contact(
|
||||||
|
false,
|
||||||
|
"view-only",
|
||||||
|
false
|
||||||
|
));
|
||||||
|
assert!(!should_flush_terminal_input_after_contact(
|
||||||
|
false,
|
||||||
|
"forward-only",
|
||||||
|
false
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn reconnect_refreshes_live_send_address_from_credentials() {
|
fn reconnect_refreshes_live_send_address_from_credentials() {
|
||||||
let mut addr = "127.0.0.1:50000".parse().unwrap();
|
let mut addr = "127.0.0.1:50000".parse().unwrap();
|
||||||
@@ -8301,6 +8726,41 @@ mod tests {
|
|||||||
assert_eq!(pending_bytes, MAX_PENDING_USER_INPUT_BYTES);
|
assert_eq!(pending_bytes, MAX_PENDING_USER_INPUT_BYTES);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transient_udp_send_errors_are_not_terminal_fatal() {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(libc::ENETUNREACH)
|
||||||
|
));
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(libc::EHOSTUNREACH)
|
||||||
|
));
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(libc::EADDRNOTAVAIL)
|
||||||
|
));
|
||||||
|
assert!(!is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(libc::EINVAL)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(10051)
|
||||||
|
)); // WSAENETUNREACH
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(10065)
|
||||||
|
)); // WSAEHOSTUNREACH
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(10049)
|
||||||
|
)); // WSAEADDRNOTAVAIL
|
||||||
|
assert!(!is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(10022)
|
||||||
|
)); // WSAEINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn stale_mouse_reports_are_stripped_from_pending_input() {
|
fn stale_mouse_reports_are_stripped_from_pending_input() {
|
||||||
let input = b"\x1b[<35;152;1Mhello\x1b[<0;107;10m";
|
let input = b"\x1b[<35;152;1Mhello\x1b[<0;107;10m";
|
||||||
@@ -8314,6 +8774,70 @@ mod tests {
|
|||||||
assert_eq!(strip_stale_mouse_reports(b"152;1Mls\r"), b"ls\r");
|
assert_eq!(strip_stale_mouse_reports(b"152;1Mls\r"), b"ls\r");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn split_stale_mouse_suffixes_are_stripped_from_pending_input() {
|
||||||
|
assert_eq!(strip_stale_mouse_reports(b"1M35;149;1Mls\r"), b"ls\r");
|
||||||
|
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]
|
#[test]
|
||||||
fn non_mouse_escape_input_survives_stale_filter() {
|
fn non_mouse_escape_input_survives_stale_filter() {
|
||||||
assert_eq!(strip_stale_mouse_reports(b"\x1b[A"), b"\x1b[A");
|
assert_eq!(strip_stale_mouse_reports(b"\x1b[A"), b"\x1b[A");
|
||||||
|
|||||||
+206
-47
@@ -28,6 +28,7 @@ use dosh::protocol::{
|
|||||||
TicketAttachBody, TicketAttachEnvelope, TicketAttachOkEnvelope,
|
TicketAttachBody, TicketAttachEnvelope, TicketAttachOkEnvelope,
|
||||||
};
|
};
|
||||||
use dosh::pty::{PtyHandle, PtyOutput, adopt_pty_from_fd, spawn_pty_session};
|
use dosh::pty::{PtyHandle, PtyOutput, adopt_pty_from_fd, spawn_pty_session};
|
||||||
|
use dosh::udp::is_transient_udp_send_error;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -51,6 +52,7 @@ const STREAM_INITIAL_WINDOW: usize = 1024 * 1024;
|
|||||||
/// have accumulated since the last mirror. Keeps the atomic write off the
|
/// 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.
|
/// per-packet hot path while bounding how much fresh output a crash can lose.
|
||||||
const SCREEN_PERSIST_BYTES: usize = 4096;
|
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`
|
/// 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
|
/// that carries an SSH-agent connection (the client splices it into its local
|
||||||
@@ -432,6 +434,7 @@ struct PendingStreamOpen {
|
|||||||
attempts: u32,
|
attempts: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
struct PendingNativeAuth {
|
struct PendingNativeAuth {
|
||||||
client: dosh::native::NativeClientHello,
|
client: dosh::native::NativeClientHello,
|
||||||
server: NativeServerHello,
|
server: NativeServerHello,
|
||||||
@@ -510,15 +513,16 @@ impl ServerState {
|
|||||||
Ok(())
|
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
|
/// With persistence enabled, every interactive session gets a detached holder
|
||||||
/// holder. Implicit `term-<millis>-<pid>` sessions are one-off terminals
|
/// so an update/restart of `dosh-server` behaves like a transient network
|
||||||
/// created by `dosh host`; users cannot intentionally reattach to them by
|
/// break. Named sessions can sit empty for the normal client timeout.
|
||||||
/// name, so persisting them only leaves stale holders that can be
|
/// Generated one-off sessions are also persisted, but cleanup gives them a
|
||||||
/// accidentally re-adopted after restarts.
|
/// shorter empty grace period so invisible abandoned holders do not linger
|
||||||
fn should_persist_session(&self, name: &str) -> bool {
|
/// indefinitely.
|
||||||
self.config.persist_sessions && !protocol::is_implicit_session_name(name)
|
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.
|
/// Spawn (or, in the persistent case, spawn-and-adopt) a PTY for a session.
|
||||||
@@ -606,20 +610,6 @@ impl ServerState {
|
|||||||
if self.sessions.contains_key(&name) {
|
if self.sessions.contains_key(&name) {
|
||||||
continue;
|
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) {
|
let (pty, control) = match self.adopt_persistent_pty(&name) {
|
||||||
Ok(pair) => pair,
|
Ok(pair) => pair,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@@ -669,6 +659,7 @@ impl ServerState {
|
|||||||
fn insert_client(&mut self, session_name: &str, client_id: [u8; 16], client: ClientState) {
|
fn insert_client(&mut self, session_name: &str, client_id: [u8; 16], client: ClientState) {
|
||||||
if let Some(session) = self.sessions.get_mut(session_name) {
|
if let Some(session) = self.sessions.get_mut(session_name) {
|
||||||
session.clients.insert(client_id, client);
|
session.clients.insert(client_id, client);
|
||||||
|
session.empty_since = None;
|
||||||
self.client_index
|
self.client_index
|
||||||
.insert(client_id, session_name.to_string());
|
.insert(client_id, session_name.to_string());
|
||||||
}
|
}
|
||||||
@@ -863,6 +854,7 @@ async fn handle_packet(
|
|||||||
| PacketKind::StreamEof
|
| PacketKind::StreamEof
|
||||||
| PacketKind::StreamWindowAdjust
|
| PacketKind::StreamWindowAdjust
|
||||||
| PacketKind::RekeyAck
|
| PacketKind::RekeyAck
|
||||||
|
| PacketKind::Detach
|
||||||
if find_client_decrypt_key(state, &packet.header).is_err() =>
|
if find_client_decrypt_key(state, &packet.header).is_err() =>
|
||||||
{
|
{
|
||||||
send_reject_to_client(socket, peer, packet.header.conn_id, "unknown client").await
|
send_reject_to_client(socket, peer, packet.header.conn_id, "unknown client").await
|
||||||
@@ -980,7 +972,7 @@ async fn handle_native_client_hello(
|
|||||||
};
|
};
|
||||||
let body = protocol::to_body(&NativeServerHelloBody { hello })?;
|
let body = protocol::to_body(&NativeServerHelloBody { hello })?;
|
||||||
let out = protocol::encode_plain(PacketKind::NativeServerHello, pending_id, 1, 0, &body)?;
|
let out = protocol::encode_plain(PacketKind::NativeServerHello, pending_id, 1, 0, &body)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -991,8 +983,8 @@ async fn handle_native_user_auth(
|
|||||||
packet: &protocol::Packet,
|
packet: &protocol::Packet,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let pending = {
|
let pending = {
|
||||||
let mut locked = state.lock().expect("server state poisoned");
|
let locked = state.lock().expect("server state poisoned");
|
||||||
locked.pending_native.remove(&packet.header.conn_id)
|
locked.pending_native.get(&packet.header.conn_id).cloned()
|
||||||
};
|
};
|
||||||
let Some(pending) = pending else {
|
let Some(pending) = pending else {
|
||||||
return send_reject_to_client(socket, peer, packet.header.conn_id, "unknown native auth")
|
return send_reject_to_client(socket, peer, packet.header.conn_id, "unknown native auth")
|
||||||
@@ -1008,11 +1000,38 @@ async fn handle_native_user_auth(
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
if pending.created_at.elapsed() > Duration::from_secs(30) {
|
if pending.created_at.elapsed() > Duration::from_secs(30) {
|
||||||
|
state
|
||||||
|
.lock()
|
||||||
|
.expect("server state poisoned")
|
||||||
|
.pending_native
|
||||||
|
.remove(&packet.header.conn_id);
|
||||||
return send_reject_to_client(socket, peer, packet.header.conn_id, "native auth expired")
|
return send_reject_to_client(socket, peer, packet.header.conn_id, "native auth expired")
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
let body = protocol::decrypt_body(packet, &pending.session_key, CLIENT_TO_SERVER)?;
|
let body = match protocol::decrypt_body(packet, &pending.session_key, CLIENT_TO_SERVER) {
|
||||||
let req: NativeUserAuthBody = protocol::from_body(&body)?;
|
Ok(body) => body,
|
||||||
|
Err(_) => {
|
||||||
|
return send_reject_to_client(
|
||||||
|
socket,
|
||||||
|
peer,
|
||||||
|
packet.header.conn_id,
|
||||||
|
"native auth decrypt failed",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let req: NativeUserAuthBody = match protocol::from_body(&body) {
|
||||||
|
Ok(req) => req,
|
||||||
|
Err(_) => {
|
||||||
|
return send_reject_to_client(
|
||||||
|
socket,
|
||||||
|
peer,
|
||||||
|
packet.header.conn_id,
|
||||||
|
"invalid native auth body",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
};
|
||||||
if pending.client.requested_mode == "doctor" {
|
if pending.client.requested_mode == "doctor" {
|
||||||
let check_result = {
|
let check_result = {
|
||||||
let locked = state.lock().expect("server state poisoned");
|
let locked = state.lock().expect("server state poisoned");
|
||||||
@@ -1048,6 +1067,11 @@ async fn handle_native_user_auth(
|
|||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
state
|
||||||
|
.lock()
|
||||||
|
.expect("server state poisoned")
|
||||||
|
.pending_native
|
||||||
|
.remove(&packet.header.conn_id);
|
||||||
let body = protocol::to_body(&check)?;
|
let body = protocol::to_body(&check)?;
|
||||||
let out = protocol::encode_encrypted(
|
let out = protocol::encode_encrypted(
|
||||||
PacketKind::NativeAuthCheckOk,
|
PacketKind::NativeAuthCheckOk,
|
||||||
@@ -1058,7 +1082,7 @@ async fn handle_native_user_auth(
|
|||||||
SERVER_TO_CLIENT,
|
SERVER_TO_CLIENT,
|
||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1228,6 +1252,11 @@ async fn handle_native_user_auth(
|
|||||||
if let Some((listener, path)) = agent_listener {
|
if let Some((listener, path)) = agent_listener {
|
||||||
spawn_agent_forward(state, socket, client_id, listener, path);
|
spawn_agent_forward(state, socket, client_id, listener, path);
|
||||||
}
|
}
|
||||||
|
state
|
||||||
|
.lock()
|
||||||
|
.expect("server state poisoned")
|
||||||
|
.pending_native
|
||||||
|
.remove(&packet.header.conn_id);
|
||||||
|
|
||||||
let ok = NativeAuthOk {
|
let ok = NativeAuthOk {
|
||||||
client_id,
|
client_id,
|
||||||
@@ -1251,7 +1280,7 @@ async fn handle_native_user_auth(
|
|||||||
SERVER_TO_CLIENT,
|
SERVER_TO_CLIENT,
|
||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1359,7 +1388,7 @@ async fn handle_bootstrap_attach(
|
|||||||
SERVER_TO_CLIENT,
|
SERVER_TO_CLIENT,
|
||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1494,7 +1523,7 @@ async fn handle_ticket_attach(
|
|||||||
};
|
};
|
||||||
let body = protocol::to_body(&envelope)?;
|
let body = protocol::to_body(&envelope)?;
|
||||||
let out = protocol::encode_plain(PacketKind::AttachOk, client_id, 1, 0, &body)?;
|
let out = protocol::encode_plain(PacketKind::AttachOk, client_id, 1, 0, &body)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1512,7 +1541,7 @@ async fn send_reject_to_client(
|
|||||||
reason: reason.to_string(),
|
reason: reason.to_string(),
|
||||||
})?;
|
})?;
|
||||||
let out = protocol::encode_plain(PacketKind::AttachReject, client_id, 0, 0, &body)?;
|
let out = protocol::encode_plain(PacketKind::AttachReject, client_id, 0, 0, &body)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1578,7 +1607,7 @@ async fn handle_resume(
|
|||||||
SERVER_TO_CLIENT,
|
SERVER_TO_CLIENT,
|
||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1690,12 +1719,19 @@ async fn handle_ping(
|
|||||||
SERVER_TO_CLIENT,
|
SERVER_TO_CLIENT,
|
||||||
b"",
|
b"",
|
||||||
)?;
|
)?;
|
||||||
socket.send_to(&out, peer).await?;
|
let _ = send_udp(socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_detach(state: &Arc<Mutex<ServerState>>, packet: &protocol::Packet) -> Result<()> {
|
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");
|
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);
|
locked.remove_client_everywhere(&packet.header.conn_id);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -1705,6 +1741,14 @@ fn remove_client(state: &Arc<Mutex<ServerState>>, client_id: [u8; 16]) {
|
|||||||
locked.remove_client_everywhere(&client_id);
|
locked.remove_client_everywhere(&client_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn send_udp(socket: &UdpSocket, packet: &[u8], peer: SocketAddr) -> Result<bool> {
|
||||||
|
match socket.send_to(packet, peer).await {
|
||||||
|
Ok(_) => Ok(true),
|
||||||
|
Err(err) if is_transient_udp_send_error(&err) => Ok(false),
|
||||||
|
Err(err) => Err(err).with_context(|| format!("send UDP packet to {peer}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn handle_ack(
|
async fn handle_ack(
|
||||||
state: &Arc<Mutex<ServerState>>,
|
state: &Arc<Mutex<ServerState>>,
|
||||||
peer: SocketAddr,
|
peer: SocketAddr,
|
||||||
@@ -2623,10 +2667,13 @@ async fn handle_file_request(
|
|||||||
let (file, temp_path, written, atomic) = if resume && final_path.exists() {
|
let (file, temp_path, written, atomic) = if resume && final_path.exists() {
|
||||||
let mut file = fs::OpenOptions::new()
|
let mut file = fs::OpenOptions::new()
|
||||||
.read(true)
|
.read(true)
|
||||||
|
.write(true)
|
||||||
.append(true)
|
.append(true)
|
||||||
.open(&final_path)
|
.open(&final_path)
|
||||||
.with_context(|| format!("open {}", final_path.display()))?;
|
.with_context(|| format!("open {}", final_path.display()))?;
|
||||||
let written = file.metadata()?.len().min(size);
|
let written = file.metadata()?.len().min(size);
|
||||||
|
file.set_len(written)
|
||||||
|
.with_context(|| format!("truncate {}", final_path.display()))?;
|
||||||
if written > 0 {
|
if written > 0 {
|
||||||
let mut prefix = fs::File::open(&final_path)?;
|
let mut prefix = fs::File::open(&final_path)?;
|
||||||
hash_exact_prefix(&mut prefix, written, &mut hasher)?;
|
hash_exact_prefix(&mut prefix, written, &mut hasher)?;
|
||||||
@@ -3020,7 +3067,7 @@ async fn send_stream_open_to_client(
|
|||||||
found
|
found
|
||||||
};
|
};
|
||||||
if let Some((endpoint, packet)) = send {
|
if let Some((endpoint, packet)) = send {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3114,7 +3161,7 @@ async fn queue_or_send_stream_data_to_client(
|
|||||||
send
|
send
|
||||||
};
|
};
|
||||||
if let Some((endpoint, packet)) = send {
|
if let Some((endpoint, packet)) = send {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3189,7 +3236,7 @@ async fn flush_stream_pending_data_to_client(
|
|||||||
let Some((endpoint, packet)) = send else {
|
let Some((endpoint, packet)) = send else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3333,7 +3380,7 @@ async fn send_stream_packet_to_client(
|
|||||||
found
|
found
|
||||||
};
|
};
|
||||||
if let Some((endpoint, packet)) = send {
|
if let Some((endpoint, packet)) = send {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3435,7 +3482,7 @@ async fn broadcast_output(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (endpoint, packet) in sends {
|
for (endpoint, packet) in sends {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3488,7 +3535,7 @@ async fn broadcast_session_exit(
|
|||||||
persist::remove_runtime_dir(&sessions_dir, &session_name);
|
persist::remove_runtime_dir(&sessions_dir, &session_name);
|
||||||
}
|
}
|
||||||
for (endpoint, packet) in sends {
|
for (endpoint, packet) in sends {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3595,7 +3642,7 @@ async fn retransmit_pending(
|
|||||||
sends
|
sends
|
||||||
};
|
};
|
||||||
for (endpoint, packet) in sends {
|
for (endpoint, packet) in sends {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3691,7 +3738,7 @@ async fn maybe_rekey_clients(
|
|||||||
sends
|
sends
|
||||||
};
|
};
|
||||||
for (endpoint, packet) in sends {
|
for (endpoint, packet) in sends {
|
||||||
socket.send_to(&packet, endpoint).await?;
|
let _ = send_udp(socket, &packet, endpoint).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -3787,9 +3834,9 @@ fn cleanup_disconnected_clients(state: &Arc<Mutex<ServerState>>) {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|(name, session)| {
|
.filter(|(name, session)| {
|
||||||
!prewarm.contains(name.as_str())
|
!prewarm.contains(name.as_str())
|
||||||
&& session
|
&& session.empty_since.is_some_and(|since| {
|
||||||
.empty_since
|
now.duration_since(since) >= empty_session_timeout(name, timeout)
|
||||||
.is_some_and(|since| now.duration_since(since) >= timeout)
|
})
|
||||||
})
|
})
|
||||||
.map(|(name, _)| name.clone())
|
.map(|(name, _)| name.clone())
|
||||||
.collect();
|
.collect();
|
||||||
@@ -3808,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
|
/// 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
|
/// 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
|
/// during the grace window still decrypts while an expired/stale epoch is
|
||||||
@@ -3854,7 +3909,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn persists_named_sessions_when_enabled() {
|
fn persists_terminal_sessions_when_enabled() {
|
||||||
let (pty_tx, _rx) = mpsc::unbounded_channel();
|
let (pty_tx, _rx) = mpsc::unbounded_channel();
|
||||||
let config = ServerConfig {
|
let config = ServerConfig {
|
||||||
persist_sessions: true,
|
persist_sessions: true,
|
||||||
@@ -3864,7 +3919,7 @@ mod tests {
|
|||||||
let state = ServerState::new(config, [0u8; 32], pty_tx);
|
let state = ServerState::new(config, [0u8; 32], pty_tx);
|
||||||
assert!(state.should_persist_session("default")); // prewarmed
|
assert!(state.should_persist_session("default")); // prewarmed
|
||||||
assert!(state.should_persist_session("work")); // explicitly named
|
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]
|
#[test]
|
||||||
@@ -4019,6 +4074,12 @@ mod tests {
|
|||||||
Some((key, "work".to_string()))
|
Some((key, "work".to_string()))
|
||||||
);
|
);
|
||||||
assert!(state.client_mut(&client_id).is_some());
|
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.
|
// Removing purges both the session map and the index.
|
||||||
assert!(state.remove_client_everywhere(&client_id));
|
assert!(state.remove_client_everywhere(&client_id));
|
||||||
@@ -4058,6 +4119,83 @@ mod tests {
|
|||||||
assert!(locked.lookup_client(&client_id).is_none());
|
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]
|
#[tokio::test]
|
||||||
async fn duplicate_stream_open_for_open_stream_resends_ok() {
|
async fn duplicate_stream_open_for_open_stream_resends_ok() {
|
||||||
let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
|
let (pty_tx, _pty_rx) = mpsc::unbounded_channel();
|
||||||
@@ -4536,4 +4674,25 @@ mod tests {
|
|||||||
};
|
};
|
||||||
remote_bind_allowed(&config, "0.0.0.0").unwrap();
|
remote_bind_allowed(&config, "0.0.0.0").unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn server_udp_send_classifier_treats_network_roaming_errors_as_transient() {
|
||||||
|
for code in [
|
||||||
|
libc::EADDRNOTAVAIL,
|
||||||
|
libc::ECONNREFUSED,
|
||||||
|
libc::ECONNRESET,
|
||||||
|
libc::EHOSTDOWN,
|
||||||
|
libc::EHOSTUNREACH,
|
||||||
|
libc::ENETDOWN,
|
||||||
|
libc::ENETRESET,
|
||||||
|
libc::ENETUNREACH,
|
||||||
|
libc::ETIMEDOUT,
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
is_transient_udp_send_error(&std::io::Error::from_raw_os_error(code)),
|
||||||
|
"expected errno {code} to be transient"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,3 +23,4 @@ pub mod pty;
|
|||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod ssh_agent;
|
pub mod ssh_agent;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
|
pub mod udp;
|
||||||
|
|||||||
+1
-1
@@ -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>> {
|
pub fn decrypt_body(packet: &Packet, key: &[u8; 32], direction: u32) -> Result<Vec<u8>> {
|
||||||
if packet.header.flags & 1 == 0 {
|
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 nonce = crypto::nonce_from(direction, packet.header.seq);
|
||||||
let aad = packet.header.aad();
|
let aad = packet.header.aad();
|
||||||
|
|||||||
+120
-6
@@ -13,6 +13,7 @@ use crate::transport::{
|
|||||||
DoshTransport, SessionEvent, SessionRole, SessionTransportConfig, TransportConfig,
|
DoshTransport, SessionEvent, SessionRole, SessionTransportConfig, TransportConfig,
|
||||||
service_name_from_target,
|
service_name_from_target,
|
||||||
};
|
};
|
||||||
|
use crate::udp::is_transient_udp_send_error;
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
use ed25519_dalek::SigningKey;
|
use ed25519_dalek::SigningKey;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
@@ -97,6 +98,7 @@ pub enum DoshServerEvent {
|
|||||||
Ignored,
|
Ignored,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
struct PendingServerAuth {
|
struct PendingServerAuth {
|
||||||
client: native::NativeClientHello,
|
client: native::NativeClientHello,
|
||||||
server: NativeServerHello,
|
server: NativeServerHello,
|
||||||
@@ -255,7 +257,7 @@ impl DoshServer {
|
|||||||
};
|
};
|
||||||
let body = protocol::to_body(&NativeServerHelloBody { hello })?;
|
let body = protocol::to_body(&NativeServerHelloBody { hello })?;
|
||||||
let out = protocol::encode_plain(PacketKind::NativeServerHello, pending_id, 1, 0, &body)?;
|
let out = protocol::encode_plain(PacketKind::NativeServerHello, pending_id, 1, 0, &body)?;
|
||||||
self.socket.send_to(&out, peer).await?;
|
let _ = send_udp(&self.socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -327,7 +329,7 @@ impl DoshServer {
|
|||||||
peer: SocketAddr,
|
peer: SocketAddr,
|
||||||
packet: &protocol::Packet,
|
packet: &protocol::Packet,
|
||||||
) -> Result<DoshServerEvent> {
|
) -> Result<DoshServerEvent> {
|
||||||
let Some(pending) = self.pending.remove(&packet.header.conn_id) else {
|
let Some(pending) = self.pending.get(&packet.header.conn_id).cloned() else {
|
||||||
self.send_reject(peer, packet.header.conn_id, "unknown native auth")
|
self.send_reject(peer, packet.header.conn_id, "unknown native auth")
|
||||||
.await?;
|
.await?;
|
||||||
return Ok(DoshServerEvent::Ignored);
|
return Ok(DoshServerEvent::Ignored);
|
||||||
@@ -338,13 +340,28 @@ impl DoshServer {
|
|||||||
return Ok(DoshServerEvent::Ignored);
|
return Ok(DoshServerEvent::Ignored);
|
||||||
}
|
}
|
||||||
if pending.created_at.elapsed() > self.config.auth_timeout {
|
if pending.created_at.elapsed() > self.config.auth_timeout {
|
||||||
|
self.pending.remove(&packet.header.conn_id);
|
||||||
self.send_reject(peer, packet.header.conn_id, "native auth expired")
|
self.send_reject(peer, packet.header.conn_id, "native auth expired")
|
||||||
.await?;
|
.await?;
|
||||||
return Ok(DoshServerEvent::Ignored);
|
return Ok(DoshServerEvent::Ignored);
|
||||||
}
|
}
|
||||||
|
|
||||||
let body = protocol::decrypt_body(packet, &pending.session_key, CLIENT_TO_SERVER)?;
|
let body = match protocol::decrypt_body(packet, &pending.session_key, CLIENT_TO_SERVER) {
|
||||||
let req: NativeUserAuthBody = protocol::from_body(&body)?;
|
Ok(body) => body,
|
||||||
|
Err(_) => {
|
||||||
|
self.send_reject(peer, packet.header.conn_id, "native auth decrypt failed")
|
||||||
|
.await?;
|
||||||
|
return Ok(DoshServerEvent::Ignored);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let req: NativeUserAuthBody = match protocol::from_body(&body) {
|
||||||
|
Ok(req) => req,
|
||||||
|
Err(_) => {
|
||||||
|
self.send_reject(peer, packet.header.conn_id, "invalid native auth body")
|
||||||
|
.await?;
|
||||||
|
return Ok(DoshServerEvent::Ignored);
|
||||||
|
}
|
||||||
|
};
|
||||||
let services = match self.verify_auth_and_services(&pending, &req.auth) {
|
let services = match self.verify_auth_and_services(&pending, &req.auth) {
|
||||||
Ok(services) => services,
|
Ok(services) => services,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@@ -353,6 +370,7 @@ impl DoshServer {
|
|||||||
return Ok(DoshServerEvent::Ignored);
|
return Ok(DoshServerEvent::Ignored);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
self.pending.remove(&packet.header.conn_id);
|
||||||
|
|
||||||
let conn_id = crypto::random_16();
|
let conn_id = crypto::random_16();
|
||||||
let key_id = protocol::session_key_id(&pending.session_key);
|
let key_id = protocol::session_key_id(&pending.session_key);
|
||||||
@@ -381,7 +399,7 @@ impl DoshServer {
|
|||||||
SERVER_TO_CLIENT,
|
SERVER_TO_CLIENT,
|
||||||
&body,
|
&body,
|
||||||
)?;
|
)?;
|
||||||
self.socket.send_to(&out, peer).await?;
|
let _ = send_udp(&self.socket, &out, peer).await?;
|
||||||
|
|
||||||
let transport = DoshTransport::new(
|
let transport = DoshTransport::new(
|
||||||
Arc::clone(&self.socket),
|
Arc::clone(&self.socket),
|
||||||
@@ -428,7 +446,7 @@ impl DoshServer {
|
|||||||
reason: reason.to_string(),
|
reason: reason.to_string(),
|
||||||
})?;
|
})?;
|
||||||
let out = protocol::encode_plain(PacketKind::AttachReject, conn_id, 0, 0, &body)?;
|
let out = protocol::encode_plain(PacketKind::AttachReject, conn_id, 0, 0, &body)?;
|
||||||
self.socket.send_to(&out, peer).await?;
|
let _ = send_udp(&self.socket, &out, peer).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,6 +457,14 @@ impl DoshServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn send_udp(socket: &UdpSocket, packet: &[u8], peer: SocketAddr) -> Result<bool> {
|
||||||
|
match socket.send_to(packet, peer).await {
|
||||||
|
Ok(_) => Ok(true),
|
||||||
|
Err(err) if is_transient_udp_send_error(&err) => Ok(false),
|
||||||
|
Err(err) => Err(err).with_context(|| format!("send UDP packet to {peer}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_requested_services(
|
fn validate_requested_services(
|
||||||
allowed_services: &HashSet<String>,
|
allowed_services: &HashSet<String>,
|
||||||
requests: &[ForwardingRequest],
|
requests: &[ForwardingRequest],
|
||||||
@@ -477,6 +503,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::client::DoshClient;
|
use crate::client::DoshClient;
|
||||||
use crate::config::{ClientConfig, HostsConfig};
|
use crate::config::{ClientConfig, HostsConfig};
|
||||||
|
use crate::protocol::{CLIENT_TO_SERVER, NativeUserAuthBody};
|
||||||
use crate::transport::TransportEvent;
|
use crate::transport::TransportEvent;
|
||||||
use ed25519_dalek::SigningKey;
|
use ed25519_dalek::SigningKey;
|
||||||
|
|
||||||
@@ -588,4 +615,91 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bad_native_auth_does_not_consume_pending_challenge() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let host_key = dir.path().join("host_key");
|
||||||
|
let authorized_keys = dir.path().join("authorized_keys");
|
||||||
|
let signing = SigningKey::from_bytes(&[93u8; 32]);
|
||||||
|
let keypair = ssh_key::private::Ed25519Keypair::from(&signing);
|
||||||
|
let private =
|
||||||
|
ssh_key::PrivateKey::new(ssh_key::private::KeypairData::from(keypair), "").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
&authorized_keys,
|
||||||
|
format!("{}\n", private.public_key().to_openssh().unwrap()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let server_config = ServerConfig {
|
||||||
|
host_key: host_key.to_string_lossy().to_string(),
|
||||||
|
authorized_keys: vec![authorized_keys.to_string_lossy().to_string()],
|
||||||
|
..ServerConfig::default()
|
||||||
|
};
|
||||||
|
let server_config = DoshServerConfig::new(server_config)
|
||||||
|
.bind_addr("127.0.0.1:0".parse().unwrap())
|
||||||
|
.require_current_user(false);
|
||||||
|
let mut server = DoshServer::bind(server_config).await.unwrap();
|
||||||
|
let peer: SocketAddr = "127.0.0.1:9".parse().unwrap();
|
||||||
|
let (client_secret, client_public) = native::generate_native_ephemeral();
|
||||||
|
let hello = native::NativeClientHello {
|
||||||
|
protocol_version: native::NATIVE_PROTOCOL_VERSION,
|
||||||
|
client_random: crypto::random_32(),
|
||||||
|
client_ephemeral_public: client_public,
|
||||||
|
requested_host: "127.0.0.1".to_string(),
|
||||||
|
requested_user: "sdk-user".to_string(),
|
||||||
|
requested_session: "test".to_string(),
|
||||||
|
requested_mode: "forward-only".to_string(),
|
||||||
|
terminal_size: (80, 24),
|
||||||
|
supported_aead: vec!["chacha20poly1305".to_string()],
|
||||||
|
supported_user_key_algorithms: vec!["ssh-ed25519".to_string()],
|
||||||
|
cached_host_key_fingerprint: None,
|
||||||
|
attach_ticket_envelope: None,
|
||||||
|
requested_env: Vec::new(),
|
||||||
|
};
|
||||||
|
let (pending_id, server_hello) = server.build_server_hello(hello.clone(), peer).unwrap();
|
||||||
|
let session_key = native::derive_native_session_key(
|
||||||
|
&client_secret,
|
||||||
|
server_hello.server_ephemeral_public,
|
||||||
|
&hello,
|
||||||
|
&server_hello,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let auth = native::sign_user_auth(&signing, &hello, &server_hello, Vec::new()).unwrap();
|
||||||
|
let body = protocol::to_body(&NativeUserAuthBody { auth }).unwrap();
|
||||||
|
let bad = protocol::encode_encrypted(
|
||||||
|
PacketKind::NativeUserAuth,
|
||||||
|
pending_id,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
&[7u8; 32],
|
||||||
|
CLIENT_TO_SERVER,
|
||||||
|
&body,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let bad = protocol::decode(&bad).unwrap();
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
server.handle_user_auth(peer, &bad).await.unwrap(),
|
||||||
|
DoshServerEvent::Ignored
|
||||||
|
));
|
||||||
|
assert!(server.pending.contains_key(&pending_id));
|
||||||
|
|
||||||
|
let valid = protocol::encode_encrypted(
|
||||||
|
PacketKind::NativeUserAuth,
|
||||||
|
pending_id,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
&session_key,
|
||||||
|
CLIENT_TO_SERVER,
|
||||||
|
&body,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let valid = protocol::decode(&valid).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
server.handle_user_auth(peer, &valid).await.unwrap(),
|
||||||
|
DoshServerEvent::Accepted(_)
|
||||||
|
));
|
||||||
|
assert!(!server.pending.contains_key(&pending_id));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+114
-10
@@ -19,6 +19,7 @@ use crate::protocol::{
|
|||||||
self, CLIENT_TO_SERVER, PacketKind, ReplayWindow, SERVER_TO_CLIENT, StreamClose, StreamData,
|
self, CLIENT_TO_SERVER, PacketKind, ReplayWindow, SERVER_TO_CLIENT, StreamClose, StreamData,
|
||||||
StreamOpen, StreamOpenOk, StreamOpenReject, StreamWindowAdjust,
|
StreamOpen, StreamOpenOk, StreamOpenReject, StreamWindowAdjust,
|
||||||
};
|
};
|
||||||
|
use crate::udp::is_transient_udp_send_error;
|
||||||
use anyhow::{Result, anyhow, bail};
|
use anyhow::{Result, anyhow, bail};
|
||||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
@@ -348,8 +349,8 @@ impl StreamMux {
|
|||||||
&mut self,
|
&mut self,
|
||||||
adjust: StreamWindowAdjust,
|
adjust: StreamWindowAdjust,
|
||||||
) -> Result<Vec<OutgoingStreamPacket>> {
|
) -> Result<Vec<OutgoingStreamPacket>> {
|
||||||
self.ack_data(adjust.stream_id, adjust.received_offset);
|
let acked_bytes = self.ack_data(adjust.stream_id, adjust.received_offset);
|
||||||
self.add_credit(adjust.stream_id, adjust.bytes as usize);
|
self.add_credit(adjust.stream_id, acked_bytes);
|
||||||
self.flush_pending_data(adjust.stream_id)
|
self.flush_pending_data(adjust.stream_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -556,9 +557,9 @@ impl StreamMux {
|
|||||||
(chunks, consumed, *expected)
|
(chunks, consumed, *expected)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ack_data(&mut self, stream_id: u64, received_offset: u64) {
|
fn ack_data(&mut self, stream_id: u64, received_offset: u64) -> usize {
|
||||||
let Some(sent) = self.sent_data.get_mut(&stream_id) else {
|
let Some(sent) = self.sent_data.get_mut(&stream_id) else {
|
||||||
return;
|
return 0;
|
||||||
};
|
};
|
||||||
let acked_offsets = sent
|
let acked_offsets = sent
|
||||||
.iter()
|
.iter()
|
||||||
@@ -567,12 +568,16 @@ impl StreamMux {
|
|||||||
(end <= received_offset).then_some(*offset)
|
(end <= received_offset).then_some(*offset)
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
let mut acked_bytes = 0usize;
|
||||||
for offset in acked_offsets {
|
for offset in acked_offsets {
|
||||||
sent.remove(&offset);
|
if let Some(chunk) = sent.remove(&offset) {
|
||||||
|
acked_bytes = acked_bytes.saturating_add(chunk.bytes.len());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if sent.is_empty() {
|
if sent.is_empty() {
|
||||||
self.sent_data.remove(&stream_id);
|
self.sent_data.remove(&stream_id);
|
||||||
}
|
}
|
||||||
|
acked_bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_credit(&mut self, stream_id: u64, bytes: usize) {
|
fn add_credit(&mut self, stream_id: u64, bytes: usize) {
|
||||||
@@ -732,11 +737,17 @@ impl DoshTransport {
|
|||||||
if packet.header.conn_id != self.conn_id {
|
if packet.header.conn_id != self.conn_id {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let plain = match protocol::decrypt_body(
|
||||||
|
&packet,
|
||||||
|
&self.session_key,
|
||||||
|
self.role.recv_direction(),
|
||||||
|
) {
|
||||||
|
Ok(plain) => plain,
|
||||||
|
Err(_) => continue,
|
||||||
|
};
|
||||||
if !self.replay.accept(packet.header.seq) {
|
if !self.replay.accept(packet.header.seq) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let plain =
|
|
||||||
protocol::decrypt_body(&packet, &self.session_key, self.role.recv_direction())?;
|
|
||||||
self.peer_addr = peer;
|
self.peer_addr = peer;
|
||||||
self.ack_seq = self.ack_seq.max(packet.header.seq);
|
self.ack_seq = self.ack_seq.max(packet.header.seq);
|
||||||
self.last_contact = Instant::now();
|
self.last_contact = Instant::now();
|
||||||
@@ -751,14 +762,21 @@ impl DoshTransport {
|
|||||||
datagram: &[u8],
|
datagram: &[u8],
|
||||||
peer: SocketAddr,
|
peer: SocketAddr,
|
||||||
) -> Result<SessionEvent> {
|
) -> Result<SessionEvent> {
|
||||||
let packet = protocol::decode(datagram)?;
|
let packet = match protocol::decode(datagram) {
|
||||||
|
Ok(packet) => packet,
|
||||||
|
Err(_) => return Ok(SessionEvent::Ignored),
|
||||||
|
};
|
||||||
if packet.header.conn_id != self.conn_id {
|
if packet.header.conn_id != self.conn_id {
|
||||||
return Ok(SessionEvent::Ignored);
|
return Ok(SessionEvent::Ignored);
|
||||||
}
|
}
|
||||||
|
let plain =
|
||||||
|
match protocol::decrypt_body(&packet, &self.session_key, self.role.recv_direction()) {
|
||||||
|
Ok(plain) => plain,
|
||||||
|
Err(_) => return Ok(SessionEvent::Ignored),
|
||||||
|
};
|
||||||
if !self.replay.accept(packet.header.seq) {
|
if !self.replay.accept(packet.header.seq) {
|
||||||
return Ok(SessionEvent::Ignored);
|
return Ok(SessionEvent::Ignored);
|
||||||
}
|
}
|
||||||
let plain = protocol::decrypt_body(&packet, &self.session_key, self.role.recv_direction())?;
|
|
||||||
self.peer_addr = peer;
|
self.peer_addr = peer;
|
||||||
self.ack_seq = self.ack_seq.max(packet.header.seq);
|
self.ack_seq = self.ack_seq.max(packet.header.seq);
|
||||||
self.last_contact = Instant::now();
|
self.last_contact = Instant::now();
|
||||||
@@ -815,7 +833,12 @@ impl DoshTransport {
|
|||||||
|
|
||||||
async fn send_kind(&mut self, kind: PacketKind, body: &[u8]) -> Result<()> {
|
async fn send_kind(&mut self, kind: PacketKind, body: &[u8]) -> Result<()> {
|
||||||
let encoded = self.encode_kind(kind, body)?;
|
let encoded = self.encode_kind(kind, body)?;
|
||||||
self.socket.send_to(&encoded, self.peer_addr).await?;
|
if let Err(err) = self.socket.send_to(&encoded, self.peer_addr).await {
|
||||||
|
if is_transient_udp_send_error(&err) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -980,6 +1003,30 @@ mod tests {
|
|||||||
assert_eq!(data.bytes, b"!");
|
assert_eq!(data.bytes, b"!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cumulative_window_adjust_restores_credit_even_if_delta_was_lost() {
|
||||||
|
let mut mux = StreamMux::new(TransportConfig {
|
||||||
|
initial_window: 5,
|
||||||
|
retransmit_after: Duration::from_secs(1),
|
||||||
|
..TransportConfig::default()
|
||||||
|
});
|
||||||
|
mux.open_stream(1, "@dosh-test", 0).unwrap();
|
||||||
|
mux.handle_open_ok(StreamOpenOk { stream_id: 1 }).unwrap();
|
||||||
|
assert_eq!(mux.send_data(1, b"hello".to_vec()).unwrap().len(), 1);
|
||||||
|
assert_eq!(mux.send_credit[&1], 0);
|
||||||
|
|
||||||
|
let flushed = mux
|
||||||
|
.handle_window_adjust(StreamWindowAdjust {
|
||||||
|
stream_id: 1,
|
||||||
|
received_offset: 5,
|
||||||
|
bytes: 0,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert!(flushed.is_empty());
|
||||||
|
assert_eq!(mux.send_credit[&1], 5);
|
||||||
|
assert_eq!(mux.send_data(1, b"!".to_vec()).unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn handle_packet_decodes_and_dispatches_stream_packets() {
|
fn handle_packet_decodes_and_dispatches_stream_packets() {
|
||||||
let mut mux = StreamMux::new(TransportConfig::default());
|
let mut mux = StreamMux::new(TransportConfig::default());
|
||||||
@@ -1096,4 +1143,61 @@ mod tests {
|
|||||||
assert!(matches!(server.recv().await.unwrap(), SessionEvent::Ping));
|
assert!(matches!(server.recv().await.unwrap(), SessionEvent::Ping));
|
||||||
assert_eq!(server.peer_addr(), roaming_addr);
|
assert_eq!(server.peer_addr(), roaming_addr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unauthenticated_datagram_does_not_poison_replay_window() {
|
||||||
|
let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let peer: SocketAddr = "127.0.0.1:9".parse().unwrap();
|
||||||
|
let key = [11u8; 32];
|
||||||
|
let wrong_key = [12u8; 32];
|
||||||
|
let conn_id = [4u8; 16];
|
||||||
|
let mut transport = DoshTransport::new_owned(
|
||||||
|
socket,
|
||||||
|
SessionTransportConfig {
|
||||||
|
role: SessionRole::Client,
|
||||||
|
conn_id,
|
||||||
|
session_key: key,
|
||||||
|
peer_addr: peer,
|
||||||
|
initial_send_seq: 1,
|
||||||
|
initial_ack: 0,
|
||||||
|
stream: TransportConfig::default(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let bad = protocol::encode_encrypted(
|
||||||
|
PacketKind::Pong,
|
||||||
|
conn_id,
|
||||||
|
9,
|
||||||
|
0,
|
||||||
|
&wrong_key,
|
||||||
|
SERVER_TO_CLIENT,
|
||||||
|
b"",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let valid = protocol::encode_encrypted(
|
||||||
|
PacketKind::Pong,
|
||||||
|
conn_id,
|
||||||
|
9,
|
||||||
|
0,
|
||||||
|
&key,
|
||||||
|
SERVER_TO_CLIENT,
|
||||||
|
b"",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
transport
|
||||||
|
.handle_datagram(b"not a dosh packet", peer)
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
SessionEvent::Ignored
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
transport.handle_datagram(&bad, peer).await.unwrap(),
|
||||||
|
SessionEvent::Ignored
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
transport.handle_datagram(&valid, peer).await.unwrap(),
|
||||||
|
SessionEvent::Pong
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
//! UDP error classification shared by Dosh clients, servers, and embedders.
|
||||||
|
|
||||||
|
pub fn is_transient_udp_send_error(err: &std::io::Error) -> bool {
|
||||||
|
matches!(
|
||||||
|
err.kind(),
|
||||||
|
std::io::ErrorKind::Interrupted
|
||||||
|
| std::io::ErrorKind::TimedOut
|
||||||
|
| std::io::ErrorKind::WouldBlock
|
||||||
|
) || err.raw_os_error().is_some_and(is_transient_udp_os_error)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn is_transient_udp_os_error(code: i32) -> bool {
|
||||||
|
matches!(
|
||||||
|
code,
|
||||||
|
libc::EADDRNOTAVAIL
|
||||||
|
| libc::ECONNREFUSED
|
||||||
|
| libc::ECONNRESET
|
||||||
|
| libc::EHOSTDOWN
|
||||||
|
| libc::EHOSTUNREACH
|
||||||
|
| libc::ENETDOWN
|
||||||
|
| libc::ENETRESET
|
||||||
|
| libc::ENETUNREACH
|
||||||
|
| libc::ETIMEDOUT
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn is_transient_udp_os_error(code: i32) -> bool {
|
||||||
|
matches!(
|
||||||
|
code,
|
||||||
|
10049 // WSAEADDRNOTAVAIL
|
||||||
|
| 10050 // WSAENETDOWN
|
||||||
|
| 10051 // WSAENETUNREACH
|
||||||
|
| 10052 // WSAENETRESET
|
||||||
|
| 10054 // WSAECONNRESET
|
||||||
|
| 10060 // WSAETIMEDOUT
|
||||||
|
| 10061 // WSAECONNREFUSED
|
||||||
|
| 10064 // WSAEHOSTDOWN
|
||||||
|
| 10065 // WSAEHOSTUNREACH
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(unix, windows)))]
|
||||||
|
fn is_transient_udp_os_error(_code: i32) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::is_transient_udp_send_error;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_portable_transient_send_errors() {
|
||||||
|
for kind in [
|
||||||
|
std::io::ErrorKind::Interrupted,
|
||||||
|
std::io::ErrorKind::TimedOut,
|
||||||
|
std::io::ErrorKind::WouldBlock,
|
||||||
|
] {
|
||||||
|
assert!(is_transient_udp_send_error(&std::io::Error::from(kind)));
|
||||||
|
}
|
||||||
|
assert!(!is_transient_udp_send_error(&std::io::Error::from(
|
||||||
|
std::io::ErrorKind::PermissionDenied,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn classifies_unix_network_churn_as_transient() {
|
||||||
|
for code in [
|
||||||
|
libc::EADDRNOTAVAIL,
|
||||||
|
libc::ECONNREFUSED,
|
||||||
|
libc::ECONNRESET,
|
||||||
|
libc::EHOSTDOWN,
|
||||||
|
libc::EHOSTUNREACH,
|
||||||
|
libc::ENETDOWN,
|
||||||
|
libc::ENETRESET,
|
||||||
|
libc::ENETUNREACH,
|
||||||
|
libc::ETIMEDOUT,
|
||||||
|
] {
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(code)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
#[test]
|
||||||
|
fn classifies_windows_network_churn_as_transient() {
|
||||||
|
for code in [
|
||||||
|
10049, 10050, 10051, 10052, 10054, 10060, 10061, 10064, 10065,
|
||||||
|
] {
|
||||||
|
assert!(is_transient_udp_send_error(
|
||||||
|
&std::io::Error::from_raw_os_error(code)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+141
-9
@@ -258,7 +258,8 @@ fn relay_loop(
|
|||||||
let mut upstream = new_upstream();
|
let mut upstream = new_upstream();
|
||||||
let mut client_addr: Option<SocketAddr> = None;
|
let mut client_addr: Option<SocketAddr> = None;
|
||||||
let mut rng = StdRng::seed_from_u64(seed);
|
let mut rng = StdRng::seed_from_u64(seed);
|
||||||
let mut held: Option<(Vec<u8>, bool)> = None; // (packet, is_c2s) held for reorder
|
let mut held_c2s: Option<Vec<u8>> = None;
|
||||||
|
let mut held_s2c: Option<Vec<u8>> = None;
|
||||||
let mut buf = [0u8; 65535];
|
let mut buf = [0u8; 65535];
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
@@ -288,10 +289,9 @@ fn relay_loop(
|
|||||||
&upstream,
|
&upstream,
|
||||||
server_addr,
|
server_addr,
|
||||||
packet,
|
packet,
|
||||||
true,
|
|
||||||
&controls,
|
&controls,
|
||||||
&mut rng,
|
&mut rng,
|
||||||
&mut held,
|
&mut held_c2s,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -310,7 +310,12 @@ fn relay_loop(
|
|||||||
let drop_pct = controls.drop_s2c_percent.load(Ordering::SeqCst);
|
let drop_pct = controls.drop_s2c_percent.load(Ordering::SeqCst);
|
||||||
if drop_pct == 0 || rng.gen_range(0..100) >= drop_pct {
|
if drop_pct == 0 || rng.gen_range(0..100) >= drop_pct {
|
||||||
forward_with_effects(
|
forward_with_effects(
|
||||||
&front, dst, packet, false, &controls, &mut rng, &mut held,
|
&front,
|
||||||
|
dst,
|
||||||
|
packet,
|
||||||
|
&controls,
|
||||||
|
&mut rng,
|
||||||
|
&mut held_s2c,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -336,23 +341,22 @@ fn forward_with_effects(
|
|||||||
out: &UdpSocket,
|
out: &UdpSocket,
|
||||||
dst: SocketAddr,
|
dst: SocketAddr,
|
||||||
packet: Vec<u8>,
|
packet: Vec<u8>,
|
||||||
is_c2s: bool,
|
|
||||||
controls: &RelayControls,
|
controls: &RelayControls,
|
||||||
rng: &mut StdRng,
|
rng: &mut StdRng,
|
||||||
held: &mut Option<(Vec<u8>, bool)>,
|
held: &mut Option<Vec<u8>>,
|
||||||
) {
|
) {
|
||||||
// Reorder: if armed, hold this packet and release the previously held one
|
// Reorder: if armed, hold this packet and release the previously held one
|
||||||
// afterward (so two consecutive packets swap order).
|
// afterward (so two consecutive packets swap order).
|
||||||
if controls.reorder_next.swap(false, Ordering::SeqCst) {
|
if controls.reorder_next.swap(false, Ordering::SeqCst) {
|
||||||
if let Some((prev, _)) = held.take() {
|
if let Some(prev) = held.take() {
|
||||||
let _ = out.send_to(&packet, dst);
|
let _ = out.send_to(&packet, dst);
|
||||||
let _ = out.send_to(&prev, dst);
|
let _ = out.send_to(&prev, dst);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
*held = Some((packet, is_c2s));
|
*held = Some(packet);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if let Some((prev, _)) = held.take() {
|
if let Some(prev) = held.take() {
|
||||||
let _ = out.send_to(&prev, dst);
|
let _ = out.send_to(&prev, dst);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -767,6 +771,46 @@ fn wait_for_text(socket: &UdpSocket, key: &[u8; 32], needle: &str, millis: u64)
|
|||||||
acc.contains(needle)
|
acc.contains(needle)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn wait_for_text_with_ack(
|
||||||
|
socket: &UdpSocket,
|
||||||
|
relay: &Relay,
|
||||||
|
client_id: [u8; 16],
|
||||||
|
seq: &mut u64,
|
||||||
|
key: &[u8; 32],
|
||||||
|
needle: &str,
|
||||||
|
millis: u64,
|
||||||
|
) -> bool {
|
||||||
|
let prev = socket.read_timeout().unwrap();
|
||||||
|
socket
|
||||||
|
.set_read_timeout(Some(Duration::from_millis(100)))
|
||||||
|
.unwrap();
|
||||||
|
let deadline = Instant::now() + Duration::from_millis(millis);
|
||||||
|
let mut acc = String::new();
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
if let Some((_header, frame)) = recv_frame(socket, key) {
|
||||||
|
acc.push_str(&String::from_utf8_lossy(&frame.bytes));
|
||||||
|
let ack = protocol::encode_encrypted(
|
||||||
|
PacketKind::Ack,
|
||||||
|
client_id,
|
||||||
|
*seq,
|
||||||
|
frame.output_seq,
|
||||||
|
key,
|
||||||
|
CLIENT_TO_SERVER,
|
||||||
|
b"",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
*seq += 1;
|
||||||
|
socket.send_to(&ack, relay.front_addr()).unwrap();
|
||||||
|
if acc.contains(needle) {
|
||||||
|
socket.set_read_timeout(prev).unwrap();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
socket.set_read_timeout(prev).unwrap();
|
||||||
|
acc.contains(needle)
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn session_survives_packet_loss_and_reorder() {
|
fn session_survives_packet_loss_and_reorder() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
@@ -820,6 +864,94 @@ fn session_survives_packet_loss_and_reorder() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore = "30-minute hostile-network TUI soak; run with `DOSH_BADNET_SOAK_SECONDS=1800 cargo test --test hostile_network bad_network_tui_work_soak_30m -- --ignored --nocapture`"]
|
||||||
|
fn bad_network_tui_work_soak_30m() {
|
||||||
|
let soak_secs = std::env::var("DOSH_BADNET_SOAK_SECONDS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.parse::<u64>().ok())
|
||||||
|
.unwrap_or(30 * 60);
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let port = free_udp_port();
|
||||||
|
let config = write_server_config(&dir, port);
|
||||||
|
let mut server = start_server(&dir, &config);
|
||||||
|
let relay = Relay::spawn(port, 0xBADC0DEu64);
|
||||||
|
let (socket, bootstrap, ok) = attach_through_relay(&config, &relay);
|
||||||
|
|
||||||
|
relay.set_drop_c2s(15);
|
||||||
|
relay.set_drop_s2c(20);
|
||||||
|
relay.set_dup(10);
|
||||||
|
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(soak_secs);
|
||||||
|
let mut seq = 2u64;
|
||||||
|
let mut iteration = 0u64;
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
if iteration.is_multiple_of(2) {
|
||||||
|
relay.arm_reorder();
|
||||||
|
}
|
||||||
|
if iteration > 0 && iteration.is_multiple_of(7) {
|
||||||
|
let _ = relay.rebind_upstream();
|
||||||
|
}
|
||||||
|
if iteration > 0 && iteration.is_multiple_of(11) {
|
||||||
|
relay.set_drop_s2c(100);
|
||||||
|
thread::sleep(Duration::from_millis(750));
|
||||||
|
relay.set_drop_s2c(20);
|
||||||
|
}
|
||||||
|
|
||||||
|
let marker = format!("DOSH_BADNET_TUI_{iteration}");
|
||||||
|
let command = format!(
|
||||||
|
"stty -echo; \
|
||||||
|
printf '\\033[?1049h\\033[?2026h\\033[?25l'; \
|
||||||
|
for i in 1 2 3 4 5 6; do \
|
||||||
|
printf '\\033[%s;4H{} ⠀⠁⠃⠇⡇⣇⣧⣷⣿ █▇▆▅▄▃▂▁ %s\\033[0m' \"$i\" \"$i\"; \
|
||||||
|
done; \
|
||||||
|
printf '\\033[?25h\\033[?2026l\\033[?1049l'\n",
|
||||||
|
marker
|
||||||
|
);
|
||||||
|
|
||||||
|
let step_deadline = Instant::now() + Duration::from_secs(8);
|
||||||
|
let mut seen = false;
|
||||||
|
let mut attempts = 0;
|
||||||
|
while Instant::now() < step_deadline && attempts < 12 {
|
||||||
|
send_input(
|
||||||
|
&socket,
|
||||||
|
&relay,
|
||||||
|
ok.client_id,
|
||||||
|
seq,
|
||||||
|
0,
|
||||||
|
&bootstrap.session_key,
|
||||||
|
command.as_bytes(),
|
||||||
|
);
|
||||||
|
seq += 1;
|
||||||
|
attempts += 1;
|
||||||
|
if wait_for_text_with_ack(
|
||||||
|
&socket,
|
||||||
|
&relay,
|
||||||
|
ok.client_id,
|
||||||
|
&mut seq,
|
||||||
|
&bootstrap.session_key,
|
||||||
|
&marker,
|
||||||
|
500,
|
||||||
|
) {
|
||||||
|
seen = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
seen,
|
||||||
|
"TUI marker {marker} did not arrive during hostile-network soak"
|
||||||
|
);
|
||||||
|
|
||||||
|
iteration += 1;
|
||||||
|
thread::sleep(Duration::from_millis(500));
|
||||||
|
}
|
||||||
|
|
||||||
|
relay.clear_impairments();
|
||||||
|
drop(relay);
|
||||||
|
let _ = server.kill();
|
||||||
|
let _ = server.wait();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn duplicated_and_replayed_input_is_applied_at_most_once() {
|
fn duplicated_and_replayed_input_is_applied_at_most_once() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
+259
-20
@@ -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::native::{host_public_key, load_or_create_host_key, ssh_ed25519_public_blob, trust_host};
|
||||||
use dosh::protocol::{
|
use dosh::protocol::{
|
||||||
self, AttachOk, AttachReject, BootstrapAttachRequest, CLIENT_TO_SERVER, Frame, Input,
|
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};
|
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
|
||||||
|
|
||||||
@@ -530,6 +531,75 @@ fn direct_attach_session(
|
|||||||
(socket, bootstrap, ok)
|
(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)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn send_encrypted(
|
fn send_encrypted(
|
||||||
socket: &UdpSocket,
|
socket: &UdpSocket,
|
||||||
@@ -1038,6 +1108,117 @@ fn native_file_copy_recursive_round_trip() {
|
|||||||
let _ = server.wait();
|
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]
|
#[test]
|
||||||
fn native_exec_command_smoke() {
|
fn native_exec_command_smoke() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
@@ -2733,7 +2914,7 @@ fn session_survives_server_restart_same_shell_and_screen() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn implicit_session_does_not_create_restart_holder() {
|
fn implicit_session_survives_update_restart_via_ticket_reattach() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let sessions_dir = dir.path().join("sessions");
|
let sessions_dir = dir.path().join("sessions");
|
||||||
let port = free_udp_port();
|
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 mut server = start_server(&dir, &config);
|
||||||
let (socket, bootstrap, ok) = direct_attach_session(&config, port, "read-write", &session);
|
let (socket, bootstrap, ok) = direct_attach_session(&config, port, "read-write", &session);
|
||||||
let key = bootstrap.session_key;
|
let key = bootstrap.session_key;
|
||||||
|
type_line(&socket, port, &ok, &key, 2, "cd /tmp\n");
|
||||||
type_line(
|
type_line(
|
||||||
&socket,
|
&socket,
|
||||||
port,
|
port,
|
||||||
&ok,
|
&ok,
|
||||||
&key,
|
&key,
|
||||||
2,
|
3,
|
||||||
"export IMPLICIT_MARK=implicit_restart_42\n",
|
"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));
|
thread::sleep(Duration::from_secs(3));
|
||||||
|
|
||||||
let shell_pid_before = holder_shell_pid(&sessions_dir, &session);
|
let shell_pid_before = holder_shell_pid(&sessions_dir, &session);
|
||||||
assert!(
|
assert!(
|
||||||
shell_pid_before.is_none(),
|
shell_pid_before.is_some(),
|
||||||
"implicit sessions must not get persistent holders when persistence is enabled"
|
"implicit sessions must get temporary holders so active clients survive updates"
|
||||||
);
|
);
|
||||||
|
|
||||||
let _ = server.kill();
|
let _ = server.kill();
|
||||||
@@ -2765,34 +2959,78 @@ fn implicit_session_does_not_create_restart_holder() {
|
|||||||
thread::sleep(Duration::from_millis(300));
|
thread::sleep(Duration::from_millis(300));
|
||||||
|
|
||||||
let mut server = start_server(&dir, &config);
|
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(
|
type_line(
|
||||||
&socket2,
|
&socket,
|
||||||
port,
|
port,
|
||||||
&ok2,
|
&ok2,
|
||||||
&key2,
|
&key2,
|
||||||
2,
|
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 shell_pid_after = holder_shell_pid(&sessions_dir, &session);
|
||||||
|
|
||||||
let _ = server.kill();
|
let _ = server.kill();
|
||||||
let _ = server.wait();
|
let _ = server.wait();
|
||||||
|
kill_holder(&sessions_dir, &session);
|
||||||
|
|
||||||
assert!(
|
assert!(
|
||||||
shell_pid_after.is_none(),
|
snapshot.contains("IMPLICIT_SCREEN_MARKER"),
|
||||||
"implicit restart attach must stay ephemeral"
|
"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!(
|
assert!(
|
||||||
post.contains("IMPLICIT_MARK=") && !post.contains("implicit_restart_42"),
|
post.contains("IMPLICIT_MARK=implicit_restart_42"),
|
||||||
"implicit session must start fresh after server restart, got {post:?}"
|
"implicit session env must survive update reconnect, got {post:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
post.contains("PWD=/tmp"),
|
||||||
|
"implicit session cwd must survive update reconnect, got {post:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn startup_discards_legacy_implicit_holders() {
|
fn startup_readopts_implicit_holders_for_update_reconnect() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let sessions_dir = dir.path().join("sessions");
|
let sessions_dir = dir.path().join("sessions");
|
||||||
let port = free_udp_port();
|
let port = free_udp_port();
|
||||||
@@ -2812,13 +3050,14 @@ fn startup_discards_legacy_implicit_holders() {
|
|||||||
let _ = server.kill();
|
let _ = server.kill();
|
||||||
let _ = server.wait();
|
let _ = server.wait();
|
||||||
assert!(
|
assert!(
|
||||||
holder_shell_pid(&sessions_dir, &session).is_none(),
|
holder_shell_pid(&sessions_dir, &session).is_some(),
|
||||||
"startup must remove old implicit holder metadata"
|
"startup must keep live implicit holders so active update reconnects can reattach"
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
unsafe { libc::kill(shell_pid, 0) } != 0,
|
unsafe { libc::kill(shell_pid, 0) } == 0,
|
||||||
"startup must shut down old implicit holder shell"
|
"startup must not shut down a live implicit holder before reconnect grace"
|
||||||
);
|
);
|
||||||
|
kill_holder(&sessions_dir, &session);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -58,6 +58,19 @@ fn encrypted_packet_round_trips() {
|
|||||||
assert_eq!(plain, b"hello");
|
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]
|
#[test]
|
||||||
fn encrypted_packet_rejects_wrong_session_key_id_before_decrypt() {
|
fn encrypted_packet_rejects_wrong_session_key_id_before_decrypt() {
|
||||||
let key = crypto::random_32();
|
let key = crypto::random_32();
|
||||||
|
|||||||
Reference in New Issue
Block a user