Compare commits

...
47 Commits
Author SHA1 Message Date
DuProcess e11ba1a652 Bump version to 1.0.0-rc16
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-10 22:49:14 -04:00
DuProcess 07c4b321d1 Harden persistent screen mirroring
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-10 22:48:32 -04:00
DuProcess 673b8ae16e Bump version to 1.0.0-rc15
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-10 22:26:04 -04:00
DuProcess 262dfaca04 Retire terminal forwarding stream ids 2026-07-10 22:23:34 -04:00
DuProcess 5ca3e98a5c Bump version to 1.0.0-rc14
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-09 20:02:34 -04:00
DuProcess 40810e4ba2 Bound retired stream tombstones 2026-07-09 19:58:39 -04:00
DuProcess 1f01338eb8 Bump version to 1.0.0-rc13
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-09 19:52:08 -04:00
DuProcess 5c8bd68aa6 Retire closed transport stream ids 2026-07-09 19:49:56 -04:00
DuProcess 68cf411143 Bump version to 1.0.0-rc12
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-09 19:34:59 -04:00
DuProcess b84f57ee9d Speed up terminal frame gap recovery 2026-07-09 19:33:13 -04:00
DuProcess 1601d474e7 Strip split stale mouse terminators 2026-07-09 19:30:25 -04:00
DuProcess 1466516053 Harden stream cleanup state 2026-07-09 19:27:45 -04:00
DuProcess bab3f777dc Harden SDK stream ids and duplicate opens
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-09 19:19:07 -04:00
DuProcess 039dc641b3 Fix resumed copy truncation
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-09 19:10:17 -04:00
DuProcess 4c9e31fd16 Harden alternate screen tracking
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 20:37:16 -04:00
DuProcess c1c672b188 Bump release candidate to rc8
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 15:34:49 -04:00
DuProcess a23f610f20 Keep generated sessions alive across updates 2026-07-07 15:34:24 -04:00
DuProcess ff2b7fff2b Bump release candidate to rc7
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 14:58:13 -04:00
DuProcess f4879090f6 Keep terminal focus reports local 2026-07-07 14:57:53 -04:00
DuProcess 37ec9fc520 Bump release candidate to rc6
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 12:01:03 -04:00
DuProcess f3c7ec225d Repaint terminal after idle tab return 2026-07-07 12:00:40 -04:00
DuProcess d3c40a06ac Bump release candidate to rc5
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-07 11:49:41 -04:00
DuProcess 6b12b3dfe0 Harden terminal reconnect packet handling 2026-07-07 11:48:59 -04:00
DuProcess b90c34dc17 Bump release candidate to rc4
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-05 18:00:59 -04:00
DuProcess f205e0c128 Harden native auth and SDK datagram handling 2026-07-05 18:00:31 -04:00
DuProcess 92c94176bd Bump release candidate to rc3
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-05 09:39:21 -04:00
DuProcess 4b2e9a62d5 Harden embedded transport under UDP churn
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-05 09:37:44 -04:00
DuProcess 689d20f7e7 Bump release candidate to rc2
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-04 23:00:18 -04:00
DuProcess 252f081a61 Suppress stale terminal mouse reports after reconnect
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-04 22:56:32 -04:00
DuProcess b1e8326b0a Stop local benchmark holder leaks 2026-07-04 22:31:14 -04:00
DuProcess 3b4931aa8f Keep server alive on transient UDP send errors 2026-07-04 22:29:52 -04:00
DuProcess 5c54601cdf Prepare Dosh 1.0.0 rc1
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-04 16:58:15 -04:00
DuProcess c085137250 Add hostile network TUI soak gate
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-04 14:37:23 -04:00
DuProcess 237ad52bef Flush queued input after reconnect contact
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-03 16:35:22 -04:00
DuProcess a8ba852f16 Keep Dosh server service alive
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-03 14:51:47 -04:00
DuProcess f1a3de7730 Rate limit terminal gap resync
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-03 10:19:53 -04:00
DuProcess 80699dcf9d Stabilize terminal frame recovery
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-03 10:06:23 -04:00
DuProcess 274c0f505e Stop sandboxing remote shells
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 20:03:42 -04:00
DuProcess b393c0e5d5 Allow netlink for terminal network monitors
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 19:40:30 -04:00
DuProcess d5bc8e3c64 Recover terminal output gaps with resume repaint
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 19:29:20 -04:00
DuProcess c40f5459ba Keep live TUI output raw under retransmit pressure
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 19:21:43 -04:00
DuProcess 601510687e Prepare Dosh 0.1.9 release
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 19:07:46 -04:00
DuProcess 60387e9222 Install Dosh binaries atomically
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 18:41:02 -04:00
DuProcess a48aa15308 Preserve raw terminal output for TUIs
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-02 18:34:09 -04:00
DuProcess 691b58e531 Harden update and release tooling
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-01 19:48:46 -04:00
DuProcess 431dcc3997 Prepare Dosh 0.1.7 release
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-01 18:03:42 -04:00
DuProcess 3224a9c699 Fix Dosh stdio proxy for VS Code
ci / test (push) Has been cancelled
ci / fuzz-smoke (push) Has been cancelled
ci / windows-client (push) Has been cancelled
ci / package-release (linux-x86_64, ubuntu-latest) (push) Has been cancelled
ci / package-release (macos-aarch64, macos-14) (push) Has been cancelled
ci / package-release (macos-x86_64, macos-13) (push) Has been cancelled
ci / package-release (windows-x86_64, windows-latest) (push) Has been cancelled
ci / remote-bench (push) Has been cancelled
2026-07-01 09:58:26 -04:00
24 changed files with 3305 additions and 564 deletions
Generated
+1 -1
View File
@@ -436,7 +436,7 @@ dependencies = [
[[package]]
name = "dosh"
version = "0.1.6"
version = "1.0.0-rc16"
dependencies = [
"anyhow",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "dosh"
version = "0.1.6"
version = "1.0.0-rc16"
edition = "2024"
license = "MIT"
+20 -1
View File
@@ -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:
cargo build --release
@@ -19,6 +19,25 @@ release-check:
cargo test
$(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:
sh install.sh --from-current
+52 -116
View File
@@ -1,33 +1,31 @@
# Dosh
Dosh is an encrypted remote terminal for fast reconnecting shells. It is meant
to replace Mosh and day-to-day interactive SSH sessions.
Dosh is an encrypted remote terminal for fast reconnecting shells.
It runs a `dosh-server` on the remote machine and a `dosh` client locally. The
first setup can use SSH. After that, Dosh can attach over encrypted UDP with
cached credentials, keep terminal sessions alive, reconnect after network
changes, and forward TCP ports.
It also includes native encrypted file copy over the Dosh stream layer.
It runs a `dosh-server` on a Unix-like host and a `dosh` client on macOS,
Linux, or Windows. Setup can use SSH, then Dosh connects over encrypted UDP,
keeps sessions alive across disconnects, supports terminal apps, and can carry
TCP forwarding, file copy, and VS Code Remote-SSH streams.
## Support
- Client: macOS, Linux, Windows
- Server: Unix-like systems with PTYs
- Server: Linux and other Unix-like systems with PTYs
- Default UDP port: `50000`
- Windows: client only
- UDP port: one configured server port, default `50000`
Dosh does not implement SFTP, X11 forwarding, or a Windows server. Windows is
client-only.
Dosh is meant to replace Mosh and everyday interactive SSH sessions. It does
not currently include SFTP, X11 forwarding, or a Windows server.
## Install
Server and client on Unix/macOS:
Unix/macOS server and client:
```sh
curl -fsSL https://git.palav.dev/Palav/dosh/raw/branch/main/install.sh | sh -s -- both --repo https://git.palav.dev/Palav/dosh.git --port 50000
```
Client only on Unix/macOS:
Unix/macOS client only:
```sh
curl -fsSL https://git.palav.dev/Palav/dosh/raw/branch/main/install.sh | sh -s -- client --repo https://git.palav.dev/Palav/dosh.git
@@ -39,123 +37,48 @@ Windows client:
irm https://git.palav.dev/Palav/dosh/raw/branch/main/install.ps1 | iex
```
## Commands
## Use
```sh
dosh setup HOST # import SSH config and trust the Dosh host key
dosh HOST # connect
dosh HOST COMMAND # connect and run a command
dosh exec HOST COMMAND # run a non-interactive remote command
dosh cp SRC DST # copy files; use host:path for a remote side
dosh ls host:path # list a remote path
dosh cat host:path # print a remote file
dosh mkdir host:path # create a remote directory
dosh rm [-r] host:path # remove a remote file or directory
dosh update # update Dosh
dosh status HOST # show remote tmux sessions and Dosh service status
dosh restart HOST # restart dosh-server and show service status
dosh doctor HOST # check config and connectivity
dosh recover HOST # clear cached attach state and re-check
dosh proxy-stdio HOST 127.0.0.1 22
dosh vscode HOST [PATH] # configure/open VS Code Remote-SSH through Dosh
dosh setup HOST
dosh HOST
dosh HOST COMMAND
dosh update
```
Examples:
Useful commands:
```sh
dosh server
dosh server tm
dosh exec server 'uname -a'
dosh cp file.txt server:tmp/file.txt
dosh cp -r server:Projects/app ./app
dosh cp -r server:Projects/app backup:app
dosh ls server:Projects
dosh cat server:tmp/file.txt
dosh forward server -L 8080:127.0.0.1:80
dosh forward server -D 1080
dosh forward server -R 2222:127.0.0.1:22
dosh proxy-stdio server 127.0.0.1 22
dosh vscode server /home/me/project
dosh exec HOST COMMAND
dosh cp SRC DST
dosh ls host:path
dosh cat host:path
dosh mkdir host:path
dosh rm [-r] host:path
dosh forward HOST -L 8080:127.0.0.1:80
dosh forward HOST -D 1080
dosh forward HOST -R 2222:127.0.0.1:22
dosh status HOST
dosh doctor HOST
dosh recover HOST
dosh restart HOST
```
Agent forwarding is opt-in with `-A` and must be enabled on the server.
File copy is enabled by `allow_file_transfer = true` on the server.
Agent forwarding is opt-in with `-A` and must also be enabled on the server.
File copy must be enabled by the server config.
## VS Code
Dosh can carry VS Code Remote-SSH without replacing VS Code's SSH workflow.
Dosh can carry VS Code Remote-SSH through its transport:
```sh
dosh vscode setup server
dosh vscode server /home/me/project
dosh vscode setup HOST
dosh vscode HOST /remote/path
```
This writes a managed SSH config entry using:
```sshconfig
ProxyCommand dosh proxy-stdio server %h %p
```
VS Code still uses Remote-SSH and the normal remote VS Code Server. Dosh carries
the SSH byte stream over its encrypted reconnecting transport.
The optional extension in `vscode-extension/` provides the same setup from the
Command Palette.
## Library
Dosh can also be used as a Rust transport for application protocols that need
encrypted streams, roaming, reconnect behavior, keepalives, retransmission,
flow control, and in-order delivery.
Use `dosh::client::DoshClient` and `dosh::server::DoshServer` for the complete
native-auth path. Use `dosh::transport::DoshTransport` or `StreamMux` only when
you already have your own session/auth layer.
Client-side SDK:
```rust
let client = dosh::client::DoshClient::load()?;
let mut dosh = client
.connect("server")
.service("myapp")
.connect()
.await?
.into_transport();
let stream = dosh.open_service("myapp").await?;
dosh.send(stream, b"hello").await?;
```
Server-side SDK:
```rust
let config = dosh::server::DoshServerConfig::default()
.service("myapp")?;
let mut server = dosh::server::DoshServer::bind(config).await?;
loop {
match server.recv().await? {
dosh::server::DoshServerEvent::Accepted(client) => {
eprintln!("accepted {:?}", client.conn_id);
}
dosh::server::DoshServerEvent::Session { conn_id, event } => {
if let dosh::transport::SessionEvent::Stream(
dosh::transport::TransportEvent::Open(open)
) = event {
server.accept_stream(conn_id, open.stream_id).await?;
}
}
dosh::server::DoshServerEvent::Ignored => {}
}
}
```
The server runtime owns UDP reads and demuxes packets by connection id, so
multiple clients can share one Dosh port without per-session readers racing.
Runnable SDK examples live in `examples/sdk_echo_server.rs` and
`examples/sdk_echo_client.rs`.
This creates a managed SSH config entry using `ProxyCommand dosh proxy-stdio`.
VS Code still uses Remote-SSH and its normal remote server; Dosh carries the
SSH byte stream.
## Config
@@ -169,8 +92,21 @@ Common client settings:
```toml
default_session = "new"
auth_preference = "native,ssh"
predict = true
cache_attach_tickets = true
disconnect_status = true
```
## Rust Library
Dosh exposes a Rust transport for encrypted, reconnecting application streams.
Use `dosh::client::DoshClient` and `dosh::server::DoshServer` for the normal
native-auth path. Use `dosh::transport::DoshTransport` only when you already
own session setup and authentication.
Runnable examples:
```text
examples/sdk_echo_client.rs
examples/sdk_echo_server.rs
```
+19 -5
View File
@@ -141,6 +141,20 @@ function Verify-ArchiveVersion($ExtractDir, $Url) {
}
}
function Install-Binary($Source, $Destination) {
$dir = Split-Path -Parent $Destination
$name = Split-Path -Leaf $Destination
$tmp = Join-Path $dir ".$name.tmp.$PID"
Copy-Item $Source $tmp -Force
try {
Move-Item $tmp $Destination -Force
}
catch {
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
throw
}
}
$bindir = Join-Path $Prefix "bin"
$configDir = Join-Path $HOME ".config\dosh"
New-Item -ItemType Directory -Force -Path $bindir, $configDir | Out-Null
@@ -168,9 +182,9 @@ function Install-Prebuilt {
if (-not $found) {
throw "prebuilt archive missing $bin"
}
Copy-Item $found.FullName (Join-Path $bindir $bin) -Force
Install-Binary $found.FullName (Join-Path $bindir $bin)
}
Copy-Item (Join-Path $bindir "dosh-client.exe") (Join-Path $bindir "dosh.exe") -Force
Install-Binary (Join-Path $bindir "dosh-client.exe") (Join-Path $bindir "dosh.exe")
return $true
}
catch {
@@ -202,9 +216,9 @@ function Install-FromSource {
try {
Push-Location $src
cargo build --release --bin dosh-client --bin dosh-bench
Copy-Item "target\release\dosh-client.exe" (Join-Path $bindir "dosh-client.exe") -Force
Copy-Item "target\release\dosh-client.exe" (Join-Path $bindir "dosh.exe") -Force
Copy-Item "target\release\dosh-bench.exe" (Join-Path $bindir "dosh-bench.exe") -Force
Install-Binary "target\release\dosh-client.exe" (Join-Path $bindir "dosh-client.exe")
Install-Binary "target\release\dosh-client.exe" (Join-Path $bindir "dosh.exe")
Install-Binary "target\release\dosh-bench.exe" (Join-Path $bindir "dosh-bench.exe")
}
finally {
Pop-Location
+20 -20
View File
@@ -12,11 +12,7 @@ start_server=1
force_config=0
update_cache="${DOSH_UPDATE_CACHE:-$HOME/.cache/dosh/source}"
quiet="${DOSH_UPDATE_QUIET:-0}"
if [ "${DOSH_UPDATE_QUIET:-0}" = "1" ] && [ "${DOSH_BINARY_REQUIRED:-0}" != "1" ]; then
use_prebuilt=0
else
use_prebuilt="${DOSH_USE_PREBUILT:-1}"
fi
binary_url="${DOSH_BINARY_URL:-}"
binary_base="${DOSH_BINARY_BASE:-}"
binary_name="${DOSH_BINARY_NAME:-}"
@@ -230,13 +226,26 @@ find_extracted_binary() {
find "$1" -type f -name "$2" 2>/dev/null | sed -n '1p'
}
install_binary() {
src="$1"
dst="$2"
dst_dir="$(dirname "$dst")"
dst_base="$(basename "$dst")"
tmp="$dst_dir/.$dst_base.tmp.$$"
install -m 0755 "$src" "$tmp"
if ! mv -f "$tmp" "$dst"; then
rm -f "$tmp"
return 1
fi
}
install_extracted_binary() {
found="$(find_extracted_binary "$1" "$2")"
if [ -z "$found" ]; then
echo "prebuilt archive missing $2" >&2
return 1
fi
install -m 0755 "$found" "$3"
install_binary "$found" "$3"
}
sha256_file() {
@@ -333,7 +342,7 @@ try_install_prebuilt() {
install_extracted_binary "$tmpdir/extract" dosh-auth "$bindir/dosh-auth" || return 1
fi
if found_bench="$(find_extracted_binary "$tmpdir/extract" dosh-bench)" && [ -n "$found_bench" ]; then
install -m 0755 "$found_bench" "$bindir/dosh-bench"
install_binary "$found_bench" "$bindir/dosh-bench"
fi
return 0
}
@@ -392,14 +401,14 @@ install_from_source() {
fi
fi
install -m 0755 target/release/dosh-client "$bindir/dosh-client"
install_binary target/release/dosh-client "$bindir/dosh-client"
ln -sf dosh-client "$bindir/dosh"
if [ "$role" = "server" ] || [ "$role" = "both" ]; then
install -m 0755 target/release/dosh-server "$bindir/dosh-server"
install -m 0755 target/release/dosh-auth "$bindir/dosh-auth"
install_binary target/release/dosh-server "$bindir/dosh-server"
install_binary target/release/dosh-auth "$bindir/dosh-auth"
fi
if [ -f target/release/dosh-bench ]; then
install -m 0755 target/release/dosh-bench "$bindir/dosh-bench"
install_binary target/release/dosh-bench "$bindir/dosh-bench"
fi
}
@@ -417,18 +426,9 @@ Wants=network-online.target
[Service]
Type=simple
ExecStart=$bindir/dosh-server serve
Restart=on-failure
Restart=always
RestartSec=1
KillMode=process
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=$config_dir $data_dir
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
[Install]
WantedBy=default.target
+1 -10
View File
@@ -6,18 +6,9 @@ Wants=network-online.target
[Service]
Type=simple
ExecStart=%h/.local/bin/dosh-server serve
Restart=on-failure
Restart=always
RestartSec=1
KillMode=process
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=%h/.config/dosh %h/.local/share/dosh
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
[Install]
WantedBy=default.target
+2
View File
@@ -67,6 +67,7 @@ cleanup() {
kill "$server_pid" 2>/dev/null || true
wait "$server_pid" 2>/dev/null || true
fi
pkill -f "$server_bin hold --runtime-dir $home/sessions/run" 2>/dev/null || true
rm -rf "$home"
}
trap cleanup EXIT INT TERM
@@ -86,6 +87,7 @@ scrollback = 5000
auth_ttl_secs = 30
attach_ticket_ttl_secs = 3600
allow_attach_tickets = true
persist_sessions = false
client_timeout_secs = 60
retransmit_window = 256
default_input_mode = "read-write"
+20
View File
@@ -99,6 +99,21 @@ fi
web_repo="${base%/}/${repo}"
failed=0
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
}
for artifact in target/dosh-release/dosh-linux-*.tar.gz target/dosh-release/dosh-macos-*.tar.gz target/dosh-release/dosh-windows-*.zip; do
[ -f "$artifact" ] || continue
name="$(basename "$artifact")"
@@ -107,6 +122,11 @@ for artifact in target/dosh-release/dosh-linux-*.tar.gz target/dosh-release/dosh
continue
;;
esac
actual="$(artifact_version "$artifact" || true)"
if [ "$actual" != "$version" ]; then
echo "skipping stale artifact $name: version ${actual:-unknown}, expected $version" >&2
continue
fi
url="$web_repo/releases/download/$tag/$name"
if curl -fsSI "$url" >/dev/null; then
echo "verified $url"
+2
View File
@@ -8,6 +8,8 @@ for test_name in \
live_output_forwards_terminal_control_sequences \
tui_control_sequences_survive_transport_verbatim \
unicode_output_survives_transport \
tui_graph_glyphs_survive_fast_repaints_without_snapshot_substitution \
btop_style_graph_output_stays_raw_when_retransmit_history_overflows \
large_tui_paint_is_delivered_in_mtu_safe_frames \
resume_snapshot_preserves_alternate_screen_mode
do
+20 -15
View File
@@ -32,6 +32,21 @@ token="${GITEA_TOKEN:-}"
title="${GITEA_TITLE:-$tag}"
expected_version="${tag#v}"
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
}
if [ -z "$token" ] && [ -f "$HOME/.config/dosh/gitea-token" ]; then
token="$(tr -d '\r\n' <"$HOME/.config/dosh/gitea-token")"
fi
@@ -52,6 +67,11 @@ if [ "$#" -eq 0 ]; then
continue
;;
esac
actual="$(artifact_version "$artifact" || true)"
if [ "$actual" != "$expected_version" ]; then
echo "skipping $artifact: version ${actual:-unknown}, expected $expected_version" >&2
continue
fi
if [ -f "$artifact.sha256" ]; then
set -- "$@" "$artifact" "$artifact.sha256"
else
@@ -103,21 +123,6 @@ delete_existing_asset() {
done
}
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
}
verify_release_artifact_version() {
artifact="$1"
name="$(basename "$artifact")"
+46
View File
@@ -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"
+1061 -87
View File
File diff suppressed because it is too large Load Diff
+513 -214
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -23,3 +23,4 @@ pub mod pty;
pub mod server;
pub mod ssh_agent;
pub mod transport;
pub mod udp;
+4
View File
@@ -435,6 +435,10 @@ pub fn run_holder(
let mut cmd = [0u8; 1];
match stream.read(&mut cmd) {
Ok(1) if cmd[0] == HOLDER_CMD_SHUTDOWN => {
if shell_pid > 0 {
let _ = unsafe { libc::kill(shell_pid, libc::SIGHUP) };
let _ = unsafe { libc::kill(shell_pid, libc::SIGTERM) };
}
let _ = std::fs::remove_dir_all(runtime_dir);
std::process::exit(0);
}
+1 -1
View File
@@ -280,7 +280,7 @@ pub fn decode(input: &[u8]) -> Result<Packet> {
pub fn decrypt_body(packet: &Packet, key: &[u8; 32], direction: u32) -> Result<Vec<u8>> {
if packet.header.flags & 1 == 0 {
return Ok(packet.body.clone());
bail!("packet body is not encrypted");
}
let nonce = crypto::nonce_from(direction, packet.header.seq);
let aad = packet.header.aad();
+120 -6
View File
@@ -13,6 +13,7 @@ use crate::transport::{
DoshTransport, SessionEvent, SessionRole, SessionTransportConfig, TransportConfig,
service_name_from_target,
};
use crate::udp::is_transient_udp_send_error;
use anyhow::{Context, Result, anyhow, bail};
use ed25519_dalek::SigningKey;
use std::collections::{HashMap, HashSet};
@@ -97,6 +98,7 @@ pub enum DoshServerEvent {
Ignored,
}
#[derive(Debug, Clone)]
struct PendingServerAuth {
client: native::NativeClientHello,
server: NativeServerHello,
@@ -255,7 +257,7 @@ impl DoshServer {
};
let body = protocol::to_body(&NativeServerHelloBody { hello })?;
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(())
}
@@ -327,7 +329,7 @@ impl DoshServer {
peer: SocketAddr,
packet: &protocol::Packet,
) -> 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")
.await?;
return Ok(DoshServerEvent::Ignored);
@@ -338,13 +340,28 @@ impl DoshServer {
return Ok(DoshServerEvent::Ignored);
}
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")
.await?;
return Ok(DoshServerEvent::Ignored);
}
let body = protocol::decrypt_body(packet, &pending.session_key, CLIENT_TO_SERVER)?;
let req: NativeUserAuthBody = protocol::from_body(&body)?;
let body = match protocol::decrypt_body(packet, &pending.session_key, CLIENT_TO_SERVER) {
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) {
Ok(services) => services,
Err(err) => {
@@ -353,6 +370,7 @@ impl DoshServer {
return Ok(DoshServerEvent::Ignored);
}
};
self.pending.remove(&packet.header.conn_id);
let conn_id = crypto::random_16();
let key_id = protocol::session_key_id(&pending.session_key);
@@ -381,7 +399,7 @@ impl DoshServer {
SERVER_TO_CLIENT,
&body,
)?;
self.socket.send_to(&out, peer).await?;
let _ = send_udp(&self.socket, &out, peer).await?;
let transport = DoshTransport::new(
Arc::clone(&self.socket),
@@ -428,7 +446,7 @@ impl DoshServer {
reason: reason.to_string(),
})?;
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(())
}
@@ -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(
allowed_services: &HashSet<String>,
requests: &[ForwardingRequest],
@@ -477,6 +503,7 @@ mod tests {
use super::*;
use crate::client::DoshClient;
use crate::config::{ClientConfig, HostsConfig};
use crate::protocol::{CLIENT_TO_SERVER, NativeUserAuthBody};
use crate::transport::TransportEvent;
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));
}
}
+622 -41
View File
@@ -19,6 +19,7 @@ use crate::protocol::{
self, CLIENT_TO_SERVER, PacketKind, ReplayWindow, SERVER_TO_CLIENT, StreamClose, StreamData,
StreamOpen, StreamOpenOk, StreamOpenReject, StreamWindowAdjust,
};
use crate::udp::is_transient_udp_send_error;
use anyhow::{Result, anyhow, bail};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::net::SocketAddr;
@@ -29,6 +30,7 @@ use tokio::net::UdpSocket;
pub const DEFAULT_INITIAL_WINDOW: usize = 1024 * 1024;
pub const DEFAULT_RETRANSMIT_AFTER: Duration = Duration::from_millis(200);
pub const DEFAULT_KEEPALIVE_AFTER: Duration = Duration::from_secs(2);
pub const DEFAULT_RETIRED_STREAM_TOMBSTONES: usize = 16 * 1024;
pub const SERVICE_TARGET_PREFIX: &str = "@dosh-";
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -36,6 +38,7 @@ pub struct TransportConfig {
pub initial_window: usize,
pub retransmit_after: Duration,
pub keepalive_after: Duration,
pub retired_stream_tombstones: usize,
}
impl Default for TransportConfig {
@@ -44,6 +47,7 @@ impl Default for TransportConfig {
initial_window: DEFAULT_INITIAL_WINDOW,
retransmit_after: DEFAULT_RETRANSMIT_AFTER,
keepalive_after: DEFAULT_KEEPALIVE_AFTER,
retired_stream_tombstones: DEFAULT_RETIRED_STREAM_TOMBSTONES,
}
}
}
@@ -120,6 +124,10 @@ pub struct AcceptedService {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportEvent {
Open(IncomingStreamOpen),
DuplicateOpen {
stream_id: u64,
response: OutgoingStreamPacket,
},
OpenOk {
stream_id: u64,
flushed: Vec<OutgoingStreamPacket>,
@@ -136,6 +144,9 @@ pub enum TransportEvent {
Close {
stream_id: u64,
},
Ignored {
stream_id: u64,
},
}
#[derive(Debug, Clone)]
@@ -165,6 +176,8 @@ pub struct StreamMux {
next_send_offset: HashMap<u64, u64>,
next_recv_offset: HashMap<u64, u64>,
recv_pending: HashMap<u64, BTreeMap<u64, Vec<u8>>>,
retired_streams: HashSet<u64>,
retired_stream_order: VecDeque<u64>,
}
#[derive(Debug, Clone, Default)]
@@ -220,6 +233,8 @@ impl StreamMux {
next_send_offset: HashMap::new(),
next_recv_offset: HashMap::new(),
recv_pending: HashMap::new(),
retired_streams: HashSet::new(),
retired_stream_order: VecDeque::new(),
}
}
@@ -230,7 +245,10 @@ impl StreamMux {
target_port: u16,
) -> Result<OutgoingStreamPacket> {
let target_host = target_host.into();
if self.opened_streams.contains(&stream_id) || self.pending_opens.contains_key(&stream_id) {
if self.opened_streams.contains(&stream_id)
|| self.pending_opens.contains_key(&stream_id)
|| self.retired_streams.contains(&stream_id)
{
bail!("stream {stream_id} already exists");
}
self.send_credit
@@ -257,6 +275,15 @@ impl StreamMux {
}
pub fn accept_open(&mut self, open: StreamOpen) -> Result<IncomingStreamOpen> {
if self.retired_streams.contains(&open.stream_id) {
bail!("stream {} was already closed", open.stream_id);
}
if self.pending_opens.contains_key(&open.stream_id) {
bail!(
"stream {} collides with a local pending open",
open.stream_id
);
}
self.opened_streams.insert(open.stream_id);
self.send_credit
.entry(open.stream_id)
@@ -284,19 +311,39 @@ impl StreamMux {
)
}
pub fn handle_open_ok(&mut self, ok: StreamOpenOk) -> Result<Vec<OutgoingStreamPacket>> {
self.pending_opens.remove(&ok.stream_id);
pub fn reject_open(
&mut self,
stream_id: u64,
reason: impl Into<String>,
) -> Result<OutgoingStreamPacket> {
if self.has_stream_state(stream_id) {
self.retire_stream(stream_id);
}
Self::open_reject(stream_id, reason)
}
pub fn handle_open_ok(
&mut self,
ok: StreamOpenOk,
) -> Result<Option<Vec<OutgoingStreamPacket>>> {
if self.pending_opens.remove(&ok.stream_id).is_none() {
return Ok(None);
}
self.opened_streams.insert(ok.stream_id);
self.send_credit
.entry(ok.stream_id)
.or_insert(self.config.initial_window);
self.next_send_offset.entry(ok.stream_id).or_insert(0);
self.next_recv_offset.entry(ok.stream_id).or_insert(0);
self.flush_pending_data(ok.stream_id)
self.flush_pending_data(ok.stream_id).map(Some)
}
pub fn handle_open_reject(&mut self, reject: StreamOpenReject) {
self.cleanup_stream(reject.stream_id);
pub fn handle_open_reject(&mut self, reject: StreamOpenReject) -> bool {
if !self.has_stream_state(reject.stream_id) {
return false;
}
self.retire_stream(reject.stream_id);
true
}
pub fn send_data(
@@ -308,8 +355,17 @@ impl StreamMux {
if bytes.is_empty() {
return Ok(Vec::new());
}
if !self.opened_streams.contains(&stream_id)
|| self.send_credit.get(&stream_id).copied().unwrap_or(0) < bytes.len()
if !self.opened_streams.contains(&stream_id) {
if self.pending_opens.contains_key(&stream_id) {
self.pending_data
.entry(stream_id)
.or_default()
.push_back(bytes);
return Ok(Vec::new());
}
bail!("stream {stream_id} is not open");
}
if self.send_credit.get(&stream_id).copied().unwrap_or(0) < bytes.len()
|| self
.pending_data
.get(&stream_id)
@@ -324,8 +380,11 @@ impl StreamMux {
Ok(vec![self.send_data_now(stream_id, bytes)?])
}
pub fn handle_data(&mut self, data: StreamData) -> Result<IncomingStreamData> {
pub fn handle_data(&mut self, data: StreamData) -> Result<Option<IncomingStreamData>> {
let stream_id = data.stream_id;
if !self.opened_streams.contains(&stream_id) {
return Ok(None);
}
let (chunks, consumed, received_offset) = self.accept_data(data);
let window_adjust = encode_packet(
PacketKind::StreamWindowAdjust,
@@ -335,68 +394,104 @@ impl StreamMux {
bytes: consumed.min(u32::MAX as usize) as u32,
},
)?;
Ok(IncomingStreamData {
Ok(Some(IncomingStreamData {
stream_id,
chunks,
consumed,
received_offset,
window_adjust,
})
}))
}
pub fn handle_window_adjust(
&mut self,
adjust: StreamWindowAdjust,
) -> Result<Vec<OutgoingStreamPacket>> {
self.ack_data(adjust.stream_id, adjust.received_offset);
self.add_credit(adjust.stream_id, adjust.bytes as usize);
self.flush_pending_data(adjust.stream_id)
) -> Result<Option<Vec<OutgoingStreamPacket>>> {
if !self.opened_streams.contains(&adjust.stream_id) {
return Ok(None);
}
let acked_bytes = self.ack_data(adjust.stream_id, adjust.received_offset);
self.add_credit(adjust.stream_id, acked_bytes);
self.flush_pending_data(adjust.stream_id).map(Some)
}
pub fn close_stream(&mut self, stream_id: u64) -> Result<OutgoingStreamPacket> {
self.cleanup_stream(stream_id);
if !self.has_stream_state(stream_id) {
bail!("stream {stream_id} is not open");
}
self.retire_stream(stream_id);
encode_packet(PacketKind::StreamClose, &StreamClose { stream_id })
}
pub fn handle_close(&mut self, close: StreamClose) {
self.cleanup_stream(close.stream_id);
pub fn handle_close(&mut self, close: StreamClose) -> bool {
if !self.has_stream_state(close.stream_id) {
return false;
}
self.retire_stream(close.stream_id);
true
}
pub fn handle_packet(&mut self, kind: PacketKind, body: &[u8]) -> Result<TransportEvent> {
match kind {
PacketKind::StreamOpen => {
let open: StreamOpen = protocol::from_body(body)?;
if self.retired_streams.contains(&open.stream_id) {
return Ok(TransportEvent::Ignored {
stream_id: open.stream_id,
});
}
if self.opened_streams.contains(&open.stream_id) {
return Ok(TransportEvent::DuplicateOpen {
stream_id: open.stream_id,
response: Self::open_ok(open.stream_id)?,
});
}
self.accept_open(open).map(TransportEvent::Open)
}
PacketKind::StreamOpenOk => {
let ok: StreamOpenOk = protocol::from_body(body)?;
let stream_id = ok.stream_id;
let flushed = self.handle_open_ok(ok)?;
Ok(TransportEvent::OpenOk { stream_id, flushed })
match self.handle_open_ok(ok)? {
Some(flushed) => Ok(TransportEvent::OpenOk { stream_id, flushed }),
None => Ok(TransportEvent::Ignored { stream_id }),
}
}
PacketKind::StreamOpenReject => {
let reject: StreamOpenReject = protocol::from_body(body)?;
self.handle_open_reject(reject.clone());
let stream_id = reject.stream_id;
if self.handle_open_reject(reject.clone()) {
Ok(TransportEvent::OpenReject {
stream_id: reject.stream_id,
stream_id,
reason: reject.reason,
})
} else {
Ok(TransportEvent::Ignored { stream_id })
}
}
PacketKind::StreamData => {
let data: StreamData = protocol::from_body(body)?;
self.handle_data(data).map(TransportEvent::Data)
let stream_id = data.stream_id;
match self.handle_data(data)? {
Some(data) => Ok(TransportEvent::Data(data)),
None => Ok(TransportEvent::Ignored { stream_id }),
}
}
PacketKind::StreamWindowAdjust => {
let adjust: StreamWindowAdjust = protocol::from_body(body)?;
let stream_id = adjust.stream_id;
let flushed = self.handle_window_adjust(adjust)?;
Ok(TransportEvent::WindowAdjust { stream_id, flushed })
match self.handle_window_adjust(adjust)? {
Some(flushed) => Ok(TransportEvent::WindowAdjust { stream_id, flushed }),
None => Ok(TransportEvent::Ignored { stream_id }),
}
}
PacketKind::StreamClose => {
let close: StreamClose = protocol::from_body(body)?;
let stream_id = close.stream_id;
self.handle_close(close);
if self.handle_close(close) {
Ok(TransportEvent::Close { stream_id })
} else {
Ok(TransportEvent::Ignored { stream_id })
}
}
_ => bail!("packet kind {kind:?} is not a stream transport packet"),
}
@@ -556,9 +651,9 @@ impl StreamMux {
(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 {
return;
return 0;
};
let acked_offsets = sent
.iter()
@@ -567,12 +662,16 @@ impl StreamMux {
(end <= received_offset).then_some(*offset)
})
.collect::<Vec<_>>();
let mut acked_bytes = 0usize;
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() {
self.sent_data.remove(&stream_id);
}
acked_bytes
}
fn add_credit(&mut self, stream_id: u64, bytes: usize) {
@@ -580,6 +679,32 @@ impl StreamMux {
*credit = credit.saturating_add(bytes).min(self.config.initial_window);
}
fn has_stream_state(&self, stream_id: u64) -> bool {
self.opened_streams.contains(&stream_id)
|| self.pending_opens.contains_key(&stream_id)
|| self.send_credit.contains_key(&stream_id)
|| self.pending_data.contains_key(&stream_id)
|| self.sent_data.contains_key(&stream_id)
|| self.next_send_offset.contains_key(&stream_id)
|| self.next_recv_offset.contains_key(&stream_id)
|| self.recv_pending.contains_key(&stream_id)
}
fn retire_stream(&mut self, stream_id: u64) {
self.cleanup_stream(stream_id);
if self.config.retired_stream_tombstones == 0 {
return;
}
if self.retired_streams.insert(stream_id) {
self.retired_stream_order.push_back(stream_id);
}
while self.retired_stream_order.len() > self.config.retired_stream_tombstones {
if let Some(expired) = self.retired_stream_order.pop_front() {
self.retired_streams.remove(&expired);
}
}
}
fn cleanup_stream(&mut self, stream_id: u64) {
self.opened_streams.remove(&stream_id);
self.pending_opens.remove(&stream_id);
@@ -620,7 +745,7 @@ impl DoshTransport {
ack_seq: config.initial_ack,
replay: ReplayWindow::default(),
mux: StreamMux::new(config.stream),
next_stream_id: 1,
next_stream_id: initial_stream_id(config.role),
last_contact: now,
last_keepalive: now,
}
@@ -664,7 +789,10 @@ impl DoshTransport {
pub fn allocate_stream_id(&mut self) -> u64 {
let id = self.next_stream_id;
self.next_stream_id = self.next_stream_id.saturating_add(1).max(1);
self.next_stream_id = self
.next_stream_id
.wrapping_add(1)
.max(initial_stream_id(self.role));
id
}
@@ -694,8 +822,8 @@ impl DoshTransport {
}
pub async fn reject_stream(&mut self, stream_id: u64, reason: impl Into<String>) -> Result<()> {
self.send_outgoing(StreamMux::open_reject(stream_id, reason)?)
.await
let packet = self.mux.reject_open(stream_id, reason)?;
self.send_outgoing(packet).await
}
pub async fn send(&mut self, stream_id: u64, bytes: impl Into<Vec<u8>>) -> Result<()> {
@@ -732,11 +860,17 @@ impl DoshTransport {
if packet.header.conn_id != self.conn_id {
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) {
continue;
}
let plain =
protocol::decrypt_body(&packet, &self.session_key, self.role.recv_direction())?;
self.peer_addr = peer;
self.ack_seq = self.ack_seq.max(packet.header.seq);
self.last_contact = Instant::now();
@@ -751,14 +885,21 @@ impl DoshTransport {
datagram: &[u8],
peer: SocketAddr,
) -> 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 {
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) {
return Ok(SessionEvent::Ignored);
}
let plain = protocol::decrypt_body(&packet, &self.session_key, self.role.recv_direction())?;
self.peer_addr = peer;
self.ack_seq = self.ack_seq.max(packet.header.seq);
self.last_contact = Instant::now();
@@ -793,6 +934,9 @@ impl DoshTransport {
async fn send_followups(&mut self, event: &TransportEvent) -> Result<()> {
match event {
TransportEvent::DuplicateOpen { response, .. } => {
self.send_outgoing(response.clone()).await?;
}
TransportEvent::OpenOk { flushed, .. }
| TransportEvent::WindowAdjust { flushed, .. } => {
for packet in flushed.clone() {
@@ -804,7 +948,8 @@ impl DoshTransport {
}
TransportEvent::Open(_)
| TransportEvent::OpenReject { .. }
| TransportEvent::Close { .. } => {}
| TransportEvent::Close { .. }
| TransportEvent::Ignored { .. } => {}
}
Ok(())
}
@@ -815,7 +960,12 @@ impl DoshTransport {
async fn send_kind(&mut self, kind: PacketKind, body: &[u8]) -> Result<()> {
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(())
}
@@ -834,6 +984,13 @@ impl DoshTransport {
}
}
fn initial_stream_id(role: SessionRole) -> u64 {
match role {
SessionRole::Client => 1,
SessionRole::Server => 1u64 << 63,
}
}
pub fn service_target(name: &str) -> Result<String> {
if name.is_empty()
|| !name
@@ -915,7 +1072,10 @@ mod tests {
assert!(mux.send_data(7, b"hello".to_vec()).unwrap().is_empty());
assert_eq!(mux.pending_bytes(7), 5);
let flushed = mux.handle_open_ok(StreamOpenOk { stream_id: 7 }).unwrap();
let flushed = mux
.handle_open_ok(StreamOpenOk { stream_id: 7 })
.unwrap()
.unwrap();
assert_eq!(flushed.len(), 1);
assert_eq!(flushed[0].kind, PacketKind::StreamData);
let data: StreamData = decode(&flushed[0]);
@@ -938,6 +1098,7 @@ mod tests {
offset: 5,
bytes: b"world".to_vec(),
})
.unwrap()
.unwrap();
assert!(first.chunks.is_empty());
assert_eq!(first.received_offset, 0);
@@ -948,6 +1109,7 @@ mod tests {
offset: 0,
bytes: b"hello".to_vec(),
})
.unwrap()
.unwrap();
assert_eq!(second.chunks, vec![b"hello".to_vec(), b"world".to_vec()]);
assert_eq!(second.consumed, 10);
@@ -962,7 +1124,9 @@ mod tests {
..TransportConfig::default()
});
mux.open_stream(1, "@dosh-test", 0).unwrap();
mux.handle_open_ok(StreamOpenOk { stream_id: 1 }).unwrap();
mux.handle_open_ok(StreamOpenOk { stream_id: 1 })
.unwrap()
.unwrap();
let sent = mux.send_data(1, b"hello".to_vec()).unwrap();
assert_eq!(sent.len(), 1);
assert!(mux.send_data(1, b"!".to_vec()).unwrap().is_empty());
@@ -973,6 +1137,7 @@ mod tests {
received_offset: 5,
bytes: 5,
})
.unwrap()
.unwrap();
assert_eq!(flushed.len(), 1);
let data: StreamData = decode(&flushed[0]);
@@ -980,6 +1145,33 @@ mod tests {
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()
.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()
.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]
fn handle_packet_decodes_and_dispatches_stream_packets() {
let mut mux = StreamMux::new(TransportConfig::default());
@@ -1000,6 +1192,281 @@ mod tests {
);
}
#[test]
fn duplicate_stream_open_reacks_without_second_open_event() {
let mut mux = StreamMux::new(TransportConfig::default());
let open = StreamOpen {
stream_id: 9,
target_host: "@dosh-app".to_string(),
target_port: 0,
};
let body = protocol::to_body(&open).unwrap();
assert!(matches!(
mux.handle_packet(PacketKind::StreamOpen, &body).unwrap(),
TransportEvent::Open(_)
));
let duplicate = mux.handle_packet(PacketKind::StreamOpen, &body).unwrap();
match duplicate {
TransportEvent::DuplicateOpen {
stream_id,
response,
} => {
assert_eq!(stream_id, 9);
assert_eq!(response.kind, PacketKind::StreamOpenOk);
let ok: StreamOpenOk = decode(&response);
assert_eq!(ok.stream_id, 9);
}
other => panic!("unexpected duplicate open event {other:?}"),
}
}
#[test]
fn send_data_to_closed_or_unknown_stream_fails() {
let mut mux = StreamMux::new(TransportConfig::default());
mux.open_stream(1, "@dosh-test", 0).unwrap();
assert!(mux.send_data(1, b"queued".to_vec()).unwrap().is_empty());
mux.handle_open_ok(StreamOpenOk { stream_id: 1 })
.unwrap()
.unwrap();
mux.close_stream(1).unwrap();
assert!(mux.send_data(1, b"lost".to_vec()).is_err());
assert!(mux.send_data(99, b"lost".to_vec()).is_err());
}
#[test]
fn rejecting_incoming_stream_retires_local_state() {
let mut mux = StreamMux::new(TransportConfig::default());
mux.accept_open(StreamOpen {
stream_id: 7,
target_host: "@dosh-test".to_string(),
target_port: 0,
})
.unwrap();
assert!(mux.is_open(7));
let reject = mux.reject_open(7, "nope").unwrap();
assert_eq!(reject.kind, PacketKind::StreamOpenReject);
assert!(!mux.is_open(7));
assert!(mux.retired_streams.contains(&7));
assert!(mux.send_data(7, b"must-not-send".to_vec()).is_err());
assert!(
mux.accept_open(StreamOpen {
stream_id: 7,
target_host: "@dosh-test".to_string(),
target_port: 0,
})
.is_err()
);
}
#[test]
fn stale_packets_after_close_do_not_recreate_stream_state() {
let mut mux = StreamMux::new(TransportConfig::default());
mux.open_stream(1, "@dosh-test", 0).unwrap();
mux.handle_open_ok(StreamOpenOk { stream_id: 1 })
.unwrap()
.unwrap();
assert_eq!(mux.send_data(1, b"hello".to_vec()).unwrap().len(), 1);
mux.close_stream(1).unwrap();
let stale_data = protocol::to_body(&StreamData {
stream_id: 1,
offset: 0,
bytes: b"stale".to_vec(),
})
.unwrap();
assert_eq!(
mux.handle_packet(PacketKind::StreamData, &stale_data)
.unwrap(),
TransportEvent::Ignored { stream_id: 1 }
);
let stale_open_ok = protocol::to_body(&StreamOpenOk { stream_id: 1 }).unwrap();
assert_eq!(
mux.handle_packet(PacketKind::StreamOpenOk, &stale_open_ok)
.unwrap(),
TransportEvent::Ignored { stream_id: 1 }
);
let stale_adjust = protocol::to_body(&StreamWindowAdjust {
stream_id: 1,
received_offset: 5,
bytes: 5,
})
.unwrap();
assert_eq!(
mux.handle_packet(PacketKind::StreamWindowAdjust, &stale_adjust)
.unwrap(),
TransportEvent::Ignored { stream_id: 1 }
);
let stale_open = protocol::to_body(&StreamOpen {
stream_id: 1,
target_host: "@dosh-test".to_string(),
target_port: 0,
})
.unwrap();
assert_eq!(
mux.handle_packet(PacketKind::StreamOpen, &stale_open)
.unwrap(),
TransportEvent::Ignored { stream_id: 1 }
);
let stale_close = protocol::to_body(&StreamClose { stream_id: 1 }).unwrap();
assert_eq!(
mux.handle_packet(PacketKind::StreamClose, &stale_close)
.unwrap(),
TransportEvent::Ignored { stream_id: 1 }
);
assert!(!mux.is_open(1));
assert!(!mux.pending_opens.contains_key(&1));
assert!(!mux.send_credit.contains_key(&1));
assert!(!mux.pending_data.contains_key(&1));
assert!(!mux.sent_data.contains_key(&1));
assert!(!mux.next_send_offset.contains_key(&1));
assert!(!mux.next_recv_offset.contains_key(&1));
assert!(!mux.recv_pending.contains_key(&1));
assert!(mux.retired_streams.contains(&1));
}
#[test]
fn retired_stream_tombstones_are_bounded() {
let mut mux = StreamMux::new(TransportConfig {
retired_stream_tombstones: 2,
..TransportConfig::default()
});
for stream_id in 1..=3 {
mux.open_stream(stream_id, "@dosh-test", 0).unwrap();
mux.close_stream(stream_id).unwrap();
}
assert_eq!(mux.retired_streams.len(), 2);
assert!(!mux.retired_streams.contains(&1));
assert!(mux.retired_streams.contains(&2));
assert!(mux.retired_streams.contains(&3));
let stale_open = protocol::to_body(&StreamOpen {
stream_id: 3,
target_host: "@dosh-test".to_string(),
target_port: 0,
})
.unwrap();
assert_eq!(
mux.handle_packet(PacketKind::StreamOpen, &stale_open)
.unwrap(),
TransportEvent::Ignored { stream_id: 3 }
);
}
#[tokio::test]
async fn session_transport_partitions_client_and_server_stream_ids() {
let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client_addr = client_socket.local_addr().unwrap();
let server_addr = server_socket.local_addr().unwrap();
let key = [44u8; 32];
let conn_id = [8u8; 16];
let mut client = DoshTransport::new_owned(
client_socket,
SessionTransportConfig {
role: SessionRole::Client,
conn_id,
session_key: key,
peer_addr: server_addr,
initial_send_seq: 1,
initial_ack: 0,
stream: TransportConfig::default(),
},
);
let mut server = DoshTransport::new_owned(
server_socket,
SessionTransportConfig {
role: SessionRole::Server,
conn_id,
session_key: key,
peer_addr: client_addr,
initial_send_seq: 1,
initial_ack: 0,
stream: TransportConfig::default(),
},
);
assert_eq!(client.allocate_stream_id(), 1);
assert_eq!(client.allocate_stream_id(), 2);
assert_eq!(server.allocate_stream_id(), 1u64 << 63);
assert_eq!(server.allocate_stream_id(), (1u64 << 63) + 1);
}
#[tokio::test]
async fn session_transport_handles_simultaneous_opens_without_id_collision() {
let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client_addr = client_socket.local_addr().unwrap();
let server_addr = server_socket.local_addr().unwrap();
let key = [45u8; 32];
let conn_id = [9u8; 16];
let mut client = DoshTransport::new_owned(
client_socket,
SessionTransportConfig {
role: SessionRole::Client,
conn_id,
session_key: key,
peer_addr: server_addr,
initial_send_seq: 1,
initial_ack: 0,
stream: TransportConfig::default(),
},
);
let mut server = DoshTransport::new_owned(
server_socket,
SessionTransportConfig {
role: SessionRole::Server,
conn_id,
session_key: key,
peer_addr: client_addr,
initial_send_seq: 1,
initial_ack: 0,
stream: TransportConfig::default(),
},
);
let client_stream = client.open_service("client_app").await.unwrap();
let server_stream = server.open_service("server_app").await.unwrap();
assert_ne!(client_stream, server_stream);
let server_seen = server.recv().await.unwrap();
let client_seen = client.recv().await.unwrap();
match server_seen {
SessionEvent::Stream(TransportEvent::Open(open)) => {
assert_eq!(open.stream_id, client_stream);
assert_eq!(open.target_host, "@dosh-client_app");
server.accept_stream(open.stream_id).await.unwrap();
}
other => panic!("unexpected server event {other:?}"),
}
match client_seen {
SessionEvent::Stream(TransportEvent::Open(open)) => {
assert_eq!(open.stream_id, server_stream);
assert_eq!(open.target_host, "@dosh-server_app");
client.accept_stream(open.stream_id).await.unwrap();
}
other => panic!("unexpected client event {other:?}"),
}
assert!(matches!(
client.recv().await.unwrap(),
SessionEvent::Stream(TransportEvent::OpenOk { stream_id, .. }) if stream_id == client_stream
));
assert!(matches!(
server.recv().await.unwrap(),
SessionEvent::Stream(TransportEvent::OpenOk { stream_id, .. }) if stream_id == server_stream
));
}
#[tokio::test]
async fn session_transport_opens_service_and_moves_data_over_encrypted_udp() {
let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -1060,6 +1527,63 @@ mod tests {
}
}
#[tokio::test]
async fn session_transport_reject_stream_retires_server_state() {
let client_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let server_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let client_addr = client_socket.local_addr().unwrap();
let server_addr = server_socket.local_addr().unwrap();
let key = [46u8; 32];
let conn_id = [10u8; 16];
let mut client = DoshTransport::new_owned(
client_socket,
SessionTransportConfig {
role: SessionRole::Client,
conn_id,
session_key: key,
peer_addr: server_addr,
initial_send_seq: 1,
initial_ack: 0,
stream: TransportConfig::default(),
},
);
let mut server = DoshTransport::new_owned(
server_socket,
SessionTransportConfig {
role: SessionRole::Server,
conn_id,
session_key: key,
peer_addr: client_addr,
initial_send_seq: 1,
initial_ack: 0,
stream: TransportConfig::default(),
},
);
let stream_id = client.open_service("app").await.unwrap();
match server.recv().await.unwrap() {
SessionEvent::Stream(TransportEvent::Open(open)) => {
assert_eq!(open.stream_id, stream_id);
assert!(server.mux().is_open(stream_id));
server.reject_stream(stream_id, "disabled").await.unwrap();
}
other => panic!("unexpected event {other:?}"),
}
assert!(!server.mux().is_open(stream_id));
assert!(
server
.send(stream_id, b"must-not-send".to_vec())
.await
.is_err()
);
assert!(matches!(
client.recv().await.unwrap(),
SessionEvent::Stream(TransportEvent::OpenReject { stream_id: rejected, reason })
if rejected == stream_id && reason == "disabled"
));
}
#[tokio::test]
async fn session_transport_roams_to_authenticated_new_peer_addr() {
let server_socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -1096,4 +1620,61 @@ mod tests {
assert!(matches!(server.recv().await.unwrap(), SessionEvent::Ping));
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
View File
@@ -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
View File
@@ -258,7 +258,8 @@ fn relay_loop(
let mut upstream = new_upstream();
let mut client_addr: Option<SocketAddr> = None;
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];
loop {
@@ -288,10 +289,9 @@ fn relay_loop(
&upstream,
server_addr,
packet,
true,
&controls,
&mut rng,
&mut held,
&mut held_c2s,
);
}
}
@@ -310,7 +310,12 @@ fn relay_loop(
let drop_pct = controls.drop_s2c_percent.load(Ordering::SeqCst);
if drop_pct == 0 || rng.gen_range(0..100) >= drop_pct {
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,
dst: SocketAddr,
packet: Vec<u8>,
is_c2s: bool,
controls: &RelayControls,
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
// afterward (so two consecutive packets swap order).
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(&prev, dst);
return;
}
*held = Some((packet, is_c2s));
*held = Some(packet);
return;
}
if let Some((prev, _)) = held.take() {
if let Some(prev) = held.take() {
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)
}
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]
fn session_survives_packet_loss_and_reorder() {
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]
fn duplicated_and_replayed_input_is_applied_at_most_once() {
let dir = tempfile::tempdir().unwrap();
+467 -29
View File
@@ -18,7 +18,8 @@ use dosh::crypto;
use dosh::native::{host_public_key, load_or_create_host_key, ssh_ed25519_public_blob, trust_host};
use dosh::protocol::{
self, AttachOk, AttachReject, BootstrapAttachRequest, CLIENT_TO_SERVER, Frame, Input,
PacketKind, Resize, ResumeRequest, SERVER_TO_CLIENT,
PacketKind, Resize, ResumeRequest, SERVER_TO_CLIENT, TicketAttachBody, TicketAttachEnvelope,
TicketAttachOkEnvelope,
};
use ed25519_dalek::{Signer, SigningKey, VerifyingKey};
@@ -98,6 +99,35 @@ persist_sessions = false
config
}
fn write_server_config_with_output_interval(
dir: &tempfile::TempDir,
port: u16,
output_frame_interval_ms: u64,
) -> std::path::PathBuf {
let config = write_server_config(dir, port);
let mut raw = fs::read_to_string(&config).unwrap();
raw.push_str(&format!(
"output_frame_interval_ms = {output_frame_interval_ms}\n"
));
fs::write(&config, raw).unwrap();
config
}
fn write_server_config_with_retransmit_window(
dir: &tempfile::TempDir,
port: u16,
retransmit_window: u64,
) -> std::path::PathBuf {
let config = write_server_config(dir, port);
let mut raw = fs::read_to_string(&config).unwrap();
raw = raw.replace(
"retransmit_window = 256\n",
&format!("retransmit_window = {retransmit_window}\n"),
);
fs::write(&config, raw).unwrap();
config
}
fn start_server(dir: &tempfile::TempDir, config: &std::path::Path) -> Child {
let server = env!("CARGO_BIN_EXE_dosh-server");
let child = Command::new(server)
@@ -501,6 +531,75 @@ fn direct_attach_session(
(socket, bootstrap, ok)
}
fn ticket_attach_session(
socket: &UdpSocket,
port: u16,
bootstrap: &dosh::auth::BootstrapResponse,
session: &str,
mode: &str,
) -> AttachOk {
let client_nonce = crypto::random_12();
let request_key = crypto::hkdf32(
&bootstrap.attach_ticket_psk,
&client_nonce,
b"dosh/ticket-attach-request/v1",
)
.unwrap();
let body = protocol::to_body(&TicketAttachBody {
session: session.to_string(),
mode: mode.to_string(),
cols: 80,
rows: 24,
requested_env: Vec::new(),
})
.unwrap();
let ciphertext = crypto::seal(
&request_key,
&client_nonce,
b"dosh-ticket-attach-request-v1",
&body,
)
.unwrap();
let envelope = TicketAttachEnvelope {
ticket: bootstrap.attach_ticket.clone(),
client_nonce,
ciphertext,
};
let packet = protocol::encode_plain(
PacketKind::TicketAttachRequest,
[0u8; 16],
1,
0,
&protocol::to_body(&envelope).unwrap(),
)
.unwrap();
socket
.send_to(&packet, format!("127.0.0.1:{port}"))
.unwrap();
let mut buf = [0u8; 65535];
let (n, _) = socket.recv_from(&mut buf).unwrap();
let packet = protocol::decode(&buf[..n]).unwrap();
assert_eq!(packet.header.kind, PacketKind::AttachOk);
let envelope: TicketAttachOkEnvelope = protocol::from_body(&packet.body).unwrap();
let mut salt = Vec::with_capacity(24);
salt.extend_from_slice(&client_nonce);
salt.extend_from_slice(&envelope.server_nonce);
let response_key = crypto::hkdf32(
&bootstrap.attach_ticket_psk,
&salt,
b"dosh/ticket-attach-ok/v1",
)
.unwrap();
let plain = crypto::open(
&response_key,
&envelope.server_nonce,
b"dosh-ticket-attach-ok-v1",
&envelope.ciphertext,
)
.unwrap();
protocol::from_body(&plain).unwrap()
}
#[allow(clippy::too_many_arguments)]
fn send_encrypted(
socket: &UdpSocket,
@@ -1009,6 +1108,117 @@ fn native_file_copy_recursive_round_trip() {
let _ = server.wait();
}
#[test]
fn native_file_copy_resume_truncates_oversized_destinations() {
let dir = tempfile::tempdir().unwrap();
let port = free_udp_port();
let config = write_server_config(&dir, port);
write_native_client_auth(&dir, &config);
let mut server = start_server(&dir, &config);
let client_bin = env!("CARGO_BIN_EXE_dosh-client");
let local_short = dir.path().join("short.txt");
fs::write(&local_short, b"short\n").unwrap();
let seed_remote = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("exec")
.arg("local")
.arg("printf 'short\\nSTALE' > \"$HOME/resume-upload.txt\"")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
seed_remote.status.success(),
"seed remote failed: stdout={} stderr={}",
String::from_utf8_lossy(&seed_remote.stdout),
String::from_utf8_lossy(&seed_remote.stderr)
);
let resume_upload = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("cp")
.arg("--resume")
.arg(&local_short)
.arg("local:resume-upload.txt")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
resume_upload.status.success(),
"resume upload failed: stdout={} stderr={}",
String::from_utf8_lossy(&resume_upload.stdout),
String::from_utf8_lossy(&resume_upload.stderr)
);
let cat_upload = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("cat")
.arg("local:resume-upload.txt")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
cat_upload.status.success(),
"cat upload failed: stdout={} stderr={}",
String::from_utf8_lossy(&cat_upload.stdout),
String::from_utf8_lossy(&cat_upload.stderr)
);
assert_eq!(String::from_utf8_lossy(&cat_upload.stdout), "short\n");
let seed_download = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("exec")
.arg("local")
.arg("printf 'tiny\\n' > \"$HOME/resume-download.txt\"")
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
seed_download.status.success(),
"seed download failed: stdout={} stderr={}",
String::from_utf8_lossy(&seed_download.stdout),
String::from_utf8_lossy(&seed_download.stderr)
);
let local_download = dir.path().join("resume-download-local.txt");
fs::write(&local_download, b"tiny\nSTALE").unwrap();
let resume_download = Command::new(client_bin)
.arg("--dosh-host")
.arg("127.0.0.1")
.arg("--dosh-port")
.arg(port.to_string())
.arg("cp")
.arg("--resume")
.arg("local:resume-download.txt")
.arg(&local_download)
.env("HOME", dir.path())
.output()
.unwrap();
assert!(
resume_download.status.success(),
"resume download failed: stdout={} stderr={}",
String::from_utf8_lossy(&resume_download.stdout),
String::from_utf8_lossy(&resume_download.stderr)
);
assert_eq!(fs::read_to_string(&local_download).unwrap(), "tiny\n");
let _ = server.kill();
let _ = server.wait();
}
#[test]
fn native_exec_command_smoke() {
let dir = tempfile::tempdir().unwrap();
@@ -1363,18 +1573,10 @@ fn server_retransmits_unacked_output_frames() {
);
let mut seen = Vec::new();
let mut duplicate = None;
let deadline = std::time::Instant::now() + Duration::from_secs(3);
let deadline = std::time::Instant::now() + Duration::from_secs(4);
while std::time::Instant::now() < deadline {
if let Some((header, frame)) = recv_frame(&socket, &bootstrap.session_key) {
if String::from_utf8_lossy(&frame.bytes).contains("DOSH_RETRANSMIT") {
if seen
.iter()
.any(|(_, output_seq)| *output_seq == frame.output_seq)
{
duplicate = Some((header.seq, frame.output_seq));
break;
}
seen.push((header.seq, frame.output_seq));
}
}
@@ -1383,9 +1585,18 @@ fn server_retransmits_unacked_output_frames() {
let _ = server.kill();
let _ = server.wait();
let max_same_output_seq = seen
.iter()
.map(|(_, output_seq)| {
seen.iter()
.filter(|(_, candidate)| candidate == output_seq)
.count()
})
.max()
.unwrap_or(0);
assert!(
duplicate.is_some(),
"expected retransmitted same output seq, seen={seen:?}"
max_same_output_seq >= 10,
"expected retransmission to continue past the old 8-attempt ceiling, seen={seen:?}"
);
}
@@ -1639,6 +1850,110 @@ fn unicode_output_survives_transport() {
);
}
#[test]
fn tui_graph_glyphs_survive_fast_repaints_without_snapshot_substitution() {
let dir = tempfile::tempdir().unwrap();
let port = free_udp_port();
let config = write_server_config_with_output_interval(&dir, port, 1000);
let mut server = start_server(&dir, &config);
let (socket, bootstrap, ok) = direct_attach(&config, port, "read-write");
let graph = "DOSH_GRAPH ⣀⣤⣶⣿ █▇▆▅▄▃▂▁ ╭╮╯╰";
let input = Input {
bytes: format!(
"printf '\\033[?1049h\\033[?25l'; for i in 1 2 3 4 5; do printf '\\033[H{} %s\\n' \"$i\"; done; printf '\\033[?25h\\033[?1049l'\n",
graph
)
.into_bytes(),
};
send_encrypted(
&socket,
port,
PacketKind::Input,
ok.client_id,
2,
0,
&bootstrap.session_key,
&protocol::to_body(&input).unwrap(),
);
let text = collect_frame_text(&socket, &bootstrap.session_key, 3000);
let _ = server.kill();
let _ = server.wait();
assert!(
text.contains(graph) && text.matches("DOSH_GRAPH").count() >= 5,
"expected repeated raw graph glyph frames, got {text:?}"
);
assert!(
text.contains("\x1b[?25l") && text.contains("\x1b[?25h"),
"expected cursor visibility controls to survive around graph repaint, got {text:?}"
);
}
#[test]
fn btop_style_graph_output_stays_raw_when_retransmit_history_overflows() {
let dir = tempfile::tempdir().unwrap();
let port = free_udp_port();
let config = write_server_config_with_retransmit_window(&dir, port, 3);
let mut server = start_server(&dir, &config);
let (socket, bootstrap, ok) = direct_attach(&config, port, "read-write");
let graph = "DOSH_BTOP_NET ⠀⠁⠃⠇⡇⣇⣧⣷⣿";
let input = Input {
bytes: format!(
"stty -echo; \
printf '\\033[?1049h\\033[?2026h\\033[?25l'; \
for i in 1 2 3 4 5 6 7 8 9 10; do \
printf '\\033[6;4H\\033[38;2;80;220;140m{} %s\\033[0m' \"$i\"; \
done; \
printf '\\033[?25h\\033[?2026l\\033[?1049l'\n",
graph
)
.into_bytes(),
};
send_encrypted(
&socket,
port,
PacketKind::Input,
ok.client_id,
2,
0,
&bootstrap.session_key,
&protocol::to_body(&input).unwrap(),
);
let mut text = String::new();
let mut snapshots = 0usize;
let deadline = std::time::Instant::now() + Duration::from_secs(3);
while std::time::Instant::now() < deadline
&& !(text.matches("DOSH_BTOP_NET").count() >= 10 && text.contains("\x1b[?2026l"))
{
if let Some((_header, frame)) = recv_frame(&socket, &bootstrap.session_key) {
if frame.snapshot {
snapshots += 1;
}
text.push_str(&String::from_utf8_lossy(&frame.bytes));
}
}
let _ = server.kill();
let _ = server.wait();
assert_eq!(
snapshots, 0,
"live btop-style graph output must not be replaced by snapshots; got {snapshots}"
);
assert!(
text.matches("DOSH_BTOP_NET").count() >= 10
&& text.contains("")
&& text.contains("\x1b[38;2;80;220;140m")
&& text.contains("\x1b[?2026h")
&& text.contains("\x1b[?2026l"),
"expected raw btop-style graph output to survive under retransmit pressure, got {text:?}"
);
}
#[test]
fn large_tui_paint_is_delivered_in_mtu_safe_frames() {
let dir = tempfile::tempdir().unwrap();
@@ -2385,6 +2700,9 @@ fn write_persistent_server_config(dir: &tempfile::TempDir, port: u16) -> std::pa
let mut raw = fs::read_to_string(&config).unwrap();
// The base writer hardcodes `persist_sessions = false`; flip it on.
raw = raw.replace("persist_sessions = false", "persist_sessions = true");
// Persistence tests attach the sessions they need explicitly. Leaving the
// base prewarm on here creates a detached default holder in every test.
raw = raw.replace("prewarm_sessions = [\"default\"]", "prewarm_sessions = []");
fs::write(&config, raw).unwrap();
config
}
@@ -2420,6 +2738,45 @@ fn kill_holder(sessions_dir: &Path, session: &str) {
.status();
}
/// Create a holder the way older Dosh builds did for implicit sessions, so
/// startup migration can be tested without depending on the new spawn policy.
fn spawn_legacy_holder(sessions_dir: &Path, session: &str) {
let server = env!("CARGO_BIN_EXE_dosh-server");
let runtime_dir = dosh::persist::ensure_runtime_dir(sessions_dir, session).unwrap();
let mut launcher = Command::new(server)
.arg("hold")
.arg("--runtime-dir")
.arg(&runtime_dir)
.arg("--session")
.arg(session)
.arg("--shell")
.arg("/bin/sh")
.arg("--cols")
.arg("80")
.arg("--rows")
.arg("24")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap();
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while std::time::Instant::now() < deadline {
if holder_shell_pid(sessions_dir, session).is_some()
&& runtime_dir.join("holder.sock").exists()
{
let _ = launcher.wait();
return;
}
if let Some(status) = launcher.try_wait().unwrap() {
panic!("legacy holder launcher exited before ready: {status}");
}
thread::sleep(Duration::from_millis(20));
}
let _ = launcher.kill();
let _ = launcher.wait();
panic!("legacy holder did not become ready");
}
/// Send one encrypted Input line and give the shell a moment to act.
fn type_line(socket: &UdpSocket, port: u16, ok: &AttachOk, key: &[u8; 32], seq: u64, line: &str) {
let input = Input {
@@ -2557,7 +2914,7 @@ fn session_survives_server_restart_same_shell_and_screen() {
}
#[test]
fn implicit_session_survives_server_restart_for_same_ticket_holder() {
fn implicit_session_survives_update_restart_via_ticket_reattach() {
let dir = tempfile::tempdir().unwrap();
let sessions_dir = dir.path().join("sessions");
let port = free_udp_port();
@@ -2567,59 +2924,140 @@ fn implicit_session_survives_server_restart_for_same_ticket_holder() {
let mut server = start_server(&dir, &config);
let (socket, bootstrap, ok) = direct_attach_session(&config, port, "read-write", &session);
let key = bootstrap.session_key;
type_line(&socket, port, &ok, &key, 2, "cd /tmp\n");
type_line(
&socket,
port,
&ok,
&key,
2,
3,
"export IMPLICIT_MARK=implicit_restart_42\n",
);
let _ = collect_frame_text(&socket, &key, 1000);
type_line(
&socket,
port,
&ok,
&key,
4,
"printf 'IMPLICIT_SCREEN_MARKER\\n'\n",
);
let pre = collect_frame_text(&socket, &key, 1500);
assert!(
pre.contains("IMPLICIT_SCREEN_MARKER"),
"implicit marker missing before restart: {pre:?}"
);
thread::sleep(Duration::from_secs(3));
let shell_pid_before = holder_shell_pid(&sessions_dir, &session);
assert!(
shell_pid_before.is_some(),
"implicit sessions should get a persistent holder when persistence is enabled"
"implicit sessions must get temporary holders so active clients survive updates"
);
let _ = server.kill();
let _ = server.wait();
thread::sleep(Duration::from_millis(300));
let pid = shell_pid_before.unwrap();
assert!(
unsafe { libc::kill(pid, 0) } == 0,
"implicit session shell pid {pid} must survive server restart"
);
let mut server = start_server(&dir, &config);
let (socket2, bootstrap2, ok2) = direct_attach_session(&config, port, "read-write", &session);
let key2 = bootstrap2.session_key;
let resume = ResumeRequest {
session: session.clone(),
last_rendered_seq: ok.initial_seq,
cols: 80,
rows: 24,
};
send_encrypted(
&socket,
port,
PacketKind::ResumeRequest,
ok.client_id,
5,
0,
&key,
&protocol::to_body(&resume).unwrap(),
);
let mut buf = [0u8; 65535];
let deadline = std::time::Instant::now() + Duration::from_secs(2);
loop {
assert!(
std::time::Instant::now() < deadline,
"old live resume did not receive unknown-client reject"
);
let (n, _) = socket.recv_from(&mut buf).unwrap();
let packet = protocol::decode(&buf[..n]).unwrap();
if packet.header.kind == PacketKind::Frame {
continue;
}
assert_eq!(packet.header.kind, PacketKind::AttachReject);
assert_eq!(packet.header.conn_id, ok.client_id);
break;
}
let ok2 = ticket_attach_session(&socket, port, &bootstrap, &session, "read-write");
let key2 = ok2.session_key;
let snapshot = String::from_utf8_lossy(&ok2.snapshot).to_string();
type_line(
&socket2,
&socket,
port,
&ok2,
&key2,
2,
"printf 'IMPLICIT_MARK=%s\\n' \"$IMPLICIT_MARK\"\n",
"printf 'IMPLICIT_MARK=%s PWD=%s\\n' \"$IMPLICIT_MARK\" \"$PWD\"\n",
);
let post = collect_frame_text(&socket2, &key2, 2000);
let post = collect_frame_text(&socket, &key2, 2000);
let shell_pid_after = holder_shell_pid(&sessions_dir, &session);
let _ = server.kill();
let _ = server.wait();
kill_holder(&sessions_dir, &session);
assert!(
snapshot.contains("IMPLICIT_SCREEN_MARKER"),
"ticket reattach snapshot must repaint the exact pre-update screen, got {snapshot:?}"
);
assert_eq!(
shell_pid_after, shell_pid_before,
"implicit session should re-adopt the same shell pid"
"implicit update reconnect must use the same holder shell"
);
assert!(
post.contains("IMPLICIT_MARK=implicit_restart_42"),
"implicit session state must survive 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]
fn startup_readopts_implicit_holders_for_update_reconnect() {
let dir = tempfile::tempdir().unwrap();
let sessions_dir = dir.path().join("sessions");
let port = free_udp_port();
let config = write_persistent_server_config(&dir, port);
let session = protocol::generate_implicit_session_name();
spawn_legacy_holder(&sessions_dir, &session);
let shell_pid = holder_shell_pid(&sessions_dir, &session).expect("legacy holder shell pid");
assert!(
unsafe { libc::kill(shell_pid, 0) } == 0,
"legacy holder shell must be live before startup"
);
let mut server = start_server(&dir, &config);
thread::sleep(Duration::from_millis(300));
let _ = server.kill();
let _ = server.wait();
assert!(
holder_shell_pid(&sessions_dir, &session).is_some(),
"startup must keep live implicit holders so active update reconnects can reattach"
);
assert!(
unsafe { libc::kill(shell_pid, 0) } == 0,
"startup must not shut down a live implicit holder before reconnect grace"
);
kill_holder(&sessions_dir, &session);
}
#[test]
+13
View File
@@ -58,6 +58,19 @@ fn encrypted_packet_round_trips() {
assert_eq!(plain, b"hello");
}
#[test]
fn plaintext_packet_never_decrypts_as_authenticated_body() {
let key = crypto::random_32();
let mut decoded = protocol::decode(
&protocol::encode_plain(PacketKind::Input, crypto::random_16(), 1, 0, b"hello").unwrap(),
)
.unwrap();
decoded.header.session_key_id = protocol::session_key_id(&key);
let err = protocol::decrypt_body(&decoded, &key, CLIENT_TO_SERVER).unwrap_err();
assert!(err.to_string().contains("not encrypted"));
}
#[test]
fn encrypted_packet_rejects_wrong_session_key_id_before_decrypt() {
let key = crypto::random_32();
+52
View File
@@ -0,0 +1,52 @@
#[test]
fn quiet_update_keeps_prebuilt_enabled_by_default() {
let install = include_str!("../install.sh");
assert!(install.contains("use_prebuilt=\"${DOSH_USE_PREBUILT:-1}\""));
assert!(
!install.contains("use_prebuilt=0"),
"quiet updates must not force source builds"
);
}
#[test]
fn release_scripts_skip_stale_artifacts_when_auto_discovering() {
let upload = include_str!("../scripts/upload-gitea-release.sh");
assert!(upload.contains("skipping $artifact: version"));
assert!(upload.contains("expected_version"));
let publish = include_str!("../scripts/publish-gitea-release.sh");
assert!(publish.contains("skipping stale artifact"));
assert!(publish.contains("actual=\"$(artifact_version \"$artifact\" || true)\""));
}
#[test]
fn systemd_service_does_not_sandbox_remote_shells() {
let service = include_str!("../packaging/systemd/dosh-server.service");
let install = include_str!("../install.sh");
for raw in [service, install] {
assert!(raw.contains("KillMode=process"));
assert!(
raw.contains("Restart=always"),
"dosh-server should come back after accidental SIGTERM while preserving child shells"
);
for directive in [
"NoNewPrivileges=",
"PrivateTmp=",
"ProtectSystem=",
"ProtectHome=",
"RestrictAddressFamilies=",
"RestrictRealtime=",
"LockPersonality=",
"MemoryDenyWriteExecute=",
] {
assert!(
!raw.contains(directive),
"dosh sessions are user shells; systemd sandbox directive {directive} changes terminal/app behavior"
);
}
assert!(
!raw.contains("ReadWritePaths="),
"remote shells must not be restricted to dosh config/data paths"
);
}
}