Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(connect): let connected servers reach local terminals

RoversXa2cc2a40fbe4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cbf47f52..84133e52 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -493,7 +493,7 @@ jobs:
shell: cmd
run: |
PATH C:\Strawberry\perl\bin;%PATH%
- cargo build --profile %CARGO_PROFILE% -p wezterm -p wezterm-gui -p wezterm-mux-server -p thinkterm-plugin-server -p strip-ansi-escapes
+ cargo build --profile %CARGO_PROFILE% -p wezterm -p wezterm-gui -p thinkterm-connect-auth -p wezterm-mux-server -p thinkterm-plugin-server -p strip-ansi-escapes
- name: Fetch the browser bundle
uses: actions/download-artifact@v8
@@ -628,6 +628,7 @@ jobs:
cargo build --profile "$CARGO_PROFILE" \
-p wezterm \
-p wezterm-gui \
+ -p thinkterm-connect-auth \
-p wezterm-mux-server \
-p thinkterm-plugin-server \
-p thinkterm-tailnet-node \
diff --git a/Cargo.lock b/Cargo.lock
index 0e38795d..a72b2c0b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2232,6 +2232,12 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "780955b8b195a21ab8e4ac6b60dd1dbdcec1dc6c51c0617964b08c81785e12c9"
+[[package]]
+name = "doctest-file"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2db04e74f0a9a93103b50e90b96024c9b2bdca8bce6a632ec71b88736d3d359"
+
[[package]]
name = "document-features"
version = "0.2.12"
@@ -4328,6 +4334,21 @@ dependencies = [
"syn 2.0.110",
]
+[[package]]
+name = "interprocess"
+version = "2.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4a4fff6c51dece332bdbf3af5fe376c49cfc8dced782725e95be0bb489e35d7"
+dependencies = [
+ "doctest-file",
+ "futures-core",
+ "libc",
+ "recvmsg",
+ "tokio",
+ "widestring",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "intl-memoizer"
version = "0.5.3"
@@ -5406,6 +5427,7 @@ dependencies = [
"fancy-regex 0.14.0",
"filedescriptor 0.8.3",
"finl_unicode 1.3.0",
+ "getrandom 0.3.4",
"hostname",
"k9",
"lazy_static",
@@ -5434,6 +5456,7 @@ dependencies = [
"termwiz-funcs",
"textwrap",
"thinkterm-proto",
+ "thinkterm-reverse-access",
"thiserror 1.0.69",
"toml 0.8.23",
"url",
@@ -6189,6 +6212,27 @@ version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12"
+[[package]]
+name = "pam-client2"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "407daa00f98b05147dbbaa6d2f6bce574e76794fa4952a5b38764681a23dde5f"
+dependencies = [
+ "bitflags 2.13.1",
+ "libc",
+ "pam-sys2",
+ "rustversion",
+]
+
+[[package]]
+name = "pam-sys2"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e07ea89c210813e1a48fc32cb358ba693aae8ca70163461e22d11f1884bf1d"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -6711,6 +6755,7 @@ dependencies = [
"downcast-rs 1.2.1",
"filedescriptor 0.8.3",
"futures",
+ "interprocess",
"lazy_static",
"libc",
"log",
@@ -7336,6 +7381,12 @@ dependencies = [
"font-types",
]
+[[package]]
+name = "recvmsg"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175"
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -9289,6 +9340,27 @@ dependencies = [
"unicode-width",
]
+[[package]]
+name = "thinkterm-connect-auth"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "embed-resource",
+ "futures-lite",
+ "futures-util",
+ "nix 0.29.0",
+ "pam-client2",
+ "serde",
+ "serde_json",
+ "smol",
+ "windows 0.62.2",
+ "windows-future",
+ "winreg",
+ "zbus",
+ "zeroize",
+ "zvariant",
+]
+
[[package]]
name = "thinkterm-core"
version = "0.1.0"
@@ -9525,6 +9597,24 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "thinkterm-reverse-access"
+version = "0.1.0"
+dependencies = [
+ "futures",
+ "getrandom 0.3.4",
+ "interprocess",
+ "nix 0.29.0",
+ "procinfo",
+ "serde",
+ "serde_json",
+ "smol",
+ "thiserror 1.0.69",
+ "tokio",
+ "tokio-util",
+ "widestring",
+]
+
[[package]]
name = "thinkterm-session"
version = "0.1.0"
@@ -9959,6 +10049,7 @@ checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594"
dependencies = [
"bytes",
"futures-core",
+ "futures-io",
"futures-sink",
"futures-util",
"pin-project-lite",
@@ -11723,6 +11814,7 @@ dependencies = [
"embed-resource",
"env-bootstrap",
"filedescriptor 0.8.3",
+ "futures",
"hostname",
"humantime",
"image",
@@ -11744,6 +11836,7 @@ dependencies = [
"thinkterm-file-index",
"thinkterm-plugin-channel",
"thinkterm-proto",
+ "thinkterm-reverse-access",
"thinkterm-tailnet",
"thinkterm-tui",
"thinkterm-update",
@@ -11856,6 +11949,7 @@ dependencies = [
"tempfile",
"termwiz 0.24.0",
"thinkterm-proto",
+ "thinkterm-reverse-access",
"thinkterm-session",
"thinkterm-update",
"thiserror 1.0.69",
@@ -12102,6 +12196,7 @@ dependencies = [
"thinkterm-plugin-panel",
"thinkterm-proto",
"thinkterm-render",
+ "thinkterm-reverse-access",
"thinkterm-snippets",
"thinkterm-syntax",
"thinkterm-tab-icons",
@@ -12298,6 +12393,7 @@ dependencies = [
"predicates",
"regex",
"rstest",
+ "russh",
"sha2 0.10.9",
"shell-words",
"smol",
@@ -12305,6 +12401,7 @@ dependencies = [
"ssh2",
"termwiz 0.24.0",
"thiserror 1.0.69",
+ "tokio",
"wezterm-uds",
"whoami",
]
@@ -12581,6 +12678,12 @@ dependencies = [
"safe_arch",
]
+[[package]]
+name = "widestring"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
+
[[package]]
name = "winapi"
version = "0.3.9"
diff --git a/Cargo.toml b/Cargo.toml
index f25a4a2f..5d7a52f7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -7,6 +7,8 @@ members = [
"sync-color-schemes",
"thinkterm-syntax",
"thinkterm-core",
+ "thinkterm-reverse-access",
+ "thinkterm-connect-auth",
"thinkterm-tailnet",
"thinkterm-tailnet-node",
"thinkterm-file-index",
diff --git a/ci/PKGBUILD.template b/ci/PKGBUILD.template
index 2e176442..0b646fb2 100644
--- a/ci/PKGBUILD.template
+++ b/ci/PKGBUILD.template
@@ -14,6 +14,7 @@ provides=('thinkterm' 'wezterm')
conflicts=('thinkterm' 'wezterm')
# Don't strip: it will break the binary and it only saves ~10% anyway
options=('!strip')
+backup=('etc/pam.d/thinkterm-connect-auth')
makedepends=('fuse')
depends=(
'dbus'
@@ -24,6 +25,8 @@ depends=(
'wayland'
'xcb-util-keysyms'
'xcb-util-wm'
+ 'pam'
+ 'zenity'
)
optdepends=(
'python-nautilus: ThinkTerm context menu in Nautilus'
@@ -51,6 +54,9 @@ package() {
install -Dm755 squashfs-root/usr/bin/thinkterm -t "${pkgdir}/usr/bin/"
install -Dm755 squashfs-root/usr/bin/wezterm -t "${pkgdir}/usr/bin/"
install -Dm755 squashfs-root/usr/bin/thinkterm-gui -t "${pkgdir}/usr/bin/"
+ install -Dm755 squashfs-root/usr/bin/thinkterm-connect-auth -t "${pkgdir}/usr/bin/"
+ install -Dm644 squashfs-root/usr/share/thinkterm/connect-auth/pam/fedora \
+ "${pkgdir}/etc/pam.d/thinkterm-connect-auth"
install -Dm755 squashfs-root/usr/bin/thinkterm-mux-server -t "${pkgdir}/usr/bin/"
install -Dm755 squashfs-root/usr/bin/thinkterm-plugin-server -t "${pkgdir}/usr/bin/"
install -Dm755 squashfs-root/usr/bin/thinkterm-tailnet -t "${pkgdir}/usr/bin/"
diff --git a/ci/appimage.sh b/ci/appimage.sh
index 238d6e6e..ae87d473 100755
--- a/ci/appimage.sh
+++ b/ci/appimage.sh
@@ -11,6 +11,9 @@ install -Dsm755 -t AppDir/usr/bin target/$PROFILE/thinkterm-mux-server
install -Dsm755 -t AppDir/usr/bin target/$PROFILE/thinkterm
install -Dsm755 -t AppDir/usr/bin target/$PROFILE/wezterm
install -Dsm755 -t AppDir/usr/bin target/$PROFILE/thinkterm-gui
+install -Dsm755 -t AppDir/usr/bin target/$PROFILE/thinkterm-connect-auth
+install -Dm644 -t AppDir/usr/share/thinkterm/connect-auth/pam thinkterm-connect-auth/pam/*
+install -Dm644 docs/thinkterm/connect-reverse-access.md AppDir/usr/share/thinkterm/connect-auth/README.md
install -Dsm755 -t AppDir/usr/bin target/$PROFILE/thinkterm-plugin-server
install -Dsm755 -t AppDir/usr/bin target/$PROFILE/thinkterm-tailnet
install -Dsm755 -t AppDir/usr/bin target/$PROFILE/strip-ansi-escapes
@@ -81,6 +84,8 @@ UPDATE_INFORMATION="$UPDATE" \
OUTPUT="$OUTPUT" \
/tmp/linuxdeploy \
--exclude-library='libwayland-client.so.0' \
+ --exclude-library='libpam.so.0' \
+ --exclude-library='libpam_misc.so.0' \
--appdir AppDir \
--output appimage \
--desktop-file assets/wezterm.desktop
diff --git a/ci/build-connect-auth.sh b/ci/build-connect-auth.sh
new file mode 100644
index 00000000..200cfefa
--- /dev/null
+++ b/ci/build-connect-auth.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -euo pipefail
+
+# The macOS helper is Swift. Linux and Windows have theirs in the workspace.
+platform=${1:?usage: build-connect-auth.sh macos arm64|x86_64 output-directory}
+arch=${2:?missing architecture}
+output=${3:?missing output directory}
+root=$(cd "$(dirname "$0")/.." && pwd)
+mkdir -p "$output"
+output=$(cd "$output" && pwd)
+
+case "$arch" in
+ arm64 | x86_64) ;;
+ *) echo "Unsupported architecture" >&2; exit 2 ;;
+esac
+
+case "$platform" in
+ macos)
+ xcrun swiftc -swift-version 5 -O -target "$arch-apple-macosx13.0" \
+ "$root/thinkterm-reverse-access/native/macos.swift" \
+ -o "$output/thinkterm-connect-auth"
+ ;;
+ *) echo "Unsupported platform" >&2; exit 2 ;;
+esac
diff --git a/ci/check-glibc.sh b/ci/check-glibc.sh
index b99ecdca..f82c9548 100755
--- a/ci/check-glibc.sh
+++ b/ci/check-glibc.sh
@@ -66,6 +66,7 @@ else
check "$bin" "$server_main"
done
check thinkterm-gui "$desktop"
+ check thinkterm-connect-auth "$desktop"
fi
exit $status
diff --git a/ci/deploy.sh b/ci/deploy.sh
index 658df44f..be0e2e29 100755
--- a/ci/deploy.sh
+++ b/ci/deploy.sh
@@ -150,6 +150,17 @@ case $OSTYPE in
fi
done
+ # Build the native authentication companion for exactly the architectures
+ # of the packaged GUI, including a local universal build.
+ auth_arches=$(lipo -archs "$zipdir/ThinkTerm.app/Contents/MacOS/thinkterm-gui")
+ auth_parts=()
+ for arch in $auth_arches ; do
+ auth_dir="$TARGET_DIR/connect-auth/$arch"
+ bash ci/build-connect-auth.sh macos "$arch" "$auth_dir"
+ auth_parts+=("$auth_dir/thinkterm-connect-auth")
+ done
+ lipo -create "${auth_parts[@]}" -output "$zipdir/ThinkTerm.app/Contents/MacOS/thinkterm-connect-auth"
+
# The symbols the dist profile writes beside each binary (split-debuginfo
# = "packed"): zipped next to the app, never inside it, so a crash
# report's addresses can be resolved against the matching build.
@@ -322,6 +333,7 @@ case $OSTYPE in
"$artifact_dir/wezterm.exe" \
"$artifact_dir/thinkterm-mux-server.exe" \
"$artifact_dir/thinkterm-gui.exe" \
+ "$artifact_dir/thinkterm-connect-auth.exe" \
"$artifact_dir/thinkterm-plugin-server.exe" \
"$artifact_dir/strip-ansi-escapes.exe" \
$win_assets/conhost/conpty.dll \
@@ -395,11 +407,11 @@ source ~/.cargo/env
cargo build --profile ${PROFILE} \
-p wezterm-gui -p wezterm -p wezterm-mux-server \
- -p thinkterm-plugin-server -p thinkterm-tailnet-node -p strip-ansi-escapes
+ -p thinkterm-plugin-server -p thinkterm-tailnet-node -p strip-ansi-escapes -p thinkterm-connect-auth
BUILDEOFEOF
)
BUILD_REQUIRES=$(cat <<BREQEOF
-BuildRequires: gcc, gcc-c++, make, curl, fontconfig-devel, openssl-devel, libxcb-devel, libxkbcommon-devel, libxkbcommon-x11-devel, wayland-devel, xcb-util-devel, xcb-util-keysyms-devel, xcb-util-image-devel, xcb-util-wm-devel, git
+BuildRequires: gcc, gcc-c++, make, curl, fontconfig-devel, openssl-devel, pam-devel, libxcb-devel, libxkbcommon-devel, libxkbcommon-x11-devel, wayland-devel, xcb-util-devel, xcb-util-keysyms-devel, xcb-util-image-devel, xcb-util-wm-devel, git
%if 0%{?suse_version}
BuildRequires: Mesa-libEGL-devel
%else
@@ -454,7 +466,7 @@ URL: https://github.com/RoversX/thinkterm
Summary: ThinkTerm workspace-first terminal emulator.
${BUILD_REQUIRES}
Conflicts: thinkterm-server, wezterm
-Requires: openssl
+Requires: openssl, pam, zenity
%if 0%{?suse_version}
Requires: dbus-1, fontconfig, libxcb1, libxkbcommon0, libxkbcommon-x11-0, libwayland-client0, libwayland-egl1, libwayland-cursor0, Mesa-libEGL1, libxcb-keysyms1, libxcb-ewmh2, libxcb-icccm4
%else
@@ -489,6 +501,12 @@ install -Dm755 assets/open-thinkterm-here assets/open-wezterm-here -t %{buildroo
install -Dsm755 $TARGET_DIR/$PROFILE/thinkterm -t %{buildroot}/usr/bin
install -Dsm755 $TARGET_DIR/$PROFILE/wezterm -t %{buildroot}/usr/bin
install -Dsm755 $TARGET_DIR/$PROFILE/thinkterm-gui -t %{buildroot}/usr/bin
+install -Dsm755 $TARGET_DIR/$PROFILE/thinkterm-connect-auth -t %{buildroot}/usr/bin
+%if 0%{?suse_version}
+install -Dm644 thinkterm-connect-auth/pam/suse %{buildroot}/etc/pam.d/thinkterm-connect-auth
+%else
+install -Dm644 thinkterm-connect-auth/pam/fedora %{buildroot}/etc/pam.d/thinkterm-connect-auth
+%endif
install -Dsm755 $TARGET_DIR/$PROFILE/thinkterm-plugin-server -t %{buildroot}/usr/bin
install -Dsm755 $TARGET_DIR/$PROFILE/thinkterm-tailnet -t %{buildroot}/usr/bin
install -Dsm755 $TARGET_DIR/$PROFILE/thinkterm-mux-server -t %{buildroot}/usr/bin
@@ -517,6 +535,8 @@ ${RPM_WEB_INSTALL}
/usr/bin/thinkterm
/usr/bin/wezterm
/usr/bin/thinkterm-gui
+/usr/bin/thinkterm-connect-auth
+%config(noreplace) /etc/pam.d/thinkterm-connect-auth
/usr/bin/thinkterm-plugin-server
/usr/bin/thinkterm-tailnet
/usr/bin/thinkterm-mux-server
@@ -665,6 +685,9 @@ EOF
install -Dsm755 -t $root/usr/bin $TARGET_DIR/$PROFILE/strip-ansi-escapes
if [[ "$variant" == desktop ]] ; then
install -Dsm755 -t $root/usr/bin $TARGET_DIR/$PROFILE/thinkterm-gui
+ install -Dsm755 -t $root/usr/bin $TARGET_DIR/$PROFILE/thinkterm-connect-auth
+ install -Dm644 thinkterm-connect-auth/pam/debian $root/etc/pam.d/thinkterm-connect-auth
+ printf '/etc/pam.d/thinkterm-connect-auth\n' > "$root/DEBIAN/conffiles"
install -Dm755 -t $root/usr/bin assets/open-thinkterm-here assets/open-wezterm-here
install -Dm644 assets/icon/terminal.png $root/usr/share/icons/hicolor/128x128/apps/com.roversx.thinkterm.png
install -Dm644 assets/wezterm.desktop $root/usr/share/applications/com.roversx.thinkterm.desktop
@@ -680,6 +703,9 @@ EOF
} > "$root/control"
local deps
deps=$(cd "pkg/$variant" && dpkg-shlibdeps -O -e debian/usr/bin/*)
+ if [[ "$variant" == desktop ]] ; then
+ deps="$deps, zenity, libpam-runtime"
+ fi
rm "$root/control"
echo $deps | sed -e 's/shlibs:Depends=/Depends: /' >> $root/DEBIAN/control
cat $root/DEBIAN/control
@@ -759,6 +785,9 @@ EOF
install -Dm644 -t "$tardir" NOTICE LICENSE.md LICENSE-MIT
install_web_bundle "$tardir/share/thinkterm/web"
if [[ "$variant" == thinkterm ]] ; then
+ install -Dsm755 "$TARGET_DIR/$PROFILE/thinkterm-connect-auth" "$tardir/bin/thinkterm-connect-auth"
+ install -Dm644 -t "$tardir/share/thinkterm/connect-auth/pam" thinkterm-connect-auth/pam/*
+ install -Dm644 docs/thinkterm/connect-reverse-access.md "$tardir/share/thinkterm/connect-auth/README.md"
install -Dm755 -t "$tardir/bin" assets/open-thinkterm-here assets/open-wezterm-here
install -Dm644 assets/wezterm.desktop "$tardir/share/applications/com.roversx.thinkterm.desktop"
install -Dm644 assets/icon/terminal.png "$tardir/share/icons/hicolor/128x128/apps/com.roversx.thinkterm.png"
diff --git a/ci/test-remote-update.py b/ci/test-remote-update.py
index 1141d78d..a4d968da 100644
--- a/ci/test-remote-update.py
+++ b/ci/test-remote-update.py
@@ -124,17 +124,32 @@ class InstallerTests(unittest.TestCase):
path.write_text(text)
path.chmod(0o755)
- def package(self, name):
+ def package(self, name, extra_files=()):
path = self.root / name
with tarfile.open(path, "w:xz" if name.endswith(".xz") else "w:gz") as archive:
- entry = tarfile.TarInfo("thinkterm-example/bin/thinkterm")
- entry.mode = 0o755
- data = b"#!/bin/sh\nexit 0\n"
- entry.size = len(data)
- archive.addfile(entry, io.BytesIO(data))
+ for relative, data, mode in [("bin/thinkterm", b"#!/bin/sh\nexit 0\n", 0o755), *extra_files]:
+ entry = tarfile.TarInfo("thinkterm-example/" + relative)
+ entry.mode = mode
+ entry.size = len(data)
+ archive.addfile(entry, io.BytesIO(data))
self.packages.append(name)
return path
+ def desktop_package(self, authentication=True):
+ files = [
+ ("bin/thinkterm-gui", b"#!/bin/sh\nexit 0\n", 0o755),
+ ("share/applications/com.roversx.thinkterm.desktop",
+ b"[Desktop Entry]\nExec=thinkterm start\nTryExec=thinkterm\n", 0o644),
+ ("share/icons/hicolor/128x128/apps/com.roversx.thinkterm.png", b"example icon", 0o644),
+ ]
+ if authentication:
+ files.append(("bin/thinkterm-connect-auth", b"#!/bin/sh\nexit 0\n", 0o755))
+ files.append(("share/thinkterm/connect-auth/README.md",
+ (ROOT / "docs/thinkterm/connect-reverse-access.md").read_bytes(), 0o644))
+ files.extend(("share/thinkterm/connect-auth/pam/" + policy.name, policy.read_bytes(), 0o644)
+ for policy in sorted((ROOT / "thinkterm-connect-auth/pam").iterdir()))
+ return self.package(f"thinkterm-{TAG}-linux-x86_64.tar.gz", files)
+
def write_api(self, missing_digest=False):
assets = []
for name in self.packages:
@@ -303,6 +318,26 @@ class InstallerTests(unittest.TestCase):
self.run_install()
self.assertTrue(any(r["name"] == name for r in self.requests()))
+ def test_linux_desktop_retains_authentication_setup_files(self):
+ archive = self.desktop_package()
+ prefix = self.home / "desktop prefix"
+ self.run_install("--desktop", "--prefix", str(prefix), "--from", str(archive),
+ "--sha256", hashlib.sha256(archive.read_bytes()).hexdigest())
+ self.assertTrue(os.access(prefix / "bin/thinkterm-connect-auth", os.X_OK))
+ installed = prefix / "share/thinkterm/connect-auth"
+ self.assertEqual((installed / "README.md").read_bytes(),
+ (ROOT / "docs/thinkterm/connect-reverse-access.md").read_bytes())
+ for policy in (ROOT / "thinkterm-connect-auth/pam").iterdir():
+ self.assertEqual((installed / "pam" / policy.name).read_bytes(), policy.read_bytes())
+ self.assertFalse((prefix / "etc/pam.d/thinkterm-connect-auth").exists())
+
+ def test_linux_desktop_without_authentication_assets_still_installs(self):
+ archive = self.desktop_package(authentication=False)
+ self.run_install("--desktop", "--from", str(archive),
+ "--sha256", hashlib.sha256(archive.read_bytes()).hexdigest())
+ self.assertTrue((self.home / ".local/bin/thinkterm-gui").is_file())
+ self.assertFalse((self.home / ".local/share/thinkterm/connect-auth").exists())
+
@unittest.skipUnless(sys.platform == "darwin", "macOS ditto required")
def test_macos_server_from_install_stays_inside_isolated_home(self):
self.env["TEST_OS"] = "Darwin"
diff --git a/ci/windows-installer.iss b/ci/windows-installer.iss
index 5b4f55de..facfc5a3 100644
--- a/ci/windows-installer.iss
+++ b/ci/windows-installer.iss
@@ -60,6 +60,7 @@ Source: "{#MyAppSourceDir}\wezterm.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#MyAppSourceDir}\thinkterm-gui.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#MyAppSourceDir}\thinkterm-mux-server.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#MyAppSourceDir}\thinkterm-plugin-server.exe"; DestDir: "{app}"; Flags: ignoreversion
+Source: "{#MyAppSourceDir}\thinkterm-connect-auth.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#MyAppSourceDir}\mesa\opengl32.dll"; DestDir: "{app}\mesa"; Flags: ignoreversion
; ANGLE has no arm64 build here
#if MyAppArch != "arm64"
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index f8f6230b..d9f5a0e8 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -897,7 +897,7 @@ macro_rules! pdu {
/// (GetPaneRenderChangesResponse::bracketed_paste).
/// 85: The machine a pane of another one is on (ListPanesResponse::
/// pane_machines), as a window gives the panes it is connected to.
-pub const CODEC_VERSION: usize = 85;
+pub const CODEC_VERSION: usize = 86;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
@@ -1037,6 +1037,18 @@ pdu! {
ShareDeny: 139,
ShareCandidates: 140,
ShareCandidatesResponse: 141,
+ GetConnectEndpoint: 142,
+ GetConnectEndpointResponse: 143,
+}
+
+/// Discovery only. This address conveys no authority to approve or export.
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
+pub struct GetConnectEndpoint {}
+
+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
+pub struct GetConnectEndpointResponse {
+ pub server_id: String,
+ pub address: String,
}
impl Pdu {
@@ -3586,7 +3598,7 @@ mod test {
// tripwire: whoever bumps the codec must come here, confirm the
// round-trips still cover the new version, and advance it
// deliberately.
- assert_eq!(CODEC_VERSION, 85);
+ assert_eq!(CODEC_VERSION, 86);
use thinkterm_proto::{
AgentEvidence, AgentState, AgentStatus, ProgramBlockedKind, ProgramReport,
ProgramReportChild, ProgramReportState,
@@ -3656,7 +3668,7 @@ mod test {
#[test]
fn foreground_program_protocol_round_trip_at_version_74() {
// Same tripwire as the agent-status test above.
- assert_eq!(CODEC_VERSION, 85);
+ assert_eq!(CODEC_VERSION, 86);
use thinkterm_proto::ForegroundProgram;
fn round_trip(pdu: &Pdu) -> Pdu {
@@ -3757,7 +3769,7 @@ mod test {
#[test]
fn run_state_protocol_round_trip_at_version_80() {
// Same tripwire as the agent-status test above.
- assert_eq!(CODEC_VERSION, 85);
+ assert_eq!(CODEC_VERSION, 86);
use thinkterm_proto::{PaneExit, PaneRunState, ProgramState, ShellCommands};
let exit = PaneExit {
@@ -3863,7 +3875,7 @@ mod test {
fn frame_control_extension_round_trips_without_changing_legacy_version() {
// The extension is asked for, so it needed no bump of its own; 74
// is the foreground program's, which a server sends unasked.
- assert_eq!(CODEC_VERSION, 85);
+ assert_eq!(CODEC_VERSION, 86);
for pdu in [
Pdu::GetKittyImage(GetKittyImage { pane_id: 3, image_id: 7, data_hash: [9; 32], have_frames: 2, image_epoch: Some(4) }),
Pdu::GetKittyFrameSelections(GetKittyFrameSelections { pane_id: 3, subscribe: true }),
diff --git a/docs/thinkterm/connect-reverse-access-implementation.md b/docs/thinkterm/connect-reverse-access-implementation.md
new file mode 100644
index 00000000..48ab2a4d
--- /dev/null
+++ b/docs/thinkterm/connect-reverse-access-implementation.md
@@ -0,0 +1,354 @@
+# Connect reverse access: implementation
+
+The [user guide](connect-reverse-access.md) describes the product workflow and platform requirements.
+This maintainer reference records the security contract, the implementation, and how to reproduce
+the SSH exchange tests.
+
+## Review contract
+
+Reverse access covers four operations over an existing ThinkTerm Connect connection: list,
+plain-text read, text input, and key input. Ordinary SSH/Mosh, third-device relays, subscriptions,
+`--wait`, and rich-text output do not enter this capability. Existing local and desktop-to-server
+permissions remain independent. Password-only SSH eligibility is a product rule, not a claim
+that passwords are safer than keys; authentication preference and host verification must not
+be weakened to make a connection eligible.
+
+Treat remote messages, terminal titles, labels, and ordinary local CLI/plugin/configuration
+calls as untrusted approval sources. Programs under the approved server account can consume
+the grant; it does not isolate individual agents. The application boundary does not resist
+reading trusted process memory, replacing trusted executables, or controlling the OS. That
+exclusion does not permit a public API to create, extend, or approve grants.
+
+The implementation and any follow-up must preserve these properties:
+
+- Only a native authentication result for a frozen, one-use intent can create or renew a grant.
+ Settings, Lua, plugins, ordinary RPC, and remote data requests cannot submit approval success.
+ Authentication occurs in a local native window, never in a remotely readable terminal.
+- Connection eligibility, user consent, and final execution checks remain separate. A pane ID,
+ label, process ID, socket path, configuration flag, or `from_desktop` field is not authority.
+- The actual terminal host checks target lifetime, owner, grant version, permission, expiry,
+ and revocation at execution and before releasing each part of a response. No implicit claim,
+ viewport takeover, or palette/layout change accompanies delegated input.
+- All-local membership may change only within the explicitly approved host, route, and scope.
+ Membership changes cannot extend expiry or widen a selected-terminal grant.
+- Cancellation, expiry, revocation, reconnect, host replacement, and lost monitoring cannot be
+ undone by a late callback or status reply. Grants and pending approvals are never persisted
+ or transferred through update, handoff, or rollback.
+- Length limits, budgets, and total deadlines apply before allocation or enqueueing and remain
+ owned until queued data is consumed or cancelled. Slow peers cannot retain unlimited work.
+- Hidden and nonexistent targets have indistinguishable access errors. Lists, errors, Debug,
+ and exceptional logs must not disclose hidden targets, terminal bodies, input, or credentials.
+- Input results describe PTY submission, including partial or unknown outcomes. Input is never
+ automatically retried, and revocation cannot recall bytes already accepted by OS buffers.
+- A failed request fails that request. Only a channel that no longer works ends the bridge, and
+ with it the grants. See "Serial channels" below.
+
+Unavailable or unverifiable authentication, session monitoring, or host identity denies access.
+A host the user accepted at the unknown-host prompt counts as verified: that is the same trust
+ordinary Connect gives it, and it is a decision the user made on that connection.
+Headless servers may request approved desktop access; headless exporting remains unsupported.
+System-authentication availability, compilation, and unit tests do not establish native usability.
+
+## Source map
+
+| Area | Sources |
+| --- | --- |
+| SSH session evidence and exchanges | `wezterm-ssh/src/authentication.rs`, `wezterm-ssh/src/authentication_tests.rs`, and `wezterm-ssh/tests/fixtures/authentication-server.py` |
+| Grants, clocks, framing, budgets, local IPC, native supervision | `thinkterm-reverse-access/src/` |
+| Native authentication | `thinkterm-reverse-access/native/`, `thinkterm-connect-auth/`, and `ci/build-connect-auth.sh` |
+| Actual host and reverse router | `mux/src/connect.rs` and `mux/src/connect/` |
+| Connection binding and guarded forwarding | `wezterm-client/src/client.rs` and `wezterm-client/src/connect.rs` |
+| GUI and CLI integration | `wezterm-gui/src/connect_access.rs`, `wezterm-gui/src/settings_window/connect_access.rs`, and `wezterm/src/cli/reverse.rs` |
+| Final read/input and host lifecycle | `mux/src/localpane.rs`, `mux/src/tab.rs`, `term/src/terminalstate/`, `pty/src/`, and mux-server handoff |
+
+## Implemented path
+
+```mermaid
+flowchart LR
+ Settings[Desktop Settings] --> Controller[GUI controller]
+ Controller -->|Verified local peer and bounded control lease| Host[Actual terminal host]
+ Host -->|Private inherited pipes| Native[Native authentication helper]
+ Native -->|One frozen transaction| Host
+ CLI[Server CLI] --> Router[Server local reverse router]
+ Router -->|Dedicated channel on the existing SSH session| Controller
+ Controller -->|Business requests only| Host
+ Host -->|Final permission and ownership check| PTY[Local terminal]
+```
+
+`wezterm-ssh` records actual authentication evidence in the owning SSH session. The client
+constructs a `VerifiedConnectSession` only from complete, host-verified password evidence.
+The original session is retained for the dedicated reverse channel and is invalidated when
+the normal connection ends. Reconnection requires a new session and approval.
+
+`AuthenticationInfo` is stored in the session's private `OnceLock` before the existing
+`SessionEvent::Authenticated` event. It has no serialization or caller-population interface.
+It retains backend, host-verification outcome, completeness, and at most 16 successful or
+partially successful authentication steps; overflow makes the evidence incomplete. It retains
+no secrets, prompt answers, account names, or hostnames and starts no background work.
+
+libssh distinguishes rejected and partially accepted keys. ssh2 cannot always distinguish them
+after an earlier failed call, so those sessions remain ineligible even if a later password succeeds.
+Keyboard-interactive, none, incomplete evidence, external connection reuse, and unverified hosts
+also remain ineligible. Method evidence alone never creates a grant. Cancelling password or
+private-key decryption cannot publish completed evidence or fall through to another method.
+
+The actual terminal host owns `Authority`, native monitoring, and the grants. A separate local
+admission socket checks kernel-supplied peer identity and the packaged executable path. The
+GUI's process identity and mux instance must match the management connection. This is an
+admission check, not proof of authentication. Grant creation consumes the host's own native
+helper result over inherited pipes. No wire type accepts an authenticated or approved flag.
+The control path supports an already running local session host without a readable authority
+token file. Replacing trusted executable files or controlling the operating system is outside
+the application-level grant boundary.
+
+The normal mux dispatcher exposes only local endpoint discovery; Web, share, and TLS peers
+cannot use that discovery operation. Remote reverse channels decode only four business
+operations. They cannot call the management commands or trigger native authentication.
+Server-account processes may register and consume a router connection, but that registration
+does not give them any desktop authority.
+
+Actual local panes are captured with their object, tab membership, client registration,
+ownership epoch, and a fresh export incarnation. The final host checks these bindings again
+under the relevant locks. A pane number, domain name, or `local_session_host` flag alone cannot
+select a permitted terminal. Ownership changes are tracked independently from geometry updates; changing away
+from an owner and back does not revive an old export. Removing a pane from its captured tab
+invalidates its membership token even if it returns before the next authorization check.
+Atomic stack and split moves within the same tab preserve membership. Tokens have a bounded
+weak registry, with entries released on removal, tab destruction, or subsequent capture after
+the last export drops them. Both individual operations and List transmission check membership.
+
+## Lifetime and execution
+
+The frontend offers connection-wide authorization of all eligible local terminals, including
+future terminals. It chooses the active local session host automatically, with in-process
+terminals as the fallback when no host is attached. The selected-terminal engine and editor
+remain in the source, with the editor disabled by a private build constant. No user-facing
+scope toggle was added.
+
+An all-local native intent starts with an empty target set and explicitly describes current and
+future terminals. The actual host captures eligible panes after authentication and refreshes
+their bounded target set on status and business requests. Existing captures retain their identities;
+removed or no-longer-owned panes are dropped, and later eligible captures receive fresh identities.
+Only an all-local grant on the exact route and version permits membership replacement. It cannot
+change permission, expiry, or the replay watermark. An empty set does not end an all-local grant.
+The final GUI output guard also matches each pane's incarnation. A target it does not know yet,
+newly added or captured again under the same pane number, waits for a trusted status. A status
+requested after the reply arrived settles it: what that status still omits is gone, and the
+reply is refused.
+
+The core stores one pending authentication transaction and freezes its route, scope, targets,
+permission, duration, renewal version, and deadline. Native callbacks are one-use capabilities
+inside the crate. Cancelling a transaction also revokes a result created but not yet delivered
+to the controller. Renewal creates a new grant version and preserves the route's replay
+watermark. Active grants and authentication callbacks are never persisted.
+
+Explicit revocation uses the route and stable grant ID, covering a renewal that completed
+after the UI rendered its button and cancelling a matching pending native renewal. Cleanup
+of an old grant object remains version-specific so it cannot revoke a successful replacement.
+
+Linux uses `CLOCK_BOOTTIME`; macOS uses `CLOCK_MONOTONIC_RAW`; Windows uses its QPC-backed
+`Instant`. These platform choices include sleep, while a generic cross-platform assumption
+about `Instant` is deliberately avoided. All deadlines use checked arithmetic and fail closed
+on clock errors or reversal. Remaining request time is reduced at each forwarding stage and
+the outer request deadline remains active; forwarding cannot restart an unrestricted ten-second
+operation. A supplied remaining duration never extends the host's grant deadline.
+
+Native monitor and GUI-control leases expire within five seconds. The monitor sends one
+heartbeat per second and cannot revive a missed lease. The GUI's final SSH-send guard uses
+conservative host status with a shorter four-second lease, anchored before requesting that
+status. Explicit GUI revocation invalidates this guard immediately and cannot be undone by
+a stale status reply. Replies naming new or renewed grants wait for a trusted control status
+before their first byte is written; they cannot approve themselves. Synchronization preserves
+the original request deadline, grant expiration, and control lease. Every partial write still
+checks the current guard. Host events propagate through the control channel; revocation does not
+claim to recall bytes already accepted by an OS or SSH buffer.
+
+Read conversion is bounded while iterating terminal cells. Plain text is held with its request
+reservation, and the host rechecks permission and target identity at each outgoing partial
+write. GUI forwarding also checks its conservative output guard at each nonblocking poll.
+Host locks are only ever tried. `Busy` means an attempt did no work, so every step that can meet
+it, from a list row's title through building a snapshot, encoding input and queueing it, yields
+and retries under the request deadline. A terminal with heavy output is held often, and a list
+covers every terminal, so failing on `Busy` would let one busy terminal fail commands for all of
+them. Retries preserve the current frame offset and repeat authorization checks; revocation,
+target loss, clock failure, and expiry still stop the send. Rate and budget limits are not
+contention: they are answered with `Failed(Busy)` straight away.
+
+## Serial channels
+
+The router-to-GUI and GUI-to-host channels carry one exchange at a time, so a request's reply is
+the only thing that puts them back in step. Three rules follow.
+
+- Every request is answered. A refusal or failure is `Reply::Failed`, and input refused on arrival
+ still has its blocks read off the channel. `exchange.rs` keeps the two outcomes apart: its outer
+ `Result` is the channel's, the inner one the request's.
+- Time is kept back for the answer. `REPLY_MARGIN` comes off the deadline at each forwarding stage:
+ router, GUI, then the host's own work, which leaves the host's operation about 8.5 of the ten
+ seconds. Input that outlasts it is cancelled and its partial result still delivered. A read that
+ outlasts it stops between blocks. List and read permits run to the reply's deadline rather than
+ the operation's, so that the frame being written when the operation ends can finish.
+- A sender that cannot continue between blocks sends `Kind::Cancel` for that sequence. The router
+ turns it into `Failed(Unavailable)`. The GUI does the same when its output guard refuses partway,
+ and when the host's operation ends with blocks still to forward, then reads the host's remaining
+ blocks without forwarding them. On a slow connection those queued blocks would otherwise outlast
+ the GUI's own deadline, and draining them as the host stops lets the host finish its frame.
+
+Once a request is on the channel the router runs the exchange to its reply, even if the requester
+has gone, and drops the result. It waits up to 15 seconds past the request's deadline for that
+reply, since a reply the desktop sent in time can still be in a slow connection's buffers; a
+desktop silent for longer has lost the channel. A reply's bytes grow the request's own reservation,
+so it needs no second slot or rate charge. If the bytes do not fit, the text is read off the
+channel and the requester gets `Failed(Busy)`.
+
+What still ends a bridge: transport loss, a protocol violation, a frame abandoned partway through
+its bytes (a guard failing during one partial write), and a peer that stays silent. The first
+three need no recovery, and all four fail closed. A connection too slow to carry one block within
+`REPLY_MARGIN`, or to empty its buffers within `LATE_REPLY`, reaches the last two during a long
+read.
+
+Reverse target resolution treats every locally claimed label or thread alias as a collision,
+including names shared by several panes. Local listing failures propagate to the caller instead
+of being interpreted as proof that no local target exists.
+
+Delegated input uses the existing ordered terminal writer queue, but carries a final-check
+closure instead of an already authorized byte buffer. Each nonblocking PTY write rechecks
+the grant, target, owner, and deadline. Text and optional Enter stay in one queue operation,
+written separately with `enter_delay` between them, the same wait the ordinary CLI path uses.
+The checks repeat throughout that wait, and ordinary input to that pane queues behind it.
+Cancellation releases the queued payload immediately; its concurrency slot remains owned
+until the queue drains, preventing repeated cancelled work from growing an unlimited queue.
+Results distinguish not submitted, fully submitted, partial, and unknown outcomes. Bracketed
+paste cancellation reports a potentially open paste rather than writing after revocation.
+
+Unix and ConPTY input adapters support bounded nonblocking submission. Ordinary terminal writes
+retain their blocking behavior and handle partial writes. Handoff first closes the old Connect
+authority and quiesces its input handles before transferring PTY descriptors. Old handles stay
+invalid, including after rollback, and dropping one cannot change the successor's descriptor
+mode. Rollback may create new handles and new grants through a new controller.
+
+## Limits and release points
+
+| Resource | Bound and ownership |
+| --- | --- |
+| Routes, grants, target references | At most 16 routes and 64 grants; one all-local grant per route with at most 256 targets; selected-terminal grants retain the 32-per-grant and 256-total limits; route/authority destruction releases them |
+| Business request | Ten-second total deadline; no transparent input retry |
+| Frame | 32 KiB including header, no compression; five-second total partial-frame deadline |
+| Payload block | 16 KiB; ordered offsets and total lengths checked before assembly |
+| Read / text / keys | 2,000 physical lines and 1 MiB / 64 KiB / 64 keys |
+| In-flight work | Process budget 32 slots and 32 MiB; route budget 8 slots and 8 MiB; channel reservations also consume these limits |
+| Rate | Process 40 requests/s with burst 80; route 10/s with burst 20 |
+| Read output | Process 8 MiB/s and route 2 MiB/s token budgets |
+| Local admissions | Eight pending handshakes, with further clients left in the listen queue until one finishes; bounded route queues; sockets are private, removed on shutdown, and swept by the next service if a process exited without unwinding |
+| Native work | One authentication attempt, 120-second timeout, bounded intent/event pipes; helper reaped on completion or cancellation |
+
+These are ceilings, not a promise that every maximum can be reached simultaneously. Buffer,
+queue, frame, and response ownership retain reservations until consumption or cancellation.
+A slow or departed CLI loses its own connection, and its reply is dropped. Closing
+the mux also closes the service and active handlers. With no editor or grant, the feature
+does not scan panes, start native helpers, or open a dedicated SSH channel.
+
+## Platform implementation and packaging
+
+| Platform | Implementation |
+| --- | --- |
+| macOS | Swift/AppKit helper with no window of its own: the system dialog's reason states the access, duration, and server. Fresh `LAContext`, native device-owner policy, zero configured Touch ID reuse, console checks and session/lock/sleep observation |
+| Windows | Rust helper: system task dialog, window-associated Hello, system credential prompt with `LogonUser` for the current local account and a SID comparison, session and power notifications |
+| Linux | Rust helper, fixed PAM service, actual secret prompt plus account checks, Zenity, logind and screensaver monitoring with pinned service owner |
+
+All three helpers show the words `text.rs` gives them, chosen by the host from the frozen intent.
+The Windows and Linux helpers confirm the scope in a window of their own first. On macOS the
+Settings button is that step and the system dialog is the only window, so its reason has to carry
+everything, with the source last so that a long one cannot push the rest out of view.
+The GUI names a language on the management connection, which only selects a translation, so no
+caller can make the window describe less than is being granted.
+
+Linux rejects remote X displays, constrains Wayland and D-Bus to the actual user's protected
+local runtime directory, and requires an unambiguous active graphical session. System policy
+and Zenity must be root-owned and protected from group/other writes. No caller-selected PAM
+service or direct `unix_chkpwd` invocation is used. Headless requesting works without desktop
+authentication; creating headless exports remains explicitly unsupported.
+
+The macOS bundle includes the Swift helper alongside executables. Windows installer/portable
+packages include `thinkterm-connect-auth.exe`, a Rust binary of a few megabytes built with the
+rest of the workspace, which replaced a .NET helper that added about 150 MB to every Windows
+package. Linux desktop packages install the helper, Zenity/PAM dependencies, and the matching
+policy; portable packages carry policy files and instructions. Release scripts include Linux
+helper binaries and macOS universal helper assembly.
+
+The Linux desktop tarball installer retains `share/thinkterm/connect-auth` under the chosen
+prefix, including the PAM templates and instructions. It does not install the system PAM
+policy itself. Older desktop archives without these optional assets remain installable.
+
+The Windows helper, `thinkterm-connect-auth/src/win.rs`, is the one place this feature uses
+`unsafe`, agreed for that file alone: Hello, the credential prompt, and the task dialog exist
+only as system calls. Everywhere else, including the crate's other platforms, it stays
+forbidden. The Windows dialog needs common controls 6, which `windows.manifest` requests; the
+helper does not load without it. Anything that ends an attempt there, such as a closed control
+pipe, a session change, or the deadline, ends the process, so no result can be reported after it.
+
+The credential buffers these helpers own are cleared, but the system's prompt and PAM keep their
+own, which prevents a universal complete-erasure claim. The helpers are short-lived and do not
+log or send credentials to the requester.
+
+Other Unix targets retain a compiling IPC implementation that rejects peer admission as
+unavailable. Reverse access is unsupported there; the library dependency does not require
+macOS/Linux-only peer variables in ordinary FreeBSD or NetBSD builds.
+
+## Development builds
+
+Build the Rust binaries first, then install the native companion beside them. On macOS, `cargo build --workspace` alone leaves a stub in its place.
+Do not replace an installed app or attach the test build to existing terminal sessions.
+
+| Development target | Companion build after the Rust build |
+| --- | --- |
+| macOS arm64 | `bash ci/build-connect-auth.sh macos arm64 target/debug` |
+| macOS x86_64 | `bash ci/build-connect-auth.sh macos x86_64 target/debug` |
+| Windows | `cargo build -p thinkterm-connect-auth` |
+| Linux | `cargo build -p thinkterm-connect-auth`, plus administrator installation of the matching PAM policy and Zenity as described in the user guide |
+
+Use the actual target/profile directory instead of `target/debug` for cross or `dist` builds.
+For macOS app-bundle testing, place the helper in `Contents/MacOS`; running the CLI or mux server
+from another directory requires its companion there as well.
+
+## Reproduce the SSH exchange tests
+
+The required workspace suite excludes `wezterm-ssh`, so run its library tests separately for
+both backends. Two partial-success tests are ignored by default: the russh 0.63.3 fixture clears
+the partial-success flag in the relevant rejection paths, so they use the independent Paramiko
+server in `wezterm-ssh/tests/fixtures/authentication-server.py`. It handles one loopback exchange,
+has a bounded lifetime, and never reads actual OS accounts, configuration, or user keys.
+
+From the repository root, use a disposable environment and keep the existing Cargo caches:
+
+```sh
+check_root=$(mktemp -d /tmp/tt-connect-check.XXXXXX)
+mkdir -p "$check_root/home" "$check_root/run"
+python3 -m venv "$check_root/python"
+"$check_root/python/bin/python" -m pip --isolated install --no-cache-dir 'paramiko==5.1.0'
+for backend in libssh-rs ssh2; do
+ env -u SSH_AUTH_SOCK -u SSH_AGENT_PID \
+ HOME="$check_root/home" \
+ CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" \
+ RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" \
+ XDG_CONFIG_HOME="$check_root/config" XDG_CACHE_HOME="$check_root/cache" \
+ XDG_DATA_HOME="$check_root/data" XDG_RUNTIME_DIR="$check_root/run" \
+ THINKTERM_AUTH_TEST_PYTHON="$check_root/python/bin/python" \
+ cargo test -p wezterm-ssh --no-default-features --features "$backend" --lib -- --include-ignored
+done
+```
+
+The exchange fixtures currently run on Unix and need loopback socket permission. Key-decryption
+cancellation also needs `ssh-keygen`, operating only on a disposable test identity. Paramiko is
+a test dependency, not a packaged runtime dependency. A passing suite without `--include-ignored`
+does not establish the two partial-success cases.
+
+## API references
+
+- [SSH authentication and partial success](https://www.rfc-editor.org/rfc/rfc4252.html#section-5.1)
+- [SSH keyboard-interactive](https://www.rfc-editor.org/rfc/rfc4256.html)
+- [Apple device-owner authentication](https://developer.apple.com/documentation/localauthentication/lapolicy/deviceownerauthentication)
+- [Apple continuous time and CLOCK_MONOTONIC_RAW](https://developer.apple.com/documentation/kernel/1646199-mach_continuous_time)
+- [Windows high-resolution time stamps](https://learn.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps)
+- [Windows desktop verification interop](https://learn.microsoft.com/en-us/windows/win32/api/userconsentverifierinterop/nf-userconsentverifierinterop-iuserconsentverifierinterop-requestverificationforwindowasync)
+- [Linux PAM conversation](https://man7.org/linux/man-pages/man3/pam_conv.3.html)
+- [Linux CLOCK_BOOTTIME](https://man7.org/linux/man-pages/man2/clock_gettime.2.html)
diff --git a/docs/thinkterm/connect-reverse-access.md b/docs/thinkterm/connect-reverse-access.md
new file mode 100644
index 00000000..79f6c24f
--- /dev/null
+++ b/docs/thinkterm/connect-reverse-access.md
@@ -0,0 +1,149 @@
+# Connect reverse terminal access
+
+Connect reverse access lets programs on a connected server read or send input to your eligible
+local terminals. It uses the existing ThinkTerm Connect session and opens no new public port.
+Access is off until you authorize that server and complete local system authentication.
+
+Use matching versions of the desktop app, CLI, and mux server. An older component can prevent
+the entire connection from attaching.
+
+## Approve access
+
+1. Connect to the server using ThinkTerm Connect.
+2. Open **Settings → Agents → Connect Reverse Access**.
+3. Select the connected server.
+4. Choose either **Read only** or **Read and input**. The scope is **All local terminals**,
+ including eligible terminals opened while this authorization is active.
+5. Review the duration and select **Authenticate**, then complete system authentication on the
+ desktop. On macOS the system's Touch ID window opens straight away and names the access, its
+ duration, and the server. On Windows and Linux a confirmation window shows these first. Both
+ follow the app's language.
+
+The default duration is 30 minutes and can be changed to 1–120 minutes. Changing this default
+does not change an existing grant. Active grants show their server, scope, permissions, remaining
+time, and **Revoke** and **Renew** actions. Renewal requires fresh authentication. Cancelling
+or failing a renewal keeps the previous grant's original deadline.
+
+Each server connection has its own authorization. Terminal creation and closure are handled
+automatically; there is no terminal selection list.
+
+The app automatically uses its active local session host, or its own local terminals when no
+local session host is attached. The authorization stays with that host and covers only terminals
+the connected desktop currently owns. Remote mirrors and separate manual terminal hosts are
+outside this scope. Changing the local host requires new authentication. Up to 256 eligible
+terminals are supported per connection; exceeding the limit ends access instead of silently
+publishing an incomplete list.
+
+Only the current Connect session's verified, complete password-only SSH authentication chain
+qualifies. Public-key, SSH-agent, certificate, keyboard-interactive, and externally reused
+connections do not qualify. Authentication evidence that cannot distinguish a rejected key
+from a partially accepted key is rejected conservatively. This restriction applies to reverse
+access and does not change ordinary Connect authentication preferences.
+
+The server's host key must be known or accepted. A host you accept at the first-connection
+prompt counts as verified, and can be authorized on that same connection.
+
+## Use the existing CLI on the server
+
+Run `list` to obtain the current reverse target name. The route suffix changes when a new
+route is established; copy the name returned by the current list.
+
+```sh
+thinkterm cli list --json
+thinkterm cli get-text --pane desktop-0123abcd/21 --trim
+thinkterm cli send-text --pane desktop-0123abcd/21 --enter 'Hello'
+thinkterm cli send-key --pane desktop-0123abcd/21 ctrl+c
+```
+
+Reverse list entries contain the target, route, label, sanitized title, permission, and
+remaining duration. They do not expose hidden terminals, working directories, account names,
+or process information. Identical or ambiguous names are rejected.
+
+Plain-text reads support the existing line range, `--trim`, and `--unwrap` behavior. Reads
+include the selected terminal's screen and scrollback, limited to 2,000 physical lines and
+1 MiB per request. Request a smaller range if either limit is exceeded. Clipboard data,
+images, VT/HTML output, event subscriptions, and `--wait` are not part of reverse access.
+
+Each connection allows about ten requests per second, with short bursts of twenty. `list` and
+`get-text` wait their turn at that limit, so reading many terminals in a row just takes longer.
+Input does not wait: it is refused with `Busy`, having submitted nothing.
+
+Text input is limited to 64 KiB before encoding; key input is limited to 64 keys. On read-only
+access these commands say so and send nothing. `--no-paste` and `--enter` are supported. Text
+and its optional Enter occupy one ordered input operation, with the same short wait between
+them as on a local terminal, so that a program reading the text as a paste does not take the
+Enter as part of it. Revoking access during that wait stops the Enter. Input never takes
+terminal ownership or changes the active layout implicitly.
+
+A successful input result means the bytes reached the terminal's PTY, not that a command
+completed successfully. If a program stops reading its input, the request ends after about
+eight seconds and reports how many bytes were submitted. On cancellation or transport loss
+the result may be partial or unknown. Do not automatically retry input. Cancellation during
+bracketed paste can leave the application in paste mode; the error reports this possibility.
+ThinkTerm does not inject a cleanup sequence after authorization has been revoked.
+
+Stopping a CLI command does not stop what it already sent. A request that has reached the
+desktop runs to its end or to its deadline, and its result is dropped.
+
+Programs under the connected server account share the approved capability. It is not
+restricted to one particular agent or process under that account.
+
+## When authorization ends
+
+Terminal removal or loss of ownership removes that terminal from the authorization. A later
+eligible terminal receives a fresh export identity; old requests cannot address it. These changes
+do not extend the deadline or revoke the entire connection-wide grant when no terminals remain.
+Revoke, expiry, reconnect, host replacement, desktop session changes, and process exit end
+the connection's authorization. Updates and mux handoff do not
+transfer grants. Start a new approval after reconnecting or upgrading.
+
+One request going wrong does not end it. A closed terminal, a timeout, a stopped CLI, or a
+request over the limit fails that request and leaves the authorization in place. Only losing
+the channel to the desktop ends it. A long read over a connection slower than about 256 kbit/s
+can count as that, so read smaller ranges there.
+
+Deadlines use the terminal host's monotonic clock and include suspend time. Changing the wall
+clock or time zone cannot extend a grant. Native session monitoring and the local controller
+have bounded heartbeats; detected monitoring failure cancels access and a missing heartbeat
+expires within five seconds. Physical link failure is detected through an event or timeout.
+Bytes already submitted to the operating system or delivered to the terminal cannot be
+recalled by revocation.
+
+Remote requests cannot open an authentication window. The GUI must initiate each approval.
+Ordinary CLI commands, configuration settings, and plugins cannot submit authentication
+success or extend a grant.
+
+## Platform requirements
+
+| Platform | Authentication and required local environment |
+| --- | --- |
+| macOS | Packaged Swift helper beside the app executables; active local console session. LocalAuthentication uses the system device-owner policy, which can allow Touch ID, the account password, or a paired Apple Watch according to system configuration. |
+| Windows | Packaged `thinkterm-connect-auth.exe` beside the executables. Windows 11 or later uses Windows Hello where it is set up. Otherwise the system credential prompt asks for the password of the current local account. Domain, Microsoft, and Entra accounts have no password path, and need a working Hello. |
+| Linux desktop | Packaged helper, `/usr/bin/zenity`, a protected `/etc/pam.d/thinkterm-connect-auth`, systemd-logind, and an active local graphical session with GNOME or freedesktop screensaver notifications. Root, forwarded X displays, ambiguous sessions, and missing or unverifiable lock monitoring are rejected. |
+
+macOS authentication returns a system decision. Windows password fallback and Linux PAM
+authentication handle the entered secret inside a short-lived local helper. It is never
+sent over Connect, placed in the business protocol, or retained as a ThinkTerm password.
+The Windows and Linux helpers clear their own copies; the system's credential prompt and PAM
+own theirs, so complete in-memory erasure is not claimed.
+
+No helper process starts merely because reverse access is available in Settings.
+
+Debian/Ubuntu, Fedora, openSUSE, and Arch desktop packages install the PAM policy. An AppImage
+or portable archive cannot install a protected system policy automatically. An administrator
+must install the appropriate supplied policy with owner `root`, mode `0644`, at
+`/etc/pam.d/thinkterm-connect-auth` and install Zenity. The supplied policy variants are in
+`share/thinkterm/connect-auth/pam` (under `usr` in an AppImage). Use the variant matching the
+distribution's existing PAM stack; missing or writable policy files are rejected.
+
+A headless server can use already approved desktop access without PAM, Hello, or a server-side
+dialog. Creating a new grant for a headless server's own terminals is unsupported. Remote
+mirrors, tmux/control-mode terminals, terminals you joined through someone else's share, and
+third-device relays cannot be exported through this feature. A terminal you are sharing out
+is still one of your local terminals, and is covered like any other.
+
+## Troubleshooting
+
+If approval is unavailable, check the connection's authentication eligibility, local terminal
+ownership, matching component versions, helper packaging, and the platform requirements above.
+Unknown authentication or session state always rejects access.
diff --git a/get-deps b/get-deps
index 14cf9568..1ae1f980 100755
--- a/get-deps
+++ b/get-deps
@@ -52,6 +52,7 @@ alpine_deps() {
'libssh2-dev' \
'libx11-dev' \
'libxkbcommon-dev' \
+ 'linux-pam-dev' \
'openssl-dev' \
'pkgconf' \
'python3' \
@@ -90,6 +91,7 @@ fedora_deps() {
'flatpak-builder' \
'fontconfig-devel' \
'openssl-devel' \
+ 'pam-devel' \
'perl-interpreter' \
'python3' \
'python3-pip' \
@@ -128,6 +130,7 @@ suse_deps() {
'gcc-c++' \
'fontconfig-devel' \
'libopenssl-devel' \
+ 'pam-devel' \
'perl' \
'python3' \
'libxcb-devel' \
@@ -158,6 +161,7 @@ debian_deps() {
'g++' \
'libegl1-mesa-dev' \
'libssl-dev' \
+ 'libpam0g-dev' \
'libfontconfig1-dev' \
'libwayland-dev' \
'libx11-xcb-dev' \
@@ -289,6 +293,7 @@ void_deps() {
'pkgconf' \
'fontconfig-devel' \
'openssl-devel' \
+ 'pam-devel' \
'wayland-devel' \
'libX11-devel' \
'libxkbcommon-devel' \
@@ -313,7 +318,8 @@ solus_deps() {
xcb-util-image-devel \
libxkbcommon-devel \
fontconfig-devel \
- libx11-devel
+ libx11-devel \
+ linux-pam-devel
}
fallback_method() {
diff --git a/install.sh b/install.sh
index 59b5debc..827f6af9 100755
--- a/install.sh
+++ b/install.sh
@@ -1276,6 +1276,12 @@ if [ -d "$root/share/thinkterm/web" ]; then
# time, so an install that rewrites them can mislead it.
cp -Rp "$root/share/thinkterm/web" "$sharedir/thinkterm/web"
fi
+if [ "$os" = linux ] && [ "$variant" = desktop ] && [ -d "$root/share/thinkterm/connect-auth" ]; then
+ # Keep the supplied policy templates and instructions for administrator
+ # setup; a user-prefix install must not write the system PAM policy.
+ rm -rf "$sharedir/thinkterm/connect-auth"
+ cp -Rp "$root/share/thinkterm/connect-auth" "$sharedir/thinkterm/connect-auth"
+fi
# Written last, so it only ever describes a completed install.
{
diff --git a/mux/Cargo.toml b/mux/Cargo.toml
index 0336630d..ce1f36c3 100644
--- a/mux/Cargo.toml
+++ b/mux/Cargo.toml
@@ -8,6 +8,7 @@ publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+thinkterm-reverse-access = { path = "../thinkterm-reverse-access" }
anyhow.workspace = true
async-trait.workspace = true
base64.workspace = true
@@ -21,6 +22,7 @@ downcast-rs.workspace = true
fancy-regex.workspace = true
filedescriptor.workspace = true
finl_unicode.workspace = true
+getrandom.workspace = true
hostname.workspace = true
lazy_static.workspace = true
libc.workspace = true
diff --git a/mux/src/connect.rs b/mux/src/connect.rs
new file mode 100644
index 00000000..42fbff00
--- /dev/null
+++ b/mux/src/connect.rs
@@ -0,0 +1,626 @@
+//! Host-side operations for a Connect export. Ordinary pane input APIs do
+//! not enter this module, and none of these handles are protocol values.
+
+use crate::client::ClientId;
+use crate::localpane::LocalPane;
+use crate::pane::{Pane, PaneId};
+use crate::tab::{PaneMembership, Tab, TabId};
+use crate::{ClientRegistrationId, FrontendAccessMode, FrontendLeaseState, Mux};
+use parking_lot::Mutex;
+use std::io;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{mpsc, Arc, Weak};
+use std::task::Poll;
+use std::time::{Duration, Instant};
+use thinkterm_reverse_access::budget::Reservation;
+use thinkterm_reverse_access::channel::Deadline;
+use thinkterm_reverse_access::protocol::{InputResult, InputStatus, ReadOptions};
+use thinkterm_reverse_access::{Error, Id, RequestPermit, Result, Target};
+
+mod host;
+pub mod service;
+pub use host::{ActiveGrant, Host, HostRoute, HostStatus, PaneChoice, PreparedReply};
+
+#[derive(Clone, PartialEq, Eq)]
+struct Ownership {
+ mode: FrontendAccessMode,
+ global_generation: u64,
+ tab_generation: u64,
+ owner: Option<ClientId>,
+}
+
+impl Ownership {
+ fn capture(lease: &FrontendLeaseState, tab: TabId, client: &ClientId) -> Result<Self> {
+ let state = lease.tabs.get(&tab);
+ let owner = match lease.access_mode {
+ FrontendAccessMode::Handoff => lease.handoff_owner.as_ref(),
+ FrontendAccessMode::TmuxLatest => state.and_then(|tab| tab.owner.as_ref()),
+ };
+ if owner.is_some_and(|owner| owner != client)
+ || (owner.is_none()
+ && lease.access_mode == FrontendAccessMode::Handoff
+ && lease.handoff_ever_owned)
+ || lease.ownership_generation == u64::MAX
+ || state.is_some_and(|state| state.ownership_generation == u64::MAX)
+ {
+ return Err(Error::Unavailable);
+ }
+ Ok(Self {
+ mode: lease.access_mode,
+ global_generation: lease.ownership_generation,
+ tab_generation: state.map_or(0, |state| state.ownership_generation),
+ owner: owner.cloned(),
+ })
+ }
+}
+
+pub struct ExportedPane {
+ target: Target,
+ mux: Weak<Mux>,
+ pane: Weak<dyn Pane>,
+ tab: Weak<Tab>,
+ tab_id: TabId,
+ client: ClientId,
+ registration: ClientRegistrationId,
+ ownership: Ownership,
+ membership: PaneMembership,
+}
+
+impl ExportedPane {
+ /// The caller is the trusted local management path. Identity, terminal
+ /// instance, and ownership are captured here by the actual terminal host.
+ pub fn capture(mux: &Arc<Mux>, pane_id: PaneId, client: &ClientId) -> Result<Arc<Self>> {
+ let pane = mux.get_pane(pane_id).ok_or(Error::Unavailable)?;
+ let local = pane.downcast_ref::<LocalPane>().ok_or(Error::Unavailable)?;
+ local.connect_eligible()?;
+ let (_, _, tab_id) = mux.resolve_pane_id(pane_id).ok_or(Error::Unavailable)?;
+ let tab = mux.get_tab(tab_id).ok_or(Error::Unavailable)?;
+ let registration = mux
+ .client_registrations
+ .try_read()
+ .ok_or(Error::Busy)?
+ .get(client)
+ .copied()
+ .ok_or(Error::Unavailable)?;
+ let ownership = Ownership::capture(&mux.frontend_lease.lock(), tab_id, client)?;
+ let membership = tab.capture_delegated_pane(pane_id)?;
+ let mut owner = [0; 16];
+ getrandom::fill(&mut owner).map_err(|_| Error::Random)?;
+ let exported = Arc::new(Self {
+ target: Target::new(pane_id as u64, Id::from_bytes(owner))?,
+ mux: Arc::downgrade(mux),
+ pane: Arc::downgrade(&pane),
+ tab: Arc::downgrade(&tab),
+ tab_id,
+ client: client.clone(),
+ registration,
+ ownership,
+ membership,
+ });
+ exported.with_current(|_| Ok(()))?;
+ Ok(exported)
+ }
+
+ pub fn target(&self) -> Target {
+ self.target
+ }
+
+ fn with_current<T>(&self, action: impl FnOnce(&LocalPane) -> Result<T>) -> Result<T> {
+ let mux = self.mux.upgrade().ok_or(Error::Unavailable)?;
+ let pane = self.pane.upgrade().ok_or(Error::Unavailable)?;
+ let tab = self.tab.upgrade().ok_or(Error::Unavailable)?;
+ let panes = mux.panes.try_read().ok_or(Error::Busy)?;
+ if !panes
+ .get(&pane.pane_id())
+ .is_some_and(|current| Arc::ptr_eq(current, &pane))
+ {
+ return Err(Error::Unavailable);
+ }
+ let tabs = mux.tabs.try_read().ok_or(Error::Busy)?;
+ if !tabs
+ .get(&self.tab_id)
+ .is_some_and(|current| Arc::ptr_eq(current, &tab))
+ {
+ return Err(Error::Unavailable);
+ }
+ tab.with_delegated_panes(&[(pane.pane_id(), &self.membership)], || {
+ let registrations = mux.client_registrations.try_read().ok_or(Error::Busy)?;
+ if registrations.get(&self.client) != Some(&self.registration) {
+ return Err(Error::Unavailable);
+ }
+ let lease = mux.frontend_lease.try_lock().ok_or(Error::Busy)?;
+ if Ownership::capture(&lease, self.tab_id, &self.client)? != self.ownership {
+ return Err(Error::Unavailable);
+ }
+ let local = pane.downcast_ref::<LocalPane>().ok_or(Error::Unavailable)?;
+ local.connect_eligible()?;
+ action(local)
+ })?
+ }
+
+ pub fn is_current(&self) -> bool {
+ matches!(self.with_current(|_| Ok(())), Ok(()) | Err(Error::Busy))
+ }
+
+ pub fn execute<T>(
+ &self,
+ permit: &RequestPermit,
+ action: impl FnOnce(&LocalPane) -> T,
+ ) -> Result<T> {
+ self.with_current(|local| permit.execute(self.target, || action(local)))
+ }
+
+ /// `execute` retried for as long as a lock another thread holds is what
+ /// stands in the way. Busy means that attempt did nothing, and a terminal
+ /// with heavy output is held often. The locks are only ever tried, and
+ /// this waits on the executor rather than on any of them.
+ async fn execute_when_free<T>(
+ &self,
+ permit: &RequestPermit,
+ deadline: &Deadline,
+ mut action: impl FnMut(&LocalPane) -> Result<T>,
+ ) -> Result<T> {
+ deadline
+ .retry_busy(|_| {
+ Poll::Ready(
+ self.execute(permit, |local| action(local))
+ .and_then(|result| result),
+ )
+ })
+ .await
+ }
+
+ pub async fn read(
+ self: &Arc<Self>,
+ permit: Arc<RequestPermit>,
+ options: ReadOptions,
+ mut reservation: Reservation,
+ deadline: &Deadline,
+ ) -> Result<TextSnapshot> {
+ // Capacity is charged before allocation, including the temporary
+ // reference array in Screen::with_phys_lines.
+ let capacity = thinkterm_reverse_access::MAX_READ_BYTES;
+ reservation.grow(
+ capacity + thinkterm_reverse_access::MAX_READ_LINES * std::mem::size_of::<usize>(),
+ )?;
+ let text = self
+ .execute_when_free(&permit, deadline, |local| local.connect_read(options))
+ .await?;
+ Ok(TextSnapshot {
+ text,
+ target: Arc::clone(self),
+ permit,
+ _reservation: reservation,
+ })
+ }
+
+ pub async fn input(
+ self: &Arc<Self>,
+ permit: Arc<RequestPermit>,
+ input: Input,
+ mut reservation: Reservation,
+ deadline: &Deadline,
+ ) -> Result<PendingInput> {
+ reservation.grow(6 * thinkterm_reverse_access::MAX_INPUT_BYTES + 1024)?;
+ let (writer, encoded) = self
+ .execute_when_free(&permit, deadline, |local| local.connect_input(&input))
+ .await?;
+ let (sender, receiver) = mpsc::sync_channel(1);
+ let task = Arc::new(InputTask {
+ cancelled: AtomicBool::new(false),
+ state: Mutex::new(InputState {
+ bytes: Some(encoded),
+ reservation,
+ progress: InputResult {
+ status: InputStatus::RejectedNotSubmitted,
+ bytes: 0,
+ enter_submitted: false,
+ paste_may_be_open: false,
+ },
+ }),
+ });
+ let queued = Arc::clone(&task);
+ let target = Arc::clone(self);
+ let queued_permit = Arc::clone(&permit);
+ let mut submit: Option<Box<dyn FnOnce() + Send>> = Some(Box::new(move || {
+ let result = queued.submit(target, queued_permit, writer);
+ let _ = sender.send(result);
+ }));
+ self.execute_when_free(&permit, deadline, |local| local.connect_queue(&mut submit))
+ .await?;
+ Ok(PendingInput {
+ task,
+ receiver: Mutex::new(receiver),
+ })
+ }
+}
+
+pub struct TextSnapshot {
+ text: String,
+ target: Arc<ExportedPane>,
+ permit: Arc<RequestPermit>,
+ _reservation: Reservation,
+}
+
+impl TextSnapshot {
+ pub fn len(&self) -> usize {
+ self.text.len()
+ }
+
+ /// `send` must be a nonblocking write. The body is not released to an
+ /// ordinary unbounded output queue after this final permission check.
+ pub fn send<T>(&self, offset: usize, limit: usize, send: impl FnOnce(&[u8]) -> T) -> Result<T> {
+ if offset > self.text.len() {
+ return Err(Error::Protocol);
+ }
+ let end = offset.saturating_add(limit).min(self.text.len());
+ self.target
+ .execute(&self.permit, |_| send(&self.text.as_bytes()[offset..end]))
+ }
+}
+
+pub enum Input {
+ Text {
+ text: String,
+ no_paste: bool,
+ enter: bool,
+ },
+ Keys(Vec<(wezterm_term::KeyCode, wezterm_term::KeyModifiers)>),
+}
+
+pub(crate) struct EncodedInput {
+ pub bytes: Vec<u8>,
+ pub text_end: usize,
+ pub enter: bool,
+ /// Between the text and its Enter, inside this one queue operation.
+ pub enter_delay: Duration,
+ pub paste: bool,
+}
+
+struct InputState {
+ bytes: Option<EncodedInput>,
+ reservation: Reservation,
+ progress: InputResult,
+}
+
+struct InputTask {
+ cancelled: AtomicBool,
+ state: Mutex<InputState>,
+}
+
+impl InputTask {
+ fn cancel(&self) {
+ self.cancelled.store(true, Ordering::Release);
+ let mut state = self.state.lock();
+ state.bytes = None;
+ // Keep the concurrency slot until this callback leaves the existing
+ // writer queue. Cancellation cannot accumulate unbounded empty jobs.
+ let bytes = state.reservation.bytes();
+ let _ = state.reservation.release_bytes(bytes);
+ }
+
+ fn submit(
+ &self,
+ target: Arc<ExportedPane>,
+ permit: Arc<RequestPermit>,
+ mut writer: Box<dyn portable_pty::TryInputWriter>,
+ ) -> InputResult {
+ self.submit_checked(
+ || permit.execute(target.target, || ()),
+ |bytes| target.execute(&permit, |_| writer.try_write(bytes)),
+ )
+ }
+
+ fn submit_checked(
+ &self,
+ mut check: impl FnMut() -> Result<()>,
+ mut write: impl FnMut(&[u8]) -> Result<io::Result<usize>>,
+ ) -> InputResult {
+ let mut text_submitted = None;
+ loop {
+ let mut state = self.state.lock();
+ if self.cancelled.load(Ordering::Acquire) {
+ return state.progress;
+ }
+ if check().is_err() {
+ return state.progress;
+ }
+ let Some(encoded) = state.bytes.as_ref() else {
+ return state.progress;
+ };
+ let offset = state.progress.bytes;
+ let text_end = encoded.text_end;
+ let enter = encoded.enter;
+ let paste = encoded.paste;
+ let length = encoded.bytes.len();
+ if offset == length {
+ state.progress.status = InputStatus::Submitted;
+ state.progress.enter_submitted = enter;
+ state.progress.paste_may_be_open = false;
+ state.bytes = None;
+ return state.progress;
+ }
+ if enter && offset == text_end && text_end > 0 {
+ // Every turn of this wait repeats the checks above, so
+ // revocation still stops the Enter.
+ let submitted = *text_submitted.get_or_insert_with(Instant::now);
+ if submitted.elapsed() < encoded.enter_delay {
+ drop(state);
+ std::thread::sleep(Duration::from_millis(10));
+ continue;
+ }
+ }
+ let block_end = if offset < text_end { text_end } else { length };
+ let end = offset.saturating_add(4096).min(block_end);
+ match write(&encoded.bytes[offset..end]) {
+ Ok(Ok(count)) if count > 0 && count <= end - offset => {
+ state.progress.bytes += count;
+ state.progress.status = if state.progress.bytes == length {
+ InputStatus::Submitted
+ } else {
+ InputStatus::PartiallySubmitted
+ };
+ state.progress.enter_submitted = enter && state.progress.bytes == length;
+ state.progress.paste_may_be_open = paste && state.progress.bytes < text_end;
+ }
+ Ok(Err(error))
+ if matches!(
+ error.kind(),
+ io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
+ ) =>
+ {
+ drop(state);
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ Err(Error::Busy) => {
+ drop(state);
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ Err(_) => return state.progress,
+ _ => {
+ state.progress.status = InputStatus::OutcomeUnknown;
+ return state.progress;
+ }
+ }
+ }
+ }
+}
+
+pub struct PendingInput {
+ task: Arc<InputTask>,
+ receiver: Mutex<mpsc::Receiver<InputResult>>,
+}
+
+impl PendingInput {
+ pub fn try_result(&self) -> Option<InputResult> {
+ match self.receiver.lock().try_recv() {
+ Ok(result) => Some(result),
+ Err(mpsc::TryRecvError::Empty) => None,
+ Err(mpsc::TryRecvError::Disconnected) => Some(self.task.state.lock().progress),
+ }
+ }
+
+ pub fn cancel(&self) -> InputResult {
+ self.task.cancel();
+ self.task.state.lock().progress
+ }
+}
+
+impl Drop for PendingInput {
+ fn drop(&mut self) {
+ self.task.cancel();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::TabFrontendLease;
+
+ fn client(id: usize) -> ClientId {
+ ClientId {
+ hostname: "devbox".into(),
+ username: "example".into(),
+ pid: 42,
+ ssh_auth_sock: None,
+ epoch: 1,
+ id,
+ }
+ }
+
+ #[test]
+ fn ownership_cannot_return_to_an_old_delegation_after_a_round_trip() {
+ let first = client(1);
+ let second = client(2);
+ let mut lease = FrontendLeaseState::default();
+ lease.set_handoff_owner(Some(first.clone()));
+ let captured = Ownership::capture(&lease, 1, &first).unwrap();
+ lease.set_handoff_owner(Some(second));
+ lease.set_handoff_owner(Some(first.clone()));
+ assert!(Ownership::capture(&lease, 1, &first).unwrap() != captured);
+ let mut tab = TabFrontendLease::default();
+ tab.set_owner(Some(first.clone()));
+ let generation = tab.ownership_generation;
+ tab.set_owner(Some(first));
+ assert_eq!(tab.ownership_generation, generation);
+ tab.set_owner(None);
+ assert_ne!(tab.ownership_generation, generation);
+ }
+
+ fn input_task(
+ bytes: &[u8],
+ enter: bool,
+ paste: bool,
+ ) -> (InputTask, thinkterm_reverse_access::budget::Budgets) {
+ let budgets = thinkterm_reverse_access::budget::Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([1; 16])).unwrap();
+ let reservation = route.acquire(bytes.len()).unwrap();
+ (
+ InputTask {
+ cancelled: AtomicBool::new(false),
+ state: Mutex::new(InputState {
+ bytes: Some(EncodedInput {
+ bytes: bytes.to_vec(),
+ text_end: bytes.len() - usize::from(enter),
+ enter,
+ enter_delay: Duration::ZERO,
+ paste,
+ }),
+ reservation,
+ progress: InputResult {
+ status: InputStatus::RejectedNotSubmitted,
+ bytes: 0,
+ enter_submitted: false,
+ paste_may_be_open: false,
+ },
+ }),
+ },
+ budgets,
+ )
+ }
+
+ #[test]
+ fn revoked_input_cannot_submit_enter_or_another_paste_chunk() {
+ let (task, _) = input_task(b"text\r", true, true);
+ let revoked = AtomicBool::new(false);
+ let mut written = Vec::new();
+ let result = task.submit_checked(
+ || {
+ if revoked.load(Ordering::Acquire) {
+ Err(Error::Revoked)
+ } else {
+ Ok(())
+ }
+ },
+ |bytes| {
+ written.extend_from_slice(&bytes[..2]);
+ revoked.store(true, Ordering::Release);
+ Ok(Ok(2))
+ },
+ );
+ assert_eq!(written, b"te");
+ assert_eq!(result.status, InputStatus::PartiallySubmitted);
+ assert_eq!(result.bytes, 2);
+ assert!(!result.enter_submitted);
+ assert!(result.paste_may_be_open);
+ }
+
+ #[test]
+ fn completed_input_remains_submitted_when_permission_is_then_revoked() {
+ let (task, _) = input_task(b"text\r", true, false);
+ let revoked = AtomicBool::new(false);
+ let result = task.submit_checked(
+ || {
+ if revoked.load(Ordering::Acquire) {
+ Err(Error::Revoked)
+ } else {
+ Ok(())
+ }
+ },
+ |bytes| {
+ revoked.store(bytes == b"\r", Ordering::Release);
+ Ok(Ok(bytes.len()))
+ },
+ );
+ assert_eq!(result.status, InputStatus::Submitted);
+ assert_eq!(result.bytes, 5);
+ assert!(result.enter_submitted);
+ }
+
+ #[test]
+ fn enter_follows_the_text_after_its_delay_as_a_separate_write() {
+ let (task, _) = input_task(b"text\r", true, true);
+ task.state.lock().bytes.as_mut().unwrap().enter_delay = Duration::from_millis(40);
+ let started = Instant::now();
+ let mut writes: Vec<(Vec<u8>, Duration)> = Vec::new();
+ let result = task.submit_checked(
+ || Ok(()),
+ |bytes| {
+ writes.push((bytes.to_vec(), started.elapsed()));
+ Ok(Ok(bytes.len()))
+ },
+ );
+ assert_eq!(result.status, InputStatus::Submitted);
+ assert!(result.enter_submitted);
+ assert!(!result.paste_may_be_open);
+ assert_eq!(writes[0].0, b"text");
+ assert_eq!(writes[1].0, b"\r");
+ assert!(writes[1].1 - writes[0].1 >= Duration::from_millis(40));
+ }
+
+ #[test]
+ fn revocation_during_the_enter_delay_keeps_the_enter_back() {
+ let (task, _) = input_task(b"text\r", true, false);
+ task.state.lock().bytes.as_mut().unwrap().enter_delay = Duration::from_secs(30);
+ let revoked = AtomicBool::new(false);
+ let mut written = Vec::new();
+ let result = task.submit_checked(
+ || {
+ if revoked.load(Ordering::Acquire) {
+ Err(Error::Revoked)
+ } else {
+ Ok(())
+ }
+ },
+ |bytes| {
+ written.extend_from_slice(bytes);
+ revoked.store(true, Ordering::Release);
+ Ok(Ok(bytes.len()))
+ },
+ );
+ assert_eq!(written, b"text");
+ assert_eq!(result.status, InputStatus::PartiallySubmitted);
+ assert!(!result.enter_submitted);
+ assert!(!result.paste_may_be_open);
+ }
+
+ #[test]
+ fn empty_text_presses_enter_without_waiting() {
+ let (task, _) = input_task(b"\r", true, false);
+ task.state.lock().bytes.as_mut().unwrap().enter_delay = Duration::from_secs(30);
+ let result = task.submit_checked(|| Ok(()), |bytes| Ok(Ok(bytes.len())));
+ assert_eq!(result.status, InputStatus::Submitted);
+ assert!(result.enter_submitted);
+ }
+
+ #[test]
+ fn cancellation_releases_queued_body_but_retains_its_queue_slot() {
+ let (task, budgets) = input_task(b"example", false, false);
+ assert_eq!(budgets.retained().unwrap(), (1, 7));
+ task.cancel();
+ assert!(task.state.lock().bytes.is_none());
+ assert_eq!(budgets.retained().unwrap(), (1, 0));
+ let result = task.submit_checked(
+ || panic!("cancelled input was checked"),
+ |_| panic!("cancelled input was submitted"),
+ );
+ assert_eq!(result.status, InputStatus::RejectedNotSubmitted);
+ drop(task);
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ }
+
+ #[test]
+ fn backpressure_rechecks_permission_and_write_errors_do_not_imply_non_execution() {
+ let (task, _) = input_task(b"example", false, false);
+ let revoked = AtomicBool::new(false);
+ let mut attempts = 0;
+ let result = task.submit_checked(
+ || {
+ if revoked.load(Ordering::Acquire) {
+ Err(Error::Revoked)
+ } else {
+ Ok(())
+ }
+ },
+ |_| {
+ attempts += 1;
+ revoked.store(true, Ordering::Release);
+ Ok(Err(io::ErrorKind::WouldBlock.into()))
+ },
+ );
+ assert_eq!(attempts, 1);
+ assert_eq!(result.status, InputStatus::RejectedNotSubmitted);
+ let result = task.submit_checked(|| Ok(()), |_| Ok(Err(io::ErrorKind::BrokenPipe.into())));
+ assert_eq!(result.status, InputStatus::OutcomeUnknown);
+ }
+}
diff --git a/mux/src/connect/host.rs b/mux/src/connect/host.rs
new file mode 100644
index 00000000..d1187482
--- /dev/null
+++ b/mux/src/connect/host.rs
@@ -0,0 +1,909 @@
+use super::*;
+use serde::{Deserialize, Serialize};
+use smol::io::{AsyncRead, AsyncWrite};
+use std::collections::{HashMap, HashSet};
+use std::convert::TryFrom;
+use std::task::Poll;
+use thinkterm_reverse_access::budget::{Budgets, RouteBudget};
+use thinkterm_reverse_access::channel::{json_frame, Channel, Deadline};
+use thinkterm_reverse_access::native::{AuthorizedGrant, NativeAttempt, NativeSession};
+use thinkterm_reverse_access::protocol::{Command, ExportRef, ExportSummary, Failure, Key, Reply};
+use thinkterm_reverse_access::wire::{Frame, Kind, Payload, MAX_BLOCK};
+use thinkterm_reverse_access::{
+ Authority, Endpoint, GrantRef, GrantScope, ListPermit, Operation, Permission, Request, Route,
+};
+
+pub struct Host {
+ mux: Weak<Mux>,
+ authority: Arc<Authority>,
+ endpoint: Endpoint,
+ budgets: Budgets,
+ state: Mutex<State>,
+}
+
+#[derive(Default)]
+struct State {
+ native: Option<NativeSession>,
+ pending: Option<PendingApproval>,
+ grants: HashMap<Id, StoredGrant>,
+ routes: HashMap<Id, Weak<HostRoute>>,
+ errors: HashMap<Id, Failure>,
+}
+
+struct PendingApproval {
+ route: Id,
+ renewal: Option<GrantRef>,
+ attempt: NativeAttempt,
+ targets: Vec<Arc<ExportedPane>>,
+}
+
+struct StoredGrant {
+ route: Id,
+ grant: AuthorizedGrant,
+ targets: Vec<Arc<ExportedPane>>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct PaneChoice {
+ pub pane: u64,
+ pub title: String,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ActiveGrant {
+ pub grant: GrantRef,
+ pub scope: GrantScope,
+ pub targets: Vec<(u64, Id)>,
+ pub permission: Permission,
+ pub remaining_ms: u64,
+}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct HostStatus {
+ pub grants: Vec<ActiveGrant>,
+ pub authenticating: bool,
+ pub error: Option<Failure>,
+}
+
+pub struct HostRoute {
+ host: Arc<Host>,
+ route: Route,
+ budget: RouteBudget,
+ source: String,
+ language: String,
+ client: ClientId,
+}
+
+impl Host {
+ pub fn close(&self) {
+ self.authority.close();
+ *self.state.lock() = State::default();
+ }
+
+ pub fn new(mux: &Arc<Mux>) -> Result<Arc<Self>> {
+ let (authority, endpoint) = Authority::new();
+ Ok(Arc::new(Self {
+ mux: Arc::downgrade(mux),
+ authority: Arc::new(authority),
+ endpoint,
+ budgets: Budgets::process()?,
+ state: Mutex::new(State::default()),
+ }))
+ }
+
+ pub fn open(
+ self: &Arc<Self>,
+ client: ClientId,
+ source: &str,
+ language: &str,
+ ) -> Result<Arc<HostRoute>> {
+ if source.is_empty() || source.len() > 256 || source.chars().any(char::is_control) {
+ return Err(Error::Protocol);
+ }
+ let route = self.authority.register_route()?;
+ let budget = self.budgets.open_route(route.id())?;
+ let route = Arc::new(HostRoute {
+ host: Arc::clone(self),
+ route,
+ budget,
+ client,
+ source: source.into(),
+ language: language.chars().take(16).collect(),
+ });
+ self.state
+ .lock()
+ .routes
+ .insert(route.id(), Arc::downgrade(&route));
+ Ok(route)
+ }
+
+ fn poll(&self, state: &mut State) {
+ if let Some(pending) = state.pending.take() {
+ match pending.attempt.try_result() {
+ Ok(None) => state.pending = Some(pending),
+ Ok(Some(grant)) => {
+ if state
+ .routes
+ .get(&pending.route)
+ .and_then(Weak::upgrade)
+ .is_some()
+ && pending.targets.iter().all(|target| target.is_current())
+ {
+ state.grants.insert(
+ grant.info().grant.id,
+ StoredGrant {
+ route: pending.route,
+ grant,
+ targets: pending.targets,
+ },
+ );
+ } else {
+ state.errors.insert(pending.route, Failure::Unavailable);
+ }
+ }
+ // The dialog already told the user; a renewal's old grant
+ // simply carries on.
+ Err(Error::Cancelled) => {}
+ Err(error) => {
+ state.errors.insert(pending.route, error.into());
+ }
+ }
+ }
+ let live: HashSet<_> = state
+ .routes
+ .values()
+ .filter_map(Weak::upgrade)
+ .flat_map(|route| self.endpoint.list(&route.route).unwrap_or_default())
+ .map(|info| info.grant.id)
+ .collect();
+ state.grants.retain(|id, grant| {
+ live.contains(id)
+ && (grant.grant.info().scope == GrantScope::AllLocalTerminals
+ || grant.targets.iter().all(|target| target.is_current()))
+ });
+ let State {
+ grants,
+ routes,
+ errors,
+ ..
+ } = state;
+ for stored in grants.values_mut() {
+ if stored.grant.info().scope != GrantScope::AllLocalTerminals {
+ continue;
+ }
+ let result: Result<()> = (|| {
+ let route = routes
+ .get(&stored.route)
+ .and_then(Weak::upgrade)
+ .ok_or(Error::Unavailable)?;
+ let mux = self.mux.upgrade().ok_or(Error::Unavailable)?;
+ let targets = route.all_local_targets(&mux, &stored.targets)?;
+ self.authority.replace_all_local_targets(
+ &route.route,
+ stored.grant.info().grant,
+ targets.iter().map(|target| target.target()).collect(),
+ )?;
+ stored.targets = targets;
+ Ok(())
+ })();
+ if let Err(error) = result {
+ if error != Error::Busy {
+ let _ = self.authority.revoke(stored.grant.info().grant);
+ errors.insert(stored.route, error.into());
+ }
+ }
+ }
+ if state.grants.is_empty() && state.pending.is_none() {
+ state.native = None;
+ }
+ }
+
+ fn forget(&self, id: Id) {
+ let mut state = self.state.lock();
+ state.routes.remove(&id);
+ state.errors.remove(&id);
+ state.grants.retain(|_, grant| grant.route != id);
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|pending| pending.route == id)
+ {
+ state.pending = None;
+ }
+ if state.grants.is_empty() && state.pending.is_none() {
+ state.native = None;
+ }
+ }
+}
+
+impl HostRoute {
+ pub fn id(&self) -> Id {
+ self.route.id()
+ }
+ pub fn budget(&self) -> &RouteBudget {
+ &self.budget
+ }
+ pub fn heartbeat(&self) -> Result<()> {
+ self.route.heartbeat()
+ }
+ pub fn close(&self) {
+ self.route.close();
+ self.host.forget(self.id());
+ }
+
+ pub fn choices(&self, after: Option<u64>) -> Result<(Vec<PaneChoice>, Option<u64>)> {
+ let mux = self.host.mux.upgrade().ok_or(Error::Unavailable)?;
+ let mut page = std::collections::BTreeSet::new();
+ for &id in mux.panes.read().keys() {
+ if after.is_some_and(|after| (id as u64) <= after) {
+ continue;
+ }
+ page.insert(id);
+ if page.len() > 33 {
+ page.pop_last();
+ }
+ }
+ let mut panes: Vec<_> = page.into_iter().collect();
+ let more = panes.len() > 32;
+ panes.truncate(32);
+ let next = more
+ .then(|| panes.last().copied().map(|id| id as u64))
+ .flatten();
+ let mut choices = Vec::new();
+ for id in panes {
+ if let Ok(pane) = ExportedPane::capture(&mux, id, &self.client) {
+ if let Ok(title) = pane.with_current(|local| local.connect_title()) {
+ choices.push(PaneChoice {
+ pane: id as u64,
+ title,
+ });
+ }
+ }
+ }
+ choices.sort_by_key(|pane| pane.pane);
+ Ok((choices, next))
+ }
+
+ fn all_local_targets(
+ &self,
+ mux: &Arc<Mux>,
+ previous: &[Arc<ExportedPane>],
+ ) -> Result<Vec<Arc<ExportedPane>>> {
+ let panes = mux.panes.try_read().ok_or(Error::Busy)?;
+ let ids: Vec<_> = panes
+ .values()
+ .filter(|pane| pane.downcast_ref::<LocalPane>().is_some())
+ .map(|pane| pane.pane_id())
+ .collect();
+ drop(panes);
+ let mut targets = Vec::new();
+ for id in ids {
+ if let Some(old) = previous
+ .iter()
+ .find(|target| target.target().pane == id as u64)
+ {
+ if old.is_current() {
+ targets.push(Arc::clone(old));
+ if targets.len() > thinkterm_reverse_access::MAX_TARGETS {
+ return Err(Error::TooLarge);
+ }
+ continue;
+ }
+ }
+ match ExportedPane::capture(mux, id, &self.client) {
+ Ok(target) => targets.push(target),
+ Err(Error::Busy) => return Err(Error::Busy),
+ Err(Error::Unavailable) => continue,
+ Err(error) => return Err(error),
+ }
+ if targets.len() > thinkterm_reverse_access::MAX_TARGETS {
+ return Err(Error::TooLarge);
+ }
+ }
+ targets.sort_by_key(|target| target.target().pane);
+ Ok(targets)
+ }
+
+ /// Native authentication consumes a frozen intent inside this host.
+ /// There is intentionally no method that accepts an approval result.
+ pub fn begin_approval(
+ &self,
+ panes: &[u64],
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ ) -> Result<()> {
+ if panes.is_empty() || panes.len() > thinkterm_reverse_access::MAX_TARGETS_PER_GRANT {
+ return Err(Error::TooLarge);
+ }
+ let mux = self.host.mux.upgrade().ok_or(Error::Unavailable)?;
+ let targets: Vec<_> = panes
+ .iter()
+ .map(|id| {
+ let id = usize::try_from(*id).map_err(|_| Error::Unavailable)?;
+ ExportedPane::capture(&mux, id, &self.client)
+ })
+ .collect::<Result<_>>()?;
+ self.begin_scoped_approval(
+ GrantScope::SelectedTerminals,
+ targets,
+ permission,
+ seconds,
+ renewal,
+ )
+ }
+
+ pub fn begin_all_local_approval(
+ &self,
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ ) -> Result<()> {
+ self.begin_scoped_approval(
+ GrantScope::AllLocalTerminals,
+ Vec::new(),
+ permission,
+ seconds,
+ renewal,
+ )
+ }
+
+ fn begin_scoped_approval(
+ &self,
+ scope: GrantScope,
+ targets: Vec<Arc<ExportedPane>>,
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ ) -> Result<()> {
+ let mut state = self.host.state.lock();
+ self.host.poll(&mut state);
+ let result: Result<()> = (|| {
+ if let Some(pending) = &state.pending {
+ // A second press of this route's button, before the status
+ // that hides it arrived, is the approval already running.
+ return if pending.route == self.id() {
+ Ok(())
+ } else {
+ Err(Error::Busy)
+ };
+ }
+ if state.native.is_none() {
+ state.native = Some(NativeSession::start(self.host.authority.clone())?);
+ }
+ let approval = match scope {
+ GrantScope::SelectedTerminals => self.host.authority.prepare(
+ &self.route,
+ targets.iter().map(|target| target.target()).collect(),
+ permission,
+ seconds,
+ renewal,
+ )?,
+ GrantScope::AllLocalTerminals => self.host.authority.prepare_all_local(
+ &self.route,
+ permission,
+ seconds,
+ renewal,
+ )?,
+ };
+ let attempt = state
+ .native
+ .as_ref()
+ .ok_or(Error::Unavailable)?
+ .authenticate(approval, &self.source, &self.language)?;
+ state.pending = Some(PendingApproval {
+ route: self.id(),
+ renewal,
+ attempt,
+ targets,
+ });
+ Ok(())
+ })();
+ match result {
+ Ok(()) => {
+ state.errors.remove(&self.id());
+ }
+ // The answer to this command is gone with the next status; this
+ // stays until the user moves on from it.
+ Err(error) => {
+ state.errors.insert(self.id(), error.into());
+ }
+ }
+ if result.is_err() && state.grants.is_empty() && state.pending.is_none() {
+ state.native = None;
+ }
+ result
+ }
+
+ pub fn cancel_approval(&self) {
+ let mut state = self.host.state.lock();
+ state.errors.remove(&self.id());
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|pending| pending.route == self.id())
+ {
+ state.pending = None;
+ }
+ self.host.poll(&mut state);
+ }
+
+ pub fn revoke(&self, grant: GrantRef) -> Result<()> {
+ let mut state = self.host.state.lock();
+ self.host.authority.revoke_current(&self.route, grant.id)?;
+ if state.pending.as_ref().is_some_and(|pending| {
+ pending.route == self.id()
+ && pending
+ .renewal
+ .is_some_and(|renewal| renewal.id == grant.id)
+ }) {
+ state.pending = None;
+ }
+ if state
+ .grants
+ .get(&grant.id)
+ .is_some_and(|stored| stored.route == self.id())
+ {
+ state.grants.remove(&grant.id);
+ }
+ self.host.poll(&mut state);
+ Ok(())
+ }
+
+ pub fn status(&self) -> HostStatus {
+ let mut state = self.host.state.lock();
+ self.host.poll(&mut state);
+ let grants = self
+ .host
+ .endpoint
+ .list(&self.route)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|info| ActiveGrant {
+ grant: info.grant,
+ scope: info.scope,
+ permission: info.permission,
+ targets: info
+ .targets
+ .iter()
+ .map(|target| (target.pane, target.incarnation))
+ .collect(),
+ remaining_ms: info.remaining.as_millis().min(u64::MAX as u128) as u64,
+ })
+ .collect();
+ HostStatus {
+ grants,
+ authenticating: state
+ .pending
+ .as_ref()
+ .is_some_and(|pending| pending.route == self.id()),
+ error: state.errors.get(&self.id()).copied(),
+ }
+ }
+
+ /// The page of a listing after `after`, with what each row needs. By
+ /// position in the order rather than by identity, so paging goes on past
+ /// a terminal that closed under it.
+ fn list_page(&self, after: Option<ExportRef>) -> Result<(Vec<ListRow>, bool)> {
+ fn order(export: &ExportRef) -> ([u8; 16], u64, u64) {
+ (
+ *export.grant.id.as_bytes(),
+ export.grant.version,
+ export.target.pane,
+ )
+ }
+ let mut state = self.host.state.lock();
+ self.host.poll(&mut state);
+ let mut items = Vec::new();
+ for info in self.host.endpoint.list(&self.route)? {
+ for target in &info.targets {
+ items.push((
+ ExportRef {
+ grant: info.grant,
+ target: *target,
+ },
+ info.permission,
+ info.remaining.as_millis().min(u64::MAX as u128) as u64,
+ ));
+ }
+ }
+ items.sort_by_key(|(export, _, _)| order(export));
+ let start = after.map_or(0, |after| {
+ items.partition_point(|(export, _, _)| order(export) <= order(&after))
+ });
+ let more = items.len() > start + 32;
+ let page = items
+ .into_iter()
+ .skip(start)
+ .take(32)
+ .map(|(export, permission, remaining_ms)| {
+ Ok((
+ export,
+ permission,
+ remaining_ms,
+ find_target(&state, self.id(), export)?,
+ ))
+ })
+ .collect::<Result<_>>()?;
+ Ok((page, more))
+ }
+
+ /// The work ends at `operation`, as in `PreparedReply::send`. List and
+ /// read permits also cover the writing of their reply, so they run to
+ /// `deadline`: expiring first, they would stop a frame partway through.
+ /// Input's is over with the operation.
+ pub async fn prepare_reply(
+ self: &Arc<Self>,
+ sequence: u64,
+ command: Command,
+ payload: Option<Payload>,
+ operation: &Deadline,
+ deadline: &Deadline,
+ ) -> Result<PreparedReply> {
+ command.validate()?;
+ let reservation = self.budget.acquire(64 * 1024)?;
+ if let Command::List { after } = command {
+ let permit =
+ self.host
+ .endpoint
+ .accept_list_for(&self.route, sequence, deadline.remaining()?)?;
+ let (page, more) = self.list_page(after)?;
+ let mut exports = Vec::new();
+ let mut targets = Vec::new();
+ for (export, permission, remaining_ms, target) in page {
+ let title = operation
+ .retry_busy(|_| Poll::Ready(target.with_current(|local| local.connect_title())))
+ .await;
+ let title = match title {
+ Ok(title) => title,
+ // Closed since the page was chosen: no longer one of them.
+ Err(Error::Unavailable) => continue,
+ Err(error) => return Err(error),
+ };
+ exports.push(ExportSummary {
+ export,
+ name: export.target.pane.to_string(),
+ title,
+ permission,
+ remaining_ms,
+ });
+ targets.push(target);
+ }
+ return Ok(PreparedReply::List {
+ exports,
+ more,
+ targets,
+ permit,
+ _reservation: reservation,
+ });
+ }
+ let (export, kind, permitted) = match &command {
+ Command::Read { export, .. } => (*export, Operation::Read, deadline),
+ Command::Text { export, .. } | Command::Keys { export, .. } => {
+ (*export, Operation::Input, operation)
+ }
+ _ => return Err(Error::Protocol),
+ };
+ let permit = Arc::new(self.host.endpoint.accept_for(
+ &self.route,
+ Request {
+ grant: export.grant,
+ target: export.target,
+ operation: kind,
+ sequence,
+ },
+ permitted.remaining()?,
+ )?);
+ let target = {
+ let mut state = self.host.state.lock();
+ self.host.poll(&mut state);
+ find_target(&state, self.id(), export)?
+ };
+ match command {
+ Command::Read { options, .. } => {
+ let snapshot = target.read(permit, options, reservation, operation).await?;
+ self.budget.charge_output(snapshot.len())?;
+ Ok(PreparedReply::Text(snapshot))
+ }
+ Command::Text {
+ bytes,
+ no_paste,
+ enter,
+ ..
+ } => {
+ let mut payload = payload.ok_or(Error::Protocol)?;
+ if payload.text().len() != bytes {
+ return Err(Error::Protocol);
+ }
+ payload.reservation().grow(bytes)?;
+ let input = Input::Text {
+ text: payload.text().to_string(),
+ no_paste,
+ enter,
+ };
+ let pending = target.input(permit, input, reservation, operation).await?;
+ Ok(PreparedReply::Input {
+ pending,
+ _payload: Some(payload),
+ })
+ }
+ Command::Keys { keys, .. } => {
+ let keys = keys.into_iter().map(decode_key).collect::<Result<_>>()?;
+ Ok(PreparedReply::Input {
+ pending: target
+ .input(permit, Input::Keys(keys), reservation, operation)
+ .await?,
+ _payload: None,
+ })
+ }
+ _ => Err(Error::Protocol),
+ }
+ }
+}
+
+impl Drop for HostRoute {
+ fn drop(&mut self) {
+ self.route.close();
+ // A temporary Weak upgrade during Host::poll can be the last owner.
+ // Cleanup must not recursively lock the state being inspected.
+ if let Some(mut state) = self.host.state.try_lock() {
+ state.routes.remove(&self.id());
+ state.errors.remove(&self.id());
+ state.grants.retain(|_, grant| grant.route != self.id());
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|pending| pending.route == self.id())
+ {
+ state.pending = None;
+ }
+ if state.grants.is_empty() && state.pending.is_none() {
+ state.native = None;
+ }
+ }
+ }
+}
+
+fn find_target(state: &State, route: Id, export: ExportRef) -> Result<Arc<ExportedPane>> {
+ let grant = state
+ .grants
+ .get(&export.grant.id)
+ .filter(|grant| grant.route == route && grant.grant.info().grant == export.grant)
+ .ok_or(Error::Unavailable)?;
+ grant
+ .targets
+ .iter()
+ .find(|target| target.target() == export.target)
+ .cloned()
+ .ok_or(Error::Unavailable)
+}
+
+fn decode_key(key: Key) -> Result<(wezterm_term::KeyCode, wezterm_term::KeyModifiers)> {
+ use wezterm_term::{KeyCode as K, KeyModifiers as M};
+ let allowed = M::CTRL | M::ALT | M::SHIFT | M::SUPER;
+ let modifiers = M::from_bits(key.modifiers)
+ .filter(|mods| allowed.contains(*mods))
+ .ok_or(Error::Protocol)?;
+ let mut chars = key.name.chars();
+ let code = match (chars.next(), chars.next()) {
+ (Some(c), None) if !c.is_control() => K::Char(c),
+ _ => match key.name.to_ascii_lowercase().as_str() {
+ "enter" => K::Enter,
+ "tab" => K::Tab,
+ "escape" => K::Escape,
+ "backspace" => K::Backspace,
+ "delete" => K::Delete,
+ "up" => K::UpArrow,
+ "down" => K::DownArrow,
+ "left" => K::LeftArrow,
+ "right" => K::RightArrow,
+ "home" => K::Home,
+ "end" => K::End,
+ "pageup" => K::PageUp,
+ "pagedown" => K::PageDown,
+ "insert" => K::Insert,
+ name => match name
+ .strip_prefix('f')
+ .and_then(|value| value.parse::<u8>().ok())
+ {
+ Some(number @ 1..=24) => K::Function(number),
+ _ => return Err(Error::Protocol),
+ },
+ },
+ };
+ Ok((code, modifiers))
+}
+
+type ListRow = (ExportRef, Permission, u64, Arc<ExportedPane>);
+
+pub enum PreparedReply {
+ List {
+ exports: Vec<ExportSummary>,
+ more: bool,
+ targets: Vec<Arc<ExportedPane>>,
+ permit: ListPermit,
+ _reservation: Reservation,
+ },
+ Text(TextSnapshot),
+ Input {
+ pending: PendingInput,
+ _payload: Option<Payload>,
+ },
+}
+
+impl PreparedReply {
+ /// Waiting and preparing end at `operation`; the reply itself may take
+ /// until `deadline`. Whatever stops the work between frames is answered,
+ /// so the channel stays in step. An error here leaves part of a frame on
+ /// it, or no reader, and closes it.
+ pub async fn send<S: AsyncRead + AsyncWrite + Unpin>(
+ &self,
+ channel: &mut Channel<S>,
+ sequence: u64,
+ operation: &Deadline,
+ deadline: &Deadline,
+ ) -> Result<()> {
+ match self {
+ Self::List {
+ exports,
+ more,
+ targets,
+ permit,
+ ..
+ } => {
+ let refs: Vec<_> = exports
+ .iter()
+ .map(|export| (export.export.grant, export.export.target))
+ .collect();
+ let allowed = operation
+ .retry_busy(|_| {
+ Poll::Ready(with_current_targets(targets, || {
+ permit.execute(&refs, || ())
+ })?)
+ })
+ .await;
+ if let Err(error) = allowed {
+ let reply = Reply::Failed(error.into());
+ return channel
+ .write_json(Kind::Reply, sequence, &reply, deadline)
+ .await;
+ }
+ let frame = json_frame(
+ Kind::Reply,
+ sequence,
+ &Reply::List {
+ exports: exports.clone(),
+ more: *more,
+ },
+ )?;
+ channel
+ .write_guarded(&frame, deadline, |write| {
+ with_current_targets(targets, || permit.execute(&refs, write))?
+ })
+ .await
+ }
+ Self::Text(snapshot) => {
+ let allowed = operation
+ .retry_busy(|_| Poll::Ready(snapshot.send(0, 0, |_| ())))
+ .await;
+ if let Err(error) = allowed {
+ let reply = Reply::Failed(error.into());
+ return channel
+ .write_json(Kind::Reply, sequence, &reply, deadline)
+ .await;
+ }
+ let header = json_frame(
+ Kind::Reply,
+ sequence,
+ &Reply::Text {
+ bytes: snapshot.len(),
+ },
+ )?;
+ channel
+ .write_guarded(&header, deadline, |write| snapshot.send(0, 0, |_| write()))
+ .await?;
+ let mut offset = 0;
+ while offset < snapshot.len() {
+ let frame = operation
+ .retry_busy(|_| {
+ Poll::Ready(snapshot.send(offset, MAX_BLOCK, |bytes| {
+ let mut block = Vec::with_capacity(bytes.len() + 4);
+ block.extend_from_slice(&(offset as u32).to_be_bytes());
+ block.extend_from_slice(bytes);
+ Frame::new(Kind::TextBlock, sequence, &block)
+ })?)
+ })
+ .await;
+ let Ok(frame) = frame else {
+ // The terminal went, or the time ran out, between two
+ // blocks: this reply ends here, and the route goes on.
+ let abandoned = Frame::new(Kind::Cancel, sequence, &[])?;
+ return channel.write(&abandoned, deadline).await;
+ };
+ channel
+ .write_guarded(&frame, deadline, |write| snapshot.send(0, 0, |_| write()))
+ .await?;
+ offset += frame.body().len() - 4;
+ }
+ Ok(())
+ }
+ Self::Input { pending, .. } => {
+ let result = loop {
+ if let Some(result) = pending.try_result() {
+ break result;
+ }
+ if operation.remaining().is_err() {
+ break pending.cancel();
+ }
+ smol::Timer::after(Duration::from_millis(2)).await;
+ };
+ channel
+ .write_json(Kind::Reply, sequence, &Reply::Input(result), deadline)
+ .await
+ }
+ }
+ }
+}
+
+fn with_current_targets<T>(targets: &[Arc<ExportedPane>], action: impl FnOnce() -> T) -> Result<T> {
+ if targets.is_empty() {
+ return Ok(action());
+ }
+ let mux = targets[0].mux.upgrade().ok_or(Error::Unavailable)?;
+ let panes = mux.panes.try_read().ok_or(Error::Busy)?;
+ let tabs = mux.tabs.try_read().ok_or(Error::Busy)?;
+ let registrations = mux.client_registrations.try_read().ok_or(Error::Busy)?;
+ let lease = mux.frontend_lease.try_lock().ok_or(Error::Busy)?;
+ let mut groups: Vec<(Arc<Tab>, Vec<(PaneId, &PaneMembership)>)> = Vec::new();
+ for target in targets {
+ if !target
+ .mux
+ .upgrade()
+ .is_some_and(|owner| Arc::ptr_eq(&owner, &mux))
+ || registrations.get(&target.client) != Some(&target.registration)
+ || Ownership::capture(&lease, target.tab_id, &target.client)? != target.ownership
+ {
+ return Err(Error::Unavailable);
+ }
+ let pane = target.pane.upgrade().ok_or(Error::Unavailable)?;
+ if !panes
+ .get(&pane.pane_id())
+ .is_some_and(|current| Arc::ptr_eq(current, &pane))
+ {
+ return Err(Error::Unavailable);
+ }
+ pane.downcast_ref::<LocalPane>()
+ .ok_or(Error::Unavailable)?
+ .connect_eligible()?;
+ let tab = target.tab.upgrade().ok_or(Error::Unavailable)?;
+ if !tabs
+ .get(&target.tab_id)
+ .is_some_and(|current| Arc::ptr_eq(current, &tab))
+ {
+ return Err(Error::Unavailable);
+ }
+ if let Some((_, panes)) = groups
+ .iter_mut()
+ .find(|(existing, _)| Arc::ptr_eq(existing, &tab))
+ {
+ panes.push((pane.pane_id(), &target.membership));
+ } else {
+ groups.push((tab, vec![(pane.pane_id(), &target.membership)]));
+ }
+ }
+ fn locked<T, F: FnOnce() -> T>(
+ groups: &[(Arc<Tab>, Vec<(PaneId, &PaneMembership)>)],
+ action: F,
+ ) -> Result<T> {
+ match groups.split_first() {
+ Some(((tab, panes), remaining)) => {
+ tab.with_delegated_panes(panes, || locked(remaining, action))?
+ }
+ None => Ok(action()),
+ }
+ }
+ locked(&groups, action)
+}
diff --git a/mux/src/connect/service.rs b/mux/src/connect/service.rs
new file mode 100644
index 00000000..aa6a0694
--- /dev/null
+++ b/mux/src/connect/service.rs
@@ -0,0 +1,1108 @@
+//! A local admission socket, separate from the general mux PDU dispatcher.
+//! The only authentication result is the host's own inherited native pipe.
+
+use super::{Host, HostRoute, HostStatus, PaneChoice};
+use crate::{client::ClientId, Mux};
+use parking_lot::Mutex;
+use serde::{Deserialize, Serialize};
+use smol::channel::{bounded, Receiver, Sender};
+use smol::future::FutureExt;
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Weak};
+use std::time::Duration;
+use thinkterm_reverse_access::budget::{Budgets, Reservation, RouteBudget};
+use thinkterm_reverse_access::channel::{parse, Channel, Deadline, REPLY_MARGIN};
+use thinkterm_reverse_access::exchange::{receive_input, receive_reply, send_payload};
+use thinkterm_reverse_access::ipc::{LocalListener, LocalStream};
+use thinkterm_reverse_access::protocol::{Command, Reply, TimedCommand};
+use thinkterm_reverse_access::wire::{Assembly, Kind, Payload};
+use thinkterm_reverse_access::{Error, GrantRef, Id, Permission, Result};
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub enum Hello {
+ Manage {
+ server_id: String,
+ client: ClientId,
+ source: String,
+ /// Of the authentication window. Only picks one of its translations.
+ language: String,
+ },
+ Data {
+ route: Id,
+ },
+ Register {
+ name: String,
+ },
+ Browse,
+ Request {
+ route: Id,
+ },
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Bound {
+ pub server_id: String,
+ pub route: Option<Id>,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub enum Control {
+ Status,
+ Choices {
+ after: Option<u64>,
+ },
+ Approve {
+ panes: Vec<u64>,
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ },
+ ApproveAllLocal {
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ },
+ Revoke {
+ grant: GrantRef,
+ },
+ Cancel,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub enum Controlled {
+ Status(HostStatus),
+ Choices {
+ panes: Vec<PaneChoice>,
+ after: Option<u64>,
+ },
+ Failed(thinkterm_reverse_access::protocol::Failure),
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct RouterRoute {
+ pub id: Id,
+ pub name: String,
+}
+
+struct Managed {
+ pid: u32,
+ route: Weak<HostRoute>,
+}
+
+struct Routed {
+ name: String,
+ queue: Sender<Forward>,
+ budget: RouteBudget,
+}
+
+struct Forward {
+ command: Command,
+ payload: Option<Payload>,
+ reply: Sender<(Reply, Option<Payload>)>,
+ deadline: Deadline,
+ reservation: Reservation,
+}
+
+/// How long past a request's own deadline its reply is waited for. The
+/// requester has gone by then, but the channel is serial: only that reply, or
+/// giving up on the desktop altogether, puts it back in step. A slow
+/// connection's buffers can hold this much of a reply the desktop sent in time.
+const LATE_REPLY: Duration = Duration::from_secs(15);
+
+pub struct Service {
+ host: Arc<Host>,
+ mux: Weak<Mux>,
+ name: String,
+ budgets: Budgets,
+ managed: Mutex<HashMap<Id, Managed>>,
+ routed: Mutex<HashMap<Id, Routed>>,
+ task: Mutex<Option<smol::Task<()>>>,
+ stop: Sender<()>,
+ stopped: Receiver<()>,
+ candidates: Arc<AtomicUsize>,
+}
+
+impl Service {
+ pub fn start(mux: &Arc<Mux>) -> Result<Arc<Self>> {
+ let listener = LocalListener::bind()?;
+ let (stop, stopped) = bounded(1);
+ let service = Arc::new(Self {
+ host: Host::new(mux)?,
+ mux: Arc::downgrade(mux),
+ name: listener.name().into(),
+ budgets: Budgets::process()?,
+ managed: Mutex::new(HashMap::new()),
+ routed: Mutex::new(HashMap::new()),
+ task: Mutex::new(None),
+ stop,
+ stopped,
+ candidates: Arc::new(AtomicUsize::new(0)),
+ });
+ let weak = Arc::downgrade(&service);
+ *service.task.lock() = Some(smol::spawn(async move {
+ loop {
+ // A peer that could not be identified, say one that has
+ // already gone, comes back as an error too: it must not stop
+ // the listener for everyone after it.
+ let Ok(stream) = listener.accept().await else {
+ smol::Timer::after(Duration::from_millis(100)).await;
+ continue;
+ };
+ // A burst of clients waits here and in the listen queue, each
+ // within its own deadline, rather than being turned away.
+ let (service, budget, reservation, admission) = loop {
+ let Some(service) = weak.upgrade() else {
+ return;
+ };
+ if let Some((budget, reservation, admission)) = service.admit() {
+ break (service, budget, reservation, admission);
+ }
+ drop(service);
+ smol::Timer::after(Duration::from_millis(5)).await;
+ };
+ smol::spawn(async move {
+ let stopped = service.stopped.clone();
+ let _ = service
+ .serve(stream, budget, reservation, admission)
+ .or(async {
+ let _ = stopped.recv().await;
+ Err(Error::Unavailable)
+ })
+ .await;
+ })
+ .detach();
+ }
+ }));
+ Ok(service)
+ }
+
+ pub fn name(&self) -> &str {
+ &self.name
+ }
+
+ /// Reserving before spawning also caps accepted idle clients.
+ fn admit(&self) -> Option<(RouteBudget, Reservation, Admission)> {
+ self.candidates
+ .fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| {
+ (count < 8).then_some(count + 1)
+ })
+ .ok()?;
+ let admission = Admission(Arc::clone(&self.candidates));
+ let budget = self.budgets.open_route(Id::random().ok()?).ok()?;
+ let reservation = budget.acquire(1024 * 1024).ok()?;
+ Some((budget, reservation, admission))
+ }
+
+ pub(crate) fn close(&self) {
+ self.stop.close();
+ self.host.close();
+ self.task.lock().take();
+ }
+
+ async fn serve(
+ self: Arc<Self>,
+ stream: LocalStream,
+ budget: RouteBudget,
+ reservation: Reservation,
+ admission: Admission,
+ ) -> Result<()> {
+ let peer = stream.peer().clone();
+ let mut channel = Channel::new(stream, reservation)?;
+ let handshake = Deadline::after(Duration::from_secs(5))?;
+ let hello: Hello = parse(&channel.read(Some(&handshake)).await?, Kind::Hello, 0)?;
+ drop(admission);
+ let server_id = self
+ .mux
+ .upgrade()
+ .ok_or(Error::Unavailable)?
+ .runtime_server_id()
+ .to_string();
+ match hello {
+ Hello::Manage {
+ server_id: expected,
+ client,
+ source,
+ language,
+ } => {
+ let executable = if cfg!(windows) {
+ "thinkterm-gui.exe"
+ } else {
+ "thinkterm-gui"
+ };
+ if !peer.is_packaged(executable)
+ || peer.pid() != client.pid
+ || expected != server_id
+ {
+ return Err(Error::Unavailable);
+ }
+ let route = self.host.open(client, &source, &language)?;
+ route.heartbeat()?;
+ self.managed.lock().insert(
+ route.id(),
+ Managed {
+ pid: peer.pid(),
+ route: Arc::downgrade(&route),
+ },
+ );
+ let guard = ManagedGuard {
+ service: Arc::downgrade(&self),
+ route: Arc::clone(&route),
+ };
+ channel
+ .write_json(
+ Kind::Bound,
+ 0,
+ &Bound {
+ server_id,
+ route: Some(route.id()),
+ },
+ &handshake,
+ )
+ .await?;
+ let mut sequence = 0;
+ loop {
+ let deadline = Deadline::after(Duration::from_secs(4))?;
+ let frame = channel.read(Some(&deadline)).await?;
+ if frame.sequence() <= sequence {
+ return Err(Error::Replay);
+ }
+ sequence = frame.sequence();
+ let command: Control = parse(&frame, Kind::Request, sequence)?;
+ route.heartbeat()?;
+ let response = match command {
+ Control::Status => Ok(Controlled::Status(route.status())),
+ Control::Choices { after } => route
+ .choices(after)
+ .map(|(panes, after)| Controlled::Choices { panes, after }),
+ Control::Approve {
+ panes,
+ permission,
+ seconds,
+ renewal,
+ } => {
+ let route = Arc::clone(&route);
+ smol::unblock(move || {
+ route.begin_approval(&panes, permission, seconds, renewal)?;
+ Ok(Controlled::Status(route.status()))
+ })
+ .await
+ }
+ Control::ApproveAllLocal {
+ permission,
+ seconds,
+ renewal,
+ } => {
+ let route = Arc::clone(&route);
+ smol::unblock(move || {
+ route.begin_all_local_approval(permission, seconds, renewal)?;
+ Ok(Controlled::Status(route.status()))
+ })
+ .await
+ }
+ Control::Revoke { grant } => route
+ .revoke(grant)
+ .map(|_| Controlled::Status(route.status())),
+ Control::Cancel => {
+ route.cancel_approval();
+ Ok(Controlled::Status(route.status()))
+ }
+ }
+ .unwrap_or_else(|error: Error| Controlled::Failed(error.into()));
+ channel
+ .write_json(Kind::Reply, sequence, &response, &Deadline::request()?)
+ .await?;
+ let _ = &guard;
+ }
+ }
+ Hello::Data { route } => {
+ let executable = if cfg!(windows) {
+ "thinkterm-gui.exe"
+ } else {
+ "thinkterm-gui"
+ };
+ if !peer.is_packaged(executable) {
+ return Err(Error::Unavailable);
+ }
+ let route = self
+ .managed
+ .lock()
+ .get(&route)
+ .filter(|managed| managed.pid == peer.pid())
+ .and_then(|managed| managed.route.upgrade())
+ .ok_or(Error::Unavailable)?;
+ channel
+ .write_json(
+ Kind::Bound,
+ 0,
+ &Bound {
+ server_id,
+ route: Some(route.id()),
+ },
+ &handshake,
+ )
+ .await?;
+ loop {
+ let frame = channel.read(None).await?;
+ let sequence = frame.sequence();
+ let timed: TimedCommand = parse(&frame, Kind::Request, sequence)?;
+ let (command, deadline) = timed.receive()?;
+ let payload =
+ receive_input(&mut channel, &command, sequence, &budget, &deadline).await?;
+ let disconnected = channel.watch_peer();
+ let result = async {
+ let prepared = async {
+ let operation = deadline.earlier(REPLY_MARGIN)?;
+ let reply = route
+ .prepare_reply(sequence, command, payload?, &operation, &deadline)
+ .await?;
+ Ok::<_, Error>((reply, operation))
+ }
+ .await;
+ match prepared {
+ Ok((reply, operation)) => {
+ reply
+ .send(&mut channel, sequence, &operation, &deadline)
+ .await
+ }
+ Err(error) => {
+ channel
+ .write_json(
+ Kind::Reply,
+ sequence,
+ &Reply::Failed(error.into()),
+ &deadline,
+ )
+ .await
+ }
+ }
+ }
+ .or(disconnected)
+ .await;
+ if result.is_err() {
+ route.close();
+ return result;
+ }
+ }
+ }
+ Hello::Register { name } => {
+ if name.is_empty()
+ || name.len() > 48
+ || name.chars().any(|c| !c.is_ascii_alphanumeric() && c != '-')
+ {
+ return Err(Error::Protocol);
+ }
+ let id = Id::random()?;
+ let (sender, receiver) = bounded(8);
+ {
+ let mut routes = self.routed.lock();
+ if routes.len() >= thinkterm_reverse_access::MAX_ROUTES {
+ return Err(Error::Busy);
+ }
+ let suffix: String = id.as_bytes()[..4]
+ .iter()
+ .map(|b| format!("{b:02x}"))
+ .collect();
+ routes.insert(
+ id,
+ Routed {
+ name: format!("{name}-{suffix}"),
+ queue: sender,
+ budget: budget.clone(),
+ },
+ );
+ }
+ let _guard = RoutedGuard {
+ service: Arc::downgrade(&self),
+ id,
+ };
+ channel
+ .write_json(
+ Kind::Bound,
+ 0,
+ &Bound {
+ server_id,
+ route: Some(id),
+ },
+ &handshake,
+ )
+ .await?;
+ route_requests(&mut channel, receiver).await
+ }
+ Hello::Browse => {
+ channel
+ .write_json(
+ Kind::Bound,
+ 0,
+ &Bound {
+ server_id,
+ route: None,
+ },
+ &handshake,
+ )
+ .await?;
+ let routes: Vec<_> = self
+ .routed
+ .lock()
+ .iter()
+ .map(|(id, route)| RouterRoute {
+ id: *id,
+ name: route.name.clone(),
+ })
+ .collect();
+ channel
+ .write_json(Kind::Reply, 1, &routes, &handshake)
+ .await?;
+ acknowledge(&mut channel, 1, &handshake).await
+ }
+ Hello::Request { route } => {
+ let (queue, route_budget) = self
+ .routed
+ .lock()
+ .get(&route)
+ .map(|route| (route.queue.clone(), route.budget.clone()))
+ .ok_or(Error::Unavailable)?;
+ channel
+ .write_json(
+ Kind::Bound,
+ 0,
+ &Bound {
+ server_id,
+ route: Some(route),
+ },
+ &handshake,
+ )
+ .await?;
+ let deadline = Deadline::request()?;
+ let frame = channel.read(Some(&deadline)).await?;
+ let timed: TimedCommand = parse(&frame, Kind::Request, 1)?;
+ let (command, remote_deadline) = timed.receive()?;
+ let deadline =
+ Deadline::after(deadline.remaining()?.min(remote_deadline.remaining()?))?;
+ let payload = receive_input(&mut channel, &command, 1, &budget, &deadline).await?;
+ let (reply, receiver) = bounded(1);
+ // Over the limit is an answer the requester can act on.
+ let queued = payload.and_then(|payload| {
+ let forward = Forward {
+ command,
+ payload,
+ reply,
+ deadline: deadline.clone(),
+ reservation: route_budget.acquire(64 * 1024)?,
+ };
+ queue.try_send(forward).map_err(|error| {
+ if error.is_full() {
+ Error::Busy
+ } else {
+ Error::Unavailable
+ }
+ })
+ });
+ if let Err(error) = queued {
+ channel
+ .write_json(Kind::Reply, 1, &Reply::Failed(error.into()), &deadline)
+ .await?;
+ return acknowledge(&mut channel, 1, &deadline).await;
+ }
+ let disconnected = channel.watch_peer();
+ let result = async {
+ let (reply, payload) = deadline
+ .run(async { receiver.recv().await.map_err(|_| Error::Unavailable) })
+ .await?;
+ channel
+ .write_json(Kind::Reply, 1, &reply, &deadline)
+ .await?;
+ if let Some(payload) = payload {
+ send_payload(
+ &mut channel,
+ payload.text().as_bytes(),
+ 1,
+ Kind::TextBlock,
+ &deadline,
+ )
+ .await?;
+ }
+ Ok(())
+ }
+ .or(disconnected)
+ .await;
+ receiver.close();
+ result?;
+ acknowledge(&mut channel, 1, &deadline).await
+ }
+ }
+ }
+}
+
+struct Admission(Arc<AtomicUsize>);
+impl Drop for Admission {
+ fn drop(&mut self) {
+ self.0.fetch_sub(1, Ordering::AcqRel);
+ }
+}
+
+struct ManagedGuard {
+ service: Weak<Service>,
+ route: Arc<HostRoute>,
+}
+impl Drop for ManagedGuard {
+ fn drop(&mut self) {
+ self.route.close();
+ if let Some(service) = self.service.upgrade() {
+ service.managed.lock().remove(&self.route.id());
+ }
+ }
+}
+
+struct RoutedGuard {
+ service: Weak<Service>,
+ id: Id,
+}
+impl Drop for RoutedGuard {
+ fn drop(&mut self) {
+ if let Some(service) = self.service.upgrade() {
+ service.routed.lock().remove(&self.id);
+ }
+ }
+}
+
+/// One exchange at a time over the desktop's channel. Once a request is on
+/// it, only its reply puts the channel back in step, so the exchange always
+/// runs to that reply, even if nobody is left to pass it to. Its requester
+/// going, a limit, or a refusal ends that request. This returns, and the
+/// desktop's authorization with it, only for a channel that no longer works.
+async fn route_requests(
+ channel: &mut Channel<LocalStream>,
+ queue: Receiver<Forward>,
+) -> Result<()> {
+ let mut sequence = 0u64;
+ loop {
+ let disconnected = channel.watch_peer();
+ let request = async { queue.recv().await.map_err(|_| Error::Unavailable).map(Some) }
+ .or(async {
+ disconnected.await?;
+ Ok(None)
+ })
+ .await?
+ .ok_or(Error::Unavailable)?;
+ let Forward {
+ command,
+ payload,
+ reply,
+ deadline,
+ reservation,
+ } = request;
+ if reply.is_closed() || deadline.remaining().is_err() {
+ continue;
+ }
+ sequence = sequence
+ .checked_add(1)
+ .filter(|n| *n != u64::MAX)
+ .ok_or(Error::Replay)?;
+ let timed = deadline
+ .earlier(REPLY_MARGIN)
+ .and_then(|forwarded| TimedCommand::new(command, &forwarded));
+ let timed = match timed {
+ Ok(timed) => timed,
+ Err(error) => {
+ let _ = reply.try_send((Reply::Failed(error.into()), None));
+ continue;
+ }
+ };
+ channel
+ .write_json(Kind::Request, sequence, &timed, &deadline)
+ .await?;
+ if let Some(payload) = &payload {
+ send_payload(
+ channel,
+ payload.text().as_bytes(),
+ sequence,
+ Kind::InputBlock,
+ &deadline,
+ )
+ .await?;
+ }
+ let late = Deadline::after(deadline.remaining().unwrap_or_default() + LATE_REPLY)?;
+ let received = receive_reply(
+ channel,
+ sequence,
+ |bytes| Assembly::reply_text(bytes, reservation),
+ &late,
+ )
+ .await?;
+ let _ =
+ reply.try_send(received.unwrap_or_else(|error| (Reply::Failed(error.into()), None)));
+ }
+}
+
+async fn acknowledge(
+ channel: &mut Channel<LocalStream>,
+ sequence: u64,
+ deadline: &Deadline,
+) -> Result<()> {
+ let frame = channel.read(Some(deadline)).await?;
+ if frame.kind() != Kind::Cancel || frame.sequence() != sequence || !frame.body().is_empty() {
+ return Err(Error::Protocol);
+ }
+ Ok(())
+}
+
+#[cfg(all(test, any(target_os = "macos", target_os = "linux", windows)))]
+mod tests {
+ use super::*;
+ use thinkterm_reverse_access::budget::ROUTE_BYTES;
+ use thinkterm_reverse_access::protocol::{
+ ExportRef, Failure, InputResult, InputStatus, ReadOptions,
+ };
+ use thinkterm_reverse_access::wire::Frame;
+ use thinkterm_reverse_access::Target;
+
+ async fn open(service: &Service, hello: Hello, budget: &RouteBudget) -> Channel<LocalStream> {
+ let stream = LocalStream::connect(service.name()).await.unwrap();
+ let mut channel = Channel::new(stream, budget.acquire(1024 * 1024).unwrap()).unwrap();
+ channel
+ .write_json(Kind::Hello, 0, &hello, &Deadline::request().unwrap())
+ .await
+ .unwrap();
+ channel
+ }
+
+ async fn bind(channel: &mut Channel<LocalStream>) -> Bound {
+ parse(
+ &channel
+ .read(Some(&Deadline::request().unwrap()))
+ .await
+ .unwrap(),
+ Kind::Bound,
+ 0,
+ )
+ .unwrap()
+ }
+
+ async fn receive(
+ request: &mut Channel<LocalStream>,
+ budget: &RouteBudget,
+ deadline: &Deadline,
+ ) -> (Reply, Option<Payload>) {
+ receive_reply(request, 1, |bytes| Assembly::text(bytes, budget), deadline)
+ .await
+ .unwrap()
+ .unwrap()
+ }
+
+ enum DesktopSays {
+ Reply(Reply),
+ Text(String),
+ Abandoned,
+ }
+
+ /// A request through the route, answered as `answer` says.
+ async fn ask(
+ service: &Service,
+ route: Id,
+ budget: &RouteBudget,
+ desktop: &mut Channel<LocalStream>,
+ sequence: u64,
+ command: Command,
+ answer: DesktopSays,
+ ) -> (Reply, Option<Payload>) {
+ let mut request = open(service, Hello::Request { route }, budget).await;
+ bind(&mut request).await;
+ let deadline = Deadline::request().unwrap();
+ request
+ .write_json(
+ Kind::Request,
+ 1,
+ &TimedCommand::new(command, &deadline).unwrap(),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ let on_the_desktop = async {
+ let frame = desktop.read(Some(&deadline)).await.unwrap();
+ assert_eq!(frame.sequence(), sequence);
+ match answer {
+ DesktopSays::Reply(reply) => {
+ desktop
+ .write_json(Kind::Reply, sequence, &reply, &deadline)
+ .await
+ .unwrap();
+ }
+ DesktopSays::Text(text) => {
+ let reply = Reply::Text { bytes: text.len() };
+ desktop
+ .write_json(Kind::Reply, sequence, &reply, &deadline)
+ .await
+ .unwrap();
+ send_payload(
+ desktop,
+ text.as_bytes(),
+ sequence,
+ Kind::TextBlock,
+ &deadline,
+ )
+ .await
+ .unwrap();
+ }
+ DesktopSays::Abandoned => {
+ let reply = Reply::Text { bytes: 100_000 };
+ desktop
+ .write_json(Kind::Reply, sequence, &reply, &deadline)
+ .await
+ .unwrap();
+ send_payload(desktop, b"example", sequence, Kind::TextBlock, &deadline)
+ .await
+ .unwrap();
+ desktop
+ .write(&Frame::new(Kind::Cancel, sequence, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ }
+ }
+ };
+ let (_, received) =
+ smol::future::zip(on_the_desktop, receive(&mut request, budget, &deadline)).await;
+ request
+ .write(&Frame::new(Kind::Cancel, 1, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ received
+ }
+
+ #[test]
+ fn local_router_preserves_payloads_and_outlives_what_goes_wrong_with_a_request() {
+ smol::block_on(async {
+ let mux = Arc::new(Mux::new(None));
+ let service = mux.connect_service().unwrap();
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+
+ // An ordinary process cannot become the authentication controller.
+ let mut denied = open(
+ &service,
+ Hello::Manage {
+ server_id: mux.runtime_server_id().into(),
+ source: "server-a".into(),
+ language: "en-US".into(),
+ client: ClientId {
+ hostname: "devbox".into(),
+ username: "user".into(),
+ pid: std::process::id(),
+ epoch: 0,
+ id: 0,
+ ssh_auth_sock: None,
+ },
+ },
+ &budget,
+ )
+ .await;
+ assert!(denied
+ .read(Some(&Deadline::request().unwrap()))
+ .await
+ .is_err());
+ drop(denied);
+ assert!(service.managed.lock().is_empty());
+
+ let mut desktop = open(
+ &service,
+ Hello::Register {
+ name: "desktop".into(),
+ },
+ &budget,
+ )
+ .await;
+ let registered = bind(&mut desktop).await;
+ let route = registered.route.unwrap();
+ let mut browse = open(&service, Hello::Browse, &budget).await;
+ assert_eq!(bind(&mut browse).await.server_id, mux.runtime_server_id());
+ let routes: Vec<RouterRoute> = parse(
+ &browse
+ .read(Some(&Deadline::request().unwrap()))
+ .await
+ .unwrap(),
+ Kind::Reply,
+ 1,
+ )
+ .unwrap();
+ assert_eq!(routes.len(), 1);
+ assert_eq!(routes[0].id, route);
+ assert!(routes[0].name.starts_with("desktop-"));
+ browse
+ .write(
+ &Frame::new(Kind::Cancel, 1, &[]).unwrap(),
+ &Deadline::request().unwrap(),
+ )
+ .await
+ .unwrap();
+ drop(browse);
+
+ let export = ExportRef {
+ grant: GrantRef {
+ id: Id::random().unwrap(),
+ version: 1,
+ },
+ target: Target::new(1, Id::random().unwrap()).unwrap(),
+ };
+ let output = "example text\n".repeat(10_000);
+ let mut request = open(&service, Hello::Request { route }, &budget).await;
+ assert_eq!(bind(&mut request).await.route, Some(route));
+ let deadline = Deadline::request().unwrap();
+ request
+ .write_json(
+ Kind::Request,
+ 1,
+ &TimedCommand::new(
+ Command::Read {
+ export,
+ options: ReadOptions::default(),
+ },
+ &deadline,
+ )
+ .unwrap(),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ let desktop_reply = async {
+ let frame = desktop.read(Some(&deadline)).await.unwrap();
+ assert_eq!(frame.sequence(), 1);
+ let timed: TimedCommand = parse(&frame, Kind::Request, 1).unwrap();
+ assert!(matches!(timed.receive().unwrap().0, Command::Read { .. }));
+ desktop
+ .write_json(
+ Kind::Reply,
+ 1,
+ &Reply::Text {
+ bytes: output.len(),
+ },
+ &deadline,
+ )
+ .await
+ .unwrap();
+ send_payload(
+ &mut desktop,
+ output.as_bytes(),
+ 1,
+ Kind::TextBlock,
+ &deadline,
+ )
+ .await
+ .unwrap();
+ };
+ let client_reply = async {
+ let (reply, payload) = receive(&mut request, &budget, &deadline).await;
+ assert!(matches!(reply, Reply::Text { bytes } if bytes == output.len()));
+ assert_eq!(payload.unwrap().text(), output);
+ request
+ .write(&Frame::new(Kind::Cancel, 1, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ };
+ smol::future::zip(desktop_reply, client_reply).await;
+ drop(request);
+
+ let input = "example input\n".repeat(2000);
+ let command = Command::Text {
+ export,
+ bytes: input.len(),
+ no_paste: false,
+ enter: true,
+ };
+ let mut request = open(&service, Hello::Request { route }, &budget).await;
+ bind(&mut request).await;
+ let deadline = Deadline::request().unwrap();
+ request
+ .write_json(
+ Kind::Request,
+ 1,
+ &TimedCommand::new(command.clone(), &deadline).unwrap(),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ send_payload(
+ &mut request,
+ input.as_bytes(),
+ 1,
+ Kind::InputBlock,
+ &deadline,
+ )
+ .await
+ .unwrap();
+ let desktop_reply = async {
+ let frame = desktop.read(Some(&deadline)).await.unwrap();
+ assert_eq!(frame.sequence(), 2);
+ let timed: TimedCommand = parse(&frame, Kind::Request, 2).unwrap();
+ let (command, _) = timed.receive().unwrap();
+ assert!(matches!(command, Command::Text { enter: true, .. }));
+ let payload = receive_input(&mut desktop, &command, 2, &budget, &deadline)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ assert_eq!(payload.text(), input);
+ desktop
+ .write_json(
+ Kind::Reply,
+ 2,
+ &Reply::Input(InputResult {
+ status: InputStatus::Submitted,
+ bytes: input.len(),
+ enter_submitted: true,
+ paste_may_be_open: false,
+ }),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ };
+ let client_reply = async {
+ let (reply, _) = receive(&mut request, &budget, &deadline).await;
+ assert!(matches!(
+ reply,
+ Reply::Input(InputResult {
+ status: InputStatus::Submitted,
+ enter_submitted: true,
+ ..
+ })
+ ));
+ request
+ .write(&Frame::new(Kind::Cancel, 1, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ };
+ smol::future::zip(desktop_reply, client_reply).await;
+ drop(request);
+
+ // A requester that goes takes its result with it, and the route
+ // stays: nobody else receives that result or repeats its request.
+ let mut request = open(&service, Hello::Request { route }, &budget).await;
+ bind(&mut request).await;
+ let deadline = Deadline::request().unwrap();
+ let list = Command::List { after: None };
+ request
+ .write_json(
+ Kind::Request,
+ 1,
+ &TimedCommand::new(list.clone(), &deadline).unwrap(),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ assert_eq!(desktop.read(Some(&deadline)).await.unwrap().sequence(), 3);
+ drop(request);
+ desktop
+ .write_json(
+ Kind::Reply,
+ 3,
+ &Reply::List {
+ exports: vec![],
+ more: false,
+ },
+ &deadline,
+ )
+ .await
+ .unwrap();
+ let (reply, _) = ask(
+ &service,
+ route,
+ &budget,
+ &mut desktop,
+ 4,
+ list.clone(),
+ DesktopSays::Reply(Reply::Failed(Failure::Timeout)),
+ )
+ .await;
+ assert!(matches!(reply, Reply::Failed(Failure::Timeout)));
+
+ // Text there is no room for is read off the channel and refused.
+ let room = service.routed.lock().get(&route).unwrap().budget.clone();
+ let held = room.acquire(ROUTE_BYTES - 1024 * 1024 - 64 * 1024).unwrap();
+ let (reply, _) = ask(
+ &service,
+ route,
+ &budget,
+ &mut desktop,
+ 5,
+ list.clone(),
+ DesktopSays::Text("example".into()),
+ )
+ .await;
+ assert!(matches!(reply, Reply::Failed(Failure::Busy)));
+ drop(held);
+
+ // A desktop can abandon a reply between two blocks.
+ let (reply, _) = ask(
+ &service,
+ route,
+ &budget,
+ &mut desktop,
+ 6,
+ list.clone(),
+ DesktopSays::Abandoned,
+ )
+ .await;
+ assert!(matches!(reply, Reply::Failed(Failure::Unavailable)));
+
+ // Over the rate limit the requester is told, and the desktop
+ // never hears of it.
+ while room.acquire(0).is_ok() {}
+ let mut request = open(&service, Hello::Request { route }, &budget).await;
+ bind(&mut request).await;
+ let deadline = Deadline::request().unwrap();
+ request
+ .write_json(
+ Kind::Request,
+ 1,
+ &TimedCommand::new(list.clone(), &deadline).unwrap(),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ let (reply, _) = receive(&mut request, &budget, &deadline).await;
+ assert!(matches!(reply, Reply::Failed(Failure::Busy)));
+ drop(request);
+ assert_eq!(service.routed.lock().len(), 1);
+ drop(room);
+
+ // Only a channel that no longer works ends the route.
+ drop(desktop);
+ let gone = Deadline::after(Duration::from_secs(1)).unwrap();
+ while !service.routed.lock().is_empty() {
+ gone.remaining().unwrap();
+ smol::Timer::after(Duration::from_millis(10)).await;
+ }
+ service.close();
+ let shutdown = Deadline::after(Duration::from_secs(1)).unwrap();
+ while LocalStream::connect(service.name()).await.is_ok() {
+ shutdown.remaining().unwrap();
+ smol::Timer::after(Duration::from_millis(10)).await;
+ }
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ });
+ }
+
+ #[test]
+ fn a_peer_that_vanishes_does_not_stop_the_listener() {
+ smol::block_on(async {
+ let mux = Arc::new(Mux::new(None));
+ let service = mux.connect_service().unwrap();
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+ // A client gone before it is accepted has no peer to identify.
+ for _ in 0..20 {
+ drop(std::os::unix::net::UnixStream::connect(service.name()).unwrap());
+ }
+ smol::Timer::after(Duration::from_millis(250)).await;
+ let mut browse = open(&service, Hello::Browse, &budget).await;
+ assert_eq!(bind(&mut browse).await.server_id, mux.runtime_server_id());
+ drop(browse);
+ service.close();
+ });
+ }
+}
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index ece03df6..a2650f50 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -41,6 +41,7 @@ pub mod activity;
pub mod agent_status;
pub mod client;
pub mod command_spec;
+pub mod connect;
pub mod connui;
pub mod default_prog;
pub mod domain;
@@ -62,6 +63,32 @@ pub mod tmux_commands;
mod tmux_pty;
pub mod window;
+/// The Mux is a process-wide singleton, and tests that install one assert on
+/// its global state: they take this and run one at a time.
+#[cfg(test)]
+pub(crate) static GLOBAL_MUX_TESTS: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
+
+pub struct ConnectSuspension {
+ mux: Weak<Mux>,
+ resume: bool,
+}
+
+impl ConnectSuspension {
+ pub fn keep(mut self) {
+ self.resume = false;
+ }
+}
+
+impl Drop for ConnectSuspension {
+ fn drop(&mut self) {
+ if self.resume {
+ if let Some(mux) = self.mux.upgrade() {
+ mux.connect_suspended.store(false, Ordering::Release);
+ }
+ }
+ }
+}
+
use crate::activity::Activity;
pub const DEFAULT_WORKSPACE: &str = "default";
@@ -264,6 +291,7 @@ pub struct FrontendAccessState {
#[derive(Default)]
struct TabFrontendLease {
owner: Option<ClientId>,
+ ownership_generation: u64,
/// Last geometry advertised by each renderer. Network claims always carry
/// their geometry and never trust this cache; it remains useful for the
/// in-process GUI, whose Pane input reaches the mux without a wire PDU.
@@ -274,6 +302,15 @@ struct TabFrontendLease {
generation: u64,
}
+impl TabFrontendLease {
+ fn set_owner(&mut self, owner: Option<ClientId>) {
+ if self.owner != owner {
+ self.ownership_generation = self.ownership_generation.saturating_add(1);
+ self.owner = owner;
+ }
+ }
+}
+
/// True when `me` is the only *live* client that has advertised geometry for
/// any tab. A sole renderer cannot be fighting anyone over the lease, so an
/// unclaimed lease is effectively its own. Two or more renderers must take it
@@ -332,6 +369,7 @@ struct FrontendLeaseState {
tabs: HashMap<TabId, TabFrontendLease>,
access_mode: FrontendAccessMode,
handoff_owner: Option<ClientId>,
+ ownership_generation: u64,
/// Distinguishes initial server startup (first renderer auto-owns) from an
/// owner disconnect (everyone stays blocked until an explicit takeover).
handoff_ever_owned: bool,
@@ -362,6 +400,7 @@ impl Default for FrontendLeaseState {
tabs: HashMap::new(),
access_mode: FrontendAccessMode::Handoff,
handoff_owner: None,
+ ownership_generation: 0,
handoff_ever_owned: false,
handoff_last_owner: None,
ever_rendered: HashSet::new(),
@@ -372,6 +411,22 @@ impl Default for FrontendLeaseState {
}
}
+impl FrontendLeaseState {
+ fn set_handoff_owner(&mut self, owner: Option<ClientId>) {
+ if self.handoff_owner != owner {
+ self.ownership_generation = self.ownership_generation.saturating_add(1);
+ self.handoff_owner = owner;
+ }
+ }
+
+ fn set_access_mode(&mut self, mode: FrontendAccessMode) {
+ if self.access_mode != mode {
+ self.ownership_generation = self.ownership_generation.saturating_add(1);
+ self.access_mode = mode;
+ }
+ }
+}
+
/// Server-side palette advice is scoped to the client that supplied it.
/// Merely attaching records advice; focus or real input activates it for OSC
/// queries. Application palette overrides are tracked by the terminal and are
@@ -473,6 +528,8 @@ impl PaletteAdvisoryState {
pub struct Mux {
runtime_server_id: String,
+ connect_service: Mutex<Option<Arc<connect::service::Service>>>,
+ connect_suspended: AtomicBool,
tabs: RwLock<HashMap<TabId, Arc<Tab>>>,
panes: RwLock<HashMap<PaneId, Arc<dyn Pane>>>,
windows: RwLock<HashMap<WindowId, Window>>,
@@ -1451,6 +1508,8 @@ impl Mux {
Self {
runtime_server_id,
+ connect_service: Mutex::new(None),
+ connect_suspended: AtomicBool::new(false),
tabs: RwLock::new(HashMap::new()),
panes: RwLock::new(HashMap::new()),
windows: RwLock::new(HashMap::new()),
@@ -1484,6 +1543,33 @@ impl Mux {
&self.runtime_server_id
}
+ pub fn connect_service(
+ self: &Arc<Self>,
+ ) -> thinkterm_reverse_access::Result<Arc<connect::service::Service>> {
+ let mut service = self.connect_service.lock();
+ if self.connect_suspended.load(Ordering::Acquire) {
+ return Err(thinkterm_reverse_access::Error::Unavailable);
+ }
+ if service.is_none() {
+ *service = Some(connect::service::Service::start(self)?);
+ }
+ Ok(Arc::clone(
+ service.as_ref().expect("initialized Connect service"),
+ ))
+ }
+
+ pub fn suspend_connect(self: &Arc<Self>) -> ConnectSuspension {
+ let mut service = self.connect_service.lock();
+ self.connect_suspended.store(true, Ordering::Release);
+ if let Some(service) = service.take() {
+ service.close();
+ }
+ ConnectSuspension {
+ mux: Arc::downgrade(self),
+ resume: true,
+ }
+ }
+
/// The agent socket panes here are given (`SSH_AUTH_SOCK`), if any.
pub fn ssh_agent_path(&self) -> Option<std::path::PathBuf> {
self.agent.as_ref().map(|agent| agent.path().to_path_buf())
@@ -1634,7 +1720,7 @@ impl Mux {
return;
}
let changed = lease.access_mode != mode;
- lease.access_mode = mode;
+ lease.set_access_mode(mode);
lease.access_initialized = true;
changed
};
@@ -1756,7 +1842,7 @@ impl Mux {
.as_ref()
.is_some_and(|last| same_device(last, client_id)))
{
- lease.handoff_owner = Some(client_id.clone());
+ lease.set_handoff_owner(Some(client_id.clone()));
lease.handoff_ever_owned = true;
lease.handoff_last_owner = None;
access_changed = true;
@@ -1784,7 +1870,7 @@ impl Mux {
};
let owner_changed = can_drive && !owner_was_me;
if owner_changed {
- state.owner = Some(client_id.clone());
+ state.set_owner(Some(client_id.clone()));
// Dropping the view on a takeover is safe because every path
// that vacates the owner also clears the view; a reseed
// therefore never discards a live scroll position.
@@ -2010,7 +2096,7 @@ impl Mux {
let mut affected_tabs = vec![tab_id];
if mode == FrontendAccessMode::Handoff {
access_changed = lease.handoff_owner.as_ref() != Some(client_id);
- lease.handoff_owner = Some(client_id.clone());
+ lease.set_handoff_owner(Some(client_id.clone()));
lease.handoff_ever_owned = true;
// An explicit claim supersedes whoever drove before: the
// returning-device rule must not hand the lease back to it.
@@ -2025,7 +2111,7 @@ impl Mux {
}
let state = lease.tabs.entry(tab_id).or_default();
state.viewports.insert(client_id.clone(), viewport.clone());
- state.owner = Some(client_id.clone());
+ state.set_owner(Some(client_id.clone()));
state.view = None;
(access_changed, affected_tabs, joined)
};
@@ -2138,14 +2224,14 @@ impl Mux {
let affected_tabs = {
let mut lease = self.frontend_lease.lock();
- lease.access_mode = mode;
+ lease.set_access_mode(mode);
lease.access_initialized = true;
match mode {
FrontendAccessMode::TmuxLatest => {
- lease.handoff_owner = None;
+ lease.set_handoff_owner(None);
}
FrontendAccessMode::Handoff => {
- lease.handoff_owner = Some(client_id.clone());
+ lease.set_handoff_owner(Some(client_id.clone()));
lease.handoff_ever_owned = true;
}
}
@@ -2157,7 +2243,7 @@ impl Mux {
}
let state = lease.tabs.entry(tab_id).or_default();
state.viewports.insert(client_id.clone(), viewport.clone());
- state.owner = Some(client_id.clone());
+ state.set_owner(Some(client_id.clone()));
if !affected.contains(&tab_id) {
affected.push(tab_id);
}
@@ -2379,7 +2465,7 @@ impl Mux {
let (mode, mut affected_tabs) = {
let mut lease = self.frontend_lease.lock();
if let Some(mode) = restore_mode {
- lease.access_mode = mode;
+ lease.set_access_mode(mode);
lease.access_initialized = true;
}
let mode = lease.access_mode;
@@ -2389,18 +2475,19 @@ impl Mux {
// The screen whose geometry failed is the one that gets
// to come back without a click, not whoever drove
// before it.
- lease.handoff_last_owner = lease.handoff_owner.take();
+ lease.handoff_last_owner = lease.handoff_owner.clone();
+ lease.set_handoff_owner(None);
lease.handoff_ever_owned = true;
for (affected_tab_id, state) in &mut lease.tabs {
- state.owner = None;
+ state.set_owner(None);
state.view = None;
affected.push(*affected_tab_id);
}
}
FrontendAccessMode::TmuxLatest => {
- lease.handoff_owner = None;
+ lease.set_handoff_owner(None);
let state = lease.tabs.entry(tab_id).or_default();
- state.owner = None;
+ state.set_owner(None);
state.view = None;
affected.push(tab_id);
}
@@ -2729,7 +2816,7 @@ impl Mux {
if state.owner.as_ref() != Some(client_id) {
continue;
}
- state.owner = None;
+ state.set_owner(None);
state.view = None;
affected.push(*tab_id);
}
@@ -2740,7 +2827,7 @@ impl Mux {
// remaining device stays opaque until one explicitly clicks,
// wheels or swipes the takeover surface -- except this very
// device coming back, which inherits (see handoff_last_owner).
- lease.handoff_owner = None;
+ lease.set_handoff_owner(None);
lease.handoff_ever_owned = true;
lease.handoff_last_owner = Some(client_id.clone());
}
@@ -3667,6 +3754,9 @@ impl Mux {
.cloned()
.ok_or_else(|| anyhow!("pane {src_pane_id} not found in any tab"))?;
let src_tab_id = src_tab.tab_id();
+ if Arc::ptr_eq(&src_tab, &target_tab) {
+ return src_tab.move_pane_to_split(src_pane_id, target_pane_id, request);
+ }
let pane = src_tab.remove_pane(src_pane_id).ok_or_else(|| {
anyhow!("pane {src_pane_id} not found in its containing tab {src_tab_id}")
})?;
@@ -4053,6 +4143,14 @@ impl Mux {
}
}
+impl Drop for Mux {
+ fn drop(&mut self) {
+ if let Some(service) = self.connect_service.get_mut().take() {
+ service.close();
+ }
+ }
+}
+
fn pane_size_for_cell_grid(size: TerminalSize, cols: usize, rows: usize) -> TerminalSize {
let cols = cols.max(1);
let rows = rows.max(1);
@@ -4434,7 +4532,7 @@ mod tests {
Some(frontend_test_size(10, 5)),
"only the driving frontend's sizes count"
);
- lease.handoff_owner = None;
+ lease.set_handoff_owner(None);
assert_eq!(driving_frontend_size_over_root(&lease, 3, 7, root), None);
lease.access_mode = FrontendAccessMode::TmuxLatest;
@@ -4616,7 +4714,7 @@ mod tests {
mux.register_client(Arc::clone(&tui));
{
let mut lease = mux.frontend_lease.lock();
- lease.handoff_owner = None;
+ lease.set_handoff_owner(None);
lease.handoff_ever_owned = true;
let state = lease.tabs.entry(tab_id).or_default();
state
@@ -4645,7 +4743,7 @@ mod tests {
let tui_registration = mux.register_client(Arc::clone(&tui));
{
let mut lease = mux.frontend_lease.lock();
- lease.handoff_owner = None;
+ lease.set_handoff_owner(None);
lease.handoff_ever_owned = true;
let state = lease.tabs.entry(tab_id).or_default();
state
diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs
index 34d6a674..414ec20c 100644
--- a/mux/src/localpane.rs
+++ b/mux/src/localpane.rs
@@ -37,6 +37,68 @@ use wezterm_term::{
const PROC_INFO_CACHE_TTL: Duration = Duration::from_millis(300);
+fn connect_plain_text(
+ term: &Terminal,
+ options: thinkterm_reverse_access::protocol::ReadOptions,
+) -> thinkterm_reverse_access::Result<String> {
+ use thinkterm_reverse_access::{Error, MAX_READ_BYTES, MAX_READ_LINES};
+ let screen = term.screen();
+ let rows = screen.scrollback_rows();
+ let top = rows.saturating_sub(screen.physical_rows);
+ let row = |relative: i64| (top as i128 + relative as i128).max(0);
+ let start = options.start.map(row).unwrap_or(top as i128);
+ let end = options.end.map(row).unwrap_or(rows as i128);
+ if start > end {
+ return Err(Error::Protocol);
+ }
+ let start = start.min(rows as i128) as usize;
+ let end = (end + 1).min(rows as i128) as usize;
+ if end - start > MAX_READ_LINES {
+ return Err(Error::TooLarge);
+ }
+ let mut text = String::with_capacity(MAX_READ_BYTES);
+ let mut result = Ok(());
+ let mut logical_start = 0;
+ let mut keep = 0;
+ let mut last_nonempty_end = 0;
+ screen.with_phys_lines(start..end, |lines| {
+ for (index, line) in lines.iter().enumerate() {
+ for cell in line.visible_cells() {
+ let value = cell.str();
+ if value.len() >= MAX_READ_BYTES - text.len() {
+ result = Err(Error::TooLarge);
+ return;
+ }
+ text.push_str(value);
+ if !value.trim().is_empty() {
+ keep = text.len();
+ }
+ }
+ if !options.unwrap || !line.last_cell_was_wrapped() || index + 1 == lines.len() {
+ if options.trim {
+ text.truncate(keep.max(logical_start));
+ }
+ if text.len() == MAX_READ_BYTES {
+ result = Err(Error::TooLarge);
+ return;
+ }
+ let nonempty = text.len() > logical_start;
+ text.push('\n');
+ if nonempty {
+ last_nonempty_end = text.len();
+ }
+ logical_start = text.len();
+ keep = logical_start;
+ }
+ }
+ });
+ result?;
+ if options.trim {
+ text.truncate(last_nonempty_end);
+ }
+ Ok(text)
+}
+
#[derive(Debug)]
enum ProcessState {
Running {
@@ -1582,6 +1644,127 @@ fn open_child_process(pid: u32) -> std::io::Result<std::os::windows::io::OwnedHa
}
impl LocalPane {
+ pub fn quiesce_connect_input(&self) -> anyhow::Result<()> {
+ self.pty.lock().quiesce_input()
+ }
+
+ pub(crate) fn connect_eligible(&self) -> thinkterm_reverse_access::Result<()> {
+ use thinkterm_reverse_access::Error;
+ if self.tmux_domain.try_lock().ok_or(Error::Busy)?.is_some() {
+ return Err(Error::Unavailable);
+ }
+ match &*self.process.try_lock().ok_or(Error::Busy)? {
+ ProcessState::Running {
+ pid: Some(_),
+ killed: false,
+ ..
+ } => Ok(()),
+ _ => Err(Error::Unavailable),
+ }
+ }
+
+ pub(crate) fn connect_read(
+ &self,
+ options: thinkterm_reverse_access::protocol::ReadOptions,
+ ) -> thinkterm_reverse_access::Result<String> {
+ let term = self
+ .terminal
+ .try_lock()
+ .ok_or(thinkterm_reverse_access::Error::Busy)?;
+ connect_plain_text(&term, options)
+ }
+
+ pub(crate) fn connect_title(&self) -> thinkterm_reverse_access::Result<String> {
+ let term = self
+ .terminal
+ .try_lock()
+ .ok_or(thinkterm_reverse_access::Error::Busy)?;
+ Ok(thinkterm_reverse_access::protocol::display_text(
+ term.get_title(),
+ 128,
+ ))
+ }
+
+ pub(crate) fn connect_input(
+ &self,
+ input: &crate::connect::Input,
+ ) -> thinkterm_reverse_access::Result<(
+ Box<dyn portable_pty::TryInputWriter>,
+ crate::connect::EncodedInput,
+ )> {
+ use crate::connect::{EncodedInput, Input};
+ use thinkterm_reverse_access::{Error, MAX_INPUT_BYTES, MAX_KEYS};
+ let term = self.terminal.try_lock().ok_or(Error::Busy)?;
+ let (mut bytes, enter, paste) = match input {
+ Input::Text {
+ text,
+ no_paste,
+ enter,
+ } => {
+ if text.len() > MAX_INPUT_BYTES {
+ return Err(Error::TooLarge);
+ }
+ let paste = !no_paste && term.bracketed_paste_enabled();
+ let bytes = if *no_paste {
+ text.clone().into_bytes()
+ } else {
+ term.encode_paste(text).into_bytes()
+ };
+ (bytes, *enter, paste)
+ }
+ Input::Keys(keys) => {
+ if keys.is_empty() || keys.len() > MAX_KEYS {
+ return Err(Error::TooLarge);
+ }
+ let mut bytes = Vec::new();
+ for (key, modifiers) in keys {
+ let encoded = term
+ .encode_key(key.clone(), *modifiers, true)
+ .map_err(|_| Error::Protocol)?;
+ if encoded.len() > MAX_INPUT_BYTES - bytes.len() {
+ return Err(Error::TooLarge);
+ }
+ bytes.extend_from_slice(encoded.as_bytes());
+ }
+ (bytes, false, false)
+ }
+ };
+ let text_end = bytes.len();
+ if enter {
+ let key = term
+ .encode_key(KeyCode::Enter, KeyModifiers::NONE, true)
+ .map_err(|_| Error::Protocol)?;
+ bytes.extend_from_slice(key.as_bytes());
+ }
+ let writer = self
+ .pty
+ .try_lock()
+ .ok_or(Error::Busy)?
+ .try_input_writer()
+ .map_err(|_| Error::Unavailable)?;
+ Ok((
+ writer,
+ EncodedInput {
+ bytes,
+ text_end,
+ enter,
+ enter_delay: thinkterm_reverse_access::protocol::enter_delay(text_end),
+ paste,
+ },
+ ))
+ }
+
+ /// Takes `submit` only once the terminal is free, so Busy can be retried.
+ pub(crate) fn connect_queue(
+ &self,
+ submit: &mut Option<Box<dyn FnOnce() + Send>>,
+ ) -> thinkterm_reverse_access::Result<()> {
+ use thinkterm_reverse_access::Error;
+ let mut term = self.terminal.try_lock().ok_or(Error::Busy)?;
+ term.queue_checked_input(submit.take().ok_or(Error::Protocol)?)
+ .map_err(|_| Error::Unavailable)
+ }
+
/// The pieces a successor server needs to adopt this pane, or None
/// for a pane that cannot travel: one over a channel rather than a
/// pty (ssh, tmux), or one whose process has already exited.
@@ -1971,6 +2154,681 @@ impl Drop for LocalPane {
}
}
+#[cfg(test)]
+mod connect_read_tests {
+ use super::*;
+ use thinkterm_reverse_access::protocol::ReadOptions;
+
+ #[derive(Debug)]
+ struct TestConfig;
+ impl TerminalConfiguration for TestConfig {
+ fn scrollback_size(&self) -> usize {
+ 32
+ }
+ fn color_palette(&self) -> ColorPalette {
+ ColorPalette::default()
+ }
+ }
+
+ fn terminal(cols: usize, rows: usize) -> Terminal {
+ Terminal::new(
+ TerminalSize {
+ cols,
+ rows,
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 96,
+ },
+ Arc::new(TestConfig),
+ "ThinkTerm",
+ "test",
+ Box::new(Vec::new()),
+ )
+ }
+
+ #[test]
+ fn connect_plain_text_preserves_wrap_trim_and_inclusive_ranges() {
+ let mut terminal = terminal(4, 4);
+ terminal.advance_bytes(b"abcde\r\nx \r\n");
+ let trim = ReadOptions {
+ trim: true,
+ ..ReadOptions::default()
+ };
+ assert_eq!(connect_plain_text(&terminal, trim).unwrap(), "abcd\ne\nx\n");
+ assert_eq!(
+ connect_plain_text(
+ &terminal,
+ ReadOptions {
+ unwrap: true,
+ ..trim
+ }
+ )
+ .unwrap(),
+ "abcde\nx\n"
+ );
+ assert_eq!(
+ connect_plain_text(
+ &terminal,
+ ReadOptions {
+ start: Some(1),
+ end: Some(1),
+ ..trim
+ }
+ )
+ .unwrap(),
+ "e\n"
+ );
+ assert!(connect_plain_text(
+ &terminal,
+ ReadOptions {
+ start: Some(2),
+ end: Some(1),
+ ..trim
+ }
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn connect_plain_text_uses_current_screen_coordinates_and_bounds_history() {
+ let mut terminal = terminal(8, 2);
+ terminal.advance_bytes(b"first\r\nsecond\r\nthird");
+ let trim = ReadOptions {
+ trim: true,
+ ..ReadOptions::default()
+ };
+ assert_eq!(
+ connect_plain_text(&terminal, trim).unwrap(),
+ "second\nthird\n"
+ );
+ assert_eq!(
+ connect_plain_text(
+ &terminal,
+ ReadOptions {
+ start: Some(-1),
+ end: Some(-1),
+ ..trim
+ }
+ )
+ .unwrap(),
+ "first\n"
+ );
+ terminal.advance_bytes(b"\x1b[?1049hALT");
+ assert_eq!(
+ connect_plain_text(
+ &terminal,
+ ReadOptions {
+ start: Some(-100),
+ ..trim
+ }
+ )
+ .unwrap(),
+ "ALT\n"
+ );
+ assert!(connect_plain_text(
+ &terminal,
+ ReadOptions {
+ start: Some(i64::MAX),
+ ..trim
+ }
+ )
+ .is_err());
+ }
+
+ /// Once the scrollback is full the line store wraps around in memory,
+ /// wherever a read's range falls in it.
+ #[test]
+ fn connect_plain_text_reads_a_full_scrollback() {
+ let trim = ReadOptions {
+ trim: true,
+ ..ReadOptions::default()
+ };
+ let mut terminal = terminal(16, 4);
+ for line in 0..2000 {
+ terminal.advance_bytes(format!("line-{line}\r\n").as_bytes());
+ if line < 40 {
+ continue;
+ }
+ assert_eq!(
+ connect_plain_text(&terminal, trim).unwrap(),
+ format!("line-{}\nline-{}\nline-{}\n", line - 2, line - 1, line)
+ );
+ assert_eq!(
+ connect_plain_text(
+ &terminal,
+ ReadOptions {
+ start: Some(-8),
+ end: Some(-1),
+ ..trim
+ }
+ )
+ .unwrap(),
+ (line - 10..=line - 3)
+ .map(|line| format!("line-{line}\n"))
+ .collect::<String>()
+ );
+ }
+ }
+
+ #[test]
+ fn connect_plain_text_rejects_a_view_over_the_line_limit() {
+ let terminal = terminal(1, thinkterm_reverse_access::MAX_READ_LINES + 1);
+ assert_eq!(
+ connect_plain_text(&terminal, ReadOptions::default()),
+ Err(thinkterm_reverse_access::Error::TooLarge)
+ );
+ }
+}
+
+#[cfg(all(test, unix))]
+mod connect_host_tests {
+ use super::*;
+ use crate::client::ClientId;
+ use crate::connect::{Host, HostRoute};
+ use crate::tab::Tab;
+ use crate::Mux;
+ use portable_pty::{native_pty_system, CommandBuilder, PtySize};
+ use smol::io::{AsyncRead, AsyncWrite};
+ use std::future::Future;
+ use std::io::Read;
+ use std::os::unix::fs::PermissionsExt;
+ use std::os::unix::net::UnixStream;
+ use std::path::PathBuf;
+ use std::pin::Pin;
+ use std::sync::Arc;
+ use std::task::{Context, Poll};
+ use thinkterm_reverse_access::budget::Budgets;
+ use thinkterm_reverse_access::channel::{Channel, Deadline};
+ use thinkterm_reverse_access::exchange::receive_reply;
+ use thinkterm_reverse_access::protocol::{Command, ExportRef, InputStatus, ReadOptions, Reply};
+ use thinkterm_reverse_access::wire::{Assembly, Payload};
+ use thinkterm_reverse_access::{Error, Id, Permission};
+
+ /// Stands in for the native window, which needs a person: approves
+ /// whatever it is asked, and keeps the session monitor's heartbeat.
+ const HELPER: &str = r#"#!/bin/sh
+case "$1" in
+--monitor)
+ printf '{"kind":"ready","id":null}\n'
+ while :; do
+ printf '{"kind":"alive","id":null}\n'
+ sleep 1
+ done
+ ;;
+--authenticate)
+ IFS= read -r line
+ id=${line#*\"Id\":\"}
+ printf '{"kind":"approved","id":"%s"}\n' "${id%%\"*}"
+ ;;
+esac
+"#;
+
+ struct InstalledHelper(PathBuf);
+ impl InstalledHelper {
+ fn new() -> Self {
+ let path = std::env::current_exe()
+ .unwrap()
+ .with_file_name("thinkterm-connect-auth");
+ std::fs::write(&path, HELPER).unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ Self(path)
+ }
+ }
+ impl Drop for InstalledHelper {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+ }
+
+ #[derive(Debug)]
+ struct TestConfig;
+ impl TerminalConfiguration for TestConfig {
+ fn scrollback_size(&self) -> usize {
+ 32
+ }
+ fn color_palette(&self) -> ColorPalette {
+ ColorPalette::default()
+ }
+ }
+
+ struct Fixture {
+ mux: Arc<Mux>,
+ pane: Arc<LocalPane>,
+ connect: Arc<Host>,
+ client: ClientId,
+ route: Arc<HostRoute>,
+ reader: Box<dyn Read + Send>,
+ sequence: u64,
+ _helper: InstalledHelper,
+ _serial: parking_lot::MutexGuard<'static, ()>,
+ }
+
+ fn fixture() -> Fixture {
+ static SCHEDULER: std::sync::Once = std::sync::Once::new();
+ SCHEDULER.call_once(|| {
+ promise::spawn::SimpleExecutor::new();
+ });
+ // Which also keeps these to the helper's one path, one at a time.
+ let serial = crate::GLOBAL_MUX_TESTS.lock();
+ let helper = InstalledHelper::new();
+ let mux = Arc::new(Mux::new(None));
+ Mux::set_mux(&mux);
+ let size = TerminalSize {
+ cols: 40,
+ rows: 6,
+ pixel_width: 0,
+ pixel_height: 0,
+ dpi: 96,
+ };
+ let pair = native_pty_system()
+ .openpty(PtySize {
+ rows: 6,
+ cols: 40,
+ pixel_width: 0,
+ pixel_height: 0,
+ })
+ .unwrap();
+ let child = pair
+ .slave
+ .spawn_command(CommandBuilder::new("/bin/cat"))
+ .unwrap();
+ let reader = pair.master.try_clone_reader().unwrap();
+ let terminal = Terminal::new(
+ size,
+ Arc::new(TestConfig),
+ "ThinkTerm",
+ "test",
+ pair.master.take_writer().unwrap(),
+ );
+ let pane = Arc::new(LocalPane::new(
+ crate::pane::alloc_pane_id(),
+ terminal,
+ child,
+ pair.master,
+ Box::new(Vec::new()),
+ 0,
+ "test".into(),
+ ));
+ let dyn_pane: Arc<dyn Pane> = pane.clone();
+ let tab = Arc::new(Tab::new(&size));
+ tab.assign_pane(&dyn_pane);
+ mux.panes.write().insert(pane.pane_id(), dyn_pane);
+ mux.add_tab_no_panes(&tab);
+ let mut window = crate::window::Window::new(Some("default".into()), None, None);
+ window.push(&tab);
+ mux.windows.write().insert(window.window_id(), window);
+ let client = ClientId {
+ hostname: "devbox".into(),
+ username: "user".into(),
+ pid: std::process::id(),
+ epoch: 0,
+ id: 0,
+ ssh_auth_sock: None,
+ };
+ mux.register_client(Arc::new(client.clone()));
+ let connect = Host::new(&mux).unwrap();
+ let route = connect
+ .open(client.clone(), "user@server-a:22", "zh-CN")
+ .unwrap();
+ route.heartbeat().unwrap();
+ route
+ .begin_all_local_approval(Permission::ReadAndInput, 60, None)
+ .unwrap();
+ let deadline = Deadline::request().unwrap();
+ while route.status().grants.is_empty() {
+ assert!(route.status().error.is_none());
+ deadline.remaining().unwrap();
+ route.heartbeat().unwrap();
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ Fixture {
+ mux,
+ pane,
+ connect,
+ client,
+ route,
+ reader,
+ sequence: 0,
+ _helper: helper,
+ _serial: serial,
+ }
+ }
+
+ impl Fixture {
+ /// One request through the host and over a real socket, as the data
+ /// connection carries it.
+ fn exchange(
+ &mut self,
+ command: Command,
+ payload: Option<Payload>,
+ ) -> thinkterm_reverse_access::Result<(Reply, Option<Payload>)> {
+ self.sequence += 1;
+ let sequence = self.sequence;
+ let route = Arc::clone(&self.route);
+ route.heartbeat()?;
+ smol::block_on(async move {
+ let budgets = Budgets::new()?;
+ let budget = budgets.open_route(Id::random()?)?;
+ let (near, far) = smol::Async::<UnixStream>::pair().unwrap();
+ let mut near = Channel::new(near, budget.acquire(1024 * 1024)?)?;
+ let mut far = Channel::new(far, budget.acquire(1024 * 1024)?)?;
+ let deadline = Deadline::request()?;
+ let reply = route
+ .prepare_reply(sequence, command, payload, &deadline, &deadline)
+ .await?;
+ let (sent, received) = smol::future::zip(
+ reply.send(&mut near, sequence, &deadline, &deadline),
+ receive_reply(
+ &mut far,
+ sequence,
+ |bytes| Assembly::text(bytes, &budget),
+ &deadline,
+ ),
+ )
+ .await;
+ sent?;
+ received?
+ })
+ }
+
+ fn list(&mut self) -> Vec<ExportRef> {
+ match self
+ .exchange(Command::List { after: None }, None)
+ .unwrap()
+ .0
+ {
+ Reply::List { exports, .. } => exports.iter().map(|item| item.export).collect(),
+ _ => panic!("not a list"),
+ }
+ }
+
+ fn read(&mut self, export: ExportRef) -> String {
+ let command = Command::Read {
+ export,
+ options: ReadOptions {
+ trim: true,
+ ..ReadOptions::default()
+ },
+ };
+ let (reply, payload) = self.exchange(command, None).unwrap();
+ assert!(matches!(reply, Reply::Text { .. }));
+ payload.unwrap().text().to_string()
+ }
+ }
+
+ impl Drop for Fixture {
+ fn drop(&mut self) {
+ self.route.close();
+ self.mux.panes.write().clear();
+ }
+ }
+
+ /// Takes a frame's first byte and then nothing until `opens`, as a
+ /// connection that has slowed down leaves a frame partly written.
+ struct Stalled {
+ socket: smol::Async<UnixStream>,
+ opens: smol::Timer,
+ started: bool,
+ open: bool,
+ }
+ impl AsyncRead for Stalled {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bytes: &mut [u8],
+ ) -> Poll<std::io::Result<usize>> {
+ Pin::new(&mut self.socket).poll_read(cx, bytes)
+ }
+ }
+ impl AsyncWrite for Stalled {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<std::io::Result<usize>> {
+ if !self.started {
+ self.started = true;
+ return Pin::new(&mut self.socket).poll_write(cx, &bytes[..1]);
+ }
+ if !self.open {
+ if Pin::new(&mut self.opens).poll(cx).is_pending() {
+ return Poll::Pending;
+ }
+ self.open = true;
+ }
+ Pin::new(&mut self.socket).poll_write(cx, bytes)
+ }
+ fn poll_flush(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.socket).poll_flush(cx)
+ }
+ fn poll_close(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.socket).poll_close(cx)
+ }
+ }
+
+ #[test]
+ fn a_grant_lists_reads_and_types_into_a_real_terminal() {
+ let mut host = fixture();
+ let exports = host.list();
+ assert_eq!(exports.len(), 1);
+ assert_eq!(exports[0].target.pane, host.pane.pane_id() as u64);
+
+ // Past the scrollback, where a read used to end the whole host.
+ {
+ let mut terminal = host.pane.terminal.lock();
+ for line in 0..500 {
+ terminal.advance_bytes(format!("line-{line}\r\n").as_bytes());
+ }
+ }
+ assert!(host.read(exports[0]).ends_with("line-499\n"));
+
+ // A terminal in the middle of its output is waited for, not failed.
+ let pane = Arc::clone(&host.pane);
+ let (locked, is_locked) = std::sync::mpsc::channel();
+ let parser = std::thread::spawn(move || {
+ let terminal = pane.terminal.lock();
+ locked.send(()).unwrap();
+ std::thread::sleep(Duration::from_millis(50));
+ drop(terminal);
+ });
+ is_locked.recv().unwrap();
+ assert!(host.read(exports[0]).ends_with("line-499\n"));
+ parser.join().unwrap();
+ let pane = Arc::clone(&host.pane);
+ let (locked, is_locked) = std::sync::mpsc::channel();
+ let parser = std::thread::spawn(move || {
+ let terminal = pane.terminal.lock();
+ locked.send(()).unwrap();
+ std::thread::sleep(Duration::from_millis(50));
+ drop(terminal);
+ });
+ is_locked.recv().unwrap();
+ assert_eq!(host.list(), exports);
+ parser.join().unwrap();
+
+ // Text, then its Enter after the delay, reach the program.
+ let started = Instant::now();
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+ let mut payload = Assembly::input(5, &budget).unwrap();
+ payload.append(0, b"hello").unwrap();
+ let (reply, _) = host
+ .exchange(
+ Command::Text {
+ export: exports[0],
+ bytes: 5,
+ no_paste: true,
+ enter: true,
+ },
+ Some(payload.finish().unwrap()),
+ )
+ .unwrap();
+ let Reply::Input(result) = reply else {
+ panic!("not an input result");
+ };
+ assert_eq!(result.status, InputStatus::Submitted);
+ assert!(result.enter_submitted);
+ assert!(started.elapsed() >= thinkterm_reverse_access::protocol::enter_delay(5));
+ let mut seen = Vec::new();
+ let mut bytes = [0; 256];
+ while !String::from_utf8_lossy(&seen).contains("hello") {
+ let count = host.reader.read(&mut bytes).unwrap();
+ assert!(count > 0);
+ seen.extend_from_slice(&bytes[..count]);
+ }
+
+ // Revoked is over, for reads as for the next list.
+ let grant = host.route.status().grants[0].grant;
+ host.route.revoke(grant).unwrap();
+ assert!(host
+ .exchange(
+ Command::Read {
+ export: exports[0],
+ options: ReadOptions::default(),
+ },
+ None,
+ )
+ .is_err());
+ assert!(host.route.status().grants.is_empty());
+ }
+
+ #[test]
+ fn a_read_out_of_time_partway_through_a_frame_finishes_it_and_cancels() {
+ let mut host = fixture();
+ let exports = host.list();
+ host.pane.terminal.lock().advance_bytes(b"example\r\n");
+ host.route.heartbeat().unwrap();
+ host.sequence += 1;
+ let sequence = host.sequence;
+ let command = Command::Read {
+ export: exports[0],
+ options: ReadOptions::default(),
+ };
+ let route = Arc::clone(&host.route);
+ let received = smol::block_on(async move {
+ let budgets = Budgets::new()?;
+ let budget = budgets.open_route(Id::random()?)?;
+ let (near, far) = smol::Async::<UnixStream>::pair().unwrap();
+ // Still stuck in the reply's first frame when the operation ends.
+ let near = Stalled {
+ socket: near,
+ opens: smol::Timer::after(Duration::from_millis(600)),
+ started: false,
+ open: false,
+ };
+ let mut near = Channel::new(near, budget.acquire(1024 * 1024)?)?;
+ let mut far = Channel::new(far, budget.acquire(1024 * 1024)?)?;
+ let deadline = Deadline::request()?;
+ let operation = Deadline::after(Duration::from_millis(400))?;
+ let reply = route
+ .prepare_reply(sequence, command, None, &operation, &deadline)
+ .await?;
+ let (sent, received) = smol::future::zip(
+ reply.send(&mut near, sequence, &operation, &deadline),
+ receive_reply(
+ &mut far,
+ sequence,
+ |bytes| Assembly::text(bytes, &budget),
+ &deadline,
+ ),
+ )
+ .await;
+ sent?;
+ received
+ })
+ .unwrap();
+ assert!(matches!(received, Err(Error::Unavailable)));
+
+ // That was one request: the route and its grant carry on.
+ assert!(host.read(exports[0]).contains("example"));
+ }
+
+ #[test]
+ fn a_second_press_of_authenticate_is_the_approval_already_running() {
+ let host = fixture();
+ let grant = host.route.status().grants[0].grant;
+ std::fs::write(
+ &host._helper.0,
+ "#!/bin/sh\nIFS= read -r line\nid=${line#*\\\"Id\\\":\\\"}\nsleep 1\n\
+ printf '{\"kind\":\"approved\",\"id\":\"%s\"}\\n' \"${id%%\\\"*}\"\n",
+ )
+ .unwrap();
+ for _ in 0..2 {
+ host.route
+ .begin_all_local_approval(Permission::Read, 60, Some(grant))
+ .unwrap();
+ let status = host.route.status();
+ assert!(status.authenticating);
+ assert!(status.error.is_none());
+ }
+
+ // Another route has not asked yet, and has to wait for this one.
+ let other = host
+ .connect
+ .open(host.client.clone(), "user@server-b:22", "zh-CN")
+ .unwrap();
+ assert!(matches!(
+ other.begin_all_local_approval(Permission::Read, 60, None),
+ Err(Error::Busy)
+ ));
+ assert!(other.status().error.is_some());
+ assert!(host.route.status().error.is_none());
+
+ let deadline = Deadline::request().unwrap();
+ while host.route.status().authenticating {
+ deadline.remaining().unwrap();
+ host.route.heartbeat().unwrap();
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let status = host.route.status();
+ assert!(status.error.is_none());
+ assert_eq!(status.grants.len(), 1);
+ assert_ne!(status.grants[0].grant, grant);
+ }
+
+ #[test]
+ fn a_refused_dialog_is_not_a_failure_and_a_missing_one_stays_reported() {
+ let host = fixture();
+ let grant = host.route.status().grants[0].grant;
+ std::fs::write(
+ &host._helper.0,
+ "#!/bin/sh\nIFS= read -r line\nid=${line#*\\\"Id\\\":\\\"}\n\
+ printf '{\"kind\":\"rejected\",\"id\":\"%s\"}\\n' \"${id%%\\\"*}\"\n",
+ )
+ .unwrap();
+ host.route
+ .begin_all_local_approval(Permission::Read, 60, Some(grant))
+ .unwrap();
+ let deadline = Deadline::request().unwrap();
+ while host.route.status().authenticating {
+ deadline.remaining().unwrap();
+ host.route.heartbeat().unwrap();
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let status = host.route.status();
+ assert!(status.error.is_none());
+ assert_eq!(status.grants[0].grant, grant);
+
+ std::fs::remove_file(&host._helper.0).unwrap();
+ host.route.revoke(grant).unwrap();
+ // The monitor ended with the last grant, so this needs a new helper.
+ assert!(host
+ .route
+ .begin_all_local_approval(Permission::Read, 60, None)
+ .is_err());
+ assert!(host.route.status().error.is_some());
+ assert!(host.route.status().error.is_some());
+ host.route.cancel_approval();
+ assert!(host.route.status().error.is_none());
+ }
+}
+
#[cfg(test)]
mod summary_tests {
use super::*;
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index a6e1a479..06d00428 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -8,7 +8,7 @@ use parking_lot::Mutex;
use rangeset::intersects_range;
use std::collections::HashMap;
use std::convert::TryInto;
-use std::sync::Arc;
+use std::sync::{Arc, Weak};
use wezterm_term::TerminalSize;
pub type PaneStackId = usize;
@@ -250,8 +250,12 @@ struct TabInner {
zoomed: Option<Arc<dyn Pane>>,
title: String,
recency: Recency,
+ delegated_panes: HashMap<PaneId, Weak<()>>,
}
+/// A pane's uninterrupted membership in this tab, retained only by exports.
+pub(crate) struct PaneMembership(Arc<()>);
+
/// A Tab is a container of Panes
pub struct Tab {
inner: Mutex<TabInner>,
@@ -1057,6 +1061,48 @@ impl Tab {
self.inner.lock().contains_pane(pane)
}
+ pub(crate) fn capture_delegated_pane(
+ &self,
+ pane: PaneId,
+ ) -> thinkterm_reverse_access::Result<PaneMembership> {
+ use thinkterm_reverse_access::Error;
+ let mut inner = self.inner.try_lock().ok_or(Error::Busy)?;
+ if !inner.contains_pane(pane) {
+ return Err(Error::Unavailable);
+ }
+ inner
+ .delegated_panes
+ .retain(|_, token| token.strong_count() > 0);
+ if let Some(token) = inner.delegated_panes.get(&pane).and_then(Weak::upgrade) {
+ return Ok(PaneMembership(token));
+ }
+ if inner.delegated_panes.len() >= thinkterm_reverse_access::MAX_TARGETS {
+ return Err(Error::TooLarge);
+ }
+ let token = Arc::new(());
+ inner.delegated_panes.insert(pane, Arc::downgrade(&token));
+ Ok(PaneMembership(token))
+ }
+
+ pub(crate) fn with_delegated_panes<T>(
+ &self,
+ panes: &[(PaneId, &PaneMembership)],
+ submit: impl FnOnce() -> T,
+ ) -> thinkterm_reverse_access::Result<T> {
+ use thinkterm_reverse_access::Error;
+ let inner = self.inner.try_lock().ok_or(Error::Busy)?;
+ if panes.iter().any(|(pane, token)| {
+ !inner.contains_pane(*pane)
+ || !inner
+ .delegated_panes
+ .get(pane)
+ .is_some_and(|current| current.ptr_eq(&Arc::downgrade(&token.0)))
+ }) {
+ return Err(Error::Unavailable);
+ }
+ Ok(submit())
+ }
+
/// Whether a native frontend viewport describes every split leaf in this
/// tab. Zoomed frontends intentionally report just the pane that fills
/// the root, and that viewport can race ahead of the separate zoom RPC.
@@ -1238,6 +1284,34 @@ impl Tab {
self.inner.lock().remove_pane(pane_id)
}
+ pub(crate) fn move_pane_to_split(
+ &self,
+ pane_id: PaneId,
+ target: PaneId,
+ request: SplitRequest,
+ ) -> anyhow::Result<Arc<dyn Pane>> {
+ let mut inner = self.inner.lock();
+ let membership = inner.delegated_panes.remove(&pane_id);
+ let pane = inner
+ .remove_pane(pane_id)
+ .ok_or_else(|| anyhow::anyhow!("pane {pane_id} not found in tab"))?;
+ let result = match inner.pane_index_for_pane(target) {
+ Some(index) => inner.split_and_insert(index, request, Arc::clone(&pane)),
+ None => Err(anyhow::anyhow!(
+ "target pane {target} vanished while moving pane"
+ )),
+ };
+ if result.is_err() {
+ inner.push_pane_into_first_stack(&pane);
+ }
+ if let Some(membership) = membership {
+ inner.delegated_panes.insert(pane_id, membership);
+ }
+ result?;
+ inner.set_active_pane(&pane);
+ Ok(pane)
+ }
+
pub fn can_close_without_prompting(&self, reason: CloseReason) -> bool {
self.inner.lock().can_close_without_prompting(reason)
}
@@ -1399,6 +1473,7 @@ impl TabInner {
zoomed: None,
title: String::new(),
recency: Recency::default(),
+ delegated_panes: HashMap::new(),
}
}
@@ -1513,6 +1588,14 @@ impl TabInner {
self.recency.tag(self.active);
self.pane.replace(cursor.tree());
self.zoomed = zoomed;
+ let retained: Vec<_> = self
+ .delegated_panes
+ .keys()
+ .copied()
+ .filter(|pane| self.contains_pane(*pane))
+ .collect();
+ self.delegated_panes
+ .retain(|pane, token| token.strong_count() > 0 && retained.contains(pane));
// For a changed topology the rebuilt tree carries the peer's cell
// geometry (derived from its pane dimensions, which for client
@@ -3082,6 +3165,9 @@ impl TabInner {
}
if !dead_panes.is_empty() {
+ for pane in &dead_panes {
+ self.delegated_panes.remove(&pane.pane_id());
+ }
self.advise_focus_change(prior);
}
@@ -3434,9 +3520,13 @@ impl TabInner {
}
// Detach: remove_pane handles emptied-stack pruning and geometry.
+ let membership = self.delegated_panes.remove(&src_pane_id);
let removed = self.remove_pane(src_pane_id).ok_or_else(|| {
anyhow::anyhow!("pane {src_pane_id} vanished while moving between stacks")
})?;
+ if let Some(membership) = membership {
+ self.delegated_panes.insert(src_pane_id, membership);
+ }
// Attach: walk the (possibly restructured) tree and push into the
// target stack. No fallible steps; resize after the removal's
@@ -3639,6 +3729,8 @@ impl TabInner {
}
fn assign_pane(&mut self, pane: &Arc<dyn Pane>) {
+ self.delegated_panes
+ .retain(|id, token| *id == pane.pane_id() && token.strong_count() > 0);
match Tree::new()
.cursor()
.assign_top(PaneStack::new(Arc::clone(pane)))
@@ -4411,8 +4503,7 @@ mod test {
// test threads would register their windows and panes into whichever
// instance is installed at that moment, corrupting each other's
// still-referenced scans — so global-Mux tests run one at a time.
- static SERIAL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
- let serial = SERIAL.lock();
+ let serial = crate::GLOBAL_MUX_TESTS.lock();
Mux::set_mux(&Arc::new(Mux::new(None)));
MuxTestGuard { _serial: serial }
}
@@ -5810,6 +5901,7 @@ mod test {
mux.add_tab_no_panes(&tab);
mux.add_pane(&target).unwrap();
mux.add_pane(&src).unwrap();
+ let membership = tab.capture_delegated_pane(src.pane_id()).unwrap();
let moved = mux
.move_pane_to_split(
@@ -5825,6 +5917,110 @@ mod test {
assert_eq!(tab.iter_panes().len(), 2);
assert!(tab.pane_index_for_pane(target.pane_id()).is_some());
assert!(tab.pane_index_for_pane(src.pane_id()).is_some());
+ assert!(tab
+ .with_delegated_panes(&[(src.pane_id(), &membership)], || ())
+ .is_ok());
+ }
+
+ #[test]
+ fn delegated_membership_does_not_survive_a_tab_round_trip() {
+ use thinkterm_reverse_access::Error;
+ let _guard = install_mux();
+ let mux = Mux::get();
+ let size = test_size();
+ let first = Arc::new(Tab::new(&size));
+ let second = Arc::new(Tab::new(&size));
+ let pane = FakePane::new(10_051, size);
+ let spare = FakePane::new(10_052, size);
+ let target = FakePane::new(10_053, size);
+ first.assign_pane(&spare);
+ first
+ .add_pane_to_stack(spare.pane_id(), pane.clone())
+ .unwrap();
+ second.assign_pane(&target);
+ for tab in [&first, &second] {
+ mux.add_tab_no_panes(tab);
+ }
+ for pane in [&pane, &spare, &target] {
+ mux.add_pane(pane).unwrap();
+ }
+ let membership = first.capture_delegated_pane(pane.pane_id()).unwrap();
+ let unaffected = first.capture_delegated_pane(spare.pane_id()).unwrap();
+ {
+ let _lock = first.inner.lock();
+ assert_eq!(
+ first.with_delegated_panes(&[(pane.pane_id(), &membership)], || ()),
+ Err(Error::Busy)
+ );
+ }
+ mux.move_pane_to_split(
+ pane.pane_id(),
+ second.tab_id(),
+ target.pane_id(),
+ SplitRequest::default(),
+ )
+ .unwrap();
+ mux.move_pane_to_split(
+ pane.pane_id(),
+ first.tab_id(),
+ spare.pane_id(),
+ SplitRequest::default(),
+ )
+ .unwrap();
+ assert_eq!(
+ first.with_delegated_panes(&[(pane.pane_id(), &membership)], || ()),
+ Err(Error::Unavailable)
+ );
+ assert!(first
+ .with_delegated_panes(&[(spare.pane_id(), &unaffected)], || ())
+ .is_ok());
+ let fresh = first.capture_delegated_pane(pane.pane_id()).unwrap();
+ assert!(first
+ .with_delegated_panes(&[(pane.pane_id(), &fresh)], || ())
+ .is_ok());
+ first.remove_pane(pane.pane_id()).unwrap();
+ assert_eq!(
+ first.with_delegated_panes(&[(pane.pane_id(), &fresh)], || ()),
+ Err(Error::Unavailable)
+ );
+ }
+
+ #[test]
+ fn delegated_membership_tracks_tree_replacement_but_not_layout_changes() {
+ use thinkterm_reverse_access::Error;
+ let _guard = install_mux();
+ let size = test_size();
+ let tab = Tab::new(&size);
+ let first = FakePane::new(1, size);
+ let second = FakePane::new(2, size);
+ tab.assign_pane(&first);
+ let membership = tab.capture_delegated_pane(1).unwrap();
+ tab.split_and_insert(0, SplitRequest::default(), second.clone())
+ .unwrap();
+ tab.move_pane_to_stack(1, 2).unwrap();
+ tab.resize(TerminalSize { cols: 100, ..size });
+ assert!(tab.with_delegated_panes(&[(1, &membership)], || ()).is_ok());
+ tab.sync_with_pane_tree(size, PaneNode::Leaf(pane_entry(1, size, true)), |_| {
+ first.clone()
+ });
+ assert!(tab.with_delegated_panes(&[(1, &membership)], || ()).is_ok());
+ tab.sync_with_pane_tree(size, PaneNode::Leaf(pane_entry(2, size, true)), |_| {
+ second.clone()
+ });
+ tab.sync_with_pane_tree(size, PaneNode::Leaf(pane_entry(1, size, true)), |_| {
+ first.clone()
+ });
+ assert_eq!(
+ tab.with_delegated_panes(&[(1, &membership)], || ()),
+ Err(Error::Unavailable)
+ );
+ let fresh = tab.capture_delegated_pane(1).unwrap();
+ tab.assign_pane(&second);
+ tab.assign_pane(&first);
+ assert_eq!(
+ tab.with_delegated_panes(&[(1, &fresh)], || ()),
+ Err(Error::Unavailable)
+ );
}
#[test]
diff --git a/nix/flake.nix b/nix/flake.nix
index 9dd3fcba..f3026367 100644
--- a/nix/flake.nix
+++ b/nix/flake.nix
@@ -68,6 +68,7 @@
]
++ lib.optionals stdenv.isLinux [
libxkbcommon
+ pam
wayland
xorg.libX11
diff --git a/pty/Cargo.toml b/pty/Cargo.toml
index 9c706ade..5153361d 100644
--- a/pty/Cargo.toml
+++ b/pty/Cargo.toml
@@ -24,6 +24,7 @@ default = []
serde_support = ["serde"]
[target."cfg(windows)".dependencies]
+interprocess = { version = "2.4.5", default-features = false }
bitflags.workspace = true
lazy_static.workspace = true
shared_library.workspace = true
diff --git a/pty/src/lib.rs b/pty/src/lib.rs
index b0247086..f98ec267 100644
--- a/pty/src/lib.rs
+++ b/pty/src/lib.rs
@@ -101,6 +101,18 @@ pub trait MasterPty: Downcast + Send {
/// It is invalid to take the writer more than once.
fn take_writer(&self) -> Result<Box<dyn std::io::Write + Send>, Error>;
+ /// A nonblocking input handle for a checked submission on the terminal's
+ /// existing writer thread. It must not be used as a second input queue.
+ fn try_input_writer(&self) -> Result<Box<dyn TryInputWriter>, Error> {
+ anyhow::bail!("this pty does not support nonblocking delegated input")
+ }
+
+ /// Invalidate delegated handles and restore ordinary descriptor mode
+ /// before exporting it to a successor that may predate this API.
+ fn quiesce_input(&self) -> Result<(), Error> {
+ Ok(())
+ }
+
/// If applicable to the type of the tty, return the local process id
/// of the process group or session leader
#[cfg(unix)]
@@ -132,6 +144,12 @@ pub trait MasterPty: Downcast + Send {
}
impl_downcast!(MasterPty);
+pub trait TryInputWriter: Send {
+ /// Submit immediately available bytes; never wait for the application.
+ /// WouldBlock means that no bytes were submitted by this call.
+ fn try_write(&mut self, bytes: &[u8]) -> IoResult<usize>;
+}
+
/// Represents a child process spawned into the pty.
/// This handle can be used to wait for or terminate that child process.
pub trait Child: std::fmt::Debug + ChildKiller + Downcast + Send {
diff --git a/pty/src/unix.rs b/pty/src/unix.rs
index 43f0f52b..2d02feb2 100644
--- a/pty/src/unix.rs
+++ b/pty/src/unix.rs
@@ -12,6 +12,7 @@ use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
+use std::sync::Arc;
use std::{io, mem, ptr};
pub use std::os::unix::io::RawFd;
@@ -52,6 +53,7 @@ fn openpty(size: PtySize) -> anyhow::Result<(UnixMasterPty, UnixSlavePty)> {
fd: PtyFd(unsafe { FileDescriptor::from_raw_fd(master) }),
took_writer: RefCell::new(false),
tty_name,
+ input_writer: RefCell::new(None),
};
let slave = UnixSlavePty {
fd: PtyFd(unsafe { FileDescriptor::from_raw_fd(slave) }),
@@ -92,19 +94,112 @@ impl std::ops::DerefMut for PtyFd {
impl Read for PtyFd {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
- match self.0.read(buf) {
- Err(ref e) if e.raw_os_error() == Some(libc::EIO) => {
- // EIO indicates that the slave pty has been closed.
- // Treat this as EOF so that std::io::Read::read_to_string
- // and similar functions gracefully terminate when they
- // encounter this condition
- Ok(0)
+ loop {
+ match self.0.read(buf) {
+ Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {
+ wait_pty(&self.0, filedescriptor::POLLIN)?;
+ }
+ Err(ref e) if e.raw_os_error() == Some(libc::EIO) => {
+ // EIO indicates that the slave pty has been closed.
+ // Treat this as EOF so that std::io::Read::read_to_string
+ // and similar functions gracefully terminate when they
+ // encounter this condition
+ return Ok(0);
+ }
+ result => return result,
}
- x => x,
}
}
}
+fn wait_pty(fd: &FileDescriptor, events: i16) -> io::Result<()> {
+ let mut fds = [filedescriptor::pollfd {
+ fd: fd.as_raw_fd(),
+ events,
+ revents: 0,
+ }];
+ loop {
+ match filedescriptor::poll(&mut fds, None) {
+ Ok(_) => return Ok(()),
+ Err(filedescriptor::Error::Poll(error))
+ if error.kind() == io::ErrorKind::Interrupted =>
+ {
+ ()
+ }
+ Err(error) => return Err(io::Error::new(io::ErrorKind::Other, error)),
+ }
+ }
+}
+
+impl Write for PtyFd {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ loop {
+ match self.0.write(buf) {
+ Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {
+ wait_pty(&self.0, filedescriptor::POLLOUT)?;
+ }
+ result => return result,
+ }
+ }
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.0.flush()
+ }
+}
+
+/// The delegated input handle of a master, which sets O_NONBLOCK on every
+/// duplicate of it. Readers and writers of that master have to allow for it.
+#[derive(Debug)]
+pub struct NonblockingInput {
+ fd: std::sync::Mutex<FileDescriptor>,
+ closed: std::sync::atomic::AtomicBool,
+}
+
+impl NonblockingInput {
+ pub fn new(master: &impl AsRawFd) -> Result<Arc<Self>, Error> {
+ let mut fd = FileDescriptor::dup(master)?;
+ fd.set_non_blocking(true)?;
+ Ok(Arc::new(Self {
+ fd: std::sync::Mutex::new(fd),
+ closed: std::sync::atomic::AtomicBool::new(false),
+ }))
+ }
+
+ pub fn writer(self: &Arc<Self>) -> Box<dyn crate::TryInputWriter> {
+ Box::new(UnixTryInput(Arc::clone(self)))
+ }
+
+ /// Writers already handed out stop working, and the master is left as
+ /// ordinary code expects it.
+ pub fn close(&self) -> Result<(), Error> {
+ let mut fd = self
+ .fd
+ .lock()
+ .map_err(|_| anyhow::anyhow!("pty input is unavailable"))?;
+ self.closed
+ .store(true, std::sync::atomic::Ordering::Release);
+ fd.set_non_blocking(false)?;
+ Ok(())
+ }
+}
+
+struct UnixTryInput(Arc<NonblockingInput>);
+
+impl crate::TryInputWriter for UnixTryInput {
+ fn try_write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ let mut fd = self
+ .0
+ .fd
+ .try_lock()
+ .map_err(|_| io::ErrorKind::WouldBlock)?;
+ if self.0.closed.load(std::sync::atomic::Ordering::Acquire) {
+ return Err(io::ErrorKind::BrokenPipe.into());
+ }
+ fd.write(bytes)
+ }
+}
+
fn tty_name(fd: RawFd) -> Option<PathBuf> {
let mut buf = vec![0 as std::ffi::c_char; 128];
@@ -304,6 +399,7 @@ struct UnixMasterPty {
fd: PtyFd,
took_writer: RefCell<bool>,
tty_name: Option<PathBuf>,
+ input_writer: RefCell<Option<Arc<NonblockingInput>>>,
}
/// A master pty this process did not open: the descriptor came from
@@ -321,6 +417,7 @@ pub fn master_from_raw_fd(
fd: PtyFd(fd),
took_writer: RefCell::new(false),
tty_name,
+ input_writer: RefCell::new(None),
}))
}
@@ -381,6 +478,26 @@ impl MasterPty for UnixMasterPty {
Ok(Box::new(UnixMasterWriter { fd }))
}
+ fn try_input_writer(&self) -> Result<Box<dyn crate::TryInputWriter>, Error> {
+ let mut cached = self.input_writer.borrow_mut();
+ if let Some(input) = cached.as_ref() {
+ return Ok(input.writer());
+ }
+ let input = NonblockingInput::new(&self.fd.0)?;
+ // Keep the mode stable for this master's lifetime. Restoring it
+ // as a previous lease drops can race with acquiring a new lease.
+ let writer = input.writer();
+ *cached = Some(input);
+ Ok(writer)
+ }
+
+ fn quiesce_input(&self) -> Result<(), Error> {
+ if let Some(input) = self.input_writer.borrow_mut().take() {
+ input.close()?;
+ }
+ Ok(())
+ }
+
fn as_raw_fd(&self) -> Option<RawFd> {
Some(self.fd.0.as_raw_fd())
}
@@ -430,3 +547,83 @@ impl Write for UnixMasterWriter {
self.fd.flush()
}
}
+
+#[cfg(test)]
+mod delegated_input_tests {
+ use super::*;
+ use std::os::fd::AsFd;
+
+ #[test]
+ fn checked_input_is_nonblocking_and_preserves_regular_io() {
+ let (master, slave) = openpty(PtySize::default()).unwrap();
+ let mut attributes = nix::sys::termios::tcgetattr(slave.fd.as_fd()).unwrap();
+ nix::sys::termios::cfmakeraw(&mut attributes);
+ nix::sys::termios::tcsetattr(
+ slave.fd.as_fd(),
+ nix::sys::termios::SetArg::TCSANOW,
+ &attributes,
+ )
+ .unwrap();
+ let mut checked = master.try_input_writer().unwrap();
+ let mut regular = master.take_writer().unwrap();
+ let mut slave_reader = slave.fd.try_clone().unwrap();
+ let block = [b'x'; 4096];
+ let mut accepted = 0;
+ loop {
+ match checked.try_write(&block) {
+ Ok(0) => panic!("nonempty PTY input made no progress"),
+ Ok(count) => accepted += count,
+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
+ Err(error) => panic!("unexpected PTY error: {}", error),
+ }
+ assert!(
+ accepted < 8 * 1024 * 1024,
+ "PTY failed to apply backpressure"
+ );
+ }
+ assert!(accepted > 0);
+ // A normal write must still wait and eventually deliver all bytes.
+ let drain = std::thread::spawn(move || {
+ let mut received = vec![0; accepted + 4];
+ slave_reader.read_exact(&mut received).unwrap();
+ assert!(received[..accepted].iter().all(|byte| *byte == b'x'));
+ assert_eq!(&received[accepted..], b"done");
+ });
+ regular.write_all(b"done").unwrap();
+ drain.join().unwrap();
+
+ let mut reader = master.try_clone_reader().unwrap();
+ let read = std::thread::spawn(move || {
+ let mut bytes = [0; 5];
+ reader.read_exact(&mut bytes).unwrap();
+ assert_eq!(&bytes, b"reply");
+ });
+ slave.fd.try_clone().unwrap().write_all(b"reply").unwrap();
+ read.join().unwrap();
+ drop(checked);
+ let mut next = master.try_input_writer().unwrap();
+ assert_eq!(next.try_write(b"next").unwrap(), 4);
+ }
+
+ #[test]
+ fn handoff_quiesces_old_writers_without_changing_successor_mode_on_drop() {
+ let (master, _slave) = openpty(PtySize::default()).unwrap();
+ let mut old = master.try_input_writer().unwrap();
+ master.quiesce_input().unwrap();
+ assert_eq!(
+ old.try_write(b"stale").unwrap_err().kind(),
+ io::ErrorKind::BrokenPipe
+ );
+ let flags = || {
+ nix::fcntl::OFlag::from_bits_truncate(
+ nix::fcntl::fcntl(master.fd.0.as_raw_fd(), nix::fcntl::FcntlArg::F_GETFL).unwrap(),
+ )
+ };
+ assert!(!flags().contains(nix::fcntl::OFlag::O_NONBLOCK));
+ let mut current = master.try_input_writer().unwrap();
+ assert!(flags().contains(nix::fcntl::OFlag::O_NONBLOCK));
+ drop(old);
+ assert!(flags().contains(nix::fcntl::OFlag::O_NONBLOCK));
+ assert_eq!(current.try_write(b"current").unwrap(), 7);
+ }
+}
diff --git a/pty/src/win/conpty.rs b/pty/src/win/conpty.rs
index 2aad0107..b3a68d5a 100644
--- a/pty/src/win/conpty.rs
+++ b/pty/src/win/conpty.rs
@@ -3,6 +3,8 @@ use crate::win::psuedocon::PsuedoCon;
use crate::{Child, MasterPty, PtyPair, PtySize, PtySystem, SlavePty};
use anyhow::Error;
use filedescriptor::{FileDescriptor, Pipe};
+use std::convert::TryInto;
+use std::io::{self, Write};
use std::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, OwnedHandle};
use std::sync::{Arc, Mutex};
use winapi::um::wincon::COORD;
@@ -79,6 +81,7 @@ pub fn master_from_handoff(
readable: unsafe { FileDescriptor::from_raw_handle(output.into_raw_handle()) },
writable: Some(unsafe { FileDescriptor::from_raw_handle(input.into_raw_handle()) }),
input_for_handoff: None,
+ delegated_input: None,
size,
})),
}))
@@ -112,6 +115,7 @@ impl PtySystem for ConPtySystem {
readable: stdout.read,
writable: Some(stdin.write),
input_for_handoff: None,
+ delegated_input: None,
size,
})),
};
@@ -134,6 +138,7 @@ struct Inner {
/// A second handle on the input pipe once the writer is taken, for a
/// handoff: the writer itself goes where this side cannot reach it.
input_for_handoff: Option<FileDescriptor>,
+ delegated_input: Option<Arc<NonblockingInput>>,
size: PtySize,
}
@@ -190,7 +195,50 @@ impl MasterPty for ConPtyMasterPty {
.take()
.ok_or_else(|| anyhow::anyhow!("writer already taken"))?;
inner.input_for_handoff = writer.try_clone().ok();
- Ok(Box::new(writer))
+ Ok(Box::new(ConPtyWriter(writer)))
+ }
+
+ fn try_input_writer(&self) -> anyhow::Result<Box<dyn crate::TryInputWriter>> {
+ let mut inner = self
+ .inner
+ .lock()
+ .map_err(|_| anyhow::anyhow!("pty is unavailable"))?;
+ let input = if let Some(input) = inner.delegated_input.as_ref() {
+ Arc::clone(input)
+ } else {
+ let fd = inner
+ .writable
+ .as_ref()
+ .or(inner.input_for_handoff.as_ref())
+ .ok_or_else(|| anyhow::anyhow!("pty input is unavailable"))?
+ .try_clone()?;
+ set_pipe_nonblocking(&fd, true)?;
+ let input = Arc::new(NonblockingInput {
+ fd: Mutex::new(fd),
+ closed: std::sync::atomic::AtomicBool::new(false),
+ });
+ inner.delegated_input = Some(Arc::clone(&input));
+ input
+ };
+ Ok(Box::new(ConPtyTryInput(input)))
+ }
+
+ fn quiesce_input(&self) -> anyhow::Result<()> {
+ let mut inner = self
+ .inner
+ .lock()
+ .map_err(|_| anyhow::anyhow!("pty input is unavailable"))?;
+ if let Some(input) = inner.delegated_input.take() {
+ let fd = input
+ .fd
+ .lock()
+ .map_err(|_| anyhow::anyhow!("pty input is unavailable"))?;
+ input
+ .closed
+ .store(true, std::sync::atomic::Ordering::Release);
+ set_pipe_nonblocking(&fd, false)?;
+ }
+ Ok(())
}
fn conpty_handoff(&self) -> anyhow::Result<ConPtyHandoff> {
@@ -208,6 +256,67 @@ impl MasterPty for ConPtyMasterPty {
}
}
+fn set_pipe_nonblocking(fd: &FileDescriptor, enabled: bool) -> anyhow::Result<()> {
+ use interprocess::os::windows::named_pipe::{pipe_mode::Bytes, SendPipeStream};
+ let handle: OwnedHandle = fd.as_file()?.into();
+ let pipe: SendPipeStream<Bytes> = handle
+ .try_into()
+ .map_err(|_| anyhow::anyhow!("pty input is not a pipe"))?;
+ let result = pipe.set_nonblocking(enabled);
+ // No flushing Drop path: this duplicate is used only to set pipe mode.
+ let handle: OwnedHandle = pipe
+ .try_into()
+ .map_err(|_| anyhow::anyhow!("pty input handle is shared"))?;
+ drop(handle);
+ result?;
+ Ok(())
+}
+
+struct NonblockingInput {
+ fd: Mutex<FileDescriptor>,
+ closed: std::sync::atomic::AtomicBool,
+}
+
+struct ConPtyTryInput(Arc<NonblockingInput>);
+
+impl crate::TryInputWriter for ConPtyTryInput {
+ fn try_write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ let mut fd = self
+ .0
+ .fd
+ .try_lock()
+ .map_err(|_| io::ErrorKind::WouldBlock)?;
+ if self.0.closed.load(std::sync::atomic::Ordering::Acquire) {
+ return Err(io::ErrorKind::BrokenPipe.into());
+ }
+ match fd.write(bytes) {
+ Ok(0) if !bytes.is_empty() => Err(io::ErrorKind::WouldBlock.into()),
+ result => result,
+ }
+ }
+}
+
+struct ConPtyWriter(FileDescriptor);
+
+impl Write for ConPtyWriter {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ loop {
+ match self.0.write(bytes) {
+ Ok(0) if !bytes.is_empty() => {
+ std::thread::sleep(std::time::Duration::from_millis(1))
+ }
+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
+ std::thread::sleep(std::time::Duration::from_millis(1))
+ }
+ result => return result,
+ }
+ }
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ self.0.flush()
+ }
+}
+
impl SlavePty for ConPtySlavePty {
fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<Box<dyn Child + Send + Sync>> {
let inner = self.inner.lock().unwrap();
@@ -215,3 +324,63 @@ impl SlavePty for ConPtySlavePty {
Ok(Box::new(child))
}
}
+
+#[cfg(test)]
+mod delegated_input_tests {
+ use super::*;
+ use crate::TryInputWriter;
+ use std::io::Read;
+ use std::sync::mpsc;
+ use std::time::Duration;
+
+ #[test]
+ fn anonymous_pipe_backpressure_is_nonblocking_and_ordinary_input_still_works() {
+ let pipe = Pipe::new().unwrap();
+ let mut reader = pipe.read;
+ let mut ordinary = ConPtyWriter(pipe.write);
+ let fd = ordinary.0.try_clone().unwrap();
+ set_pipe_nonblocking(&fd, true).unwrap();
+ let (done, completed) = mpsc::sync_channel(1);
+ let worker = std::thread::spawn(move || {
+ let mut writer = ConPtyTryInput(Arc::new(NonblockingInput {
+ fd: Mutex::new(fd),
+ closed: std::sync::atomic::AtomicBool::new(false),
+ }));
+ let mut written = 0;
+ loop {
+ match writer.try_write(&[b'x'; 4096]) {
+ Ok(count) if count > 0 => {
+ written += count;
+ assert!(
+ written <= 4 * 1024 * 1024,
+ "undrained pipe did not apply backpressure"
+ );
+ }
+ Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
+ result => panic!("unexpected pipe write result: {:?}", result),
+ }
+ }
+ done.send(written).unwrap();
+ });
+ let written = match completed.recv_timeout(Duration::from_secs(5)) {
+ Ok(written) => written,
+ Err(error) => {
+ // Closing the reader also releases an incorrectly blocking
+ // writer, so a failed test cannot strand a pipe worker.
+ drop(reader);
+ let _ = worker.join();
+ panic!("delegated pipe write blocked: {}", error);
+ }
+ };
+ worker.join().unwrap();
+ assert!(written > 0);
+ let mut bytes = vec![0; written];
+ reader.read_exact(&mut bytes).unwrap();
+ assert!(bytes.iter().all(|byte| *byte == b'x'));
+ ordinary.write_all(b"ordinary").unwrap();
+ let mut bytes = [0; 8];
+ reader.read_exact(&mut bytes).unwrap();
+ assert_eq!(&bytes, b"ordinary");
+ set_pipe_nonblocking(&ordinary.0, false).unwrap();
+ }
+}
diff --git a/term/src/terminalstate/keyboard.rs b/term/src/terminalstate/keyboard.rs
index 340eedfe..4e6c0258 100644
--- a/term/src/terminalstate/keyboard.rs
+++ b/term/src/terminalstate/keyboard.rs
@@ -28,18 +28,7 @@ impl TerminalState {
mods: KeyModifiers,
is_down: bool,
) -> anyhow::Result<()> {
- let encoding = self.effective_keyboard_encoding();
-
- let to_send = key.encode(
- mods,
- KeyCodeEncodeModes {
- encoding,
- newline_mode: self.newline_mode,
- application_cursor_keys: self.application_cursor_keys,
- modify_other_keys: self.modify_other_keys,
- },
- is_down,
- )?;
+ let to_send = self.encode_key(key.clone(), mods, is_down)?;
if to_send.is_empty() {
return Ok(());
@@ -64,4 +53,24 @@ impl TerminalState {
pub fn key_down(&mut self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()> {
self.key_up_down(key, mods, true)
}
+
+ /// Encode without queuing input or logging its contents. Delegated input
+ /// uses this snapshot before its checked writer operation is enqueued.
+ pub fn encode_key(
+ &self,
+ key: KeyCode,
+ mods: KeyModifiers,
+ is_down: bool,
+ ) -> anyhow::Result<String> {
+ Ok(key.encode(
+ mods,
+ KeyCodeEncodeModes {
+ encoding: self.effective_keyboard_encoding(),
+ newline_mode: self.newline_mode,
+ application_cursor_keys: self.application_cursor_keys,
+ modify_other_keys: self.modify_other_keys,
+ },
+ is_down,
+ )?)
+ }
}
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index f467d0e3..94b8da89 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -541,6 +541,7 @@ struct ThreadedWriter {
enum WriterMessage {
Data(Vec<u8>),
Flush,
+ CheckedInput(Box<dyn FnOnce() + Send>),
}
impl ThreadedWriter {
@@ -561,7 +562,7 @@ impl ThreadedWriter {
while let Ok(msg) = receiver.recv() {
match msg {
WriterMessage::Data(buf) => {
- if writer.write(&buf).is_err() {
+ if writer.write_all(&buf).is_err() {
break;
}
}
@@ -570,6 +571,7 @@ impl ThreadedWriter {
break;
}
}
+ WriterMessage::CheckedInput(submit) => submit(),
}
}
});
@@ -603,14 +605,14 @@ impl std::io::Write for ThreadedWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.sender
.send(WriterMessage::Data(buf.to_vec()))
- .map_err(|err| std::io::Error::new(std::io::ErrorKind::BrokenPipe, err))?;
+ .map_err(|_| std::io::ErrorKind::BrokenPipe)?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.sender
.send(WriterMessage::Flush)
- .map_err(|err| std::io::Error::new(std::io::ErrorKind::BrokenPipe, err))?;
+ .map_err(|_| std::io::ErrorKind::BrokenPipe)?;
Ok(())
}
}
@@ -1081,6 +1083,36 @@ impl TerminalState {
Box::new(self.writer.get_ref().handle())
}
+ /// One bounded delegated operation, ordered with ordinary terminal input.
+ /// The operation owns its budget and performs authorization again at each
+ /// nonblocking PTY write. The callback is never exposed to Lua or RPC.
+ #[cfg(not(target_family = "wasm"))]
+ pub fn queue_checked_input(&mut self, submit: Box<dyn FnOnce() + Send>) -> std::io::Result<()> {
+ self.writer.flush()?;
+ self.writer
+ .get_ref()
+ .sender
+ .send(WriterMessage::CheckedInput(submit))
+ .map_err(|_| std::io::ErrorKind::BrokenPipe.into())
+ }
+
+ pub fn encode_paste(&self, text: &str) -> String {
+ let canon = if self.bracketed_paste {
+ NewlineCanon::None
+ } else {
+ self.config.canonicalize_pasted_newlines()
+ };
+ let text = canon
+ .canonicalize(text)
+ .replace("\x1b[200~", "")
+ .replace("\x1b[201~", "");
+ if self.bracketed_paste {
+ format!("\x1b[200~{text}\x1b[201~")
+ } else {
+ text
+ }
+ }
+
pub fn send_paste(&mut self, text: &str) -> Result<(), Error> {
let mut buf = String::new();
if self.bracketed_paste {
diff --git a/thinkterm-connect-auth/Cargo.toml b/thinkterm-connect-auth/Cargo.toml
new file mode 100644
index 00000000..f0d35332
--- /dev/null
+++ b/thinkterm-connect-auth/Cargo.toml
@@ -0,0 +1,48 @@
+[package]
+name = "thinkterm-connect-auth"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[target.'cfg(windows)'.build-dependencies]
+embed-resource.workspace = true
+
+[dependencies]
+serde = { workspace = true, features = ["derive"] }
+serde_json.workspace = true
+
+[target.'cfg(windows)'.dependencies]
+anyhow.workspace = true
+windows-future = "0.3"
+winreg.workspace = true
+zeroize = "1.8"
+
+[target.'cfg(windows)'.dependencies.windows]
+version = "0.62"
+features = [
+ "Foundation",
+ "Security_Credentials_UI",
+ "Win32_Foundation",
+ "Win32_Graphics_Gdi",
+ "Win32_Security",
+ "Win32_Security_Credentials",
+ "Win32_System_Com",
+ "Win32_System_LibraryLoader",
+ "Win32_System_RemoteDesktop",
+ "Win32_System_Threading",
+ "Win32_System_WinRT",
+ "Win32_System_WindowsProgramming",
+ "Win32_UI_Controls",
+ "Win32_UI_WindowsAndMessaging",
+]
+
+[target.'cfg(target_os = "linux")'.dependencies]
+anyhow.workspace = true
+futures-lite.workspace = true
+futures-util.workspace = true
+nix = { workspace = true, features = ["user", "process", "signal"] }
+pam-client = { package = "pam-client2", version = "0.5.5", default-features = false }
+smol.workspace = true
+zbus.workspace = true
+zvariant.workspace = true
+zeroize = "1.8"
diff --git a/thinkterm-connect-auth/build.rs b/thinkterm-connect-auth/build.rs
new file mode 100644
index 00000000..67e519f7
--- /dev/null
+++ b/thinkterm-connect-auth/build.rs
@@ -0,0 +1,20 @@
+fn main() {
+ // The confirmation window comes from version 6 of the common controls,
+ // which a program has to ask for: without this it does not even load.
+ #[cfg(windows)]
+ {
+ use std::io::Write;
+ println!("cargo:rerun-if-changed=windows.manifest");
+ let manifest = std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
+ .join("windows.manifest");
+ let resource = std::path::Path::new(&std::env::var_os("OUT_DIR").unwrap()).join("auth.rc");
+ // 24 is RT_MANIFEST, spelled out to need no system header.
+ writeln!(
+ std::fs::File::create(&resource).unwrap(),
+ "1 24 \"{}\"",
+ manifest.display().to_string().replace('\\', "\\\\"),
+ )
+ .unwrap();
+ embed_resource::compile(resource);
+ }
+}
diff --git a/thinkterm-connect-auth/pam/debian b/thinkterm-connect-auth/pam/debian
new file mode 100644
index 00000000..70f4d68c
--- /dev/null
+++ b/thinkterm-connect-auth/pam/debian
@@ -0,0 +1,3 @@
+# Installed as /etc/pam.d/thinkterm-connect-auth by the system package.
+@include common-auth
+@include common-account
diff --git a/thinkterm-connect-auth/pam/fedora b/thinkterm-connect-auth/pam/fedora
new file mode 100644
index 00000000..2afeb364
--- /dev/null
+++ b/thinkterm-connect-auth/pam/fedora
@@ -0,0 +1,3 @@
+# Installed as /etc/pam.d/thinkterm-connect-auth by the system package.
+auth substack system-auth
+account include system-auth
diff --git a/thinkterm-connect-auth/pam/suse b/thinkterm-connect-auth/pam/suse
new file mode 100644
index 00000000..5894632b
--- /dev/null
+++ b/thinkterm-connect-auth/pam/suse
@@ -0,0 +1,2 @@
+auth include common-auth
+account include common-account
diff --git a/thinkterm-connect-auth/src/linux.rs b/thinkterm-connect-auth/src/linux.rs
new file mode 100644
index 00000000..2a508dea
--- /dev/null
+++ b/thinkterm-connect-auth/src/linux.rs
@@ -0,0 +1,460 @@
+use super::{emit, Intent};
+use anyhow::{bail, Context};
+use futures_lite::future;
+use futures_util::StreamExt;
+use nix::unistd::{Uid, User};
+use pam_client::{ConversationHandler, ErrorCode, Flag};
+use std::collections::HashMap;
+use std::ffi::{CStr, CString};
+use std::io::{IsTerminal, Read};
+use std::os::unix::fs::{FileTypeExt, MetadataExt};
+use std::path::Path;
+use std::process::{Command, Stdio};
+use std::time::Duration;
+use zeroize::Zeroizing;
+use zvariant::{OwnedObjectPath, OwnedValue};
+
+const SERVICE: &str = "thinkterm-connect-auth";
+const ZENITY: &str = "/usr/bin/zenity";
+
+fn local_x_display(display: &str) -> Option<&str> {
+ let number = display
+ .strip_prefix(':')
+ .or_else(|| display.strip_prefix("unix:"))?;
+ let mut parts = number.split('.');
+ let number = parts.next()?;
+ if number.is_empty() || number.len() > 6 || !number.bytes().all(|c| c.is_ascii_digit()) {
+ return None;
+ }
+ if let Some(screen) = parts.next() {
+ if screen.is_empty() || screen.len() > 6 || !screen.bytes().all(|c| c.is_ascii_digit()) {
+ return None;
+ }
+ }
+ if parts.next().is_some() {
+ return None;
+ }
+ Some(number)
+}
+
+fn local_desktop_environment() -> anyhow::Result<()> {
+ let uid = Uid::current().as_raw();
+ let runtime = std::path::PathBuf::from(format!("/run/user/{uid}"));
+ let metadata = std::fs::symlink_metadata(&runtime)?;
+ if !metadata.is_dir() || metadata.uid() != uid || metadata.mode() & 0o077 != 0 {
+ bail!("desktop runtime directory is unavailable");
+ }
+ let bus = runtime.join("bus");
+ let metadata = std::fs::symlink_metadata(&bus)?;
+ if !metadata.file_type().is_socket() || metadata.uid() != uid {
+ bail!("desktop bus is unavailable");
+ }
+ let wayland = std::env::var("WAYLAND_DISPLAY").ok().filter(|name| {
+ !name.is_empty()
+ && name.len() <= 100
+ && name
+ .bytes()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
+ && std::fs::symlink_metadata(runtime.join(name))
+ .is_ok_and(|metadata| metadata.file_type().is_socket() && metadata.uid() == uid)
+ });
+ let display = std::env::var("DISPLAY").ok().filter(|display| {
+ local_x_display(display).is_some_and(|number| {
+ std::fs::symlink_metadata(format!("/tmp/.X11-unix/X{number}")).is_ok_and(|metadata| {
+ metadata.file_type().is_socket() && (metadata.uid() == 0 || metadata.uid() == uid)
+ })
+ })
+ });
+ if wayland.is_none() && display.is_none() {
+ bail!("local desktop display is unavailable");
+ }
+ // A forwarded X display or arbitrary D-Bus address must never receive
+ // the authentication dialog or its password conversation.
+ std::env::set_var("XDG_RUNTIME_DIR", &runtime);
+ std::env::set_var(
+ "DBUS_SESSION_BUS_ADDRESS",
+ format!("unix:path={}", bus.display()),
+ );
+ std::env::remove_var("DBUS_SYSTEM_BUS_ADDRESS");
+ std::env::remove_var("DISPLAY");
+ std::env::remove_var("WAYLAND_DISPLAY");
+ std::env::set_var(
+ "GDK_BACKEND",
+ match (&wayland, &display) {
+ (Some(_), Some(_)) => "wayland,x11",
+ (Some(_), None) => "wayland",
+ _ => "x11",
+ },
+ );
+ if let Some(name) = wayland {
+ std::env::set_var("WAYLAND_DISPLAY", name);
+ }
+ if let Some(display) = display {
+ std::env::set_var("DISPLAY", display);
+ }
+ Ok(())
+}
+
+fn trusted_system_file(path: &Path) -> anyhow::Result<()> {
+ let path = path.canonicalize()?;
+ for component in path.ancestors() {
+ let metadata = std::fs::metadata(component)?;
+ if metadata.uid() != 0 || metadata.mode() & 0o022 != 0 {
+ bail!("system authentication component is not protected");
+ }
+ }
+ Ok(())
+}
+
+fn dialog(args: &[&str]) -> anyhow::Result<Zeroizing<Vec<u8>>> {
+ let mut child = Command::new(ZENITY)
+ .args(args)
+ .arg("--timeout=110")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()?;
+ let mut bytes = Zeroizing::new(Vec::new());
+ child
+ .stdout
+ .take()
+ .context("dialog pipe")?
+ .take(4097)
+ .read_to_end(&mut bytes)?;
+ if bytes.len() > 4096 {
+ let _ = child.kill();
+ let _ = child.wait();
+ bail!("authentication response is too large");
+ }
+ if !child.wait()?.success() {
+ bail!("authentication cancelled");
+ }
+ if bytes.last() == Some(&b'\n') {
+ bytes.pop();
+ }
+ Ok(bytes)
+}
+
+struct Conversation {
+ username: CString,
+ title: String,
+ prompted: bool,
+ prompts: usize,
+}
+
+impl ConversationHandler for Conversation {
+ fn prompt_echo_on(&mut self, _: &CStr) -> std::result::Result<CString, ErrorCode> {
+ Ok(self.username.clone())
+ }
+
+ fn prompt_echo_off(&mut self, prompt: &CStr) -> std::result::Result<CString, ErrorCode> {
+ self.prompts += 1;
+ if self.prompts > 3 {
+ return Err(ErrorCode::CONV_ERR);
+ }
+ let prompt = prompt.to_str().map_err(|_| ErrorCode::CONV_ERR)?;
+ if prompt.len() > 512 || prompt.chars().any(char::is_control) {
+ return Err(ErrorCode::CONV_ERR);
+ }
+ let password = dialog(&[
+ "--password",
+ &format!("--title={}", self.title),
+ "--no-markup",
+ "--text",
+ prompt,
+ ])
+ .map_err(|_| ErrorCode::CONV_ERR)?;
+ if password.is_empty() {
+ return Err(ErrorCode::CONV_ERR);
+ }
+ self.prompted = true;
+ // PAM owns its response allocation. The collector's temporary bytes
+ // are erased, and this helper exits at the end of the transaction.
+ CString::new(password.as_slice()).map_err(|_| ErrorCode::CONV_ERR)
+ }
+
+ fn text_info(&mut self, _: &CStr) {}
+ fn error_msg(&mut self, _: &CStr) {}
+}
+
+fn authenticate(intent: Intent) -> anyhow::Result<()> {
+ trusted_system_file(Path::new(ZENITY))?;
+ trusted_system_file(Path::new("/etc/pam.d/thinkterm-connect-auth"))?;
+ let user = User::from_uid(Uid::current())?.context("account is unavailable")?;
+ if user.uid.is_root() {
+ bail!("root authentication is unavailable");
+ }
+ let text = &intent.text;
+ let summary = format!(
+ "{}\n\n{}\n\n{}\n{}\n\n{}",
+ text.heading, text.connection, text.terminals, intent.targets, text.detail,
+ );
+ // Declining is an answer, as a wrong password is below.
+ if dialog(&[
+ "--question",
+ &format!("--title={}", text.title),
+ "--no-markup",
+ "--width=620",
+ &format!("--ok-label={}", text.approve),
+ &format!("--cancel-label={}", text.cancel),
+ "--text",
+ &summary,
+ ])
+ .is_err()
+ {
+ return Ok(emit("rejected", Some(&intent.id))?);
+ }
+ let conversation = Conversation {
+ username: CString::new(user.name.clone())?,
+ title: text.password.clone(),
+ prompted: false,
+ prompts: 0,
+ };
+ let mut pam = pam_client::Context::new(SERVICE, Some(&user.name), conversation)
+ .map_err(|_| anyhow::anyhow!("system authentication is unavailable"))?;
+ let approved = pam.authenticate(Flag::DISALLOW_NULL_AUTHTOK).is_ok()
+ && pam.conversation().prompted
+ && pam.acct_mgmt(Flag::DISALLOW_NULL_AUTHTOK).is_ok()
+ && pam.user().ok().as_deref() == Some(user.name.as_str());
+ drop(pam);
+ emit(
+ if approved { "approved" } else { "rejected" },
+ Some(&intent.id),
+ )?;
+ Ok(())
+}
+
+async fn session_path(connection: &zbus::Connection) -> anyhow::Result<OwnedObjectPath> {
+ let manager = zbus::Proxy::new(
+ connection,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ )
+ .await?;
+ if let Ok(path) = manager
+ .call::<_, _, OwnedObjectPath>("GetSessionByPID", &(std::process::id(),))
+ .await
+ {
+ return Ok(path);
+ }
+ // A persistent session host can be outside a logind session's cgroup.
+ // Only an unambiguous active, local graphical session of this UID qualifies.
+ let sessions: Vec<(String, u32, String, String, OwnedObjectPath)> =
+ manager.call("ListSessions", &()).await?;
+ let mut selected = None;
+ for (_, uid, _, _, path) in sessions {
+ if uid != Uid::current().as_raw() {
+ continue;
+ }
+ let session = zbus::Proxy::new(
+ connection,
+ "org.freedesktop.login1",
+ path.clone(),
+ "org.freedesktop.login1.Session",
+ )
+ .await?;
+ if available(&session).await.is_ok() {
+ if selected.is_some() {
+ bail!("desktop session is ambiguous");
+ }
+ selected = Some(path);
+ }
+ }
+ selected.context("no active desktop session")
+}
+
+async fn available(session: &zbus::Proxy<'_>) -> anyhow::Result<()> {
+ let (uid, _): (u32, OwnedObjectPath) = session.get_property("User").await?;
+ let active: bool = session.get_property("Active").await?;
+ let locked: bool = session.get_property("LockedHint").await?;
+ let remote: bool = session.get_property("Remote").await?;
+ let class: String = session.get_property("Class").await?;
+ let kind: String = session.get_property("Type").await?;
+ let seat: (String, OwnedObjectPath) = session.get_property("Seat").await?;
+ if uid != Uid::current().as_raw()
+ || !active
+ || locked
+ || remote
+ || class != "user"
+ || !matches!(kind.as_str(), "x11" | "wayland")
+ || seat.0.is_empty()
+ {
+ bail!("desktop session is unavailable");
+ }
+ Ok(())
+}
+
+async fn screensaver(connection: &zbus::Connection) -> anyhow::Result<zbus::Proxy<'_>> {
+ for (service, path, interface) in [
+ (
+ "org.gnome.ScreenSaver",
+ "/org/gnome/ScreenSaver",
+ "org.gnome.ScreenSaver",
+ ),
+ (
+ "org.freedesktop.ScreenSaver",
+ "/ScreenSaver",
+ "org.freedesktop.ScreenSaver",
+ ),
+ ] {
+ let proxy = zbus::Proxy::new(connection, service, path, interface).await?;
+ if let Ok(active) = proxy.call::<_, _, bool>("GetActive", &()).await {
+ if active {
+ bail!("desktop is locked");
+ }
+ return Ok(proxy);
+ }
+ }
+ bail!("desktop lock notifications are unavailable")
+}
+
+async fn monitor() -> anyhow::Result<()> {
+ let system = zbus::Connection::system().await?;
+ let desktop = zbus::Connection::session().await?;
+ let path = session_path(&system).await?;
+ let session = zbus::Proxy::new(
+ &system,
+ "org.freedesktop.login1",
+ path.clone(),
+ "org.freedesktop.login1.Session",
+ )
+ .await?;
+ let properties = zbus::Proxy::new(
+ &system,
+ "org.freedesktop.login1",
+ path,
+ "org.freedesktop.DBus.Properties",
+ )
+ .await?;
+ let manager = zbus::Proxy::new(
+ &system,
+ "org.freedesktop.login1",
+ "/org/freedesktop/login1",
+ "org.freedesktop.login1.Manager",
+ )
+ .await?;
+ let saver = screensaver(&desktop).await?;
+ let desktop_bus = zbus::fdo::DBusProxy::new(&desktop).await?;
+ let saver_name: zbus::names::BusName<'_> = saver.destination().clone();
+ let saver_owner = desktop_bus.get_name_owner(saver_name.clone()).await?;
+ let mut changes = futures_util::stream::select_all(vec![
+ session.receive_signal("Lock").await?.map(|_| 0).boxed(),
+ session.receive_signal("Unlock").await?.map(|_| 0).boxed(),
+ manager
+ .receive_signal("PrepareForSleep")
+ .await?
+ .map(|_| 0)
+ .boxed(),
+ saver
+ .receive_signal("ActiveChanged")
+ .await?
+ .map(|_| 0)
+ .boxed(),
+ properties
+ .receive_signal("PropertiesChanged")
+ .await?
+ .map(|message| {
+ match message
+ .body()
+ .deserialize::<(String, HashMap<String, OwnedValue>, Vec<String>)>()
+ {
+ Ok((_, changed, invalidated))
+ if !["LockedHint", "Active", "State"].iter().any(|key| {
+ changed.contains_key(*key)
+ || invalidated.iter().any(|entry| entry == key)
+ }) =>
+ {
+ 2
+ }
+ _ => 1,
+ }
+ })
+ .boxed(),
+ ]);
+ available(&session).await?;
+ emit("ready", None)?;
+ loop {
+ let event = future::or(async { changes.next().await.unwrap_or(0) }, async {
+ smol::Timer::after(Duration::from_secs(1)).await;
+ 1
+ })
+ .await;
+ if event == 0 {
+ bail!("desktop session changed");
+ }
+ if event == 2 {
+ continue;
+ }
+ available(&session).await?;
+ if saver.call::<_, _, bool>("GetActive", &()).await?
+ || desktop_bus.get_name_owner(saver_name.clone()).await? != saver_owner
+ {
+ bail!("desktop lock monitor changed");
+ }
+ emit("alive", None)?;
+ }
+}
+
+pub(super) fn run() -> anyhow::Result<()> {
+ if std::io::stdin().is_terminal() || std::io::stdout().is_terminal() || Uid::current().is_root()
+ {
+ bail!("a private control pipe and desktop account are required");
+ }
+ if nix::unistd::getpgrp() != nix::unistd::getpid() {
+ bail!("an isolated helper process group is required");
+ }
+ local_desktop_environment()?;
+ let mut args = std::env::args().skip(1);
+ let mode = args.next().context("mode is required")?;
+ if args.next().is_some() {
+ bail!("unexpected argument");
+ }
+ let intent = if mode == "--authenticate" {
+ Some(Intent::read(&mut std::io::stdin().lock()).context("invalid intent")?)
+ } else if mode == "--monitor" {
+ None
+ } else {
+ bail!("unknown mode");
+ };
+ std::thread::spawn(|| {
+ let mut byte = [0];
+ let _ = std::io::stdin().read(&mut byte);
+ // Parent death/cancellation must also close any native child dialog.
+ let _ = nix::sys::signal::killpg(nix::unistd::getpgrp(), nix::sys::signal::Signal::SIGKILL);
+ });
+ if let Some(intent) = intent {
+ std::thread::spawn(|| {
+ std::thread::sleep(Duration::from_secs(120));
+ let _ =
+ nix::sys::signal::killpg(nix::unistd::getpgrp(), nix::sys::signal::Signal::SIGKILL);
+ });
+ authenticate(intent)
+ } else {
+ let result = smol::block_on(monitor());
+ let _ = emit("unavailable", None);
+ result
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn authentication_display_never_uses_an_ssh_or_tcp_forward() {
+ assert_eq!(local_x_display(":0"), Some("0"));
+ assert_eq!(local_x_display(":1.0"), Some("1"));
+ assert_eq!(local_x_display("unix:2.1"), Some("2"));
+ for display in [
+ "localhost:10.0",
+ "server-a:0",
+ "192.0.2.1:0",
+ ":",
+ ":1.",
+ ":1.0.0",
+ ] {
+ assert_eq!(local_x_display(display), None);
+ }
+ }
+}
diff --git a/thinkterm-connect-auth/src/main.rs b/thinkterm-connect-auth/src/main.rs
new file mode 100644
index 00000000..652bc90d
--- /dev/null
+++ b/thinkterm-connect-auth/src/main.rs
@@ -0,0 +1,142 @@
+#![cfg_attr(not(windows), forbid(unsafe_code))]
+#![cfg_attr(windows, deny(unsafe_code))]
+
+use serde::Deserialize;
+use std::io::{BufRead, Read};
+
+// Not every platform's window reads every field.
+#[allow(dead_code)]
+#[derive(Deserialize)]
+#[serde(rename_all = "PascalCase", deny_unknown_fields)]
+struct Intent {
+ id: String,
+ source: String,
+ targets: String,
+ input: bool,
+ seconds: u64,
+ text: Text,
+}
+
+/// What the window says, already in the user's language.
+#[allow(dead_code)]
+#[derive(Deserialize)]
+#[serde(rename_all = "PascalCase", deny_unknown_fields)]
+struct Text {
+ title: String,
+ heading: String,
+ connection: String,
+ terminals: String,
+ detail: String,
+ approve: String,
+ cancel: String,
+ reason: String,
+ password: String,
+}
+
+impl Intent {
+ #[allow(dead_code)]
+ fn read(reader: &mut impl BufRead) -> Option<Self> {
+ let mut line = Vec::new();
+ reader.take(8192).read_until(b'\n', &mut line).ok()?;
+ if line.len() >= 8192 || line.last() != Some(&b'\n') {
+ return None;
+ }
+ let value: Self = serde_json::from_slice(&line).ok()?;
+ let text_valid = |text: &str, limit, multiline| {
+ !text.is_empty()
+ && text.len() <= limit
+ && !text
+ .chars()
+ .any(|c| c.is_control() && !(multiline && c == '\n'))
+ };
+ if value.id.len() != 32
+ || !value.id.bytes().all(|byte| byte.is_ascii_hexdigit())
+ || value.seconds == 0
+ || value.seconds > 7200
+ || !text_valid(&value.source, 256, false)
+ || !text_valid(&value.targets, 4096, true)
+ || ![
+ &value.text.title,
+ &value.text.heading,
+ &value.text.connection,
+ &value.text.terminals,
+ &value.text.approve,
+ &value.text.cancel,
+ &value.text.reason,
+ &value.text.password,
+ ]
+ .iter()
+ .all(|text| text_valid(text, 512, false))
+ || !text_valid(&value.text.detail, 1024, true)
+ {
+ return None;
+ }
+ Some(value)
+ }
+}
+
+#[cfg(any(target_os = "linux", windows))]
+fn emit(kind: &str, id: Option<&str>) -> std::io::Result<()> {
+ use std::io::Write;
+ let mut out = std::io::stdout().lock();
+ serde_json::to_writer(&mut out, &serde_json::json!({ "kind": kind, "id": id }))?;
+ out.write_all(b"\n")?;
+ out.flush()
+}
+
+#[cfg(target_os = "linux")]
+mod linux;
+#[cfg(windows)]
+#[allow(unsafe_code)]
+mod win;
+
+fn main() {
+ #[cfg(target_os = "linux")]
+ let result = linux::run();
+ #[cfg(windows)]
+ let result = win::run();
+ #[cfg(any(target_os = "linux", windows))]
+ if result.is_ok() {
+ return;
+ }
+ // macOS packages its native platform implementation.
+ std::process::exit(2);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_intent_rejects_controls_extra_fields_and_large_input() {
+ let request = serde_json::json!({
+ "Id": "0123456789abcdef0123456789abcdef", "Source": "server-a",
+ "Targets": "21 [example]\n22 [example]", "Input": true, "Seconds": 1800,
+ "Text": {
+ "Title": "title", "Heading": "heading", "Connection": "Connection: server-a",
+ "Terminals": "Terminals:", "Detail": "Access: example\nDuration: 30 minutes",
+ "Approve": "Allow", "Cancel": "Cancel", "Reason": "reason", "Password": "password",
+ },
+ });
+ let read = |value: &serde_json::Value| {
+ let line = format!("{value}\n");
+ Intent::read(&mut line.as_bytes())
+ };
+ let parsed = read(&request).unwrap();
+ assert!(parsed.input);
+ assert_eq!(parsed.seconds, 1800);
+ let mut changed = request.clone();
+ changed["Source"] = "server-a\nRead only".into();
+ assert!(read(&changed).is_none());
+ changed = request.clone();
+ changed["Success"] = true.into();
+ assert!(read(&changed).is_none());
+ changed = request.clone();
+ changed["Seconds"] = 0.into();
+ assert!(read(&changed).is_none());
+ changed = request;
+ changed["Text"]["Heading"] = "heading\nRead only".into();
+ assert!(read(&changed).is_none());
+ assert!(Intent::read(&mut vec![b' '; 8192].as_slice()).is_none());
+ }
+}
diff --git a/thinkterm-connect-auth/src/win.rs b/thinkterm-connect-auth/src/win.rs
new file mode 100644
index 00000000..62a5ccd8
--- /dev/null
+++ b/thinkterm-connect-auth/src/win.rs
@@ -0,0 +1,647 @@
+//! The Windows window: what is being allowed, then Windows Hello, or the
+//! account's password where Hello is not set up. The session watcher here
+//! also serves the host's monitor.
+//!
+//! This is the one place reverse access uses `unsafe`: Hello, the credential
+//! prompt and the window exist only as system calls.
+
+use super::{emit, Intent, Text};
+use anyhow::{bail, Context};
+use std::cell::{Cell, RefCell};
+use std::ffi::c_void;
+use std::io::{IsTerminal, Read};
+use std::mem::size_of;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{mpsc, Arc, OnceLock};
+use std::time::Duration;
+use windows::core::{factory, w, HRESULT, HSTRING, PCWSTR, PWSTR};
+use windows::Security::Credentials::UI::{
+ UserConsentVerificationResult, UserConsentVerifier, UserConsentVerifierAvailability,
+};
+use windows::Win32::Foundation::{
+ CloseHandle, ERROR_CANCELLED, ERROR_LOGON_FAILURE, ERROR_SUCCESS, HANDLE, HWND, LPARAM,
+ LRESULT, S_FALSE, S_OK, WPARAM,
+};
+use windows::Win32::Security::Credentials::{
+ CredPackAuthenticationBufferW, CredUIPromptForWindowsCredentialsW,
+ CredUnPackAuthenticationBufferW, CREDUIWIN_GENERIC, CREDUI_INFOW, CRED_PACK_FLAGS,
+ CRED_PACK_GENERIC_CREDENTIALS,
+};
+use windows::Win32::Security::{
+ EqualSid, GetTokenInformation, IsWellKnownSid, LogonUserW, LookupAccountSidW, TokenUser,
+ WinLocalSystemSid, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, PSID, SID_NAME_USE,
+ TOKEN_QUERY, TOKEN_USER,
+};
+use windows::Win32::System::Com::{
+ CoInitializeEx, CoTaskMemFree, COINIT_APARTMENTTHREADED, COINIT_MULTITHREADED,
+};
+use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::System::RemoteDesktop::{
+ WTSRegisterSessionNotification, NOTIFY_FOR_THIS_SESSION,
+};
+use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
+use windows::Win32::System::WinRT::IUserConsentVerifierInterop;
+use windows::Win32::System::WindowsProgramming::GetComputerNameW;
+use windows::Win32::UI::Controls::{
+ TaskDialogIndirect, TASKDIALOGCONFIG, TASKDIALOGCONFIG_0, TASKDIALOG_BUTTON,
+ TASKDIALOG_NOTIFICATIONS, TDF_ALLOW_DIALOG_CANCELLATION, TDM_CLICK_BUTTON, TDM_ENABLE_BUTTON,
+ TDN_BUTTON_CLICKED, TDN_CREATED, TD_WARNING_ICON,
+};
+use windows::Win32::UI::WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, PostMessageW, RegisterClassW,
+ SendMessageW, SetForegroundWindow, SetWindowPos, HWND_TOPMOST, IDCANCEL, MSG,
+ PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND, PBT_APMSUSPEND, SWP_NOMOVE, SWP_NOSIZE,
+ WINDOW_EX_STYLE, WM_POWERBROADCAST, WM_WTSSESSION_CHANGE, WNDCLASSW, WS_OVERLAPPED,
+};
+use windows_future::{AsyncOperationCompletedHandler, AsyncStatus, IAsyncOperation};
+use zeroize::{Zeroize, Zeroizing};
+
+/// Hello's window interface needs this Windows 11 build.
+const HELLO_BUILD: u32 = 22000;
+const APPROVE: i32 = 100;
+const PASSWORD_ATTEMPTS: usize = 3;
+/// In UTF-16 units, past anything Windows accepts as a name or a password.
+const CREDENTIAL_LIMIT: usize = 1024;
+
+pub(super) fn run() -> anyhow::Result<()> {
+ if std::io::stdin().is_terminal() || std::io::stdout().is_terminal() {
+ bail!("a private control pipe is required");
+ }
+ let mut args = std::env::args().skip(1);
+ let mode = args.next().context("mode is required")?;
+ if args.next().is_some() {
+ bail!("unexpected argument");
+ }
+ match mode.as_str() {
+ "--monitor" => monitor(),
+ "--authenticate" => {
+ // In a statement of its own, so that this lock ends here: the
+ // thread watching the control pipe needs it.
+ let intent = Intent::read(&mut std::io::stdin().lock()).context("invalid intent")?;
+ authenticate(intent)
+ }
+ _ => bail!("unknown mode"),
+ }
+}
+
+fn monitor() -> anyhow::Result<()> {
+ fn unavailable() {
+ let _ = emit("unavailable", None);
+ std::process::exit(0);
+ }
+ watch_session(unavailable)?;
+ emit("ready", None)?;
+ std::thread::spawn(|| {
+ let _ = std::io::stdin().read(&mut [0]);
+ unavailable();
+ });
+ loop {
+ std::thread::sleep(Duration::from_secs(1));
+ emit("alive", None)?;
+ }
+}
+
+fn authenticate(intent: Intent) -> anyhow::Result<()> {
+ // Each of these ends the attempt by ending this process: whatever window
+ // is up goes with it, and no result is ever reported.
+ fn abandon() {
+ std::process::exit(2);
+ }
+ watch_session(abandon)?;
+ std::thread::spawn(|| {
+ let _ = std::io::stdin().read(&mut [0]);
+ abandon();
+ });
+ std::thread::spawn(|| {
+ std::thread::sleep(Duration::from_secs(120));
+ abandon();
+ });
+ unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }.ok()?;
+ let approved = match confirm(&intent)? {
+ Confirmation::Declined => false,
+ Confirmation::Verified => true,
+ Confirmation::NeedsPassword => verify_password(&intent.text)?,
+ };
+ emit(
+ if approved { "approved" } else { "rejected" },
+ Some(&intent.id),
+ )?;
+ Ok(())
+}
+
+static SESSION_ENDED: OnceLock<fn()> = OnceLock::new();
+
+/// Calls `ended` on any change of the session, such as a lock, and on suspend
+/// or resume. Returns once that is in place.
+fn watch_session(ended: fn()) -> anyhow::Result<()> {
+ SESSION_ENDED
+ .set(ended)
+ .ok()
+ .context("the session is already watched")?;
+ let (ready, started) = mpsc::channel();
+ std::thread::Builder::new()
+ .name("session-watch".into())
+ .spawn(move || {
+ let window = session_window();
+ let watching = window.is_ok();
+ let _ = ready.send(window);
+ if watching {
+ let mut message = MSG::default();
+ while unsafe { GetMessageW(&mut message, None, 0, 0) }.as_bool() {
+ unsafe { DispatchMessageW(&message) };
+ }
+ }
+ })?;
+ started.recv()?.context("watching the desktop session")
+}
+
+/// Hidden, and top-level because power broadcasts do not reach a message-only
+/// window.
+fn session_window() -> windows::core::Result<()> {
+ let instance = unsafe { GetModuleHandleW(None) }?.into();
+ let class = w!("ThinkTermConnectSession");
+ let description = WNDCLASSW {
+ lpfnWndProc: Some(session_event),
+ hInstance: instance,
+ lpszClassName: class,
+ ..Default::default()
+ };
+ if unsafe { RegisterClassW(&description) } == 0 {
+ return Err(windows::core::Error::from_thread());
+ }
+ let window = unsafe {
+ CreateWindowExW(
+ WINDOW_EX_STYLE(0),
+ class,
+ w!(""),
+ WS_OVERLAPPED,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance),
+ None,
+ )
+ }?;
+ unsafe { WTSRegisterSessionNotification(window, NOTIFY_FOR_THIS_SESSION) }
+}
+
+unsafe extern "system" fn session_event(
+ window: HWND,
+ message: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+) -> LRESULT {
+ let changed = match message {
+ WM_WTSSESSION_CHANGE => true,
+ WM_POWERBROADCAST => matches!(
+ wparam.0 as u32,
+ PBT_APMSUSPEND | PBT_APMRESUMEAUTOMATIC | PBT_APMRESUMESUSPEND
+ ),
+ _ => false,
+ };
+ if changed {
+ if let Some(ended) = SESSION_ENDED.get() {
+ ended();
+ }
+ }
+ unsafe { DefWindowProcW(window, message, wparam, lparam) }
+}
+
+enum Confirmation {
+ Declined,
+ Verified,
+ NeedsPassword,
+}
+
+/// Hello's outcome, which arrives on a thread of its own.
+#[derive(Default)]
+struct HelloResult {
+ answered: AtomicBool,
+ verified: AtomicBool,
+ declined: AtomicBool,
+}
+
+/// The dialog's state, used only on its thread, for as long as it is up.
+struct Prompt {
+ hello: Cell<bool>,
+ reason: HSTRING,
+ result: Arc<HelloResult>,
+ operation: RefCell<Option<IAsyncOperation<UserConsentVerificationResult>>>,
+}
+
+impl Prompt {
+ /// Hello's own window opens over the dialog, which stays until it answers.
+ fn begin_hello(&self, dialog: HWND) -> windows::core::Result<()> {
+ let interop = factory::<UserConsentVerifier, IUserConsentVerifierInterop>()?;
+ let operation: IAsyncOperation<UserConsentVerificationResult> =
+ unsafe { interop.RequestVerificationForWindowAsync(dialog, &self.reason) }?;
+ unsafe {
+ SendMessageW(
+ dialog,
+ TDM_ENABLE_BUTTON.0 as u32,
+ Some(WPARAM(APPROVE as usize)),
+ Some(LPARAM(0)),
+ )
+ };
+ let result = Arc::clone(&self.result);
+ let dialog = dialog.0 as isize;
+ operation.SetCompleted(&AsyncOperationCompletedHandler::new(
+ move |operation, status| {
+ let verified = status == AsyncStatus::Completed
+ && operation.as_ref().is_some_and(|operation| {
+ operation.GetResults() == Ok(UserConsentVerificationResult::Verified)
+ });
+ result.verified.store(verified, Ordering::SeqCst);
+ result.answered.store(true, Ordering::SeqCst);
+ // Back on the dialog's thread, which closes it.
+ unsafe {
+ PostMessageW(
+ Some(HWND(dialog as *mut c_void)),
+ TDM_CLICK_BUTTON.0 as u32,
+ WPARAM(IDCANCEL.0 as usize),
+ LPARAM(0),
+ )
+ }
+ },
+ ))?;
+ *self.operation.borrow_mut() = Some(operation);
+ Ok(())
+ }
+}
+
+unsafe extern "system" fn dialog_event(
+ dialog: HWND,
+ notification: TASKDIALOG_NOTIFICATIONS,
+ wparam: WPARAM,
+ _: LPARAM,
+ data: isize,
+) -> HRESULT {
+ // `data` is the `Prompt` in `confirm`, which outlives the dialog.
+ let prompt = unsafe { &*(data as *const Prompt) };
+ match notification {
+ // Started by a background process, it would otherwise open behind
+ // whatever the user is doing.
+ TDN_CREATED => unsafe {
+ let _ = SetWindowPos(
+ dialog,
+ Some(HWND_TOPMOST),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE,
+ );
+ let _ = SetForegroundWindow(dialog);
+ },
+ TDN_BUTTON_CLICKED if wparam.0 as i32 == APPROVE => {
+ if prompt.hello.get() {
+ if prompt.begin_hello(dialog).is_ok() {
+ return S_FALSE;
+ }
+ prompt.hello.set(false);
+ }
+ }
+ TDN_BUTTON_CLICKED if !prompt.result.answered.load(Ordering::SeqCst) => {
+ prompt.result.declined.store(true, Ordering::SeqCst);
+ }
+ _ => {}
+ }
+ S_OK
+}
+
+fn confirm(intent: &Intent) -> anyhow::Result<Confirmation> {
+ let text = &intent.text;
+ let title = HSTRING::from(text.title.as_str());
+ let heading = HSTRING::from(text.heading.as_str());
+ let content = HSTRING::from(format!(
+ "{}\n\n{}\n{}\n\n{}",
+ text.connection, text.terminals, intent.targets, text.detail
+ ));
+ let approve = HSTRING::from(text.approve.as_str());
+ let cancel = HSTRING::from(text.cancel.as_str());
+ let buttons = [
+ TASKDIALOG_BUTTON {
+ nButtonID: APPROVE,
+ pszButtonText: PCWSTR(approve.as_ptr()),
+ },
+ TASKDIALOG_BUTTON {
+ nButtonID: IDCANCEL.0,
+ pszButtonText: PCWSTR(cancel.as_ptr()),
+ },
+ ];
+ let prompt = Prompt {
+ hello: Cell::new(hello_available()),
+ reason: HSTRING::from(text.reason.as_str()),
+ result: Arc::default(),
+ operation: RefCell::new(None),
+ };
+ let config = TASKDIALOGCONFIG {
+ cbSize: size_of::<TASKDIALOGCONFIG>() as u32,
+ dwFlags: TDF_ALLOW_DIALOG_CANCELLATION,
+ pszWindowTitle: PCWSTR(title.as_ptr()),
+ Anonymous1: TASKDIALOGCONFIG_0 {
+ pszMainIcon: TD_WARNING_ICON,
+ },
+ pszMainInstruction: PCWSTR(heading.as_ptr()),
+ pszContent: PCWSTR(content.as_ptr()),
+ cButtons: buttons.len() as u32,
+ pButtons: buttons.as_ptr(),
+ // A stray Enter must not be the thing that allows this.
+ nDefaultButton: IDCANCEL.0,
+ pfCallback: Some(dialog_event),
+ lpCallbackData: &prompt as *const Prompt as isize,
+ ..Default::default()
+ };
+ let mut button = 0;
+ unsafe { TaskDialogIndirect(&config, Some(&mut button), None, None) }?;
+ let result = &prompt.result;
+ Ok(if button == APPROVE && !prompt.hello.get() {
+ Confirmation::NeedsPassword
+ } else if result.verified.load(Ordering::SeqCst) && !result.declined.load(Ordering::SeqCst) {
+ Confirmation::Verified
+ } else {
+ Confirmation::Declined
+ })
+}
+
+fn hello_available() -> bool {
+ let build = winreg::RegKey::predef(winreg::enums::HKEY_LOCAL_MACHINE)
+ .open_subkey(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
+ .and_then(|key| key.get_value::<String, _>("CurrentBuildNumber"))
+ .ok()
+ .and_then(|build| build.parse::<u32>().ok());
+ if !build.is_some_and(|build| build >= HELLO_BUILD) {
+ return false;
+ }
+ // Waiting here would stall the window's thread, so it is not done there.
+ std::thread::spawn(|| {
+ unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok()?;
+ UserConsentVerifier::CheckAvailabilityAsync()?.join()
+ })
+ .join()
+ .is_ok_and(|availability| {
+ matches!(availability, Ok(UserConsentVerifierAvailability::Available))
+ })
+}
+
+/// This process's account. The password is only ever tried against it, under
+/// its own name and on this machine, whatever is typed in the name field.
+struct Account {
+ /// A `TOKEN_USER`, whose SID points into the same buffer.
+ token_user: Vec<usize>,
+ name: Vec<u16>,
+ domain: Vec<u16>,
+}
+
+impl Account {
+ fn current() -> anyhow::Result<Self> {
+ let mut token = HANDLE::default();
+ unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }?;
+ let token_user = token_user(token);
+ unsafe { CloseHandle(token) }?;
+ let token_user = token_user?;
+ let sid = sid_of(&token_user);
+ if unsafe { IsWellKnownSid(sid, WinLocalSystemSid) }.as_bool() {
+ bail!("the system account cannot authenticate");
+ }
+ let (mut name_size, mut domain_size) = (0, 0);
+ let mut kind = SID_NAME_USE::default();
+ // Asked with no room, this reports how much it needs and fails.
+ let _ = unsafe {
+ LookupAccountSidW(
+ PCWSTR::null(),
+ sid,
+ None,
+ &mut name_size,
+ None,
+ &mut domain_size,
+ &mut kind,
+ )
+ };
+ let mut name = vec![0; name_size as usize];
+ let mut domain = vec![0; domain_size as usize];
+ unsafe {
+ LookupAccountSidW(
+ PCWSTR::null(),
+ sid,
+ Some(PWSTR(name.as_mut_ptr())),
+ &mut name_size,
+ Some(PWSTR(domain.as_mut_ptr())),
+ &mut domain_size,
+ &mut kind,
+ )
+ }?;
+ Ok(Self {
+ token_user,
+ name,
+ domain,
+ })
+ }
+
+ /// Other account types use Hello: this path never sends a password to
+ /// another machine.
+ fn is_local(&self) -> bool {
+ let mut computer = [0; 256];
+ let mut size = computer.len() as u32;
+ unsafe { GetComputerNameW(Some(PWSTR(computer.as_mut_ptr())), &mut size) }.is_ok()
+ && same_name(&computer[..size as usize], &self.domain)
+ }
+
+ fn accepts(&self, password: &[u16]) -> bool {
+ // An empty password would not be proof of anything.
+ if password.first().is_none_or(|first| *first == 0) {
+ return false;
+ }
+ let mut token = HANDLE::default();
+ let logged_on = unsafe {
+ LogonUserW(
+ PCWSTR(self.name.as_ptr()),
+ PCWSTR(self.domain.as_ptr()),
+ PCWSTR(password.as_ptr()),
+ LOGON32_LOGON_INTERACTIVE,
+ LOGON32_PROVIDER_DEFAULT,
+ &mut token,
+ )
+ };
+ if logged_on.is_err() {
+ return false;
+ }
+ let same = token_user(token).is_ok_and(|logged_on| {
+ unsafe { EqualSid(sid_of(&logged_on), sid_of(&self.token_user)) }.is_ok()
+ });
+ let _ = unsafe { CloseHandle(token) };
+ same
+ }
+}
+
+fn token_user(token: HANDLE) -> anyhow::Result<Vec<usize>> {
+ let mut size = 0;
+ // Asked with no room, this reports how much it needs and fails.
+ let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, &mut size) };
+ let mut buffer = vec![0usize; (size as usize).div_ceil(size_of::<usize>())];
+ unsafe {
+ GetTokenInformation(
+ token,
+ TokenUser,
+ Some(buffer.as_mut_ptr().cast()),
+ size,
+ &mut size,
+ )
+ }?;
+ Ok(buffer)
+}
+
+fn sid_of(token_user: &[usize]) -> PSID {
+ // `token_user` is what `GetTokenInformation` filled, aligned for this.
+ unsafe { (*token_user.as_ptr().cast::<TOKEN_USER>()).User.Sid }
+}
+
+/// Windows compares names without regard to case. Either may end in NUL.
+fn same_name(first: &[u16], second: &[u16]) -> bool {
+ let name = |units: &[u16]| {
+ String::from_utf16_lossy(units)
+ .trim_end_matches('\0')
+ .to_lowercase()
+ };
+ name(first) == name(second)
+}
+
+fn verify_password(text: &Text) -> anyhow::Result<bool> {
+ let account = Account::current()?;
+ if !account.is_local() {
+ return Ok(false);
+ }
+ let mut failure = ERROR_SUCCESS;
+ for _ in 0..PASSWORD_ATTEMPTS {
+ let Some(password) = ask_password(text, &account, failure.0)? else {
+ return Ok(false);
+ };
+ if account.accepts(&password) {
+ return Ok(true);
+ }
+ failure = ERROR_LOGON_FAILURE;
+ }
+ Ok(false)
+}
+
+/// What the credential prompt returned, gone again with this.
+struct PackedCredentials {
+ bytes: *mut u8,
+ size: usize,
+}
+
+impl Drop for PackedCredentials {
+ fn drop(&mut self) {
+ unsafe {
+ std::slice::from_raw_parts_mut(self.bytes, self.size).zeroize();
+ CoTaskMemFree(Some(self.bytes.cast()));
+ }
+ }
+}
+
+/// The password typed, NUL-terminated, or None if the user declined.
+fn ask_password(
+ text: &Text,
+ account: &Account,
+ failure: u32,
+) -> anyhow::Result<Option<Zeroizing<Vec<u16>>>> {
+ let caption = HSTRING::from(text.password.as_str());
+ let message = HSTRING::from(text.reason.as_str());
+ let info = CREDUI_INFOW {
+ cbSize: size_of::<CREDUI_INFOW>() as u32,
+ pszMessageText: PCWSTR(message.as_ptr()),
+ pszCaptionText: PCWSTR(caption.as_ptr()),
+ ..Default::default()
+ };
+ // Shows whose password this is.
+ let name = PCWSTR(account.name.as_ptr());
+ let mut filled_size = 0;
+ let _ = unsafe {
+ CredPackAuthenticationBufferW(
+ CRED_PACK_GENERIC_CREDENTIALS,
+ name,
+ w!(""),
+ None,
+ &mut filled_size,
+ )
+ };
+ let mut filled = vec![0u8; filled_size as usize];
+ unsafe {
+ CredPackAuthenticationBufferW(
+ CRED_PACK_GENERIC_CREDENTIALS,
+ name,
+ w!(""),
+ Some(filled.as_mut_ptr()),
+ &mut filled_size,
+ )
+ }?;
+ let mut package = 0;
+ let mut bytes: *mut c_void = std::ptr::null_mut();
+ let mut size = 0;
+ let answer = unsafe {
+ CredUIPromptForWindowsCredentialsW(
+ Some(&info),
+ failure,
+ &mut package,
+ Some(filled.as_ptr().cast()),
+ filled_size,
+ &mut bytes,
+ &mut size,
+ None,
+ CREDUIWIN_GENERIC,
+ )
+ };
+ if answer == ERROR_CANCELLED.0 {
+ return Ok(None);
+ }
+ if answer != ERROR_SUCCESS.0 {
+ bail!("the credential prompt failed");
+ }
+ let packed = PackedCredentials {
+ bytes: bytes.cast(),
+ size: size as usize,
+ };
+ let mut user = [0; CREDENTIAL_LIMIT];
+ let mut domain = [0; CREDENTIAL_LIMIT];
+ let mut password = Zeroizing::new(vec![0; CREDENTIAL_LIMIT]);
+ let (mut user_size, mut domain_size, mut password_size) = (
+ CREDENTIAL_LIMIT as u32,
+ CREDENTIAL_LIMIT as u32,
+ CREDENTIAL_LIMIT as u32,
+ );
+ unsafe {
+ CredUnPackAuthenticationBufferW(
+ CRED_PACK_FLAGS(0),
+ packed.bytes.cast(),
+ packed.size as u32,
+ Some(PWSTR(user.as_mut_ptr())),
+ &mut user_size,
+ Some(PWSTR(domain.as_mut_ptr())),
+ Some(&mut domain_size),
+ Some(PWSTR(password.as_mut_ptr())),
+ &mut password_size,
+ )
+ }?;
+ Ok(Some(password))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn wide(text: &str) -> Vec<u16> {
+ text.encode_utf16().collect()
+ }
+
+ #[test]
+ fn account_domains_compare_as_windows_compares_them() {
+ let mut terminated = wide("DEVBOX");
+ terminated.push(0);
+ assert!(same_name(&wide("devbox"), &terminated));
+ assert!(!same_name(&wide("devbox"), &wide("server-a")));
+ assert!(!same_name(&wide("devbox"), &wide("devbox2")));
+ }
+}
diff --git a/thinkterm-connect-auth/windows.manifest b/thinkterm-connect-auth/windows.manifest
new file mode 100644
index 00000000..cb003532
--- /dev/null
+++ b/thinkterm-connect-auth/windows.manifest
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
+ <assemblyIdentity version="1.0.0.0" type="win32" name="ThinkTerm.Connect.Auth" />
+ <dependency>
+ <dependentAssembly>
+ <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0"
+ processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
+ </dependentAssembly>
+ </dependency>
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
+ <security><requestedPrivileges>
+ <requestedExecutionLevel level="asInvoker" uiAccess="false" />
+ </requestedPrivileges></security>
+ </trustInfo>
+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+ <application>
+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
+ </application>
+ </compatibility>
+ <application xmlns="urn:schemas-microsoft-com:asm.v3">
+ <windowsSettings>
+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
+ </windowsSettings>
+ </application>
+</assembly>
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index bb4281e0..a09996bd 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -1831,3 +1831,48 @@ settings-privacy-checking = Wird geprüft…
settings-privacy-holder-server = ThinkTerm-Hintergrunddienst
settings-privacy-holder-app = ThinkTerm
settings-privacy-holder-description = Diese Berechtigungen gelten unter seinem Namen. Festplattenvollzugriff muss von Hand hinzugefügt werden: in den Systemeinstellungen auf + klicken und ihn in die Liste ziehen.
+
+settings-reverse-heading = Connect-Rückzugriff
+settings-reverse-intro = Verbundenen Server auf lokale Terminals zugreifen lassen
+settings-reverse-description = Standardmäßig aus. Jeder Server benötigt eine Systemauthentifizierung auf diesem Computer. Auch später geöffnete lokale Terminals sind enthalten. Programme desselben Serverkontos teilen den Zugriff. Sperren, Trennen oder Neustarten beendet ihn.
+settings-reverse-duration = Standarddauer
+settings-reverse-duration-description = 1–120 Minuten. Gilt für die nächste Freigabe oder Verlängerung; bestehende Fristen bleiben unverändert.
+settings-reverse-minutes = { $minutes } Min.
+settings-reverse-source = Verbundener Server
+settings-reverse-source-description = Eine bestehende ThinkTerm-Connect-Verbindung verwenden.
+settings-reverse-host = Lokale Terminals
+settings-reverse-host-description = Den Ausführungsort der Terminals auswählen. Jeder Host authentifiziert und prüft seine Berechtigungen selbst.
+settings-reverse-local-sessions = Lokale Sitzungen
+settings-reverse-this-window = Terminals der Desktop-App
+settings-reverse-no-connection = Nicht verbunden
+settings-reverse-ineligible-short = Connect mit Passwortauthentifizierung erforderlich
+settings-reverse-ineligible = Die aktuelle Connect-Sitzung muss nachweislich nur per Passwort authentifiziert sein. Schlüssel, SSH-Agenten, interaktive Tastaturauthentifizierung und extern wiederverwendete SSH-Sitzungen sind nicht zulässig.
+settings-reverse-select = Freizugebende Terminals auswählen
+settings-reverse-select-description = Die Auswahl allein erteilt keinen Zugriff. Angezeigt werden nur lokale Terminals, die Sie aktuell steuern.
+settings-reverse-choose = Terminals auswählen
+settings-reverse-loading = Zugriff wird vorbereitet…
+settings-reverse-pane = Terminal { $pane }
+settings-reverse-permission = Berechtigung
+settings-reverse-permission-description = Lesen umfasst Bildschirm und Verlauf. Eingaben können Befehle mit den Rechten des Terminalkontos ausführen.
+settings-reverse-read = Nur lesen
+settings-reverse-input = Lesen und Eingabe
+settings-reverse-approve = Ausgewählte Terminals freigeben
+settings-reverse-approve-description = Den festgelegten Umfang im Authentifizierungsfenster prüfen und anschließend beim Betriebssystem authentifizieren.
+settings-reverse-authenticate = Authentifizieren…
+settings-reverse-authenticating = Systemauthentifizierung ausstehend. Ein Abbruch der Verlängerung erhält die bisherige Berechtigung und Frist.
+settings-reverse-cancel = Authentifizierung abbrechen
+settings-reverse-refresh = Terminalauswahl aktualisieren
+settings-reverse-refresh-description = Löscht die Auswahl und bricht eine laufende Authentifizierung ab.
+settings-reverse-refresh-button = Aktualisieren
+settings-reverse-active = { $count } Terminal(s) ({ $panes }) · { $permission } · noch { $time }
+settings-reverse-revoke = Widerrufen
+settings-reverse-renew = Berechtigung verlängern
+settings-reverse-renew-description = Erfordert eine neue Systemauthentifizierung. Eine fehlgeschlagene Verlängerung verlängert den bestehenden Zugriff nicht.
+settings-reverse-ended = Berechtigung beendet. Für erneuten Zugriff ist eine neue Freigabe erforderlich.
+settings-reverse-unavailable = Nicht verfügbar
+settings-reverse-error = Authentifizierung, Steuerungsrecht oder Verbindung nicht verfügbar. Prüfen Sie den lokalen Authentifizierungshelfer und die Desktopsitzung und versuchen Sie es erneut.
+settings-reverse-dismiss = Schließen
+settings-reverse-all-local = Alle lokalen Terminals
+settings-reverse-all-description = Umfasst Ihre aktuellen und zukünftigen lokalen Terminals. Öffnen und Schließen wird automatisch berücksichtigt.
+settings-reverse-all-active = Alle lokalen Terminals · { $permission } · noch { $time }
+settings-reverse-connect-first = Verbinden Sie zuerst einen Server. Berechtigung, Dauer und Widerruf gelten für jede Verbindung einzeln.
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index 02f513e5..411691a4 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -1831,3 +1831,48 @@ settings-privacy-checking = Checking…
settings-privacy-holder-server = ThinkTerm Background Service
settings-privacy-holder-app = ThinkTerm
settings-privacy-holder-description = These permissions are kept under its name. Full Disk Access has to be added by hand: click + in System Settings and drag it into the list.
+
+settings-reverse-heading = Connect Reverse Access
+settings-reverse-intro = Let a connected server access your local terminals
+settings-reverse-description = Off by default. Authorize each server with system authentication on this computer. Access includes future local terminals and is shared by programs under that server account. Locking, disconnecting or restarting ends access.
+settings-reverse-duration = Default duration
+settings-reverse-duration-description = 1–120 minutes. Applies to the next approval or renewal; existing grants keep their deadline.
+settings-reverse-minutes = { $minutes } min
+settings-reverse-source = Connected server
+settings-reverse-source-description = Use an existing ThinkTerm Connect connection.
+settings-reverse-host = Local terminals
+settings-reverse-host-description = Choose where the terminals run. Each host authenticates and enforces its own grants.
+settings-reverse-local-sessions = Local sessions
+settings-reverse-this-window = Desktop app terminals
+settings-reverse-no-connection = No connection
+settings-reverse-ineligible-short = Password-authenticated Connect required
+settings-reverse-ineligible = Reverse access requires verified password-only authentication on the current Connect session. Key, agent, keyboard-interactive and externally reused SSH sessions are not eligible.
+settings-reverse-select = Select terminals to authorize
+settings-reverse-select-description = Selection alone grants no access. Only local terminals you currently own are offered.
+settings-reverse-choose = Choose terminals
+settings-reverse-loading = Preparing access…
+settings-reverse-pane = Terminal { $pane }
+settings-reverse-permission = Permission
+settings-reverse-permission-description = Read includes the screen and scrollback. Input can run commands with this terminal's account privileges.
+settings-reverse-read = Read only
+settings-reverse-input = Read and input
+settings-reverse-approve = Approve the selected terminals
+settings-reverse-approve-description = Review the frozen scope in the authentication window, then verify with the operating system.
+settings-reverse-authenticate = Authenticate…
+settings-reverse-authenticating = Waiting for system authentication. Cancelling a renewal keeps the previous grant and deadline.
+settings-reverse-cancel = Cancel authentication
+settings-reverse-refresh = Refresh terminal choices
+settings-reverse-refresh-description = Clears the selection and cancels pending authentication.
+settings-reverse-refresh-button = Refresh
+settings-reverse-active = { $count } terminal(s) ({ $panes }) · { $permission } · { $time } remaining
+settings-reverse-revoke = Revoke
+settings-reverse-renew = Renew authorization
+settings-reverse-renew-description = Fresh system authentication is required. A failed renewal does not extend existing access.
+settings-reverse-ended = Authorization ended. Create a new approval to enable access again.
+settings-reverse-unavailable = Unavailable
+settings-reverse-error = Authentication, ownership or the connection is unavailable. Check the local authentication helper and desktop session, then try again.
+settings-reverse-dismiss = Dismiss
+settings-reverse-all-local = All local terminals
+settings-reverse-all-description = Includes current and future local terminals you own. Terminal creation and closure are handled automatically.
+settings-reverse-all-active = All local terminals · { $permission } · { $time } remaining
+settings-reverse-connect-first = Connect to a server first. Each connection has its own permission, duration and revoke control.
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 3e099604..89a9fc33 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -1825,3 +1825,48 @@ settings-privacy-checking = Vérification…
settings-privacy-holder-server = Service d'arrière-plan de ThinkTerm
settings-privacy-holder-app = ThinkTerm
settings-privacy-holder-description = Ces autorisations sont enregistrées à son nom. L'accès complet au disque s'ajoute à la main : cliquez sur + dans Réglages Système et faites-le glisser dans la liste.
+
+settings-reverse-heading = Accès inverse Connect
+settings-reverse-intro = Autoriser un serveur connecté à accéder aux terminaux locaux
+settings-reverse-description = Désactivé par défaut. Autorisez chaque serveur par authentification système sur cet ordinateur. Les futurs terminaux locaux sont inclus. Les programmes du même compte serveur partagent l’accès. Verrouiller, déconnecter ou redémarrer y met fin.
+settings-reverse-duration = Durée par défaut
+settings-reverse-duration-description = De 1 à 120 minutes. S’applique à la prochaine autorisation ou au renouvellement ; les échéances existantes restent inchangées.
+settings-reverse-minutes = { $minutes } min
+settings-reverse-source = Serveur connecté
+settings-reverse-source-description = Utiliser une connexion ThinkTerm Connect existante.
+settings-reverse-host = Terminaux locaux
+settings-reverse-host-description = Choisir où les terminaux s’exécutent. Chaque hôte authentifie et applique ses propres autorisations.
+settings-reverse-local-sessions = Sessions locales
+settings-reverse-this-window = Terminaux de l’application de bureau
+settings-reverse-no-connection = Non connecté
+settings-reverse-ineligible-short = Connect authentifié par mot de passe requis
+settings-reverse-ineligible = La session Connect actuelle doit être authentifiée uniquement par mot de passe, avec preuve vérifiable. Les clés, agents SSH, authentifications interactives au clavier et sessions SSH réutilisées à l’extérieur ne sont pas éligibles.
+settings-reverse-select = Choisir les terminaux à autoriser
+settings-reverse-select-description = La sélection seule n’accorde aucun accès. Seuls les terminaux locaux que vous contrôlez sont proposés.
+settings-reverse-choose = Choisir les terminaux
+settings-reverse-loading = Préparation de l’accès…
+settings-reverse-pane = Terminal { $pane }
+settings-reverse-permission = Autorisation
+settings-reverse-permission-description = La lecture inclut l’écran et l’historique. La saisie peut exécuter des commandes avec les droits du compte du terminal.
+settings-reverse-read = Lecture seule
+settings-reverse-input = Lecture et saisie
+settings-reverse-approve = Autoriser les terminaux sélectionnés
+settings-reverse-approve-description = Vérifiez la portée figée dans la fenêtre d’authentification, puis authentifiez-vous auprès du système.
+settings-reverse-authenticate = S’authentifier…
+settings-reverse-authenticating = En attente d’authentification système. Annuler un renouvellement conserve l’autorisation et l’échéance précédentes.
+settings-reverse-cancel = Annuler l’authentification
+settings-reverse-refresh = Actualiser les terminaux proposés
+settings-reverse-refresh-description = Efface la sélection et annule l’authentification en cours.
+settings-reverse-refresh-button = Actualiser
+settings-reverse-active = { $count } terminal(aux) ({ $panes }) · { $permission } · { $time } restantes
+settings-reverse-revoke = Révoquer
+settings-reverse-renew = Renouveler l’autorisation
+settings-reverse-renew-description = Une nouvelle authentification système est nécessaire. Un échec ne prolonge pas l’accès existant.
+settings-reverse-ended = L’autorisation a pris fin. Une nouvelle approbation est nécessaire pour réactiver l’accès.
+settings-reverse-unavailable = Indisponible
+settings-reverse-error = Authentification, droit de contrôle ou connexion indisponible. Vérifiez l’assistant d’authentification local et la session de bureau, puis réessayez.
+settings-reverse-dismiss = Fermer
+settings-reverse-all-local = Tous les terminaux locaux
+settings-reverse-all-description = Inclut vos terminaux locaux actuels et futurs. Leur ouverture et leur fermeture sont prises en compte automatiquement.
+settings-reverse-all-active = Tous les terminaux locaux · { $permission } · { $time } restantes
+settings-reverse-connect-first = Connectez d’abord un serveur. Chaque connexion possède ses propres droits, durée et commande de révocation.
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 9e27c3d0..54b4dfed 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -1779,3 +1779,48 @@ settings-privacy-checking = 確認中…
settings-privacy-holder-server = ThinkTerm バックグラウンドサービス
settings-privacy-holder-app = ThinkTerm
settings-privacy-holder-description = これらの権限はこのプログラムの名前で記録されます。フルディスクアクセスは手動で追加します:システム設定で + を押し、これをリストにドラッグしてください。
+
+settings-reverse-heading = Connect の逆方向アクセス
+settings-reverse-intro = 接続先サーバーにローカルターミナルへのアクセスを許可
+settings-reverse-description = 既定では無効です。サーバーごとにこのコンピューターでシステム認証を行います。後から開くローカルターミナルも含まれ、サーバーの同じアカウントのプログラムが権限を共有します。ロック、切断、再起動で終了します。
+settings-reverse-duration = 既定の許可時間
+settings-reverse-duration-description = 1~120 分。次の許可または更新に適用され、既存の期限は変わりません。
+settings-reverse-minutes = { $minutes } 分
+settings-reverse-source = 接続先サーバー
+settings-reverse-source-description = 既存の ThinkTerm Connect 接続を使用します。
+settings-reverse-host = ローカルターミナル
+settings-reverse-host-description = ターミナルの実行場所を選択します。各ホストが認証と権限の確認を行います。
+settings-reverse-local-sessions = ローカルセッション
+settings-reverse-this-window = デスクトップアプリの端末
+settings-reverse-no-connection = 未接続
+settings-reverse-ineligible-short = パスワード認証の Connect 接続が必要
+settings-reverse-ineligible = 現在の Connect セッションがパスワードのみで認証されたことを確認できる必要があります。鍵、SSH エージェント、キーボード対話認証、外部で再利用された SSH セッションは対象外です。
+settings-reverse-select = 許可するターミナルを選択
+settings-reverse-select-description = 選択だけでは許可されません。現在あなたが操作権を持つローカルターミナルのみ表示します。
+settings-reverse-choose = ターミナルを選択
+settings-reverse-loading = アクセスを準備しています…
+settings-reverse-pane = ターミナル { $pane }
+settings-reverse-permission = 権限
+settings-reverse-permission-description = 読み取りには画面とスクロールバックを含みます。入力によりターミナルのアカウント権限でコマンドを実行できます。
+settings-reverse-read = 読み取り専用
+settings-reverse-input = 読み取りと入力
+settings-reverse-approve = 選択したターミナルを許可
+settings-reverse-approve-description = 認証ウィンドウで確定した許可範囲を確認し、OS の認証を行ってください。
+settings-reverse-authenticate = 認証…
+settings-reverse-authenticating = システム認証を待っています。更新をキャンセルしても以前の許可と期限は維持されます。
+settings-reverse-cancel = 認証をキャンセル
+settings-reverse-refresh = ターミナルの候補を更新
+settings-reverse-refresh-description = 選択を解除し、進行中の認証をキャンセルします。
+settings-reverse-refresh-button = 更新
+settings-reverse-active = { $count } 個の端末({ $panes })· { $permission } · 残り { $time }
+settings-reverse-revoke = 取り消す
+settings-reverse-renew = 許可を更新
+settings-reverse-renew-description = 新たなシステム認証が必要です。更新に失敗しても既存の期限は延長されません。
+settings-reverse-ended = 許可は終了しました。再度アクセスするには新しい許可が必要です。
+settings-reverse-unavailable = 利用不可
+settings-reverse-error = 認証、操作権、または接続を利用できません。ローカルの認証ヘルパーとデスクトップセッションを確認して再試行してください。
+settings-reverse-dismiss = 閉じる
+settings-reverse-all-local = すべてのローカルターミナル
+settings-reverse-all-description = 現在および今後開く、自分が所有するローカルターミナルが対象です。追加や終了は自動で反映されます。
+settings-reverse-all-active = すべてのローカルターミナル · { $permission } · 残り { $time }
+settings-reverse-connect-first = まずサーバーに接続してください。接続ごとに権限と有効期間を設定し、いつでも取り消せます。
diff --git a/thinkterm-i18n/i18n/ru-RU.ftl b/thinkterm-i18n/i18n/ru-RU.ftl
index a6860d78..bd2a2969 100644
--- a/thinkterm-i18n/i18n/ru-RU.ftl
+++ b/thinkterm-i18n/i18n/ru-RU.ftl
@@ -1740,3 +1740,48 @@ settings-privacy-checking = Проверка…
settings-privacy-holder-server = Фоновая служба ThinkTerm
settings-privacy-holder-app = ThinkTerm
settings-privacy-holder-description = Разрешения сохраняются под этим именем. Полный доступ к диску нужно добавить вручную: нажмите + в системных настройках и перетащите объект в список.
+
+settings-reverse-heading = Обратный доступ Connect
+settings-reverse-intro = Разрешить подключённому серверу доступ к локальным терминалам
+settings-reverse-description = По умолчанию выключено. Каждый сервер требует системной аутентификации на этом компьютере. Доступ включает будущие локальные терминалы и общий для программ одной учётной записи сервера. Блокировка, отключение или перезапуск прекращает доступ.
+settings-reverse-duration = Срок по умолчанию
+settings-reverse-duration-description = От 1 до 120 минут. Применяется к следующему разрешению или продлению; текущие сроки не меняются.
+settings-reverse-minutes = { $minutes } мин
+settings-reverse-source = Подключённый сервер
+settings-reverse-source-description = Используется существующее подключение ThinkTerm Connect.
+settings-reverse-host = Локальные терминалы
+settings-reverse-host-description = Выберите, где работают терминалы. Каждый узел самостоятельно выполняет аутентификацию и проверяет разрешения.
+settings-reverse-local-sessions = Локальные сеансы
+settings-reverse-this-window = Терминалы настольного приложения
+settings-reverse-no-connection = Нет подключения
+settings-reverse-ineligible-short = Требуется Connect с парольной аутентификацией
+settings-reverse-ineligible = Текущий сеанс Connect должен иметь проверяемое подтверждение аутентификации только паролем. Ключи, SSH-агенты, интерактивная аутентификация с клавиатуры и внешнее повторное использование SSH-сеансов не поддерживаются.
+settings-reverse-select = Выбрать терминалы для доступа
+settings-reverse-select-description = Сам выбор не даёт доступа. Показаны только локальные терминалы, которыми вы сейчас управляете.
+settings-reverse-choose = Выбрать терминалы
+settings-reverse-loading = Подготовка доступа…
+settings-reverse-pane = Терминал { $pane }
+settings-reverse-permission = Разрешение
+settings-reverse-permission-description = Чтение включает экран и историю прокрутки. Ввод позволяет выполнять команды с правами учётной записи терминала.
+settings-reverse-read = Только чтение
+settings-reverse-input = Чтение и ввод
+settings-reverse-approve = Разрешить доступ к выбранным терминалам
+settings-reverse-approve-description = Проверьте зафиксированный объём доступа в окне аутентификации, затем подтвердите личность средствами ОС.
+settings-reverse-authenticate = Подтвердить личность…
+settings-reverse-authenticating = Ожидание системной аутентификации. Отмена продления сохраняет прежнее разрешение и срок.
+settings-reverse-cancel = Отменить аутентификацию
+settings-reverse-refresh = Обновить список терминалов
+settings-reverse-refresh-description = Снимает выбор и отменяет текущую аутентификацию.
+settings-reverse-refresh-button = Обновить
+settings-reverse-active = Терминалов: { $count } ({ $panes }) · { $permission } · осталось { $time }
+settings-reverse-revoke = Отозвать
+settings-reverse-renew = Продлить разрешение
+settings-reverse-renew-description = Требуется новая системная аутентификация. Неудачное продление не увеличивает срок текущего доступа.
+settings-reverse-ended = Разрешение завершено. Для возобновления доступа требуется новое подтверждение.
+settings-reverse-unavailable = Недоступно
+settings-reverse-error = Аутентификация, право управления или подключение недоступно. Проверьте локальный помощник аутентификации и сеанс рабочего стола, затем повторите попытку.
+settings-reverse-dismiss = Закрыть
+settings-reverse-all-local = Все локальные терминалы
+settings-reverse-all-description = Включает ваши текущие и будущие локальные терминалы. Открытие и закрытие учитываются автоматически.
+settings-reverse-all-active = Все локальные терминалы · { $permission } · осталось { $time }
+settings-reverse-connect-first = Сначала подключитесь к серверу. У каждого подключения свои права, срок действия и отзыв разрешения.
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index 90f940b5..c7bff5e7 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -1779,3 +1779,48 @@ settings-privacy-checking = 正在查…
settings-privacy-holder-server = ThinkTerm 后台服务
settings-privacy-holder-app = ThinkTerm
settings-privacy-holder-description = 这些权限记在它名下。完全磁盘访问要自己加:在系统设置里点 +,把它拖进列表。
+
+settings-reverse-heading = Connect 反向访问
+settings-reverse-intro = 允许已连接的服务器访问本机的本地终端
+settings-reverse-description = 默认关闭。每台服务器分别授权,并在本机完成系统认证。授权包含之后新开的本地终端,服务器同一账户下的程序共享此权限。锁屏、断线或重启后失效。
+settings-reverse-duration = 默认授权时间
+settings-reverse-duration-description = 1–120 分钟。仅用于下一次授权或续期,不改变现有授权的到期时间。
+settings-reverse-minutes = { $minutes } 分钟
+settings-reverse-source = 已连接的服务器
+settings-reverse-source-description = 使用现有的 ThinkTerm Connect 连接。
+settings-reverse-host = 本地终端
+settings-reverse-host-description = 选择终端运行的位置。各宿主分别完成认证并执行权限检查。
+settings-reverse-local-sessions = 本地会话
+settings-reverse-this-window = 桌面应用的终端
+settings-reverse-no-connection = 未连接
+settings-reverse-ineligible-short = 需要密码认证的 Connect 连接
+settings-reverse-ineligible = 反向访问要求当前 Connect 会话有可验证的纯密码认证记录。密钥、SSH agent、键盘交互认证及外部复用的 SSH 会话暂不支持。
+settings-reverse-select = 选择要授权的终端
+settings-reverse-select-description = 仅选择不会授予权限。这里只列出当前由你控制的本地终端。
+settings-reverse-choose = 选择终端
+settings-reverse-loading = 正在准备访问…
+settings-reverse-pane = 终端 { $pane }
+settings-reverse-permission = 权限
+settings-reverse-permission-description = 读取包括当前屏幕和历史滚动内容。输入可使用此终端账户的权限运行命令。
+settings-reverse-read = 只读
+settings-reverse-input = 读取和输入
+settings-reverse-approve = 授权选定的终端
+settings-reverse-approve-description = 在认证窗口核对已固定的授权范围,再完成操作系统认证。
+settings-reverse-authenticate = 系统认证…
+settings-reverse-authenticating = 等待系统认证。取消续期会保留原授权及其到期时间。
+settings-reverse-cancel = 取消认证
+settings-reverse-refresh = 刷新可选终端
+settings-reverse-refresh-description = 清除选择并取消正在进行的认证。
+settings-reverse-refresh-button = 刷新
+settings-reverse-active = { $count } 个终端({ $panes })· { $permission } · 剩余 { $time }
+settings-reverse-revoke = 撤销
+settings-reverse-renew = 续期授权
+settings-reverse-renew-description = 需要重新进行系统认证。续期失败不会延长现有访问权限。
+settings-reverse-ended = 授权已结束。再次开放访问需要重新授权。
+settings-reverse-unavailable = 不可用
+settings-reverse-error = 认证、终端控制权或连接不可用。请检查本机认证组件和桌面会话后重试。
+settings-reverse-dismiss = 关闭
+settings-reverse-all-local = 全部本地终端
+settings-reverse-all-description = 包含你拥有的现有和之后新开的本地终端。终端新增、关闭自动处理,无需逐个管理。
+settings-reverse-all-active = 全部本地终端 · { $permission } · 剩余 { $time }
+settings-reverse-connect-first = 请先连接服务器。每条连接分别设置权限、有效期,并可随时撤销。
diff --git a/thinkterm-reverse-access/Cargo.toml b/thinkterm-reverse-access/Cargo.toml
new file mode 100644
index 00000000..8b9054ed
--- /dev/null
+++ b/thinkterm-reverse-access/Cargo.toml
@@ -0,0 +1,23 @@
+[package]
+name = "thinkterm-reverse-access"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+getrandom.workspace = true
+thiserror.workspace = true
+serde = { workspace = true, features = ["derive"] }
+serde_json.workspace = true
+futures.workspace = true
+smol.workspace = true
+procinfo = { path = "../procinfo", default-features = false }
+
+[target.'cfg(unix)'.dependencies]
+nix = { workspace = true, features = ["time", "process", "signal", "socket", "user"] }
+
+[target.'cfg(windows)'.dependencies]
+widestring = "1.2.1"
+interprocess = { version = "2.4.7", default-features = false, features = ["tokio"] }
+tokio = { workspace = true, features = ["rt-multi-thread", "net", "time"] }
+tokio-util = { version = "0.7", features = ["compat"] }
diff --git a/thinkterm-reverse-access/native/macos.swift b/thinkterm-reverse-access/native/macos.swift
new file mode 100644
index 00000000..3b3227f1
--- /dev/null
+++ b/thinkterm-reverse-access/native/macos.swift
@@ -0,0 +1,167 @@
+import AppKit
+import CoreGraphics
+import LocalAuthentication
+
+/// What the system's dialog says, already in the user's language.
+struct Text: Decodable {
+ let Cancel: String
+ let Reason: String
+}
+
+struct Intent: Decodable {
+ let Id: String
+ let Source: String
+ let Targets: String
+ let Input: Bool
+ let Seconds: UInt64
+ let Text: Text
+
+ static func read() throws -> Intent {
+ var data = Data()
+ while data.count < 8192 {
+ guard let byte = try FileHandle.standardInput.read(upToCount: 1), !byte.isEmpty else {
+ throw Failure.invalid
+ }
+ if byte[0] == 10 {
+ guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],
+ Set(object.keys) == Set(["Id", "Source", "Targets", "Input", "Seconds", "Text"]) else {
+ throw Failure.invalid
+ }
+ let intent = try JSONDecoder().decode(Intent.self, from: data)
+ guard intent.Id.count == 32,
+ intent.Id.utf8.allSatisfy({ (48...57).contains($0) || (65...70).contains($0) || (97...102).contains($0) }),
+ intent.Seconds > 0, intent.Seconds <= 7200,
+ validText(intent.Source, limit: 256, multiline: false),
+ validText(intent.Targets, limit: 4096, multiline: true),
+ [intent.Text.Cancel, intent.Text.Reason].allSatisfy({
+ validText($0, limit: 512, multiline: false)
+ }) else {
+ throw Failure.invalid
+ }
+ return intent
+ }
+ data.append(byte)
+ }
+ throw Failure.invalid
+ }
+
+ private static func validText(_ value: String, limit: Int, multiline: Bool) -> Bool {
+ !value.isEmpty && value.utf8.count <= limit && value.unicodeScalars.allSatisfy {
+ !CharacterSet.controlCharacters.contains($0) || (multiline && $0.value == 10)
+ }
+ }
+}
+
+enum Failure: Error { case invalid }
+
+func emit(_ kind: String, id: String? = nil) {
+ let event: [String: Any] = ["kind": kind, "id": id as Any? ?? NSNull()]
+ guard let data = try? JSONSerialization.data(withJSONObject: event),
+ let line = String(data: data, encoding: .utf8) else { exit(2) }
+ FileHandle.standardOutput.write(Data((line + "\n").utf8))
+}
+
+func consoleSessionAvailable() -> Bool {
+ guard let session = CGSessionCopyCurrentDictionary() as? [String: Any],
+ session[kCGSessionOnConsoleKey as String] as? Bool == true,
+ session[kCGSessionLoginDoneKey as String] as? Bool == true,
+ let uid = session[kCGSessionUserIDKey as String] as? UInt32,
+ uid == getuid() else { return false }
+ return true
+}
+
+final class NativeAuth: NSObject, NSApplicationDelegate {
+ private let intent: Intent?
+ private var context: LAContext?
+ private var consumed = false
+ private var deadline = ContinuousClock.now.advanced(by: .seconds(120))
+ private var timer: Timer?
+ private var observers: [NSObjectProtocol] = []
+
+ init(intent: Intent?) { self.intent = intent }
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ guard consoleSessionAvailable() else { finish(false); return }
+ let workspace = NSWorkspace.shared.notificationCenter
+ for name in [NSWorkspace.willSleepNotification, NSWorkspace.sessionDidResignActiveNotification] {
+ observers.append(workspace.addObserver(forName: name, object: nil, queue: .main) {
+ [weak self] _ in self?.finish(false)
+ })
+ }
+ DistributedNotificationCenter.default().addObserver(
+ self, selector: #selector(unavailable),
+ name: NSNotification.Name("com.apple.screenIsLocked"), object: nil)
+ FileHandle.standardInput.readabilityHandler = { [weak self] handle in
+ _ = handle.availableData
+ DispatchQueue.main.async { self?.finish(false) }
+ }
+ timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
+ guard let self else { return }
+ if !consoleSessionAvailable() || (self.intent != nil && ContinuousClock.now >= self.deadline) {
+ self.finish(false)
+ } else if self.intent == nil {
+ emit("alive")
+ }
+ }
+ if let intent {
+ authenticate(intent)
+ } else {
+ emit("ready")
+ }
+ }
+
+ /// The system's dialog is the only window: its reason states all that is
+ /// being allowed, in words the host chose from the frozen intent.
+ private func authenticate(_ intent: Intent) {
+ let context = LAContext()
+ self.context = context
+ context.touchIDAuthenticationAllowableReuseDuration = 0
+ context.localizedCancelTitle = intent.Text.Cancel
+ var error: NSError?
+ guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
+ // No dialog will say so. Ending without a result reads as
+ // unavailable, where a refusal would pass in silence.
+ exit(2)
+ }
+ NSApp.activate(ignoringOtherApps: true)
+ // The system's device-owner policy can use Touch ID, the account
+ // password, or a paired Apple Watch, according to the user's setup.
+ context.evaluatePolicy(.deviceOwnerAuthentication,
+ localizedReason: intent.Text.Reason) {
+ [weak self] success, _ in
+ DispatchQueue.main.async {
+ guard let self else { return }
+ self.finish(success && consoleSessionAvailable() && ContinuousClock.now < self.deadline)
+ }
+ }
+ }
+
+ @objc private func unavailable() { finish(false) }
+
+ private func finish(_ approved: Bool) {
+ guard !consumed else { return }
+ consumed = true
+ context?.invalidate()
+ context = nil
+ timer?.invalidate()
+ FileHandle.standardInput.readabilityHandler = nil
+ if let intent { emit(approved ? "approved" : "rejected", id: intent.Id) }
+ else { emit("unavailable") }
+ NSApp.terminate(nil)
+ }
+}
+
+guard CommandLine.arguments.count == 2,
+ isatty(STDIN_FILENO) == 0, isatty(STDOUT_FILENO) == 0 else { exit(2) }
+let mode = CommandLine.arguments[1]
+let intent: Intent?
+do {
+ if mode == "--authenticate" { intent = try Intent.read() }
+ else if mode == "--monitor" { intent = nil }
+ else { exit(2) }
+} catch { exit(2) }
+let app = NSApplication.shared
+let delegate = NativeAuth(intent: intent)
+app.delegate = delegate
+app.setActivationPolicy(.accessory)
+app.run()
diff --git a/thinkterm-reverse-access/src/authorization.rs b/thinkterm-reverse-access/src/authorization.rs
new file mode 100644
index 00000000..87e97fed
--- /dev/null
+++ b/thinkterm-reverse-access/src/authorization.rs
@@ -0,0 +1,950 @@
+use crate::clock::{Clock, SystemClock, Tick};
+use crate::{
+ Error, Result, AUTH_TIMEOUT_SECS, MAX_DURATION_SECS, MAX_GRANTS, MAX_ROUTES, MAX_TARGETS,
+ MAX_TARGETS_PER_GRANT, REQUEST_TIMEOUT_SECS,
+};
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, Mutex, MutexGuard, Weak};
+use std::time::Duration;
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+pub struct Id([u8; 16]);
+
+impl Id {
+ pub fn random() -> Result<Self> {
+ let mut bytes = [0; 16];
+ getrandom::fill(&mut bytes).map_err(|_| Error::Random)?;
+ Ok(Self(bytes))
+ }
+
+ pub fn from_bytes(bytes: [u8; 16]) -> Self {
+ Self(bytes)
+ }
+
+ pub fn as_bytes(&self) -> &[u8; 16] {
+ &self.0
+ }
+}
+
+impl fmt::Debug for Id {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("Id(..)")
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub enum Permission {
+ Read,
+ ReadAndInput,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub enum GrantScope {
+ SelectedTerminals,
+ AllLocalTerminals,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Operation {
+ Read,
+ Input,
+}
+
+impl Permission {
+ fn allows(self, operation: Operation) -> bool {
+ operation == Operation::Read || self == Self::ReadAndInput
+ }
+}
+
+/// Captured by the actual host, not copied from a request's pane label.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Target {
+ pub pane: u64,
+ pub incarnation: Id,
+ pub owner: Id,
+}
+
+impl Target {
+ pub fn new(pane: u64, owner: Id) -> Result<Self> {
+ Ok(Self {
+ pane,
+ incarnation: Id::random()?,
+ owner,
+ })
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GrantRef {
+ pub id: Id,
+ pub version: u64,
+}
+
+#[derive(Debug, Clone)]
+pub struct GrantInfo {
+ pub grant: GrantRef,
+ pub scope: GrantScope,
+ pub permission: Permission,
+ pub targets: Vec<Target>,
+ pub remaining: Duration,
+}
+
+struct Grant {
+ approval: Id,
+ reference: GrantRef,
+ route: Id,
+ scope: GrantScope,
+ permission: Permission,
+ targets: Vec<Target>,
+ deadline: Tick,
+}
+
+struct RouteState {
+ // Retained after revocation and renewal, until this route closes.
+ last_request: u64,
+ control_deadline: Option<Tick>,
+}
+
+struct Intent {
+ id: Id,
+ route: Id,
+ scope: GrantScope,
+ permission: Permission,
+ targets: Vec<Target>,
+ duration: Duration,
+ renewal: Option<GrantRef>,
+ deadline: Tick,
+ session: u64,
+}
+
+struct State {
+ closed: bool,
+ routes: HashMap<Id, RouteState>,
+ grants: HashMap<Id, Grant>,
+ pending: Option<Intent>,
+ session: u64,
+ session_available: bool,
+ monitor_deadline: Option<Tick>,
+ last_tick: Option<Tick>,
+}
+
+impl State {
+ fn revoke_all(&mut self) {
+ self.grants.clear();
+ self.pending = None;
+ }
+
+ fn observe(&mut self, value: Result<Tick>) -> Result<Tick> {
+ if self.closed {
+ return Err(Error::Unavailable);
+ }
+ let now = match value {
+ Ok(now) if self.last_tick.is_none_or(|last| now >= last) => now,
+ _ => {
+ self.revoke_all();
+ self.session_available = false;
+ return Err(Error::Clock);
+ }
+ };
+ self.last_tick = Some(now);
+ self.routes
+ .retain(|_, route| route.control_deadline.is_none_or(|deadline| now < deadline));
+ self.grants
+ .retain(|_, grant| self.routes.contains_key(&grant.route));
+ if self
+ .pending
+ .as_ref()
+ .is_some_and(|intent| !self.routes.contains_key(&intent.route))
+ {
+ self.pending = None;
+ }
+ if self
+ .monitor_deadline
+ .is_some_and(|deadline| now >= deadline)
+ {
+ self.revoke_all();
+ self.session_available = false;
+ self.monitor_deadline = None;
+ }
+ self.grants.retain(|_, grant| now < grant.deadline);
+ if self
+ .pending
+ .as_ref()
+ .is_some_and(|intent| now >= intent.deadline)
+ {
+ self.pending = None;
+ }
+ Ok(now)
+ }
+}
+
+struct Shared {
+ state: Mutex<State>,
+ clock: Arc<dyn Clock>,
+}
+
+impl Shared {
+ fn lock(&self) -> Result<(MutexGuard<'_, State>, Tick)> {
+ let mut state = self.state.lock().map_err(|_| Error::Unavailable)?;
+ let now = state.observe(self.clock.now())?;
+ Ok((state, now))
+ }
+}
+
+/// Kept by the native approval UI in the actual terminal host. Never put
+/// this handle in a Lua value, configuration object, RPC, or plugin API.
+pub struct Authority {
+ shared: Arc<Shared>,
+}
+
+/// Data-plane access has no grant creation or authentication entry point.
+#[derive(Clone)]
+pub struct Endpoint {
+ shared: Arc<Shared>,
+}
+
+impl Authority {
+ pub fn new() -> (Self, Endpoint) {
+ Self::with_clock(SystemClock::shared())
+ }
+
+ fn with_clock(clock: Arc<dyn Clock>) -> (Self, Endpoint) {
+ let shared = Arc::new(Shared {
+ clock,
+ state: Mutex::new(State {
+ closed: false,
+ routes: HashMap::new(),
+ grants: HashMap::new(),
+ pending: None,
+ session: 0,
+ session_available: false,
+ monitor_deadline: None,
+ last_tick: None,
+ }),
+ });
+ (
+ Self {
+ shared: shared.clone(),
+ },
+ Endpoint { shared },
+ )
+ }
+
+ #[cfg(test)]
+ fn session_changed(&self, available: bool) -> Result<()> {
+ let (mut state, _) = self.shared.lock()?;
+ state.revoke_all();
+ state.session = state.session.checked_add(1).ok_or(Error::Unavailable)?;
+ state.session_available = available;
+ state.monitor_deadline = None;
+ Ok(())
+ }
+
+ /// Created only after the packaged native monitor has connected through
+ /// its inherited pipe. A missed heartbeat invalidates access at execution,
+ /// even when the UI or the monitor reader is no longer being scheduled.
+ pub(crate) fn start_monitor(&self) -> Result<Monitor> {
+ let (mut state, now) = self.shared.lock()?;
+ state.revoke_all();
+ state.session = state.session.checked_add(1).ok_or(Error::Unavailable)?;
+ state.session_available = true;
+ state.monitor_deadline = Some(now.after(Duration::from_secs(5))?);
+ Ok(Monitor {
+ shared: Arc::downgrade(&self.shared),
+ session: state.session,
+ })
+ }
+
+ /// Only the owner of a verified Connect session may hold this route.
+ /// Dropping it removes grants and the route's replay watermark.
+ pub fn register_route(&self) -> Result<Route> {
+ let id = Id::random()?;
+ let (mut state, _) = self.shared.lock()?;
+ if state.routes.len() >= MAX_ROUTES {
+ return Err(Error::Busy);
+ }
+ state.routes.insert(
+ id,
+ RouteState {
+ last_request: 0,
+ control_deadline: None,
+ },
+ );
+ Ok(Route {
+ id,
+ shared: Arc::downgrade(&self.shared),
+ })
+ }
+
+ pub fn prepare(
+ &self,
+ route: &Route,
+ targets: Vec<Target>,
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ ) -> Result<Approval> {
+ self.prepare_scope(
+ route,
+ GrantScope::SelectedTerminals,
+ targets,
+ permission,
+ seconds,
+ renewal,
+ )
+ }
+
+ pub fn prepare_all_local(
+ &self,
+ route: &Route,
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ ) -> Result<Approval> {
+ self.prepare_scope(
+ route,
+ GrantScope::AllLocalTerminals,
+ Vec::new(),
+ permission,
+ seconds,
+ renewal,
+ )
+ }
+
+ fn prepare_scope(
+ &self,
+ route: &Route,
+ scope: GrantScope,
+ targets: Vec<Target>,
+ permission: Permission,
+ seconds: u64,
+ renewal: Option<GrantRef>,
+ ) -> Result<Approval> {
+ if seconds == 0 || seconds > MAX_DURATION_SECS {
+ return Err(Error::Duration);
+ }
+ if scope == GrantScope::SelectedTerminals
+ && (targets.is_empty() || targets.len() > MAX_TARGETS_PER_GRANT)
+ {
+ return Err(Error::TooLarge);
+ }
+ let mut unique = std::collections::HashSet::new();
+ if targets.iter().any(|target| !unique.insert(target.pane)) {
+ return Err(Error::Protocol);
+ }
+ if !route.belongs_to(&self.shared) {
+ return Err(Error::Unavailable);
+ }
+ let id = Id::random()?;
+ let (mut state, now) = self.shared.lock()?;
+ if !state.session_available || !state.routes.contains_key(&route.id) {
+ return Err(Error::Unavailable);
+ }
+ if state.pending.is_some() {
+ return Err(Error::Busy);
+ }
+ if let Some(reference) = renewal {
+ let old = state.grants.get(&reference.id).ok_or(Error::Revoked)?;
+ if old.reference != reference || old.route != route.id || old.scope != scope {
+ return Err(Error::Revoked);
+ }
+ }
+ if state.grants.values().any(|grant| {
+ grant.route == route.id
+ && Some(grant.reference) != renewal
+ && (scope == GrantScope::AllLocalTerminals
+ || grant.scope == GrantScope::AllLocalTerminals
+ || grant
+ .targets
+ .iter()
+ .any(|target| unique.contains(&target.pane)))
+ }) {
+ return Err(Error::Busy);
+ }
+ state.pending = Some(Intent {
+ id,
+ route: route.id,
+ scope,
+ permission,
+ targets,
+ duration: Duration::from_secs(seconds),
+ renewal,
+ deadline: now.after(Duration::from_secs(AUTH_TIMEOUT_SECS))?,
+ session: state.session,
+ });
+ Ok(Approval {
+ id,
+ shared: Arc::downgrade(&self.shared),
+ })
+ }
+
+ /// Only the actual host can refresh the eligible terminals covered by a
+ /// native approval that explicitly included current and future terminals.
+ /// Updating membership never renews the grant or its replay watermark.
+ pub fn replace_all_local_targets(
+ &self,
+ route: &Route,
+ reference: GrantRef,
+ targets: Vec<Target>,
+ ) -> Result<()> {
+ if !route.belongs_to(&self.shared) {
+ return Err(Error::Unavailable);
+ }
+ if targets.len() > MAX_TARGETS {
+ return Err(Error::TooLarge);
+ }
+ let mut unique = std::collections::HashSet::new();
+ if targets.iter().any(|target| !unique.insert(target.pane)) {
+ return Err(Error::Protocol);
+ }
+ let (mut state, _) = self.shared.lock()?;
+ let grant = state.grants.get_mut(&reference.id).ok_or(Error::Revoked)?;
+ if grant.route != route.id
+ || grant.reference != reference
+ || grant.scope != GrantScope::AllLocalTerminals
+ {
+ return Err(Error::Revoked);
+ }
+ grant.targets = targets;
+ Ok(())
+ }
+
+ pub fn close(&self) {
+ if let Ok(mut state) = self.shared.state.lock() {
+ state.closed = true;
+ state.revoke_all();
+ state.routes.clear();
+ state.session_available = false;
+ state.monitor_deadline = None;
+ }
+ }
+
+ /// Version-specific cleanup must not revoke a successful replacement.
+ pub fn revoke(&self, reference: GrantRef) -> Result<()> {
+ let (mut state, _) = self.shared.lock()?;
+ if state
+ .grants
+ .get(&reference.id)
+ .is_some_and(|grant| grant.reference == reference)
+ {
+ state.grants.remove(&reference.id);
+ }
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|intent| intent.renewal == Some(reference))
+ {
+ state.pending = None;
+ }
+ Ok(())
+ }
+
+ /// Explicit user revocation covers the route's current grant and pending
+ /// renewal even when the UI still holds an older version of the grant.
+ pub fn revoke_current(&self, route: &Route, id: Id) -> Result<()> {
+ if !route.belongs_to(&self.shared) {
+ return Err(Error::Unavailable);
+ }
+ let (mut state, _) = self.shared.lock()?;
+ if state
+ .grants
+ .get(&id)
+ .is_some_and(|grant| grant.route == route.id)
+ {
+ state.grants.remove(&id);
+ }
+ if state.pending.as_ref().is_some_and(|intent| {
+ intent.route == route.id && intent.renewal.is_some_and(|grant| grant.id == id)
+ }) {
+ state.pending = None;
+ }
+ Ok(())
+ }
+
+ /// Called before removal, ownership changes, or host/domain replacement.
+ pub fn invalidate_target(&self, target: Target) -> Result<()> {
+ let (mut state, _) = self.shared.lock()?;
+ state.grants.retain(|_, grant| {
+ grant.scope == GrantScope::AllLocalTerminals || !grant.targets.contains(&target)
+ });
+ for grant in state
+ .grants
+ .values_mut()
+ .filter(|grant| grant.scope == GrantScope::AllLocalTerminals)
+ {
+ grant.targets.retain(|current| *current != target);
+ }
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|intent| intent.targets.contains(&target))
+ {
+ state.pending = None;
+ }
+ Ok(())
+ }
+}
+
+impl Drop for Authority {
+ fn drop(&mut self) {
+ if let Ok(mut state) = self.shared.state.lock() {
+ state.revoke_all();
+ state.session_available = false;
+ }
+ }
+}
+
+/// A single-use, in-process completion capability. Native authentication
+/// owns it while its dialog is open. There is no wire representation.
+pub struct Approval {
+ id: Id,
+ shared: Weak<Shared>,
+}
+
+pub(crate) struct ApprovalDetails {
+ pub id: Id,
+ pub scope: GrantScope,
+ pub targets: Vec<Target>,
+ pub permission: Permission,
+ pub seconds: u64,
+}
+
+impl Approval {
+ pub(crate) fn cancellation(&self) -> ApprovalCancellation {
+ ApprovalCancellation {
+ id: self.id,
+ shared: self.shared.clone(),
+ }
+ }
+
+ pub(crate) fn details(&self) -> Result<ApprovalDetails> {
+ let shared = self.shared.upgrade().ok_or(Error::StaleApproval)?;
+ let (state, _) = shared.lock()?;
+ let intent = state
+ .pending
+ .as_ref()
+ .filter(|intent| intent.id == self.id)
+ .ok_or(Error::StaleApproval)?;
+ Ok(ApprovalDetails {
+ id: self.id,
+ scope: intent.scope,
+ targets: intent.targets.clone(),
+ permission: intent.permission,
+ seconds: intent.duration.as_secs(),
+ })
+ }
+
+ pub fn reject(self) {}
+
+ /// Invoke only from the native provider's successful completion. The
+ /// handle freezes the intent; the callback cannot supply a new scope.
+ pub(crate) fn authenticated(self) -> Result<GrantInfo> {
+ let shared = self.shared.upgrade().ok_or(Error::StaleApproval)?;
+ let (mut state, now) = shared.lock()?;
+ if !state
+ .pending
+ .as_ref()
+ .is_some_and(|intent| intent.id == self.id)
+ {
+ return Err(Error::StaleApproval);
+ }
+ let intent = state.pending.take().ok_or(Error::StaleApproval)?;
+ if !state.session_available
+ || state.session != intent.session
+ || !state.routes.contains_key(&intent.route)
+ {
+ return Err(Error::StaleApproval);
+ }
+ let reference = if let Some(reference) = intent.renewal {
+ let old = state
+ .grants
+ .get(&reference.id)
+ .ok_or(Error::StaleApproval)?;
+ if old.reference != reference || old.route != intent.route {
+ return Err(Error::StaleApproval);
+ }
+ GrantRef {
+ id: reference.id,
+ version: reference
+ .version
+ .checked_add(1)
+ .ok_or(Error::StaleApproval)?,
+ }
+ } else {
+ if state.grants.len() >= MAX_GRANTS {
+ return Err(Error::Busy);
+ }
+ GrantRef {
+ id: Id::random()?,
+ version: 1,
+ }
+ };
+ let retained = state
+ .grants
+ .values()
+ .filter(|grant| {
+ grant.reference.id != reference.id && grant.scope == GrantScope::SelectedTerminals
+ })
+ .map(|grant| grant.targets.len())
+ .sum::<usize>();
+ if intent.scope == GrantScope::SelectedTerminals
+ && retained + intent.targets.len() > MAX_TARGETS
+ {
+ return Err(Error::Busy);
+ }
+ let info = GrantInfo {
+ grant: reference,
+ scope: intent.scope,
+ permission: intent.permission,
+ targets: intent.targets.clone(),
+ remaining: intent.duration,
+ };
+ state.grants.insert(
+ reference.id,
+ Grant {
+ approval: self.id,
+ reference,
+ route: intent.route,
+ scope: intent.scope,
+ permission: intent.permission,
+ targets: intent.targets,
+ deadline: now.after(intent.duration)?,
+ },
+ );
+ Ok(info)
+ }
+}
+
+pub(crate) struct ApprovalCancellation {
+ id: Id,
+ shared: Weak<Shared>,
+}
+
+impl ApprovalCancellation {
+ pub(crate) fn cancel(&self) {
+ if let Some(shared) = self.shared.upgrade() {
+ if let Ok(mut state) = shared.state.lock() {
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|intent| intent.id == self.id)
+ {
+ state.pending = None;
+ }
+ state.grants.retain(|_, grant| grant.approval != self.id);
+ }
+ }
+ }
+}
+
+pub(crate) struct Monitor {
+ shared: Weak<Shared>,
+ session: u64,
+}
+
+impl Monitor {
+ pub(crate) fn check(&self) -> Result<()> {
+ let shared = self.shared.upgrade().ok_or(Error::Unavailable)?;
+ let (state, _) = shared.lock()?;
+ if state.session_available && state.session == self.session {
+ Ok(())
+ } else {
+ Err(Error::Unavailable)
+ }
+ }
+
+ pub(crate) fn heartbeat(&self) -> Result<()> {
+ let shared = self.shared.upgrade().ok_or(Error::Unavailable)?;
+ let (mut state, now) = shared.lock()?;
+ if !state.session_available || state.session != self.session {
+ return Err(Error::Unavailable);
+ }
+ state.monitor_deadline = Some(now.after(Duration::from_secs(5))?);
+ Ok(())
+ }
+
+ pub(crate) fn close(&self) {
+ if let Some(shared) = self.shared.upgrade() {
+ if let Ok(mut state) = shared.state.lock() {
+ if state.session == self.session {
+ state.revoke_all();
+ state.session_available = false;
+ state.monitor_deadline = None;
+ }
+ }
+ }
+ }
+}
+
+impl Drop for Monitor {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+impl Drop for Approval {
+ fn drop(&mut self) {
+ if let Some(shared) = self.shared.upgrade() {
+ if let Ok(mut state) = shared.state.lock() {
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|intent| intent.id == self.id)
+ {
+ state.pending = None;
+ }
+ }
+ }
+ }
+}
+
+pub struct Route {
+ id: Id,
+ shared: Weak<Shared>,
+}
+
+impl Route {
+ pub fn id(&self) -> Id {
+ self.id
+ }
+
+ /// Only the trusted local management connection calls this. Business
+ /// traffic has an Endpoint and cannot renew a control lease.
+ pub fn heartbeat(&self) -> Result<()> {
+ let shared = self.shared.upgrade().ok_or(Error::Unavailable)?;
+ let (mut state, now) = shared.lock()?;
+ state
+ .routes
+ .get_mut(&self.id)
+ .ok_or(Error::Unavailable)?
+ .control_deadline = Some(now.after(Duration::from_secs(5))?);
+ Ok(())
+ }
+
+ pub fn close(&self) {
+ if let Some(shared) = self.shared.upgrade() {
+ if let Ok(mut state) = shared.state.lock() {
+ state.routes.remove(&self.id);
+ state.grants.retain(|_, grant| grant.route != self.id);
+ if state
+ .pending
+ .as_ref()
+ .is_some_and(|intent| intent.route == self.id)
+ {
+ state.pending = None;
+ }
+ }
+ }
+ }
+
+ fn belongs_to(&self, shared: &Arc<Shared>) -> bool {
+ self.shared
+ .upgrade()
+ .is_some_and(|owner| Arc::ptr_eq(&owner, shared))
+ }
+}
+
+impl Drop for Route {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Request {
+ pub grant: GrantRef,
+ pub target: Target,
+ pub operation: Operation,
+ pub sequence: u64,
+}
+
+fn validate(state: &State, route: Id, request: Request) -> Result<()> {
+ if !state.session_available || !state.routes.contains_key(&route) {
+ return Err(Error::Unavailable);
+ }
+ let grant = state
+ .grants
+ .get(&request.grant.id)
+ .ok_or(Error::Unavailable)?;
+ if grant.route != route
+ || grant.reference != request.grant
+ || !grant.permission.allows(request.operation)
+ || !grant.targets.contains(&request.target)
+ {
+ return Err(Error::Unavailable);
+ }
+ Ok(())
+}
+
+impl Endpoint {
+ pub fn accept_list(&self, route: &Route, sequence: u64) -> Result<ListPermit> {
+ self.accept_list_for(route, sequence, Duration::from_secs(REQUEST_TIMEOUT_SECS))
+ }
+
+ pub fn accept_list_for(
+ &self,
+ route: &Route,
+ sequence: u64,
+ remaining: Duration,
+ ) -> Result<ListPermit> {
+ validate_remaining(remaining)?;
+ if !route.belongs_to(&self.shared) {
+ return Err(Error::Unavailable);
+ }
+ let (mut state, now) = self.shared.lock()?;
+ if !state.session_available {
+ return Err(Error::Unavailable);
+ }
+ let route_state = state.routes.get_mut(&route.id).ok_or(Error::Unavailable)?;
+ if sequence == 0 || sequence <= route_state.last_request {
+ return Err(Error::Replay);
+ }
+ if sequence == u64::MAX {
+ state.routes.remove(&route.id);
+ state.grants.retain(|_, grant| grant.route != route.id);
+ return Err(Error::Protocol);
+ }
+ route_state.last_request = sequence;
+ Ok(ListPermit {
+ shared: self.shared.clone(),
+ route: route.id,
+ deadline: now.after(remaining)?,
+ })
+ }
+
+ pub fn list(&self, route: &Route) -> Result<Vec<GrantInfo>> {
+ if !route.belongs_to(&self.shared) {
+ return Err(Error::Unavailable);
+ }
+ let (state, now) = self.shared.lock()?;
+ if !state.session_available || !state.routes.contains_key(&route.id) {
+ return Err(Error::Unavailable);
+ }
+ state
+ .grants
+ .values()
+ .filter(|grant| grant.route == route.id)
+ .map(|grant| {
+ Ok(GrantInfo {
+ grant: grant.reference,
+ scope: grant.scope,
+ permission: grant.permission,
+ targets: grant.targets.clone(),
+ remaining: grant.deadline.elapsed_since(now)?,
+ })
+ })
+ .collect()
+ }
+
+ /// Reserve the sequence before any terminal access. Dropping a permit
+ /// never makes its sequence eligible for retry.
+ pub fn accept(&self, route: &Route, request: Request) -> Result<RequestPermit> {
+ self.accept_for(route, request, Duration::from_secs(REQUEST_TIMEOUT_SECS))
+ }
+
+ pub fn accept_for(
+ &self,
+ route: &Route,
+ request: Request,
+ remaining: Duration,
+ ) -> Result<RequestPermit> {
+ validate_remaining(remaining)?;
+ if !route.belongs_to(&self.shared) {
+ return Err(Error::Unavailable);
+ }
+ let (mut state, now) = self.shared.lock()?;
+ validate(&state, route.id, request)?;
+ let route_state = state.routes.get_mut(&route.id).ok_or(Error::Unavailable)?;
+ if request.sequence == 0 || request.sequence <= route_state.last_request {
+ return Err(Error::Replay);
+ }
+ if request.sequence == u64::MAX {
+ state.routes.remove(&route.id);
+ state.grants.retain(|_, grant| grant.route != route.id);
+ return Err(Error::Protocol);
+ }
+ route_state.last_request = request.sequence;
+ Ok(RequestPermit {
+ shared: self.shared.clone(),
+ route: route.id,
+ request,
+ deadline: now.after(remaining)?,
+ })
+ }
+}
+
+fn validate_remaining(remaining: Duration) -> Result<()> {
+ if remaining.is_zero() {
+ return Err(Error::Timeout);
+ }
+ if remaining > Duration::from_secs(REQUEST_TIMEOUT_SECS) {
+ return Err(Error::Protocol);
+ }
+ Ok(())
+}
+
+pub struct RequestPermit {
+ shared: Arc<Shared>,
+ route: Id,
+ request: Request,
+ deadline: Tick,
+}
+
+pub struct ListPermit {
+ shared: Arc<Shared>,
+ route: Id,
+ deadline: Tick,
+}
+
+impl ListPermit {
+ pub fn execute<T>(
+ &self,
+ exports: &[(GrantRef, Target)],
+ send: impl FnOnce() -> T,
+ ) -> Result<T> {
+ let (state, now) = self.shared.lock()?;
+ if now >= self.deadline {
+ return Err(Error::Timeout);
+ }
+ if !state.session_available || !state.routes.contains_key(&self.route) {
+ return Err(Error::Unavailable);
+ }
+ for &(grant, target) in exports {
+ validate(
+ &state,
+ self.route,
+ Request {
+ grant,
+ target,
+ operation: Operation::Read,
+ sequence: 1,
+ },
+ )?;
+ }
+ Ok(send())
+ }
+}
+
+impl RequestPermit {
+ /// Serializes a final check with one nonblocking host submission or
+ /// transport write. Never enqueue unchecked work from this closure.
+ pub fn execute<T>(&self, current_target: Target, submit: impl FnOnce() -> T) -> Result<T> {
+ let (state, now) = self.shared.lock()?;
+ if now >= self.deadline {
+ return Err(Error::Timeout);
+ }
+ if current_target != self.request.target {
+ return Err(Error::Unavailable);
+ }
+ validate(&state, self.route, self.request)?;
+ let result = submit();
+ drop(state);
+ Ok(result)
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/thinkterm-reverse-access/src/authorization/tests.rs b/thinkterm-reverse-access/src/authorization/tests.rs
new file mode 100644
index 00000000..1712e1b5
--- /dev/null
+++ b/thinkterm-reverse-access/src/authorization/tests.rs
@@ -0,0 +1,762 @@
+use super::*;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+
+#[test]
+fn repeated_grant_request_revoke_and_disconnect_releases_state_and_budgets() {
+ let fixture = Fixture::new();
+ let budgets = crate::budget::Budgets::with_clock(fixture.clock.clone()).unwrap();
+ for second in 1..=100 {
+ fixture.clock.set(second);
+ let route = fixture.authority.register_route().unwrap();
+ let budget = budgets.open_route(route.id()).unwrap();
+ let grant = fixture
+ .authority
+ .prepare(&route, vec![fixture.target], Permission::Read, 60, None)
+ .unwrap()
+ .authenticated()
+ .unwrap()
+ .grant;
+ let request = Request {
+ grant,
+ target: fixture.target,
+ operation: Operation::Read,
+ sequence: 1,
+ };
+ let permit = fixture.endpoint.accept(&route, request).unwrap();
+ let reservation = budget.acquire(4096).unwrap();
+ permit.execute(fixture.target, || ()).unwrap();
+ fixture.authority.revoke(grant).unwrap();
+ assert!(permit.execute(fixture.target, || ()).is_err());
+ drop((permit, reservation, budget, route));
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ let state = fixture.authority.shared.state.lock().unwrap();
+ assert!(state.grants.is_empty());
+ assert!(state.pending.is_none());
+ assert_eq!(state.routes.len(), 1);
+ }
+}
+
+#[test]
+fn closing_the_authority_invalidates_work_and_cannot_be_reopened() {
+ let fixture = Fixture::new();
+ let grant = fixture.grant();
+ let permit = fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 1))
+ .unwrap();
+ let pending = fixture.pending(Some(grant));
+ fixture.authority.close();
+ assert!(permit.execute(fixture.target, || ()).is_err());
+ assert!(pending.authenticated().is_err());
+ assert!(fixture.endpoint.list(&fixture.route).is_err());
+ assert!(fixture.authority.register_route().is_err());
+ assert!(fixture.authority.start_monitor().is_err());
+ fixture.authority.close();
+}
+
+#[test]
+fn missing_native_monitor_heartbeat_revokes_at_the_execution_boundary() {
+ let fixture = Fixture::new();
+ let monitor = fixture.authority.start_monitor().unwrap();
+ let grant = fixture.grant();
+ let permit = fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 1))
+ .unwrap();
+ fixture.clock.set(5);
+ let called = AtomicBool::new(false);
+ assert!(permit
+ .execute(fixture.target, || called.store(true, Ordering::Relaxed))
+ .is_err());
+ assert!(!called.load(Ordering::Relaxed));
+ assert!(monitor.heartbeat().is_err());
+ assert!(fixture.endpoint.list(&fixture.route).is_err());
+}
+
+#[test]
+fn old_monitor_cannot_revoke_or_extend_a_replacement_session() {
+ let fixture = Fixture::new();
+ let old = fixture.authority.start_monitor().unwrap();
+ let current = fixture.authority.start_monitor().unwrap();
+ let grant = fixture.grant();
+ assert!(old.heartbeat().is_err());
+ drop(old);
+ let permit = fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 1))
+ .unwrap();
+ assert!(permit.execute(fixture.target, || ()).is_ok());
+ current.close();
+ assert!(permit.execute(fixture.target, || ()).is_err());
+}
+
+#[test]
+fn cancelling_native_work_also_revokes_a_result_not_yet_delivered_to_the_ui() {
+ let fixture = Fixture::new();
+ let approval = fixture.pending(None);
+ let cancellation = approval.cancellation();
+ let grant = approval.authenticated().unwrap().grant;
+ cancellation.cancel();
+ assert!(fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 1))
+ .is_err());
+ let pending = fixture.pending(None);
+ let cancellation = pending.cancellation();
+ cancellation.cancel();
+ assert!(pending.authenticated().is_err());
+}
+
+#[derive(Default)]
+struct TestClock {
+ seconds: AtomicU64,
+ failed: AtomicBool,
+}
+
+impl Clock for TestClock {
+ fn now(&self) -> Result<Tick> {
+ if self.failed.load(Ordering::Relaxed) {
+ return Err(Error::Clock);
+ }
+ Ok(Tick::seconds(self.seconds.load(Ordering::Relaxed)))
+ }
+}
+
+impl TestClock {
+ fn set(&self, seconds: u64) {
+ self.seconds.store(seconds, Ordering::Relaxed);
+ }
+}
+
+struct Fixture {
+ authority: Authority,
+ endpoint: Endpoint,
+ clock: Arc<TestClock>,
+ route: Route,
+ target: Target,
+}
+
+#[test]
+fn all_local_membership_changes_preserve_expiry_and_reject_old_work() {
+ let fixture = Fixture::new();
+ let approval = fixture
+ .authority
+ .prepare_all_local(&fixture.route, Permission::ReadAndInput, 60, None)
+ .unwrap();
+ assert_eq!(
+ approval.details().unwrap().scope,
+ GrantScope::AllLocalTerminals
+ );
+ let info = approval.authenticated().unwrap();
+ assert!(info.targets.is_empty());
+ let grant = info.grant;
+ assert!(fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 1))
+ .is_err());
+ fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![fixture.target])
+ .unwrap();
+ let permit = fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 2))
+ .unwrap();
+ assert!(permit.execute(fixture.target, || ()).is_ok());
+ fixture.clock.set(10);
+ fixture.authority.invalidate_target(fixture.target).unwrap();
+ let remaining = fixture.endpoint.list(&fixture.route).unwrap();
+ assert_eq!(remaining.len(), 1);
+ assert!(remaining[0].targets.is_empty());
+ assert_eq!(remaining[0].remaining, Duration::from_secs(50));
+ assert!(permit.execute(fixture.target, || ()).is_err());
+
+ let replacement = Target::new(fixture.target.pane, fixture.target.owner).unwrap();
+ fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![replacement])
+ .unwrap();
+ let request = Request {
+ target: replacement,
+ ..fixture.request(grant, 3)
+ };
+ let permit = fixture.endpoint.accept(&fixture.route, request).unwrap();
+ assert!(permit.execute(replacement, || ()).is_ok());
+ assert!(fixture.endpoint.accept(&fixture.route, request).is_err());
+ assert!(fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(grant, 4))
+ .is_err());
+ fixture.clock.set(60);
+ assert!(fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![replacement])
+ .is_err());
+ assert!(permit.execute(replacement, || ()).is_err());
+}
+
+#[test]
+fn all_local_refresh_cannot_widen_selected_grants_or_cross_routes() {
+ let fixture = Fixture::new();
+ let selected = fixture.grant();
+ assert!(fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, selected, vec![])
+ .is_err());
+ assert!(fixture
+ .authority
+ .prepare_all_local(&fixture.route, Permission::Read, 60, Some(selected))
+ .is_err());
+ fixture.authority.revoke(selected).unwrap();
+ let grant = fixture
+ .authority
+ .prepare_all_local(&fixture.route, Permission::Read, 60, None)
+ .unwrap()
+ .authenticated()
+ .unwrap()
+ .grant;
+ let other = fixture.authority.register_route().unwrap();
+ assert!(fixture
+ .authority
+ .replace_all_local_targets(&other, grant, vec![fixture.target])
+ .is_err());
+ assert!(fixture
+ .authority
+ .prepare(
+ &fixture.route,
+ vec![fixture.target],
+ Permission::Read,
+ 60,
+ Some(grant)
+ )
+ .is_err());
+ assert!(fixture
+ .authority
+ .prepare(
+ &fixture.route,
+ vec![fixture.target],
+ Permission::Read,
+ 60,
+ None
+ )
+ .is_err());
+ assert!(fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![fixture.target; 2])
+ .is_err());
+ let oversized = (0..=MAX_TARGETS)
+ .map(|pane| Target {
+ pane: pane as u64,
+ ..fixture.target
+ })
+ .collect();
+ assert_eq!(
+ fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, oversized),
+ Err(Error::TooLarge)
+ );
+ fixture
+ .authority
+ .revoke_current(&fixture.route, grant.id)
+ .unwrap();
+ assert!(fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![fixture.target])
+ .is_err());
+}
+
+#[test]
+fn all_local_renewal_retains_scope_and_invalidates_previous_membership() {
+ let fixture = Fixture::new();
+ let grant = fixture
+ .authority
+ .prepare_all_local(&fixture.route, Permission::Read, 60, None)
+ .unwrap()
+ .authenticated()
+ .unwrap()
+ .grant;
+ fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![fixture.target])
+ .unwrap();
+ let renewal = fixture
+ .authority
+ .prepare_all_local(&fixture.route, Permission::Read, 60, Some(grant))
+ .unwrap()
+ .authenticated()
+ .unwrap();
+ assert_eq!(renewal.scope, GrantScope::AllLocalTerminals);
+ assert!(renewal.targets.is_empty());
+ assert!(fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, grant, vec![fixture.target])
+ .is_err());
+ fixture
+ .authority
+ .replace_all_local_targets(&fixture.route, renewal.grant, vec![fixture.target])
+ .unwrap();
+ assert!(fixture
+ .endpoint
+ .accept(
+ &fixture.route,
+ Request {
+ operation: Operation::Read,
+ ..fixture.request(renewal.grant, 1)
+ }
+ )
+ .is_ok());
+ assert!(fixture
+ .endpoint
+ .accept(&fixture.route, fixture.request(renewal.grant, 2))
+ .is_err());
+}
+
+impl Fixture {
+ fn new() -> Self {
+ let clock = Arc::new(TestClock::default());
+ let (authority, endpoint) = Authority::with_clock(clock.clone());
+ authority.session_changed(true).unwrap();
+ let route = authority.register_route().unwrap();
+ let target = Target::new(1, Id::from_bytes([1; 16])).unwrap();
+ Self {
+ authority,
+ endpoint,
+ clock,
+ route,
+ target,
+ }
+ }
+
+ fn pending(&self, renewal: Option<GrantRef>) -> Approval {
+ self.authority
+ .prepare(
+ &self.route,
+ vec![self.target],
+ Permission::ReadAndInput,
+ 60,
+ renewal,
+ )
+ .unwrap()
+ }
+
+ fn grant(&self) -> GrantRef {
+ self.pending(None).authenticated().unwrap().grant
+ }
+
+ fn request(&self, grant: GrantRef, sequence: u64) -> Request {
+ Request {
+ grant,
+ target: self.target,
+ operation: Operation::Input,
+ sequence,
+ }
+ }
+}
+
+#[test]
+fn rejected_or_abandoned_approval_creates_no_grant() {
+ let f = Fixture::new();
+ f.pending(None).reject();
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+ drop(f.pending(None));
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+ assert!(f.pending(None).authenticated().is_ok());
+}
+
+#[test]
+fn failed_renewal_keeps_the_original_scope_and_deadline() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ f.clock.set(30);
+ f.pending(Some(grant)).reject();
+ let grants = f.endpoint.list(&f.route).unwrap();
+ assert_eq!(grants[0].grant, grant);
+ assert_eq!(grants[0].remaining, Duration::from_secs(30));
+ f.clock.set(60);
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+}
+
+#[test]
+fn expired_or_revoked_grant_cannot_be_revived_by_a_late_renewal() {
+ for revoke in [false, true] {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let pending = f.pending(Some(grant));
+ if revoke {
+ f.authority.revoke(grant).unwrap();
+ } else {
+ f.clock.set(60);
+ }
+ assert!(matches!(pending.authenticated(), Err(Error::StaleApproval)));
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+ }
+}
+
+#[test]
+fn explicit_revocation_covers_a_renewal_completed_after_the_ui_snapshot() {
+ for operation in [Operation::Read, Operation::Input] {
+ let f = Fixture::new();
+ let displayed = f.grant();
+ let renewed = f.pending(Some(displayed)).authenticated().unwrap().grant;
+ let mut request = f.request(renewed, 1);
+ request.operation = operation;
+ let permit = f.endpoint.accept(&f.route, request).unwrap();
+ permit.execute(f.target, || ()).unwrap();
+
+ f.authority.revoke_current(&f.route, displayed.id).unwrap();
+
+ let mut submitted = false;
+ assert!(permit.execute(f.target, || submitted = true).is_err());
+ assert!(!submitted);
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+ assert!(f.endpoint.accept(&f.route, f.request(renewed, 2)).is_err());
+ f.authority.revoke_current(&f.route, displayed.id).unwrap();
+ }
+}
+
+#[test]
+fn explicit_revocation_cancels_pending_renewals_of_any_version() {
+ for renew_first in [false, true] {
+ let f = Fixture::new();
+ let displayed = f.grant();
+ let current = if renew_first {
+ f.pending(Some(displayed)).authenticated().unwrap().grant
+ } else {
+ displayed
+ };
+ let pending = f.pending(Some(current));
+ f.authority.revoke_current(&f.route, displayed.id).unwrap();
+ assert!(matches!(pending.authenticated(), Err(Error::StaleApproval)));
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+ assert!(f.pending(None).authenticated().is_ok());
+ }
+}
+
+#[test]
+fn explicit_revocation_leaves_other_grants_and_approvals_intact() {
+ for renewal in [false, true] {
+ let f = Fixture::new();
+ let displayed = f.grant();
+ let other_target = Target::new(2, f.target.owner).unwrap();
+ let other = if renewal {
+ Some(
+ f.authority
+ .prepare(&f.route, vec![other_target], Permission::Read, 60, None)
+ .unwrap()
+ .authenticated()
+ .unwrap()
+ .grant,
+ )
+ } else {
+ None
+ };
+ let pending = f
+ .authority
+ .prepare(&f.route, vec![other_target], Permission::Read, 60, other)
+ .unwrap();
+ f.authority.revoke_current(&f.route, displayed.id).unwrap();
+ let approved = pending.authenticated().unwrap();
+ let grants = f.endpoint.list(&f.route).unwrap();
+ assert_eq!(grants.len(), 1);
+ assert_eq!(grants[0].grant, approved.grant);
+ assert_eq!(grants[0].targets, [other_target]);
+ }
+}
+
+#[test]
+fn explicit_revocation_cannot_cross_route_or_authority_boundaries() {
+ let f = Fixture::new();
+ let current = f.grant();
+ let pending = f.pending(Some(current));
+ let other_route = f.authority.register_route().unwrap();
+ f.authority
+ .revoke_current(&other_route, current.id)
+ .unwrap();
+ let other_authority = Fixture::new();
+ assert!(f
+ .authority
+ .revoke_current(&other_authority.route, current.id)
+ .is_err());
+ let permit = f.endpoint.accept(&f.route, f.request(current, 1)).unwrap();
+ assert!(permit.execute(f.target, || ()).is_ok());
+ assert!(pending.authenticated().is_ok());
+}
+
+#[test]
+fn version_specific_cleanup_preserves_a_replacement_and_its_pending_renewal() {
+ let f = Fixture::new();
+ let old = f.grant();
+ let current = f.pending(Some(old)).authenticated().unwrap().grant;
+ let pending = f.pending(Some(current));
+ f.authority.revoke(old).unwrap();
+ let permit = f.endpoint.accept(&f.route, f.request(current, 1)).unwrap();
+ assert!(permit.execute(f.target, || ()).is_ok());
+ assert!(pending.authenticated().is_ok());
+}
+
+#[test]
+fn lock_and_unlock_invalidate_the_old_authentication_callback() {
+ let f = Fixture::new();
+ let pending = f.pending(None);
+ f.authority.session_changed(false).unwrap();
+ f.authority.session_changed(true).unwrap();
+ assert!(matches!(pending.authenticated(), Err(Error::StaleApproval)));
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+}
+
+#[test]
+fn authentication_has_an_absolute_deadline() {
+ let f = Fixture::new();
+ let pending = f.pending(None);
+ f.clock.set(AUTH_TIMEOUT_SECS);
+ assert!(matches!(pending.authenticated(), Err(Error::StaleApproval)));
+}
+
+#[test]
+fn input_is_checked_again_at_each_submission_step() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let permit = f.endpoint.accept(&f.route, f.request(grant, 1)).unwrap();
+ let mut submissions = vec![];
+ permit
+ .execute(f.target, || submissions.push("text"))
+ .unwrap();
+ f.authority.revoke(grant).unwrap();
+ assert!(permit
+ .execute(f.target, || submissions.push("enter"))
+ .is_err());
+ assert_eq!(submissions, ["text"]);
+}
+
+#[test]
+fn snapshot_revoked_before_send_is_not_released() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let mut request = f.request(grant, 1);
+ request.operation = Operation::Read;
+ let permit = f.endpoint.accept(&f.route, request).unwrap();
+ let body = permit.execute(f.target, || "example output").unwrap();
+ f.authority.invalidate_target(f.target).unwrap();
+ let mut released = false;
+ assert!(permit
+ .execute(f.target, || {
+ let _ = body;
+ released = true;
+ })
+ .is_err());
+ assert!(!released);
+}
+
+#[test]
+fn renewal_invalidates_queued_work_without_resetting_the_replay_watermark() {
+ let f = Fixture::new();
+ let old = f.grant();
+ let permit = f.endpoint.accept(&f.route, f.request(old, 7)).unwrap();
+ let new = f.pending(Some(old)).authenticated().unwrap().grant;
+ assert_eq!(new.id, old.id);
+ assert_eq!(new.version, old.version + 1);
+ assert!(permit.execute(f.target, || ()).is_err());
+ assert!(matches!(
+ f.endpoint.accept(&f.route, f.request(new, 7)),
+ Err(Error::Replay)
+ ));
+ assert!(f.endpoint.accept(&f.route, f.request(new, 8)).is_ok());
+}
+
+#[test]
+fn dropping_a_request_does_not_make_input_retryable() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ drop(f.endpoint.accept(&f.route, f.request(grant, 42)).unwrap());
+ assert!(matches!(
+ f.endpoint.accept(&f.route, f.request(grant, 42)),
+ Err(Error::Replay)
+ ));
+}
+
+#[test]
+fn route_shutdown_cancels_pending_approval_and_queued_requests() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let permit = f.endpoint.accept(&f.route, f.request(grant, 1)).unwrap();
+ let pending = f.pending(Some(grant));
+ drop(f.route);
+ assert!(permit.execute(f.target, || ()).is_err());
+ assert!(matches!(pending.authenticated(), Err(Error::StaleApproval)));
+}
+
+#[test]
+fn an_identical_pane_number_on_another_route_or_incarnation_is_denied() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let other = f.authority.register_route().unwrap();
+ assert!(f.endpoint.accept(&other, f.request(grant, 1)).is_err());
+ let permit = f.endpoint.accept(&f.route, f.request(grant, 1)).unwrap();
+ let new = Target::new(f.target.pane, f.target.owner).unwrap();
+ assert!(permit.execute(new, || ()).is_err());
+ let new_owner = Target {
+ owner: Id::from_bytes([2; 16]),
+ ..f.target
+ };
+ assert!(permit.execute(new_owner, || ()).is_err());
+}
+
+#[test]
+fn unavailable_clock_or_backwards_time_revokes_existing_authorization() {
+ for backwards in [false, true] {
+ let f = Fixture::new();
+ f.clock.set(10);
+ let grant = f.grant();
+ let permit = f.endpoint.accept(&f.route, f.request(grant, 1)).unwrap();
+ if backwards {
+ f.clock.set(9);
+ } else {
+ f.clock.failed.store(true, Ordering::Relaxed);
+ }
+ assert!(matches!(permit.execute(f.target, || ()), Err(Error::Clock)));
+ f.clock.failed.store(false, Ordering::Relaxed);
+ f.clock.set(11);
+ f.authority.session_changed(true).unwrap();
+ assert!(f.endpoint.list(&f.route).unwrap().is_empty());
+ }
+}
+
+#[test]
+fn a_pending_request_cannot_extend_its_deadline_by_making_progress() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let permit = f.endpoint.accept(&f.route, f.request(grant, 1)).unwrap();
+ for second in 0..REQUEST_TIMEOUT_SECS {
+ f.clock.set(second);
+ permit.execute(f.target, || ()).unwrap();
+ }
+ f.clock.set(REQUEST_TIMEOUT_SECS);
+ assert!(matches!(
+ permit.execute(f.target, || ()),
+ Err(Error::Timeout)
+ ));
+}
+
+#[test]
+fn read_only_grants_cannot_be_used_for_input() {
+ let f = Fixture::new();
+ let grant = f
+ .authority
+ .prepare(&f.route, vec![f.target], Permission::Read, 60, None)
+ .unwrap()
+ .authenticated()
+ .unwrap()
+ .grant;
+ assert!(f.endpoint.accept(&f.route, f.request(grant, 1)).is_err());
+ let mut request = f.request(grant, 1);
+ request.operation = Operation::Read;
+ assert!(f.endpoint.accept(&f.route, request).is_ok());
+}
+
+#[test]
+fn a_route_has_one_round_trippable_export_per_pane() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let captured_again = Target::new(f.target.pane, Id::from_bytes([9; 16])).unwrap();
+ assert!(matches!(
+ f.authority
+ .prepare(&f.route, vec![captured_again], Permission::Read, 60, None),
+ Err(Error::Busy)
+ ));
+ assert!(f
+ .authority
+ .prepare(
+ &f.route,
+ vec![captured_again],
+ Permission::Read,
+ 60,
+ Some(grant)
+ )
+ .is_ok());
+}
+
+#[test]
+fn forwarding_may_shorten_but_cannot_extend_executor_deadlines() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ assert!(f
+ .endpoint
+ .accept_for(&f.route, f.request(grant, 1), Duration::from_secs(11))
+ .is_err());
+ let permit = f
+ .endpoint
+ .accept_for(&f.route, f.request(grant, 1), Duration::from_secs(2))
+ .unwrap();
+ let list = f
+ .endpoint
+ .accept_list_for(&f.route, 2, Duration::from_secs(1))
+ .unwrap();
+ f.clock.set(1);
+ assert!(list.execute(&[(grant, f.target)], || ()).is_err());
+ assert!(permit.execute(f.target, || ()).is_ok());
+ f.clock.set(2);
+ assert_eq!(permit.execute(f.target, || ()), Err(Error::Timeout));
+}
+
+#[test]
+fn repeated_authorize_request_revoke_disconnect_cycles_release_all_permits() {
+ use crate::budget::Budgets;
+ use crate::wire::Assembly;
+ let clock = Arc::new(TestClock::default());
+ let (authority, endpoint) = Authority::with_clock(clock.clone());
+ let budgets = Budgets::with_clock(clock.clone()).unwrap();
+ authority.session_changed(true).unwrap();
+ for cycle in 0..100 {
+ clock.set(cycle * 20);
+ let route = authority.register_route().unwrap();
+ let budget = budgets.open_route(route.id()).unwrap();
+ let target = Target::new(cycle, Id::from_bytes([1; 16])).unwrap();
+ let grant = authority
+ .prepare(&route, vec![target], Permission::ReadAndInput, 60, None)
+ .unwrap()
+ .authenticated()
+ .unwrap()
+ .grant;
+ let request = Request {
+ grant,
+ target,
+ operation: Operation::Input,
+ sequence: 1,
+ };
+ let permit = endpoint.accept(&route, request).unwrap();
+ let mut body = Assembly::input(7, &budget).unwrap();
+ body.append(0, b"example").unwrap();
+ let body = body.finish().unwrap();
+ assert_eq!(permit.execute(target, || body.text().len()).unwrap(), 7);
+ authority.revoke(grant).unwrap();
+ assert!(permit.execute(target, || ()).is_err());
+ assert!(endpoint.accept(&route, request).is_err());
+ drop((body, permit, route, budget));
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ let state = authority.shared.state.lock().unwrap();
+ assert!(state.grants.is_empty());
+ assert!(state.routes.is_empty());
+ assert!(state.pending.is_none());
+ }
+}
+
+#[test]
+fn authority_exit_revokes_even_when_the_data_plane_remains_alive() {
+ let f = Fixture::new();
+ let grant = f.grant();
+ let permit = f.endpoint.accept(&f.route, f.request(grant, 1)).unwrap();
+ drop(f.authority);
+ assert!(permit.execute(f.target, || ()).is_err());
+}
+
+#[test]
+fn another_authority_cannot_register_a_route_or_target_for_this_one() {
+ let f = Fixture::new();
+ let other = Fixture::new();
+ assert!(f
+ .authority
+ .prepare(&other.route, vec![f.target], Permission::Read, 60, None)
+ .is_err());
+ assert!(f.endpoint.list(&other.route).is_err());
+}
diff --git a/thinkterm-reverse-access/src/budget.rs b/thinkterm-reverse-access/src/budget.rs
new file mode 100644
index 00000000..6e12c4a2
--- /dev/null
+++ b/thinkterm-reverse-access/src/budget.rs
@@ -0,0 +1,341 @@
+use crate::clock::{Clock, SystemClock, Tick};
+use crate::{Error, Id, Result, MAX_ROUTES};
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+pub const ROUTE_BYTES: usize = 8 * 1024 * 1024;
+pub const PROCESS_BYTES: usize = 32 * 1024 * 1024;
+pub const ROUTE_REQUESTS: usize = 8;
+pub const PROCESS_REQUESTS: usize = 32;
+
+#[derive(Clone, Copy)]
+struct Rate {
+ credit: u64,
+ last: Tick,
+}
+
+impl Rate {
+ const UNIT: u64 = 1_000_000_000;
+
+ fn new(now: Tick, burst: u64) -> Self {
+ Self {
+ credit: burst * Self::UNIT,
+ last: now,
+ }
+ }
+
+ fn replenished(self, now: Tick, per_second: u64, burst: u64) -> Result<Self> {
+ let elapsed = now.elapsed_since(self.last)?.as_nanos();
+ let added = elapsed.saturating_mul(u128::from(per_second));
+ let credit = (u128::from(self.credit) + added).min(u128::from(burst * Self::UNIT));
+ Ok(Self {
+ credit: credit as u64,
+ last: now,
+ })
+ }
+}
+
+struct Usage {
+ bytes: usize,
+ requests: usize,
+ rate: Rate,
+ output: Rate,
+}
+
+struct State {
+ total: Usage,
+ routes: HashMap<Id, Usage>,
+}
+
+struct Shared {
+ clock: Arc<dyn Clock>,
+ state: Mutex<State>,
+}
+
+#[derive(Clone)]
+pub struct Budgets {
+ shared: Arc<Shared>,
+}
+
+impl Budgets {
+ pub fn process() -> Result<Self> {
+ static BUDGETS: std::sync::OnceLock<Result<Budgets>> = std::sync::OnceLock::new();
+ BUDGETS.get_or_init(Self::new).clone()
+ }
+
+ pub fn new() -> Result<Self> {
+ Self::with_clock(SystemClock::shared())
+ }
+
+ pub(crate) fn with_clock(clock: Arc<dyn Clock>) -> Result<Self> {
+ let now = clock.now()?;
+ Ok(Self {
+ shared: Arc::new(Shared {
+ clock,
+ state: Mutex::new(State {
+ total: Usage {
+ bytes: 0,
+ requests: 0,
+ rate: Rate::new(now, 80),
+ output: Rate::new(now, 8 * 1024 * 1024),
+ },
+ routes: HashMap::new(),
+ }),
+ }),
+ })
+ }
+
+ pub fn open_route(&self, id: Id) -> Result<RouteBudget> {
+ let mut state = self.shared.state.lock().map_err(|_| Error::Unavailable)?;
+ if state.routes.len() >= MAX_ROUTES || state.routes.contains_key(&id) {
+ return Err(Error::Busy);
+ }
+ let now = self.shared.clock.now()?;
+ state.routes.insert(
+ id,
+ Usage {
+ bytes: 0,
+ requests: 0,
+ rate: Rate::new(now, 20),
+ output: Rate::new(now, 2 * 1024 * 1024),
+ },
+ );
+ Ok(RouteBudget {
+ inner: Arc::new(RouteInner {
+ id,
+ shared: self.shared.clone(),
+ }),
+ })
+ }
+
+ pub fn retained(&self) -> Result<(usize, usize)> {
+ let state = self.shared.state.lock().map_err(|_| Error::Unavailable)?;
+ Ok((state.total.requests, state.total.bytes))
+ }
+}
+
+struct RouteInner {
+ id: Id,
+ shared: Arc<Shared>,
+}
+
+impl Drop for RouteInner {
+ fn drop(&mut self) {
+ if let Ok(mut state) = self.shared.state.lock() {
+ if let Some(usage) = state.routes.remove(&self.id) {
+ debug_assert_eq!((usage.requests, usage.bytes), (0, 0));
+ }
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct RouteBudget {
+ inner: Arc<RouteInner>,
+}
+
+impl RouteBudget {
+ pub fn charge_output(&self, bytes: usize) -> Result<()> {
+ let mut state = self
+ .inner
+ .shared
+ .state
+ .lock()
+ .map_err(|_| Error::Unavailable)?;
+ let now = self.inner.shared.clock.now()?;
+ let route = state.routes.get(&self.inner.id).ok_or(Error::Unavailable)?;
+ let route_rate = route
+ .output
+ .replenished(now, 2 * 1024 * 1024, 2 * 1024 * 1024)?;
+ let global_rate = state
+ .total
+ .output
+ .replenished(now, 8 * 1024 * 1024, 8 * 1024 * 1024)?;
+ let cost = u64::try_from(bytes)
+ .ok()
+ .and_then(|n| n.checked_mul(Rate::UNIT))
+ .ok_or(Error::TooLarge)?;
+ if cost > route_rate.credit || cost > global_rate.credit {
+ return Err(Error::Busy);
+ }
+ state
+ .routes
+ .get_mut(&self.inner.id)
+ .ok_or(Error::Unavailable)?
+ .output = Rate {
+ credit: route_rate.credit - cost,
+ ..route_rate
+ };
+ state.total.output = Rate {
+ credit: global_rate.credit - cost,
+ ..global_rate
+ };
+ Ok(())
+ }
+
+ /// Acquired before a request allocates or queues its payload. Retain
+ /// this reservation through encoding and the last pending send.
+ pub fn acquire(&self, bytes: usize) -> Result<Reservation> {
+ if bytes > ROUTE_BYTES {
+ return Err(Error::TooLarge);
+ }
+ let mut state = self
+ .inner
+ .shared
+ .state
+ .lock()
+ .map_err(|_| Error::Unavailable)?;
+ let route = state.routes.get(&self.inner.id).ok_or(Error::Unavailable)?;
+ if route.requests >= ROUTE_REQUESTS
+ || state.total.requests >= PROCESS_REQUESTS
+ || bytes > ROUTE_BYTES - route.bytes
+ || bytes > PROCESS_BYTES - state.total.bytes
+ {
+ return Err(Error::Busy);
+ }
+ let now = self.inner.shared.clock.now()?;
+ let global_rate = state.total.rate.replenished(now, 40, 80)?;
+ let route_rate = route.rate.replenished(now, 10, 20)?;
+ if global_rate.credit < Rate::UNIT || route_rate.credit < Rate::UNIT {
+ return Err(Error::Busy);
+ }
+ let route = state
+ .routes
+ .get_mut(&self.inner.id)
+ .ok_or(Error::Unavailable)?;
+ route.rate = Rate {
+ credit: route_rate.credit - Rate::UNIT,
+ ..route_rate
+ };
+ route.bytes += bytes;
+ route.requests += 1;
+ state.total.rate = Rate {
+ credit: global_rate.credit - Rate::UNIT,
+ ..global_rate
+ };
+ state.total.bytes += bytes;
+ state.total.requests += 1;
+ Ok(Reservation {
+ route: self.inner.clone(),
+ bytes,
+ })
+ }
+}
+
+pub struct Reservation {
+ route: Arc<RouteInner>,
+ bytes: usize,
+}
+
+impl Reservation {
+ /// Copies and encoded output need their own bytes, without releasing
+ /// the original request's concurrency slot.
+ pub fn grow(&mut self, additional: usize) -> Result<()> {
+ let mut state = self
+ .route
+ .shared
+ .state
+ .lock()
+ .map_err(|_| Error::Unavailable)?;
+ let route = state.routes.get(&self.route.id).ok_or(Error::Unavailable)?;
+ if additional > ROUTE_BYTES - route.bytes || additional > PROCESS_BYTES - state.total.bytes
+ {
+ return Err(Error::Busy);
+ }
+ state
+ .routes
+ .get_mut(&self.route.id)
+ .ok_or(Error::Unavailable)?
+ .bytes += additional;
+ state.total.bytes += additional;
+ self.bytes += additional;
+ Ok(())
+ }
+
+ pub fn release_bytes(&mut self, bytes: usize) -> Result<()> {
+ if bytes > self.bytes {
+ return Err(Error::Protocol);
+ }
+ let mut state = self
+ .route
+ .shared
+ .state
+ .lock()
+ .map_err(|_| Error::Unavailable)?;
+ state
+ .routes
+ .get_mut(&self.route.id)
+ .ok_or(Error::Unavailable)?
+ .bytes -= bytes;
+ state.total.bytes -= bytes;
+ self.bytes -= bytes;
+ Ok(())
+ }
+
+ pub fn bytes(&self) -> usize {
+ self.bytes
+ }
+}
+
+impl Drop for Reservation {
+ fn drop(&mut self) {
+ if let Ok(mut state) = self.route.shared.state.lock() {
+ if let Some(route) = state.routes.get_mut(&self.route.id) {
+ route.bytes -= self.bytes;
+ route.requests -= 1;
+ state.total.bytes -= self.bytes;
+ state.total.requests -= 1;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn queued_output_keeps_its_request_and_byte_budget() {
+ let budgets = Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([1; 16])).unwrap();
+ let mut held = route.acquire(1024).unwrap();
+ held.grow(2048).unwrap();
+ drop(route);
+ assert_eq!(budgets.retained().unwrap(), (1, 3072));
+ held.release_bytes(1024).unwrap();
+ assert_eq!(budgets.retained().unwrap(), (1, 2048));
+ drop(held);
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ assert!(budgets.open_route(Id::from_bytes([1; 16])).is_ok());
+ }
+
+ #[test]
+ fn route_and_process_limits_apply_before_allocation() {
+ let budgets = Budgets::new().unwrap();
+ let routes: Vec<_> = (0..5)
+ .map(|id| budgets.open_route(Id::from_bytes([id; 16])).unwrap())
+ .collect();
+ let mut held = vec![];
+ for route in &routes[..4] {
+ for _ in 0..ROUTE_REQUESTS {
+ held.push(route.acquire(1024 * 1024).unwrap());
+ }
+ assert!(matches!(route.acquire(1), Err(Error::Busy)));
+ }
+ assert_eq!(budgets.retained().unwrap(), (32, PROCESS_BYTES));
+ assert!(matches!(routes[4].acquire(1), Err(Error::Busy)));
+ assert!(matches!(held[0].grow(1), Err(Error::Busy)));
+ drop(held);
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ }
+
+ #[test]
+ fn short_requests_do_not_evade_rate_limits() {
+ let budgets = Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([1; 16])).unwrap();
+ for _ in 0..20 {
+ drop(route.acquire(0).unwrap());
+ }
+ assert!(matches!(route.acquire(0), Err(Error::Busy)));
+ }
+}
diff --git a/thinkterm-reverse-access/src/channel.rs b/thinkterm-reverse-access/src/channel.rs
new file mode 100644
index 00000000..4d2888d8
--- /dev/null
+++ b/thinkterm-reverse-access/src/channel.rs
@@ -0,0 +1,496 @@
+use crate::budget::Reservation;
+use crate::clock::{Clock, SystemClock, Tick};
+use crate::wire::{Decoder, Frame, Kind, MAX_FRAME};
+use crate::{Error, Result};
+use futures::future::poll_fn;
+use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite};
+use serde::{de::DeserializeOwned, Serialize};
+use smol::future::FutureExt;
+use std::io::{self, Write};
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+use std::task::{Context, Poll};
+use std::time::Duration;
+
+#[derive(Clone)]
+pub struct Deadline {
+ clock: Arc<dyn Clock>,
+ end: Tick,
+ last: Arc<Mutex<Tick>>,
+}
+
+/// Kept back at each forwarding stage, so that whatever a request ran out of
+/// time on can still be answered: a serial channel needs its reply.
+pub const REPLY_MARGIN: Duration = Duration::from_millis(500);
+
+impl Deadline {
+ pub fn after(duration: Duration) -> Result<Self> {
+ let clock = SystemClock::shared();
+ let now = clock.now()?;
+ Ok(Self {
+ clock,
+ end: now.after(duration)?,
+ last: Arc::new(Mutex::new(now)),
+ })
+ }
+
+ pub fn request() -> Result<Self> {
+ Self::after(Duration::from_secs(crate::REQUEST_TIMEOUT_SECS))
+ }
+
+ /// This deadline, `margin` sooner.
+ pub fn earlier(&self, margin: Duration) -> Result<Self> {
+ Self::after(
+ self.remaining()?
+ .checked_sub(margin)
+ .filter(|left| !left.is_zero())
+ .ok_or(Error::Timeout)?,
+ )
+ }
+
+ pub fn remaining(&self) -> Result<Duration> {
+ let now = self.clock.now()?;
+ let mut last = self.last.lock().map_err(|_| Error::Clock)?;
+ if now < *last {
+ return Err(Error::Clock);
+ }
+ *last = now;
+ if now >= self.end {
+ return Err(Error::Timeout);
+ }
+ self.end.elapsed_since(now)
+ }
+
+ pub async fn run<T>(&self, future: impl std::future::Future<Output = Result<T>>) -> Result<T> {
+ let remaining = self.remaining()?;
+ let result = future
+ .or(async {
+ smol::Timer::after(remaining).await;
+ Err(Error::Timeout)
+ })
+ .await;
+ self.remaining()?;
+ result
+ }
+
+ /// Busy means this attempt did no work. Yield before retrying the
+ /// guarded operation, without restarting the request's deadline.
+ pub async fn retry_busy<T>(
+ &self,
+ mut operation: impl FnMut(&mut Context<'_>) -> Poll<Result<T>>,
+ ) -> Result<T> {
+ self.run(async {
+ loop {
+ let result = poll_fn(|cx| {
+ if let Err(error) = self.remaining() {
+ return Poll::Ready(Err(error));
+ }
+ operation(cx)
+ })
+ .await;
+ match result {
+ Err(Error::Busy) => {
+ smol::Timer::after(Duration::from_millis(1)).await;
+ }
+ result => return result,
+ }
+ }
+ })
+ .await
+ }
+}
+
+/// A single bounded receive buffer and frame decoder. The reservation also
+/// accounts for JSON collections and outgoing frame copies. It survives
+/// every read and write for this connection's lifetime.
+pub struct Channel<S> {
+ stream: SharedStream<S>,
+ decoder: Decoder,
+ buffer: [u8; 8192],
+ start: usize,
+ end: usize,
+ frame_deadline: Option<Deadline>,
+ clock: Arc<dyn Clock>,
+ _reservation: Reservation,
+}
+
+impl<S: AsyncRead + AsyncWrite + Unpin> Channel<S> {
+ pub fn new(stream: S, reservation: Reservation) -> Result<Self> {
+ if reservation.bytes() < 1024 * 1024 {
+ return Err(Error::Protocol);
+ }
+ Ok(Self {
+ stream: SharedStream(Arc::new(Mutex::new(stream))),
+ decoder: Decoder::default(),
+ buffer: [0; 8192],
+ start: 0,
+ end: 0,
+ frame_deadline: None,
+ clock: SystemClock::shared(),
+ _reservation: reservation,
+ })
+ }
+
+ /// With no request deadline, an entirely idle channel sleeps until its
+ /// first byte. A partial frame always has a five-second total deadline.
+ pub async fn read(&mut self, deadline: Option<&Deadline>) -> Result<Frame> {
+ loop {
+ if let Some(deadline) = deadline {
+ deadline.remaining()?;
+ }
+ if let Some(frame) = &self.frame_deadline {
+ frame.remaining()?;
+ }
+ if self.start == self.end {
+ let stream = &mut self.stream;
+ let buffer = &mut self.buffer;
+ let read = async { stream.read(buffer).await.map_err(|_| Error::Unavailable) };
+ let request_remaining = deadline.map(Deadline::remaining).transpose()?;
+ let frame_remaining = self
+ .frame_deadline
+ .as_ref()
+ .map(Deadline::remaining)
+ .transpose()?;
+ let timeout = match (request_remaining, frame_remaining) {
+ (Some(a), Some(b)) => Some(a.min(b)),
+ (a, b) => a.or(b),
+ };
+ self.end = if let Some(timeout) = timeout {
+ read.or(async {
+ smol::Timer::after(timeout).await;
+ Err(Error::Timeout)
+ })
+ .await?
+ } else {
+ read.await?
+ };
+ self.start = 0;
+ if self.end == 0 {
+ return Err(Error::Unavailable);
+ }
+ }
+ if self.decoder.is_idle() && self.frame_deadline.is_none() {
+ self.frame_deadline = Some(Deadline::after(Duration::from_secs(5))?);
+ }
+ if let Some(deadline) = deadline {
+ deadline.remaining()?;
+ }
+ self.frame_deadline
+ .as_ref()
+ .ok_or(Error::Protocol)?
+ .remaining()?;
+ let (used, frame) = self
+ .decoder
+ .push(&self.buffer[self.start..self.end], self.clock.now()?)?;
+ self.start += used;
+ if let Some(frame) = frame {
+ self.frame_deadline = None;
+ return Ok(frame);
+ }
+ }
+ }
+
+ pub async fn write(&mut self, frame: &Frame, deadline: &Deadline) -> Result<()> {
+ self.write_guarded(frame, deadline, |write| Ok(write()))
+ .await
+ }
+
+ /// The authorization guard encloses each nonblocking poll, including
+ /// retries after Pending. It never authorizes an unchecked future write.
+ pub async fn write_guarded<G>(
+ &mut self,
+ frame: &Frame,
+ deadline: &Deadline,
+ mut guard: G,
+ ) -> Result<()>
+ where
+ G: FnMut(&mut dyn FnMut() -> Poll<io::Result<usize>>) -> Result<Poll<io::Result<usize>>>,
+ {
+ let header = frame.header();
+ for part in [&header[..], frame.body()] {
+ let mut offset = 0;
+ while offset < part.len() {
+ let count = deadline
+ .retry_busy(|cx| {
+ match guard(&mut || {
+ Pin::new(&mut self.stream).poll_write(cx, &part[offset..])
+ }) {
+ Ok(Poll::Pending) => Poll::Pending,
+ Ok(Poll::Ready(Ok(count))) if count > 0 => Poll::Ready(Ok(count)),
+ Ok(Poll::Ready(_)) => Poll::Ready(Err(Error::Unavailable)),
+ Err(error) => Poll::Ready(Err(error)),
+ }
+ })
+ .await?;
+ if count > part.len() - offset {
+ return Err(Error::Protocol);
+ }
+ offset += count;
+ }
+ }
+ Ok(())
+ }
+
+ pub async fn write_json<T: Serialize>(
+ &mut self,
+ kind: Kind,
+ sequence: u64,
+ value: &T,
+ deadline: &Deadline,
+ ) -> Result<()> {
+ self.write(&json_frame(kind, sequence, value)?, deadline)
+ .await
+ }
+
+ /// Business exchanges are serial. After receiving the complete request,
+ /// any further byte is a protocol violation; EOF cancels the operation.
+ pub fn watch_peer(&self) -> PeerWatch<S> {
+ PeerWatch {
+ stream: SharedStream(Arc::clone(&self.stream.0)),
+ buffered: self.start != self.end,
+ }
+ }
+}
+
+struct SharedStream<S>(Arc<Mutex<S>>);
+
+impl<S: AsyncRead + Unpin> AsyncRead for SharedStream<S> {
+ fn poll_read(
+ self: Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ bytes: &mut [u8],
+ ) -> Poll<io::Result<usize>> {
+ match self.0.lock() {
+ Ok(mut stream) => Pin::new(&mut *stream).poll_read(cx, bytes),
+ Err(_) => Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
+ }
+ }
+}
+
+impl<S: AsyncWrite + Unpin> AsyncWrite for SharedStream<S> {
+ fn poll_write(
+ self: Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ match self.0.lock() {
+ Ok(mut stream) => Pin::new(&mut *stream).poll_write(cx, bytes),
+ Err(_) => Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
+ }
+ }
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<io::Result<()>> {
+ match self.0.lock() {
+ Ok(mut stream) => Pin::new(&mut *stream).poll_flush(cx),
+ Err(_) => Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
+ }
+ }
+ fn poll_close(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<io::Result<()>> {
+ match self.0.lock() {
+ Ok(mut stream) => Pin::new(&mut *stream).poll_close(cx),
+ Err(_) => Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
+ }
+ }
+}
+
+pub struct PeerWatch<S> {
+ stream: SharedStream<S>,
+ buffered: bool,
+}
+
+impl<S: AsyncRead + Unpin> std::future::Future for PeerWatch<S> {
+ type Output = Result<()>;
+ fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
+ if self.buffered {
+ return Poll::Ready(Err(Error::Protocol));
+ }
+ match Pin::new(&mut self.stream).poll_read(cx, &mut [0; 1]) {
+ Poll::Pending => Poll::Pending,
+ Poll::Ready(Ok(count)) if count > 0 => Poll::Ready(Err(Error::Protocol)),
+ Poll::Ready(_) => Poll::Ready(Err(Error::Unavailable)),
+ }
+ }
+}
+
+pub fn json_frame<T: Serialize>(kind: Kind, sequence: u64, value: &T) -> Result<Frame> {
+ struct Bounded(Vec<u8>);
+ impl Write for Bounded {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ if bytes.len() > MAX_FRAME - self.0.len() {
+ return Err(io::ErrorKind::InvalidInput.into());
+ }
+ self.0.extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+ let mut output = Bounded(Vec::with_capacity(MAX_FRAME));
+ serde_json::to_writer(&mut output, value).map_err(|_| Error::TooLarge)?;
+ Frame::new(kind, sequence, &output.0)
+}
+
+pub fn parse<T: DeserializeOwned>(frame: &Frame, kind: Kind, sequence: u64) -> Result<T> {
+ if frame.kind() != kind || frame.sequence() != sequence {
+ return Err(Error::Protocol);
+ }
+ serde_json::from_slice(frame.body()).map_err(|_| Error::Protocol)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::budget::Budgets;
+ use crate::Id;
+
+ struct Partial(Vec<u8>);
+ impl AsyncRead for Partial {
+ fn poll_read(
+ self: Pin<&mut Self>,
+ _: &mut std::task::Context<'_>,
+ _: &mut [u8],
+ ) -> Poll<io::Result<usize>> {
+ Poll::Pending
+ }
+ }
+ impl AsyncWrite for Partial {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ _: &mut std::task::Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ self.0.push(bytes[0]);
+ Poll::Ready(Ok(1))
+ }
+ fn poll_flush(
+ self: Pin<&mut Self>,
+ _: &mut std::task::Context<'_>,
+ ) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ fn poll_close(
+ self: Pin<&mut Self>,
+ _: &mut std::task::Context<'_>,
+ ) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ }
+ fn channel() -> Channel<Partial> {
+ let budgets = Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([1; 16])).unwrap();
+ Channel::new(Partial(vec![]), route.acquire(1024 * 1024).unwrap()).unwrap()
+ }
+
+ #[test]
+ fn an_earlier_deadline_ends_sooner_and_never_outlives_its_own() {
+ let deadline = Deadline::after(Duration::from_secs(10)).unwrap();
+ let earlier = deadline.earlier(Duration::from_secs(4)).unwrap();
+ assert!(earlier.remaining().unwrap() <= Duration::from_secs(6));
+ assert!(earlier.remaining().unwrap() < deadline.remaining().unwrap());
+ assert!(matches!(
+ deadline.earlier(Duration::from_secs(11)),
+ Err(Error::Timeout)
+ ));
+ }
+
+ #[test]
+ fn transient_guard_contention_resumes_partial_frames_without_duplication() {
+ let mut channel = channel();
+ let frame = Frame::new(Kind::Reply, 1, b"example text").unwrap();
+ let mut checks = 0;
+ let result =
+ smol::block_on(
+ channel.write_guarded(&frame, &Deadline::request().unwrap(), |write| {
+ checks += 1;
+ if [1, 5, 25].contains(&checks) {
+ Err(Error::Busy)
+ } else {
+ Ok(write())
+ }
+ }),
+ );
+ assert_eq!(result, Ok(()));
+ let mut expected = frame.header().to_vec();
+ expected.extend_from_slice(frame.body());
+ assert_eq!(channel.stream.0.lock().unwrap().0, expected);
+ assert_eq!(checks, expected.len() + 3);
+ }
+
+ #[test]
+ fn a_busy_guard_rechecks_revocation_and_other_terminal_failures() {
+ for error in [
+ Error::Revoked,
+ Error::Unavailable,
+ Error::Clock,
+ Error::Timeout,
+ ] {
+ let mut channel = channel();
+ let frame = Frame::new(Kind::Reply, 1, b"example text").unwrap();
+ let mut checks = 0;
+ let result = smol::block_on(channel.write_guarded(
+ &frame,
+ &Deadline::request().unwrap(),
+ |write| {
+ checks += 1;
+ match checks {
+ 1 | 2 => Ok(write()),
+ 3 => Err(Error::Busy),
+ _ => Err(error),
+ }
+ },
+ ));
+ assert_eq!(result, Err(error));
+ assert_eq!(channel.stream.0.lock().unwrap().0, &frame.header()[..2]);
+ assert_eq!(checks, 4);
+ }
+ }
+
+ #[test]
+ fn repeated_contention_cannot_restart_the_request_deadline() {
+ use std::sync::atomic::{AtomicU64, Ordering};
+ struct TestClock(AtomicU64);
+ impl Clock for TestClock {
+ fn now(&self) -> Result<Tick> {
+ Ok(Tick::seconds(self.0.load(Ordering::Acquire)))
+ }
+ }
+ let clock = Arc::new(TestClock(AtomicU64::new(0)));
+ let deadline = Deadline {
+ clock: clock.clone(),
+ end: Tick::seconds(10),
+ last: Arc::new(Mutex::new(Tick::seconds(0))),
+ };
+ let mut channel = channel();
+ let frame = Frame::new(Kind::Reply, 1, b"example text").unwrap();
+ let mut checks = 0;
+ let result = smol::block_on(channel.write_guarded(&frame, &deadline, |_| {
+ checks += 1;
+ clock.0.store(8 + checks, Ordering::Release);
+ Err(Error::Busy)
+ }));
+ assert_eq!(result, Err(Error::Timeout));
+ assert_eq!(checks, 2);
+ assert!(channel.stream.0.lock().unwrap().0.is_empty());
+ }
+
+ #[test]
+ fn revocation_guard_runs_before_every_partial_transport_write() {
+ let mut channel = channel();
+ let frame = Frame::new(Kind::Reply, 1, b"private text").unwrap();
+ let mut checks = 0;
+ let result =
+ smol::block_on(
+ channel.write_guarded(&frame, &Deadline::request().unwrap(), |write| {
+ checks += 1;
+ if checks > 3 {
+ Err(Error::Revoked)
+ } else {
+ Ok(write())
+ }
+ }),
+ );
+ assert_eq!(result, Err(Error::Revoked));
+ assert_eq!(channel.stream.0.lock().unwrap().0.len(), 3);
+ assert_eq!(checks, 4);
+ }
+}
diff --git a/thinkterm-reverse-access/src/clock.rs b/thinkterm-reverse-access/src/clock.rs
new file mode 100644
index 00000000..cfcec235
--- /dev/null
+++ b/thinkterm-reverse-access/src/clock.rs
@@ -0,0 +1,71 @@
+use crate::{Error, Result};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// Time in the executor's clock domain. Values never travel on the wire.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Tick(Duration);
+
+impl Tick {
+ pub fn after(self, duration: Duration) -> Result<Self> {
+ self.0.checked_add(duration).map(Self).ok_or(Error::Clock)
+ }
+
+ pub fn elapsed_since(self, earlier: Self) -> Result<Duration> {
+ self.0.checked_sub(earlier.0).ok_or(Error::Clock)
+ }
+
+ #[cfg(test)]
+ pub(crate) fn seconds(value: u64) -> Self {
+ Self(Duration::from_secs(value))
+ }
+}
+
+pub trait Clock: Send + Sync {
+ fn now(&self) -> Result<Tick>;
+}
+
+pub struct SystemClock {
+ #[cfg(windows)]
+ started: std::time::Instant,
+}
+
+impl SystemClock {
+ pub fn shared() -> Arc<dyn Clock> {
+ Arc::new(Self {
+ #[cfg(windows)]
+ started: std::time::Instant::now(),
+ })
+ }
+}
+
+impl Clock for SystemClock {
+ fn now(&self) -> Result<Tick> {
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
+ {
+ use nix::time::{clock_gettime, ClockId};
+ #[cfg(target_os = "macos")]
+ let clock = ClockId::from_raw(nix::libc::CLOCK_MONOTONIC_RAW);
+ #[cfg(target_os = "linux")]
+ let clock = ClockId::CLOCK_BOOTTIME;
+ let value = clock_gettime(clock).map_err(|_| Error::Clock)?;
+ let seconds = u64::try_from(value.tv_sec()).map_err(|_| Error::Clock)?;
+ let nanos = u32::try_from(value.tv_nsec()).map_err(|_| Error::Clock)?;
+ if nanos >= 1_000_000_000 {
+ return Err(Error::Clock);
+ }
+ Ok(Tick(Duration::new(seconds, nanos)))
+ }
+ #[cfg(windows)]
+ {
+ // Rust's Windows Instant uses QueryPerformanceCounter. Windows
+ // includes sleep in QPC; this is not assumed for other targets.
+ std::time::Instant::now()
+ .checked_duration_since(self.started)
+ .map(Tick)
+ .ok_or(Error::Clock)
+ }
+ #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
+ Err(Error::Clock)
+ }
+}
diff --git a/thinkterm-reverse-access/src/exchange.rs b/thinkterm-reverse-access/src/exchange.rs
new file mode 100644
index 00000000..f2d2a36f
--- /dev/null
+++ b/thinkterm-reverse-access/src/exchange.rs
@@ -0,0 +1,305 @@
+use crate::budget::RouteBudget;
+use crate::channel::{parse, Channel, Deadline};
+use crate::protocol::{Command, Reply};
+use crate::wire::{Assembly, Frame, Kind, Payload, MAX_BLOCK};
+use crate::{Error, Result, MAX_READ_BYTES};
+use futures::io::{AsyncRead, AsyncWrite};
+
+/// The outer `Result` of these functions is the channel's: after an error it
+/// is out of step with its peer and has to close. This inner one is the
+/// request's: the request's frames were consumed, so the channel carries on
+/// and only that request is refused.
+pub type Refusable<T> = std::result::Result<T, Error>;
+
+pub async fn receive_input<S: AsyncRead + AsyncWrite + Unpin>(
+ channel: &mut Channel<S>,
+ command: &Command,
+ sequence: u64,
+ budget: &RouteBudget,
+ deadline: &Deadline,
+) -> Result<Refusable<Option<Payload>>> {
+ command.validate()?;
+ match command {
+ Command::Text { bytes, .. } => Ok(receive_payload(
+ channel,
+ *bytes,
+ sequence,
+ Kind::InputBlock,
+ Assembly::input(*bytes, budget),
+ deadline,
+ )
+ .await?
+ .map(Some)),
+ _ => Ok(Ok(None)),
+ }
+}
+
+pub async fn receive_reply<S: AsyncRead + AsyncWrite + Unpin>(
+ channel: &mut Channel<S>,
+ sequence: u64,
+ reserve: impl FnOnce(usize) -> Result<Assembly>,
+ deadline: &Deadline,
+) -> Result<Refusable<(Reply, Option<Payload>)>> {
+ let reply: Reply = parse(&channel.read(Some(deadline)).await?, Kind::Reply, sequence)?;
+ let payload = match &reply {
+ Reply::Text { bytes } => {
+ if *bytes > MAX_READ_BYTES {
+ return Err(Error::Protocol);
+ }
+ match receive_payload(
+ channel,
+ *bytes,
+ sequence,
+ Kind::TextBlock,
+ reserve(*bytes),
+ deadline,
+ )
+ .await?
+ {
+ Ok(payload) => Some(payload),
+ Err(error) => return Ok(Err(error)),
+ }
+ }
+ Reply::List { exports, .. } => {
+ if exports.len() > 32
+ || exports.iter().any(|item| {
+ item.name.len() > 128
+ || item.title.len() > 1024
+ || item.remaining_ms > crate::MAX_DURATION_SECS * 1000
+ || crate::protocol::display_text(&item.name, 128) != item.name
+ || crate::protocol::display_text(&item.title, 1024) != item.title
+ })
+ {
+ return Err(Error::Protocol);
+ }
+ None
+ }
+ _ => None,
+ };
+ Ok(Ok((reply, payload)))
+}
+
+/// Consume the rest of a reply whose text is not wanted, to stay in step.
+pub async fn discard_text<S: AsyncRead + AsyncWrite + Unpin>(
+ channel: &mut Channel<S>,
+ mut received: usize,
+ total: usize,
+ sequence: u64,
+ deadline: &Deadline,
+) -> Result<()> {
+ while received < total {
+ let frame = channel.read(Some(deadline)).await?;
+ match next_block(&frame, Kind::TextBlock, sequence, received, total)? {
+ Some(bytes) => received += bytes.len(),
+ None => break,
+ }
+ }
+ Ok(())
+}
+
+/// The bytes of the next block of a payload, checked against what came
+/// before them. None is a sender giving up on its text between two blocks.
+pub fn next_block<'a>(
+ frame: &'a Frame,
+ kind: Kind,
+ sequence: u64,
+ received: usize,
+ total: usize,
+) -> Result<Option<&'a [u8]>> {
+ if kind == Kind::TextBlock
+ && frame.kind() == Kind::Cancel
+ && frame.sequence() == sequence
+ && frame.body().is_empty()
+ {
+ return Ok(None);
+ }
+ if frame.kind() != kind || frame.sequence() != sequence || frame.body().len() <= 4 {
+ return Err(Error::Protocol);
+ }
+ let offset =
+ u32::from_be_bytes(frame.body()[..4].try_into().map_err(|_| Error::Protocol)?) as usize;
+ let bytes = &frame.body()[4..];
+ if offset != received || bytes.len() > total - received {
+ return Err(Error::Protocol);
+ }
+ Ok(Some(bytes))
+}
+
+/// A refused `assembly` still reads every block, into nothing.
+async fn receive_payload<S: AsyncRead + AsyncWrite + Unpin>(
+ channel: &mut Channel<S>,
+ total: usize,
+ sequence: u64,
+ kind: Kind,
+ mut assembly: Refusable<Assembly>,
+ deadline: &Deadline,
+) -> Result<Refusable<Payload>> {
+ let mut received = 0;
+ while received < total {
+ let frame = channel.read(Some(deadline)).await?;
+ let Some(bytes) = next_block(&frame, kind, sequence, received, total)? else {
+ return Ok(Err(Error::Unavailable));
+ };
+ if let Ok(assembly) = &mut assembly {
+ assembly.append(received, bytes)?;
+ }
+ received += bytes.len();
+ }
+ match assembly {
+ Ok(assembly) => Ok(Ok(assembly.finish()?)),
+ Err(error) => Ok(Err(error)),
+ }
+}
+
+pub async fn send_payload<S: AsyncRead + AsyncWrite + Unpin>(
+ channel: &mut Channel<S>,
+ bytes: &[u8],
+ sequence: u64,
+ kind: Kind,
+ deadline: &Deadline,
+) -> Result<()> {
+ let limit = if kind == Kind::InputBlock {
+ crate::MAX_INPUT_BYTES
+ } else if kind == Kind::TextBlock {
+ crate::MAX_READ_BYTES
+ } else {
+ return Err(Error::Protocol);
+ };
+ if bytes.len() > limit {
+ return Err(Error::TooLarge);
+ }
+ for (index, block) in bytes.chunks(MAX_BLOCK).enumerate() {
+ let mut body = Vec::with_capacity(block.len() + 4);
+ body.extend_from_slice(&((index * MAX_BLOCK) as u32).to_be_bytes());
+ body.extend_from_slice(block);
+ channel
+ .write(&Frame::new(kind, sequence, &body)?, deadline)
+ .await?;
+ }
+ Ok(())
+}
+
+#[cfg(all(test, unix))]
+mod tests {
+ use super::*;
+ use crate::budget::Budgets;
+ use crate::channel::Deadline;
+ use crate::Id;
+ use std::os::unix::net::UnixStream;
+
+ type Pair = (
+ Channel<smol::Async<UnixStream>>,
+ Channel<smol::Async<UnixStream>>,
+ );
+
+ fn pair(budget: &RouteBudget) -> Pair {
+ let (near, far) = smol::Async::<UnixStream>::pair().unwrap();
+ (
+ Channel::new(near, budget.acquire(1024 * 1024).unwrap()).unwrap(),
+ Channel::new(far, budget.acquire(1024 * 1024).unwrap()).unwrap(),
+ )
+ }
+
+ fn text_reply(bytes: usize) -> Reply {
+ Reply::Text { bytes }
+ }
+
+ #[test]
+ fn a_refused_payload_is_consumed_so_the_next_frame_is_read_in_step() {
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+ let (mut near, mut far) = pair(&budget);
+ let deadline = Deadline::request().unwrap();
+ let text = "example".repeat(10_000);
+ smol::block_on(async {
+ let send = async {
+ near.write_json(Kind::Reply, 1, &text_reply(text.len()), &deadline)
+ .await?;
+ send_payload(&mut near, text.as_bytes(), 1, Kind::TextBlock, &deadline).await?;
+ near.write_json(Kind::Reply, 2, &text_reply(0), &deadline)
+ .await
+ };
+ let receive = async {
+ let refused = receive_reply(&mut far, 1, |_| Err(Error::Busy), &deadline).await?;
+ let next = receive_reply(
+ &mut far,
+ 2,
+ |bytes| Assembly::text(bytes, &budget),
+ &deadline,
+ )
+ .await?;
+ Ok::<_, Error>((refused, next))
+ };
+ let (sent, received) = smol::future::zip(send, receive).await;
+ sent.unwrap();
+ let (refused, next) = received.unwrap();
+ assert_eq!(refused.err(), Some(Error::Busy));
+ assert!(next.is_ok());
+ });
+ }
+
+ #[test]
+ fn a_sender_can_give_up_between_blocks_without_losing_the_channel() {
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+ let (mut near, mut far) = pair(&budget);
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ near.write_json(Kind::Reply, 1, &text_reply(100_000), &deadline)
+ .await
+ .unwrap();
+ send_payload(&mut near, &[b'x'; 100], 1, Kind::TextBlock, &deadline)
+ .await
+ .unwrap();
+ near.write(&Frame::new(Kind::Cancel, 1, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ let received = receive_reply(
+ &mut far,
+ 1,
+ |bytes| Assembly::text(bytes, &budget),
+ &deadline,
+ )
+ .await
+ .unwrap();
+ assert_eq!(received.err(), Some(Error::Unavailable));
+ });
+ // The reservation of the abandoned text went with it.
+ assert_eq!(budgets.retained().unwrap().0, 2);
+ }
+
+ #[test]
+ fn a_reply_joins_its_requests_reservation_without_a_new_slot_or_rate_charge() {
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+ for _ in 0..19 {
+ drop(budget.acquire(0).unwrap());
+ }
+ let request = budget.acquire(64).unwrap();
+ // The rate limit is spent; the request it paid for still gets through.
+ assert!(matches!(budget.acquire(0), Err(Error::Busy)));
+ let assembly = Assembly::reply_text(1024, request).unwrap();
+ assert_eq!(budgets.retained().unwrap(), (1, 1088));
+ drop(assembly);
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ }
+
+ #[test]
+ fn a_block_out_of_place_is_a_protocol_error_even_when_discarding() {
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::random().unwrap()).unwrap();
+ let (mut near, mut far) = pair(&budget);
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut body = 7u32.to_be_bytes().to_vec();
+ body.extend_from_slice(b"example");
+ near.write(&Frame::new(Kind::TextBlock, 1, &body).unwrap(), &deadline)
+ .await
+ .unwrap();
+ assert_eq!(
+ discard_text(&mut far, 0, 100, 1, &deadline).await,
+ Err(Error::Protocol)
+ );
+ });
+ }
+}
diff --git a/thinkterm-reverse-access/src/ipc.rs b/thinkterm-reverse-access/src/ipc.rs
new file mode 100644
index 00000000..077321e0
--- /dev/null
+++ b/thinkterm-reverse-access/src/ipc.rs
@@ -0,0 +1,495 @@
+//! Local transport only. Peer metadata is an admission check, never proof
+//! that native authentication succeeded. Approval stays in the actual host.
+
+use crate::{Error, Result};
+use futures::io::{AsyncRead, AsyncWrite};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::pin::Pin;
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+pub fn random_name() -> Result<String> {
+ let mut bytes = [0; 16];
+ getrandom::fill(&mut bytes).map_err(|_| Error::Random)?;
+ Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
+}
+
+struct ListenerInner {
+ listener: Option<platform::Listener>,
+ directory: Option<PathBuf>,
+}
+
+impl Drop for ListenerInner {
+ fn drop(&mut self) {
+ self.listener.take();
+ if let Some(directory) = &self.directory {
+ let _ = std::fs::remove_file(directory.join("s"));
+ let _ = std::fs::remove_dir(directory);
+ }
+ }
+}
+
+/// The shutdown of most processes is an exit, which runs no destructors, so
+/// a listener's directory usually outlives it. Each new one clears up after
+/// those of this account that nothing answers on any more.
+#[cfg(unix)]
+fn remove_abandoned() {
+ let Ok(entries) = std::fs::read_dir("/tmp") else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let is_listener = name
+ .to_str()
+ .is_some_and(|name| local_name(&format!("/tmp/{name}/s")));
+ if is_listener {
+ remove_if_abandoned(&entry.path(), std::time::Duration::from_secs(60));
+ }
+ }
+}
+
+/// `settled` covers a listener between its bind and its listen.
+#[cfg(unix)]
+fn remove_if_abandoned(directory: &Path, settled: std::time::Duration) {
+ use std::os::unix::fs::{FileTypeExt, MetadataExt};
+ let socket = directory.join("s");
+ let abandoned = std::fs::symlink_metadata(directory).is_ok_and(|metadata| {
+ metadata.is_dir() && metadata.uid() == nix::unistd::geteuid().as_raw()
+ }) && std::fs::symlink_metadata(&socket).is_ok_and(|metadata| {
+ metadata.file_type().is_socket()
+ && metadata
+ .modified()
+ .ok()
+ .and_then(|time| time.elapsed().ok())
+ .is_some_and(|age| age >= settled)
+ }) && matches!(
+ std::os::unix::net::UnixStream::connect(&socket),
+ Err(error) if error.kind() == io::ErrorKind::ConnectionRefused
+ );
+ if abandoned {
+ let _ = std::fs::remove_file(&socket);
+ let _ = std::fs::remove_dir(directory);
+ }
+}
+
+pub struct LocalListener {
+ inner: Arc<ListenerInner>,
+ name: String,
+}
+
+impl LocalListener {
+ pub fn bind() -> Result<Self> {
+ let suffix = random_name()?;
+ #[cfg(unix)]
+ let (name, directory) = {
+ use std::os::unix::fs::DirBuilderExt;
+ let _ = std::thread::Builder::new()
+ .name("connect-stale-sockets".into())
+ .spawn(remove_abandoned);
+ let directory = PathBuf::from(format!("/tmp/tt-connect-{suffix}"));
+ std::fs::DirBuilder::new()
+ .mode(0o700)
+ .create(&directory)
+ .map_err(|_| Error::Unavailable)?;
+ (
+ directory.join("s").to_string_lossy().into_owned(),
+ Some(directory),
+ )
+ };
+ #[cfg(windows)]
+ let (name, directory) = (format!(r"\\.\pipe\ThinkTerm.Connect.{suffix}"), None);
+ let listener = match platform::bind(&name) {
+ Ok(listener) => listener,
+ Err(error) => {
+ if let Some(directory) = directory {
+ let _ = std::fs::remove_dir(directory);
+ }
+ return Err(error);
+ }
+ };
+ Ok(Self {
+ inner: Arc::new(ListenerInner {
+ listener: Some(listener),
+ directory,
+ }),
+ name,
+ })
+ }
+
+ pub fn name(&self) -> &str {
+ &self.name
+ }
+
+ pub async fn accept(&self) -> Result<LocalStream> {
+ platform::accept(Arc::clone(&self.inner)).await
+ }
+}
+
+#[derive(Clone)]
+pub struct Peer {
+ pid: u32,
+}
+
+impl Peer {
+ pub fn pid(&self) -> u32 {
+ self.pid
+ }
+
+ pub fn is_packaged(&self, name: &str) -> bool {
+ let current = match std::env::current_exe().and_then(std::fs::canonicalize) {
+ Ok(path) => path,
+ Err(_) => return false,
+ };
+ let expected = match current
+ .parent()
+ .map(|dir| dir.join(name))
+ .and_then(|path| path.canonicalize().ok())
+ {
+ Some(path) => path,
+ None => return false,
+ };
+ procinfo::LocalProcessInfo::executable_path(self.pid)
+ .and_then(|path| path.canonicalize().ok())
+ .is_some_and(|path| same_image(&path, &expected))
+ }
+}
+
+fn same_image(actual: &Path, expected: &Path) -> bool {
+ actual == expected
+}
+
+pub struct LocalStream {
+ stream: platform::Stream,
+ peer: Peer,
+}
+
+impl LocalStream {
+ fn new(stream: platform::Stream) -> Result<Self> {
+ let peer = platform::peer(&stream)?;
+ if peer.pid == 0 {
+ return Err(Error::Unavailable);
+ }
+ Ok(Self { stream, peer })
+ }
+
+ pub async fn connect(name: &str) -> Result<Self> {
+ if !local_name(name) {
+ return Err(Error::Protocol);
+ }
+ platform::connect(name).await
+ }
+
+ pub fn peer(&self) -> &Peer {
+ &self.peer
+ }
+}
+
+fn local_name(name: &str) -> bool {
+ #[cfg(unix)]
+ let suffix = name
+ .strip_prefix("/tmp/tt-connect-")
+ .and_then(|name| name.strip_suffix("/s"));
+ #[cfg(windows)]
+ let suffix = name.strip_prefix(r"\\.\pipe\ThinkTerm.Connect.");
+ suffix.is_some_and(|suffix| {
+ suffix.len() == 32 && suffix.bytes().all(|byte| byte.is_ascii_hexdigit())
+ })
+}
+
+impl std::fmt::Debug for LocalStream {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ConnectLocalStream(..)")
+ }
+}
+
+impl AsyncRead for LocalStream {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bytes: &mut [u8],
+ ) -> Poll<io::Result<usize>> {
+ Pin::new(&mut self.stream).poll_read(cx, bytes)
+ }
+}
+
+impl AsyncWrite for LocalStream {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ Pin::new(&mut self.stream).poll_write(cx, bytes)
+ }
+ fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Pin::new(&mut self.stream).poll_flush(cx)
+ }
+ fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Pin::new(&mut self.stream).poll_close(cx)
+ }
+}
+
+impl Drop for LocalStream {
+ fn drop(&mut self) {
+ platform::discard(&self.stream);
+ }
+}
+
+#[cfg(unix)]
+mod platform {
+ use super::*;
+ pub type Listener = smol::Async<std::os::unix::net::UnixListener>;
+ pub type Stream = smol::Async<std::os::unix::net::UnixStream>;
+
+ pub fn bind(name: &str) -> Result<Listener> {
+ Listener::bind(name).map_err(|_| Error::Unavailable)
+ }
+
+ pub async fn accept(listener: Arc<ListenerInner>) -> Result<LocalStream> {
+ let (stream, _) = listener
+ .listener
+ .as_ref()
+ .ok_or(Error::Unavailable)?
+ .accept()
+ .await
+ .map_err(|_| Error::Unavailable)?;
+ LocalStream::new(stream)
+ }
+
+ pub async fn connect(name: &str) -> Result<LocalStream> {
+ LocalStream::new(
+ Stream::connect(name)
+ .await
+ .map_err(|_| Error::Unavailable)?,
+ )
+ }
+
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
+ pub fn peer(stream: &Stream) -> Result<Peer> {
+ #[cfg(target_os = "macos")]
+ let (uid, pid) = {
+ use nix::sys::socket::{getsockopt, sockopt};
+ (
+ getsockopt(stream.get_ref(), sockopt::LocalPeerCred)
+ .map_err(|_| Error::Unavailable)?
+ .uid(),
+ getsockopt(stream.get_ref(), sockopt::LocalPeerPid)
+ .map_err(|_| Error::Unavailable)?,
+ )
+ };
+ #[cfg(target_os = "linux")]
+ let (uid, pid) = {
+ let credentials = nix::sys::socket::getsockopt(
+ stream.get_ref(),
+ nix::sys::socket::sockopt::PeerCredentials,
+ )
+ .map_err(|_| Error::Unavailable)?;
+ (credentials.uid(), credentials.pid())
+ };
+ if uid != nix::unistd::geteuid().as_raw() {
+ return Err(Error::Unavailable);
+ }
+ Ok(Peer {
+ pid: u32::try_from(pid).map_err(|_| Error::Unavailable)?,
+ })
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
+ pub fn peer(_: &Stream) -> Result<Peer> {
+ Err(Error::Unavailable)
+ }
+
+ pub fn discard(_: &Stream) {}
+}
+
+#[cfg(windows)]
+mod platform {
+ use super::*;
+ use interprocess::local_socket::{
+ tokio::{Listener as NativeListener, Stream as NativeStream},
+ traits::{
+ tokio::{Listener as _, Stream as _},
+ StreamCommon,
+ },
+ GenericFilePath, ListenerOptions, ToFsName,
+ };
+ use std::sync::OnceLock;
+ use tokio_util::compat::{Compat, TokioAsyncReadCompatExt};
+ pub type Listener = NativeListener;
+ pub type Stream = Compat<NativeStream>;
+
+ fn runtime() -> Result<&'static tokio::runtime::Runtime> {
+ static RUNTIME: OnceLock<std::result::Result<tokio::runtime::Runtime, ()>> =
+ OnceLock::new();
+ RUNTIME
+ .get_or_init(|| {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .max_blocking_threads(4)
+ .enable_io()
+ .enable_time()
+ .thread_name("connect-local-io")
+ .build()
+ .map_err(|_| ())
+ })
+ .as_ref()
+ .map_err(|_| Error::Unavailable)
+ }
+
+ async fn join<T>(task: tokio::task::JoinHandle<T>) -> Result<T> {
+ struct Abort<T>(tokio::task::JoinHandle<T>);
+ impl<T> Drop for Abort<T> {
+ fn drop(&mut self) {
+ self.0.abort();
+ }
+ }
+ let mut task = Abort(task);
+ (&mut task.0).await.map_err(|_| Error::Unavailable)
+ }
+
+ pub fn bind(name: &str) -> Result<Listener> {
+ use interprocess::os::windows::{
+ local_socket::ListenerOptionsExt, security_descriptor::SecurityDescriptor,
+ };
+ // No Everyone or anonymous ACE. Remote connections are refused by
+ // Interprocess's named-pipe listener defaults.
+ let sddl =
+ widestring::U16CString::from_str("D:P(A;;GA;;;OW)").map_err(|_| Error::Unavailable)?;
+ let security = SecurityDescriptor::deserialize(&sddl).map_err(|_| Error::Unavailable)?;
+ let _runtime = runtime()?.enter();
+ ListenerOptions::new()
+ .name(
+ name.to_fs_name::<GenericFilePath>()
+ .map_err(|_| Error::Protocol)?,
+ )
+ .security_descriptor(security)
+ .create_tokio()
+ .map_err(|_| Error::Unavailable)
+ }
+
+ pub async fn accept(listener: Arc<ListenerInner>) -> Result<LocalStream> {
+ let task = runtime()?.spawn(async move {
+ listener
+ .listener
+ .as_ref()
+ .ok_or(Error::Unavailable)?
+ .accept()
+ .await
+ .map_err(|_| Error::Unavailable)
+ });
+ LocalStream::new(join(task).await??.compat())
+ }
+
+ pub async fn connect(name: &str) -> Result<LocalStream> {
+ let name = name.to_string();
+ let task = runtime()?.spawn(async move {
+ NativeStream::connect(
+ name.as_str()
+ .to_fs_name::<GenericFilePath>()
+ .map_err(|_| Error::Protocol)?,
+ )
+ .await
+ .map_err(|_| Error::Unavailable)
+ });
+ LocalStream::new(join(task).await??.compat())
+ }
+
+ pub fn peer(stream: &Stream) -> Result<Peer> {
+ let credentials = stream
+ .get_ref()
+ .peer_creds()
+ .map_err(|_| Error::Unavailable)?;
+ Ok(Peer {
+ pid: credentials.pid().ok_or(Error::Unavailable)?,
+ })
+ }
+
+ pub fn discard(stream: &Stream) {
+ let NativeStream::NamedPipe(pipe) = stream.get_ref();
+ // Cancellation must not leave a FlushFileBuffers job in a background
+ // queue. Successful replies use an explicit protocol acknowledgement.
+ pipe.inner().assume_flushed();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[cfg(any(target_os = "macos", target_os = "linux", windows))]
+ use futures::io::{AsyncReadExt, AsyncWriteExt};
+
+ #[test]
+ fn discovery_cannot_redirect_to_an_arbitrary_or_remote_pipe() {
+ let listener_name = if cfg!(unix) {
+ "/tmp/tt-connect-0123456789abcdef0123456789abcdef/s"
+ } else {
+ r"\\.\pipe\ThinkTerm.Connect.0123456789abcdef0123456789abcdef"
+ };
+ assert!(local_name(listener_name));
+ for name in [
+ r"\\server-a\pipe\example",
+ "/tmp/example",
+ "/tmp/tt-connect-../s",
+ "",
+ ] {
+ assert!(!local_name(name));
+ }
+ }
+ #[cfg(unix)]
+ #[test]
+ fn only_a_socket_nothing_answers_on_counts_as_abandoned() {
+ use std::time::Duration;
+ let listener = LocalListener::bind().unwrap();
+ let live = PathBuf::from(listener.name());
+ let live = live.parent().unwrap();
+ remove_if_abandoned(live, Duration::ZERO);
+ assert!(live.join("s").exists());
+
+ let stale = PathBuf::from(format!("/tmp/tt-connect-{}", random_name().unwrap()));
+ std::fs::create_dir(&stale).unwrap();
+ drop(std::os::unix::net::UnixListener::bind(stale.join("s")).unwrap());
+ remove_if_abandoned(&stale, Duration::from_secs(600));
+ assert!(stale.join("s").exists(), "too recent to be sure");
+ remove_if_abandoned(&stale, Duration::ZERO);
+ assert!(!stale.exists());
+ }
+
+ #[cfg(any(target_os = "macos", target_os = "linux", windows))]
+ #[test]
+ fn local_transport_binds_kernel_peer_identity_and_releases_its_name() {
+ smol::block_on(async {
+ let listener = LocalListener::bind().unwrap();
+ let name = listener.name().to_string();
+ let (accepted, connected) =
+ futures::join!(listener.accept(), LocalStream::connect(&name));
+ let mut accepted = accepted.unwrap();
+ let mut connected = connected.unwrap();
+ assert_eq!(accepted.peer().pid(), std::process::id());
+ assert_eq!(connected.peer().pid(), std::process::id());
+ connected.write_all(b"hello").await.unwrap();
+ let mut bytes = [0; 5];
+ accepted.read_exact(&mut bytes).await.unwrap();
+ assert_eq!(&bytes, b"hello");
+ drop(connected);
+ drop(accepted);
+ drop(listener);
+ #[cfg(unix)]
+ assert!(!Path::new(&name).exists());
+ });
+ }
+
+ #[cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))]
+ #[test]
+ fn unsupported_unix_transport_refuses_peers_and_releases_its_name() {
+ smol::block_on(async {
+ let listener = LocalListener::bind().unwrap();
+ let name = listener.name().to_string();
+ let (accepted, connected) =
+ futures::join!(listener.accept(), LocalStream::connect(&name));
+ assert!(matches!(accepted, Err(Error::Unavailable)));
+ assert!(matches!(connected, Err(Error::Unavailable)));
+ drop(listener);
+ assert!(!Path::new(&name).exists());
+ });
+ }
+}
diff --git a/thinkterm-reverse-access/src/lib.rs b/thinkterm-reverse-access/src/lib.rs
new file mode 100644
index 00000000..b146a8f1
--- /dev/null
+++ b/thinkterm-reverse-access/src/lib.rs
@@ -0,0 +1,66 @@
+//! Authorization and bounded messages for a Connect reverse channel.
+//!
+//! The authority stays in the process that owns the terminal. Its handles
+//! cannot be deserialized from a request. A route, grant ID, or configuration
+//! value is never a substitute for an authentication transaction.
+
+#![forbid(unsafe_code)]
+
+mod authorization;
+pub mod budget;
+pub mod channel;
+pub mod clock;
+pub mod exchange;
+pub mod ipc;
+pub mod native;
+pub mod protocol;
+mod text;
+pub mod wire;
+
+pub use authorization::{
+ Approval, Authority, Endpoint, GrantInfo, GrantRef, GrantScope, Id, ListPermit, Operation,
+ Permission, Request, RequestPermit, Route, Target,
+};
+
+pub const MAX_ROUTES: usize = 16;
+pub const MAX_GRANTS: usize = 64;
+pub const MAX_TARGETS: usize = 256;
+pub const MAX_TARGETS_PER_GRANT: usize = 32;
+pub const MAX_READ_BYTES: usize = 1024 * 1024;
+pub const MAX_READ_LINES: usize = 2000;
+pub const MAX_INPUT_BYTES: usize = 64 * 1024;
+pub const MAX_KEYS: usize = 64;
+pub const MAX_DURATION_SECS: u64 = 120 * 60;
+pub const DEFAULT_DURATION_SECS: u64 = 30 * 60;
+pub const AUTH_TIMEOUT_SECS: u64 = 120;
+pub const REQUEST_TIMEOUT_SECS: u64 = 10;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum Error {
+ #[error("authorization or target is unavailable")]
+ Unavailable,
+ #[error("authorization is no longer valid")]
+ Revoked,
+ #[error("authentication transaction is no longer valid")]
+ StaleApproval,
+ #[error("authentication was cancelled or refused")]
+ Cancelled,
+ #[error("the operation timed out")]
+ Timeout,
+ #[error("the request exceeds the operation limit")]
+ TooLarge,
+ #[error("the Connect request limit is reached")]
+ Busy,
+ #[error("the request was already handled")]
+ Replay,
+ #[error("invalid Connect message")]
+ Protocol,
+ #[error("invalid authorization duration")]
+ Duration,
+ #[error("the authorization clock is unavailable")]
+ Clock,
+ #[error("secure randomness is unavailable")]
+ Random,
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
diff --git a/thinkterm-reverse-access/src/native.rs b/thinkterm-reverse-access/src/native.rs
new file mode 100644
index 00000000..c0827b3d
--- /dev/null
+++ b/thinkterm-reverse-access/src/native.rs
@@ -0,0 +1,413 @@
+//! The only production caller of `Approval::authenticated`.
+//!
+//! Helpers are packaged next to the executable, started by the authority,
+//! and answer through an inherited anonymous pipe. Neither a mux PDU nor a
+//! user-supplied executable path can complete an authentication transaction.
+
+use crate::authorization::{ApprovalCancellation, Monitor};
+use crate::text::Text;
+use crate::{Approval, Authority, Error, GrantInfo, GrantScope, Permission, Result};
+use serde::{Deserialize, Serialize};
+use std::io::{BufRead, BufReader, Read, Write};
+use std::path::PathBuf;
+use std::process::{Child, Command, Stdio};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{mpsc, Arc, Mutex};
+use std::time::{Duration, Instant};
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct Event {
+ kind: String,
+ id: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "PascalCase")]
+struct Intent {
+ id: String,
+ source: String,
+ targets: String,
+ input: bool,
+ seconds: u64,
+ text: Text,
+}
+
+fn id_text(id: crate::Id) -> String {
+ id.as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect()
+}
+
+fn read_event(reader: &mut impl BufRead) -> Result<Event> {
+ let mut line = Vec::new();
+ reader
+ .take(1025)
+ .read_until(b'\n', &mut line)
+ .map_err(|_| Error::Unavailable)?;
+ if line.len() > 1024 || line.last() != Some(&b'\n') {
+ return Err(Error::Protocol);
+ }
+ serde_json::from_slice(&line).map_err(|_| Error::Protocol)
+}
+
+fn helper_command(mode: &str) -> Result<Command> {
+ let executable = std::env::current_exe().map_err(|_| Error::Unavailable)?;
+ let directory = executable.parent().ok_or(Error::Unavailable)?;
+ let helper: PathBuf = directory.join(if cfg!(windows) {
+ "thinkterm-connect-auth.exe"
+ } else {
+ "thinkterm-connect-auth"
+ });
+ if !helper.is_file() {
+ return Err(Error::Unavailable);
+ }
+ let mut command = Command::new(helper);
+ command
+ .arg(mode)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+ // Do not inherit loader hooks, language startup files, or custom toolkit
+ // modules from the configuration environment.
+ command.env_clear();
+ for key in [
+ "SystemRoot",
+ "WINDIR",
+ "DISPLAY",
+ "WAYLAND_DISPLAY",
+ "XAUTHORITY",
+ "DBUS_SESSION_BUS_ADDRESS",
+ "XDG_RUNTIME_DIR",
+ "XDG_SESSION_ID",
+ "HOME",
+ "TMPDIR",
+ ] {
+ if let Some(value) = std::env::var_os(key) {
+ command.env(key, value);
+ }
+ }
+ command
+ .env("PATH", "/usr/bin:/bin")
+ .env("LANG", "en_US.UTF-8");
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ command.process_group(0);
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW; the helper creates its own dialog.
+ }
+ Ok(command)
+}
+
+fn kill(child: &Mutex<Child>) {
+ if let Ok(mut child) = child.lock() {
+ #[cfg(unix)]
+ if matches!(child.try_wait(), Ok(None)) {
+ let _ = nix::sys::signal::killpg(
+ nix::unistd::Pid::from_raw(child.id() as i32),
+ nix::sys::signal::Signal::SIGKILL,
+ );
+ }
+ let _ = child.kill();
+ }
+}
+
+fn reap(child: &Mutex<Child>) {
+ kill(child);
+ if let Ok(mut child) = child.lock() {
+ let _ = child.wait();
+ }
+}
+
+pub struct NativeSession {
+ authority: Arc<Authority>,
+ monitor: Arc<Monitor>,
+ child: Arc<Mutex<Child>>,
+}
+
+impl NativeSession {
+ pub fn start(authority: Arc<Authority>) -> Result<Self> {
+ let mut child = helper_command("--monitor")?
+ .spawn()
+ .map_err(|_| Error::Unavailable)?;
+ let stdout = child.stdout.take().ok_or(Error::Unavailable)?;
+ let child = Arc::new(Mutex::new(child));
+ let (sender, receiver) = mpsc::sync_channel(1);
+ let (monitor_sender, monitor_receiver) = mpsc::sync_channel::<Arc<Monitor>>(1);
+ let child_worker = child.clone();
+ std::thread::Builder::new()
+ .name("connect-session-monitor".into())
+ .spawn(move || {
+ let mut reader = BufReader::with_capacity(1024, stdout);
+ let result: Result<()> = (|| {
+ let event = read_event(&mut reader)?;
+ if event.kind != "ready" || event.id.is_some() {
+ return Err(Error::Protocol);
+ }
+ sender.send(Ok(())).map_err(|_| Error::Unavailable)?;
+ let monitor = monitor_receiver
+ .recv_timeout(Duration::from_secs(5))
+ .map_err(|_| Error::Unavailable)?;
+ let result = (|| loop {
+ let event = read_event(&mut reader)?;
+ if event.kind != "alive" || event.id.is_some() {
+ return Err(Error::Unavailable);
+ }
+ monitor.heartbeat()?;
+ })();
+ monitor.close();
+ result
+ })();
+ if let Err(error) = result {
+ let _ = sender.try_send(Err(error));
+ }
+ reap(&child_worker);
+ })
+ .map_err(|_| {
+ reap(&child);
+ Error::Unavailable
+ })?;
+ if !matches!(receiver.recv_timeout(Duration::from_secs(5)), Ok(Ok(()))) {
+ kill(&child);
+ return Err(Error::Unavailable);
+ }
+ let monitor = Arc::new(authority.start_monitor().map_err(|error| {
+ kill(&child);
+ error
+ })?);
+ monitor_sender.send(monitor.clone()).map_err(|_| {
+ kill(&child);
+ Error::Unavailable
+ })?;
+ Ok(Self {
+ authority,
+ monitor,
+ child,
+ })
+ }
+
+ /// Source is display text from the verified SSH session. Scope, duration,
+ /// and transaction identity are read from the frozen internal approval.
+ /// The language picks a translation of what the window says about them.
+ pub fn authenticate(
+ &self,
+ approval: Approval,
+ source: &str,
+ language: &str,
+ ) -> Result<NativeAttempt> {
+ self.monitor.check()?;
+ if source.is_empty() || source.len() > 256 || source.chars().any(char::is_control) {
+ return Err(Error::Protocol);
+ }
+ let details = approval.details()?;
+ let cancellation = approval.cancellation();
+ let input = details.permission == Permission::ReadAndInput;
+ let (text, all_terminals) = Text::new(
+ language,
+ source,
+ details.scope == GrantScope::AllLocalTerminals,
+ input,
+ details.seconds,
+ );
+ let intent = Intent {
+ id: id_text(details.id),
+ source: source.to_string(),
+ targets: match details.scope {
+ GrantScope::AllLocalTerminals => all_terminals.into(),
+ GrantScope::SelectedTerminals => details
+ .targets
+ .iter()
+ .map(|target| format!("{} [{}]", target.pane, id_text(target.incarnation)))
+ .collect::<Vec<_>>()
+ .join("\n"),
+ },
+ input,
+ seconds: details.seconds,
+ text,
+ };
+ let mut encoded = serde_json::to_vec(&intent).map_err(|_| Error::Protocol)?;
+ if encoded.len() >= 8192 {
+ return Err(Error::TooLarge);
+ }
+ encoded.push(b'\n');
+ let mut child = helper_command("--authenticate")?
+ .spawn()
+ .map_err(|_| Error::Unavailable)?;
+ let mut stdin = child.stdin.take().ok_or(Error::Unavailable)?;
+ let stdout = child.stdout.take().ok_or(Error::Unavailable)?;
+ let child = Arc::new(Mutex::new(child));
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let (sender, receiver) = mpsc::sync_channel(1);
+ let (finished_sender, finished_receiver) = mpsc::sync_channel::<()>(1);
+ let deadline_child = child.clone();
+ let deadline_cancelled = cancelled.clone();
+ let deadline_monitor = self.monitor.clone();
+ std::thread::Builder::new()
+ .name("connect-auth-deadline".into())
+ .spawn(move || {
+ let started = Instant::now();
+ loop {
+ match finished_receiver.recv_timeout(Duration::from_millis(100)) {
+ Ok(()) => break,
+ Err(mpsc::RecvTimeoutError::Disconnected) => {
+ deadline_cancelled.store(true, Ordering::SeqCst);
+ kill(&deadline_child);
+ break;
+ }
+ Err(mpsc::RecvTimeoutError::Timeout) => {}
+ }
+ if started.elapsed() < Duration::from_secs(crate::AUTH_TIMEOUT_SECS)
+ && deadline_monitor.check().is_ok()
+ && !deadline_cancelled.load(Ordering::SeqCst)
+ {
+ continue;
+ }
+ deadline_cancelled.store(true, Ordering::SeqCst);
+ kill(&deadline_child);
+ break;
+ }
+ })
+ .map_err(|_| {
+ reap(&child);
+ Error::Unavailable
+ })?;
+ let child_worker = child.clone();
+ let cancelled_worker = cancelled.clone();
+ let authority = self.authority.clone();
+ std::thread::Builder::new()
+ .name("connect-native-auth".into())
+ .spawn(move || {
+ let result = (|| {
+ stdin.write_all(&encoded).map_err(|_| Error::Unavailable)?;
+ let mut reader = BufReader::with_capacity(1024, stdout);
+ let event = read_event(&mut reader)?;
+ if event.kind == "rejected" && event.id.as_deref() == Some(&intent.id) {
+ return Err(Error::Cancelled);
+ }
+ if event.kind != "approved"
+ || event.id.as_deref() != Some(&intent.id)
+ || cancelled_worker.load(Ordering::SeqCst)
+ {
+ return Err(Error::Unavailable);
+ }
+ let started = Instant::now();
+ loop {
+ let status = child_worker
+ .lock()
+ .map_err(|_| Error::Unavailable)?
+ .try_wait()
+ .map_err(|_| Error::Unavailable)?;
+ if let Some(status) = status {
+ if !status.success() {
+ return Err(Error::Unavailable);
+ }
+ break;
+ }
+ if started.elapsed() >= Duration::from_secs(2)
+ || cancelled_worker.load(Ordering::SeqCst)
+ {
+ return Err(Error::Timeout);
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let info = approval.authenticated()?;
+ Ok(AuthorizedGrant { info, authority })
+ })();
+ reap(&child_worker);
+ let _ = finished_sender.send(());
+ let _ = sender.send(result);
+ // Keep the helper's control input open until it has completed.
+ drop(stdin);
+ })
+ .map_err(|_| {
+ reap(&child);
+ Error::Unavailable
+ })?;
+ Ok(NativeAttempt {
+ child,
+ cancelled,
+ cancellation,
+ receiver,
+ adopted: AtomicBool::new(false),
+ })
+ }
+}
+
+impl Drop for NativeSession {
+ fn drop(&mut self) {
+ self.monitor.close();
+ kill(&self.child);
+ }
+}
+
+pub struct NativeAttempt {
+ child: Arc<Mutex<Child>>,
+ cancelled: Arc<AtomicBool>,
+ cancellation: ApprovalCancellation,
+ receiver: mpsc::Receiver<Result<AuthorizedGrant>>,
+ adopted: AtomicBool,
+}
+
+impl NativeAttempt {
+ pub fn try_result(&self) -> Result<Option<AuthorizedGrant>> {
+ match self.receiver.try_recv() {
+ Ok(result) => result.map(|grant| {
+ self.adopted.store(true, Ordering::SeqCst);
+ Some(grant)
+ }),
+ Err(mpsc::TryRecvError::Empty) => Ok(None),
+ Err(mpsc::TryRecvError::Disconnected) => Err(Error::Unavailable),
+ }
+ }
+}
+
+impl Drop for NativeAttempt {
+ fn drop(&mut self) {
+ self.cancelled.store(true, Ordering::SeqCst);
+ if !self.adopted.load(Ordering::SeqCst) {
+ self.cancellation.cancel();
+ }
+ kill(&self.child);
+ }
+}
+
+/// Dropping an undelivered result or an abandoned UI grant revokes it.
+pub struct AuthorizedGrant {
+ info: GrantInfo,
+ authority: Arc<Authority>,
+}
+
+impl AuthorizedGrant {
+ pub fn info(&self) -> &GrantInfo {
+ &self.info
+ }
+}
+
+impl Drop for AuthorizedGrant {
+ fn drop(&mut self) {
+ let _ = self.authority.revoke(self.info.grant);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_output_is_bounded_and_strict() {
+ assert_eq!(
+ read_event(&mut &b"{\"kind\":\"ready\",\"id\":null}\n"[..])
+ .unwrap()
+ .kind,
+ "ready"
+ );
+ assert!(read_event(&mut &b"{\"kind\":\"approved\",\"success\":true}\n"[..]).is_err());
+ assert!(read_event(&mut &b"{\"kind\":\"ready\"}"[..]).is_err());
+ assert!(read_event(&mut vec![b'x'; 1025].as_slice()).is_err());
+ }
+}
diff --git a/thinkterm-reverse-access/src/protocol.rs b/thinkterm-reverse-access/src/protocol.rs
new file mode 100644
index 00000000..7eeb0606
--- /dev/null
+++ b/thinkterm-reverse-access/src/protocol.rs
@@ -0,0 +1,216 @@
+use crate::channel::Deadline;
+use crate::{Error, GrantRef, Permission, Result, Target, MAX_INPUT_BYTES, MAX_KEYS};
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ExportRef {
+ pub grant: GrantRef,
+ pub target: Target,
+}
+
+#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ReadOptions {
+ pub start: Option<i64>,
+ pub end: Option<i64>,
+ pub trim: bool,
+ pub unwrap: bool,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Key {
+ pub name: String,
+ pub modifiers: u16,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub enum Command {
+ List {
+ after: Option<ExportRef>,
+ },
+ Read {
+ export: ExportRef,
+ options: ReadOptions,
+ },
+ Text {
+ export: ExportRef,
+ bytes: usize,
+ no_paste: bool,
+ enter: bool,
+ },
+ Keys {
+ export: ExportRef,
+ keys: Vec<Key>,
+ },
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct TimedCommand {
+ command: Command,
+ remaining_ms: u64,
+}
+
+impl TimedCommand {
+ pub fn new(command: Command, deadline: &Deadline) -> Result<Self> {
+ command.validate()?;
+ let remaining_ms = deadline
+ .remaining()?
+ .as_millis()
+ .min(u128::from(crate::REQUEST_TIMEOUT_SECS * 1000)) as u64;
+ if remaining_ms == 0 {
+ return Err(Error::Timeout);
+ }
+ Ok(Self {
+ command,
+ remaining_ms,
+ })
+ }
+
+ pub fn receive(self) -> Result<(Command, Deadline)> {
+ if self.remaining_ms == 0 || self.remaining_ms > crate::REQUEST_TIMEOUT_SECS * 1000 {
+ return Err(Error::Protocol);
+ }
+ self.command.validate()?;
+ Ok((
+ self.command,
+ Deadline::after(Duration::from_millis(self.remaining_ms))?,
+ ))
+ }
+}
+
+impl std::fmt::Debug for Command {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Self::List { .. } => "List",
+ Self::Read { .. } => "Read",
+ Self::Text { .. } => "Text(..)",
+ Self::Keys { .. } => "Keys(..)",
+ })
+ }
+}
+
+impl Command {
+ pub fn validate(&self) -> Result<()> {
+ match self {
+ Self::Text { bytes, .. } if *bytes > MAX_INPUT_BYTES => Err(Error::TooLarge),
+ Self::Keys { keys, .. }
+ if keys.is_empty()
+ || keys.len() > MAX_KEYS
+ || keys.iter().any(|key| {
+ key.name.is_empty()
+ || key.name.len() > 32
+ || key.name.chars().any(char::is_control)
+ }) =>
+ {
+ Err(Error::TooLarge)
+ }
+ _ => Ok(()),
+ }
+ }
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ExportSummary {
+ pub export: ExportRef,
+ pub name: String,
+ pub title: String,
+ pub permission: Permission,
+ pub remaining_ms: u64,
+}
+
+impl std::fmt::Debug for ExportSummary {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ExportSummary(..)")
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub enum InputStatus {
+ RejectedNotSubmitted,
+ Submitted,
+ PartiallySubmitted,
+ OutcomeUnknown,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct InputResult {
+ pub status: InputStatus,
+ pub bytes: usize,
+ pub enter_submitted: bool,
+ pub paste_may_be_open: bool,
+}
+
+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
+pub enum Failure {
+ Unavailable,
+ Busy,
+ TooLarge,
+ Timeout,
+ Protocol,
+ Replay,
+}
+
+impl From<Error> for Failure {
+ fn from(error: Error) -> Self {
+ match error {
+ Error::Busy => Self::Busy,
+ Error::TooLarge => Self::TooLarge,
+ Error::Timeout => Self::Timeout,
+ Error::Protocol => Self::Protocol,
+ Error::Replay => Self::Replay,
+ _ => Self::Unavailable,
+ }
+ }
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub enum Reply {
+ List {
+ exports: Vec<ExportSummary>,
+ more: bool,
+ },
+ Text {
+ bytes: usize,
+ },
+ Input(InputResult),
+ Failed(Failure),
+}
+
+impl std::fmt::Debug for Reply {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Self::List { .. } => "List(..)",
+ Self::Text { .. } => "Text(..)",
+ Self::Input(_) => "Input(..)",
+ Self::Failed(_) => "Failed(..)",
+ })
+ }
+}
+
+/// How long `--enter` waits after `len` bytes of text: a moment, and a
+/// little more for a long text a program takes longer to read, up to two
+/// seconds. Sent together, a program reading a paste can take the Enter as
+/// part of it.
+pub fn enter_delay(len: usize) -> Duration {
+ Duration::from_millis((300 + len as u64 / 1024 * 50).min(2000))
+}
+
+pub fn display_text(value: &str, max_chars: usize) -> String {
+ value
+ .chars()
+ .filter(|c| {
+ !c.is_control()
+ && !matches!(*c,
+ '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
+ })
+ .take(max_chars)
+ .collect()
+}
diff --git a/thinkterm-reverse-access/src/text.rs b/thinkterm-reverse-access/src/text.rs
new file mode 100644
index 00000000..a7f7a307
--- /dev/null
+++ b/thinkterm-reverse-access/src/text.rs
@@ -0,0 +1,267 @@
+//! What native authentication says. It is chosen here, in the actual host,
+//! from the frozen intent: a caller picks a language, never the words, so no
+//! language can make it describe less than is granted. On macOS the system's
+//! dialog is the only window, so `reason` alone has to state all of that.
+
+use serde::Serialize;
+
+struct Language {
+ code: &'static str,
+ title: &'static str,
+ heading: &'static str,
+ connection: &'static str,
+ all_terminals: &'static str,
+ terminals: &'static str,
+ access: &'static str,
+ read_only: &'static str,
+ read_and_input: &'static str,
+ duration: &'static str,
+ warning: &'static str,
+ approve: &'static str,
+ cancel: &'static str,
+ /// Finishes the system's "… is trying to", and ends with the source so
+ /// that a long one cannot push the rest out of the dialog.
+ reason: &'static str,
+ all_local: &'static str,
+ selected: &'static str,
+ password: &'static str,
+}
+
+const ENGLISH: Language = Language {
+ code: "en-US",
+ title: "ThinkTerm Connect — Allow terminal access",
+ heading: "Allow this connection to access your terminals",
+ connection: "Connection: {}",
+ all_terminals: "All local terminals you own, including terminals opened while this authorization is active.",
+ terminals: "Terminals:",
+ access: "Access: {}",
+ read_only: "Read only",
+ read_and_input: "Read and send input",
+ duration: "Duration: {} minutes",
+ warning: "Sending input can execute commands with your account's permissions.",
+ approve: "Authenticate and allow",
+ cancel: "Cancel",
+ reason: "allow access to {scope} ({access}, {minutes} minutes): {source}",
+ all_local: "all local terminals",
+ selected: "the selected terminals",
+ password: "ThinkTerm Connect — System authentication",
+};
+
+const LANGUAGES: [Language; 6] = [
+ ENGLISH,
+ Language {
+ code: "zh-CN",
+ title: "ThinkTerm Connect — 允许访问终端",
+ heading: "允许此连接访问你的终端",
+ connection: "连接:{}",
+ all_terminals: "你拥有的全部本地终端,包括授权期间新开的终端。",
+ terminals: "终端:",
+ access: "权限:{}",
+ read_only: "只读",
+ read_and_input: "读取和输入",
+ duration: "时长:{} 分钟",
+ warning: "输入可使用你的账户权限运行命令。",
+ approve: "认证并允许",
+ cancel: "取消",
+ reason: "允许访问{scope}({access},{minutes} 分钟):{source}",
+ all_local: "全部本地终端",
+ selected: "选定的终端",
+ password: "ThinkTerm Connect — 系统认证",
+ },
+ Language {
+ code: "de-DE",
+ title: "ThinkTerm Connect — Terminalzugriff erlauben",
+ heading: "Dieser Verbindung den Zugriff auf Ihre Terminals erlauben",
+ connection: "Verbindung: {}",
+ all_terminals: "Alle Ihre lokalen Terminals, auch die, die während dieser Autorisierung geöffnet werden.",
+ terminals: "Terminals:",
+ access: "Zugriff: {}",
+ read_only: "Nur lesen",
+ read_and_input: "Lesen und Eingaben senden",
+ duration: "Dauer: {} Minuten",
+ warning: "Eingaben können Befehle mit den Rechten Ihres Kontos ausführen.",
+ approve: "Authentifizieren und erlauben",
+ cancel: "Abbrechen",
+ reason: "den Zugriff auf {scope} erlauben ({access}, {minutes} Minuten): {source}",
+ all_local: "alle lokalen Terminals",
+ selected: "die ausgewählten Terminals",
+ password: "ThinkTerm Connect — Systemauthentifizierung",
+ },
+ Language {
+ code: "fr-FR",
+ title: "ThinkTerm Connect — Autoriser l’accès aux terminaux",
+ heading: "Autoriser cette connexion à accéder à vos terminaux",
+ connection: "Connexion : {}",
+ all_terminals: "Tous vos terminaux locaux, y compris ceux ouverts pendant cette autorisation.",
+ terminals: "Terminaux :",
+ access: "Accès : {}",
+ read_only: "Lecture seule",
+ read_and_input: "Lecture et saisie",
+ duration: "Durée : {} minutes",
+ warning: "La saisie peut exécuter des commandes avec les droits de votre compte.",
+ approve: "S’authentifier et autoriser",
+ cancel: "Annuler",
+ reason: "autoriser l’accès {scope} ({access}, {minutes} minutes) : {source}",
+ all_local: "à tous les terminaux locaux",
+ selected: "aux terminaux sélectionnés",
+ password: "ThinkTerm Connect — Authentification système",
+ },
+ Language {
+ code: "ja-JP",
+ title: "ThinkTerm Connect — ターミナルへのアクセスを許可",
+ heading: "この接続にターミナルへのアクセスを許可します",
+ connection: "接続: {}",
+ all_terminals: "所有するすべてのローカルターミナル(この認可の間に開くものを含む)。",
+ terminals: "ターミナル:",
+ access: "アクセス: {}",
+ read_only: "読み取りのみ",
+ read_and_input: "読み取りと入力",
+ duration: "期間: {} 分",
+ warning: "入力を送信すると、あなたのアカウントの権限でコマンドを実行できます。",
+ approve: "認証して許可",
+ cancel: "キャンセル",
+ reason: "{scope}へのアクセスを許可する({access}、{minutes} 分): {source}",
+ all_local: "すべてのローカルターミナル",
+ selected: "選択したターミナル",
+ password: "ThinkTerm Connect — システム認証",
+ },
+ Language {
+ code: "ru-RU",
+ title: "ThinkTerm Connect — разрешить доступ к терминалам",
+ heading: "Разрешить этому подключению доступ к вашим терминалам",
+ connection: "Подключение: {}",
+ all_terminals: "Все ваши локальные терминалы, включая открытые во время действия этого разрешения.",
+ terminals: "Терминалы:",
+ access: "Доступ: {}",
+ read_only: "Только чтение",
+ read_and_input: "Чтение и ввод",
+ duration: "Длительность: {} мин.",
+ warning: "Ввод может выполнять команды с правами вашей учётной записи.",
+ approve: "Аутентифицироваться и разрешить",
+ cancel: "Отмена",
+ reason: "разрешить доступ к {scope} ({access}, {minutes} мин.): {source}",
+ all_local: "всем локальным терминалам",
+ selected: "выбранным терминалам",
+ password: "ThinkTerm Connect — системная аутентификация",
+ },
+];
+
+#[derive(Serialize)]
+#[serde(rename_all = "PascalCase")]
+pub(crate) struct Text {
+ title: String,
+ heading: String,
+ connection: String,
+ terminals: String,
+ detail: String,
+ approve: String,
+ cancel: String,
+ reason: String,
+ password: String,
+}
+
+impl Text {
+ pub(crate) fn new(
+ language: &str,
+ source: &str,
+ all_terminals: bool,
+ input: bool,
+ seconds: u64,
+ ) -> (Self, &'static str) {
+ let text = LANGUAGES
+ .iter()
+ .find(|text| text.code == language)
+ .unwrap_or(&ENGLISH);
+ let access = if input {
+ text.read_and_input
+ } else {
+ text.read_only
+ };
+ let minutes = seconds.div_ceil(60).to_string();
+ let detail = format!(
+ "{}\n{}\n\n{}",
+ text.access.replace("{}", access),
+ text.duration.replace("{}", &minutes),
+ text.warning,
+ );
+ // The source last: what it contains is not a placeholder.
+ let reason = text
+ .reason
+ .replace(
+ "{scope}",
+ if all_terminals {
+ text.all_local
+ } else {
+ text.selected
+ },
+ )
+ .replace("{access}", access)
+ .replace("{minutes}", &minutes)
+ .replace("{source}", source);
+ let scope = if all_terminals {
+ text.all_terminals
+ } else {
+ ""
+ };
+ (
+ Self {
+ title: text.title.into(),
+ heading: text.heading.into(),
+ connection: text.connection.replace("{}", source),
+ terminals: text.terminals.into(),
+ detail,
+ approve: text.approve.into(),
+ cancel: text.cancel.into(),
+ reason,
+ password: text.password.into(),
+ },
+ scope,
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_language_states_the_frozen_access() {
+ for language in &LANGUAGES {
+ let (read, scope) = Text::new(language.code, "server-a", true, false, 1800);
+ let (input, _) = Text::new(language.code, "server-a", true, true, 1800);
+ assert!(read.connection.contains("server-a"));
+ assert!(read.detail.contains(language.read_only));
+ assert!(read.detail.contains("30"));
+ assert!(input.detail.contains(language.read_and_input));
+ assert_eq!(scope, language.all_terminals);
+ assert!(!read.detail.contains("{}") && !read.connection.contains("{}"));
+
+ // macOS shows nothing else.
+ assert!(read.reason.contains("server-a"));
+ assert!(read.reason.contains(language.all_local));
+ assert!(read.reason.contains(language.read_only));
+ assert!(read.reason.contains("30"));
+ assert!(input.reason.contains(language.read_and_input));
+ assert!(!read.reason.contains('{'));
+ let (selected, _) = Text::new(language.code, "server-a", false, false, 1800);
+ assert!(selected.reason.contains(language.selected));
+ }
+ }
+
+ #[test]
+ fn the_longest_source_fits_what_the_helpers_accept_and_stays_a_source() {
+ let source = "{minutes}".repeat(28);
+ assert!(source.len() <= 256);
+ for language in &LANGUAGES {
+ let (text, _) = Text::new(language.code, &source, true, true, 7200);
+ assert!(text.reason.len() <= 512);
+ assert!(text.reason.ends_with(&source));
+ }
+ }
+
+ #[test]
+ fn an_unknown_language_reads_as_english() {
+ let (text, _) = Text::new("xx-XX", "server-a", false, false, 60);
+ assert_eq!(text.title, ENGLISH.title);
+ }
+}
diff --git a/thinkterm-reverse-access/src/wire.rs b/thinkterm-reverse-access/src/wire.rs
new file mode 100644
index 00000000..17080217
--- /dev/null
+++ b/thinkterm-reverse-access/src/wire.rs
@@ -0,0 +1,369 @@
+use crate::budget::{Reservation, RouteBudget};
+use crate::clock::Tick;
+use crate::{Error, Result, MAX_INPUT_BYTES, MAX_READ_BYTES};
+use std::fmt;
+use std::time::Duration;
+
+pub const HEADER_SIZE: usize = 20;
+pub const MAX_FRAME: usize = 32 * 1024;
+pub const MAX_BLOCK: usize = 16 * 1024;
+const RECEIVE_TIMEOUT: Duration = Duration::from_secs(5);
+const MAGIC: &[u8; 4] = b"TTCR";
+const VERSION: u8 = 1;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum Kind {
+ Hello = 1,
+ Bound = 2,
+ Request = 3,
+ InputBlock = 4,
+ Reply = 5,
+ TextBlock = 6,
+ Cancel = 7,
+ Withdraw = 8,
+}
+
+impl Kind {
+ fn parse(value: u8) -> Result<Self> {
+ match value {
+ 1 => Ok(Self::Hello),
+ 2 => Ok(Self::Bound),
+ 3 => Ok(Self::Request),
+ 4 => Ok(Self::InputBlock),
+ 5 => Ok(Self::Reply),
+ 6 => Ok(Self::TextBlock),
+ 7 => Ok(Self::Cancel),
+ 8 => Ok(Self::Withdraw),
+ _ => Err(Error::Protocol),
+ }
+ }
+
+ fn limit(self) -> usize {
+ match self {
+ Self::Hello | Self::Bound | Self::Cancel | Self::Withdraw => 1024,
+ Self::InputBlock | Self::TextBlock => MAX_BLOCK + 4,
+ Self::Request | Self::Reply => MAX_FRAME - HEADER_SIZE,
+ }
+ }
+
+ fn check_sequence(self, sequence: u64) -> Result<()> {
+ let connection_message = matches!(self, Self::Hello | Self::Bound | Self::Withdraw);
+ if connection_message != (sequence == 0) {
+ return Err(Error::Protocol);
+ }
+ Ok(())
+ }
+}
+
+pub struct Frame {
+ kind: Kind,
+ sequence: u64,
+ body: Vec<u8>,
+}
+
+impl fmt::Debug for Frame {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Frame")
+ .field("kind", &self.kind)
+ .field("sequence", &self.sequence)
+ .field("bytes", &self.body.len())
+ .finish()
+ }
+}
+
+impl Frame {
+ pub fn new(kind: Kind, sequence: u64, body: &[u8]) -> Result<Self> {
+ kind.check_sequence(sequence)?;
+ if body.len() > kind.limit() {
+ return Err(Error::TooLarge);
+ }
+ Ok(Self {
+ kind,
+ sequence,
+ body: body.to_vec(),
+ })
+ }
+
+ pub fn kind(&self) -> Kind {
+ self.kind
+ }
+ pub fn sequence(&self) -> u64 {
+ self.sequence
+ }
+ pub fn body(&self) -> &[u8] {
+ &self.body
+ }
+
+ pub fn header(&self) -> [u8; HEADER_SIZE] {
+ let mut header = [0; HEADER_SIZE];
+ header[..4].copy_from_slice(MAGIC);
+ header[4] = VERSION;
+ header[5] = self.kind as u8;
+ // Flags/reserved bytes stay zero. Compression is not supported.
+ header[8..16].copy_from_slice(&self.sequence.to_be_bytes());
+ header[16..].copy_from_slice(&(self.body.len() as u32).to_be_bytes());
+ header
+ }
+}
+
+#[derive(Default)]
+pub struct Decoder {
+ header: [u8; HEADER_SIZE],
+ header_len: usize,
+ pending: Option<Frame>,
+ body_len: usize,
+ started: Option<Tick>,
+ failed: bool,
+}
+
+impl Decoder {
+ /// Feed at most one frame. The caller retains a frame-sized receive
+ /// reservation while the decoder is alive. Lengths are checked before
+ /// body allocation; a trickle never resets the absolute deadline.
+ pub fn push(&mut self, bytes: &[u8], now: Tick) -> Result<(usize, Option<Frame>)> {
+ if self.failed {
+ return Err(Error::Protocol);
+ }
+ let result = self.push_inner(bytes, now);
+ if result.is_err() {
+ self.failed = true;
+ self.pending = None;
+ }
+ result
+ }
+
+ fn push_inner(&mut self, bytes: &[u8], now: Tick) -> Result<(usize, Option<Frame>)> {
+ if let Some(started) = self.started {
+ if now.elapsed_since(started)? >= RECEIVE_TIMEOUT {
+ return Err(Error::Timeout);
+ }
+ } else if !bytes.is_empty() {
+ self.started = Some(now);
+ }
+ let mut used = 0;
+ if self.header_len < HEADER_SIZE {
+ let count = bytes.len().min(HEADER_SIZE - self.header_len);
+ self.header[self.header_len..self.header_len + count].copy_from_slice(&bytes[..count]);
+ self.header_len += count;
+ used += count;
+ if self.header_len != HEADER_SIZE {
+ return Ok((used, None));
+ }
+ if &self.header[..4] != MAGIC
+ || self.header[4] != VERSION
+ || self.header[6] != 0
+ || self.header[7] != 0
+ {
+ return Err(Error::Protocol);
+ }
+ let kind = Kind::parse(self.header[5])?;
+ let sequence = u64::from_be_bytes(self.header[8..16].try_into().unwrap());
+ kind.check_sequence(sequence)?;
+ self.body_len = u32::from_be_bytes(self.header[16..20].try_into().unwrap()) as usize;
+ if self.body_len > kind.limit() {
+ return Err(Error::TooLarge);
+ }
+ self.pending = Some(Frame {
+ kind,
+ sequence,
+ body: Vec::with_capacity(self.body_len),
+ });
+ }
+ let pending = self.pending.as_mut().ok_or(Error::Protocol)?;
+ let count = (self.body_len - pending.body.len()).min(bytes.len() - used);
+ pending.body.extend_from_slice(&bytes[used..used + count]);
+ used += count;
+ if pending.body.len() == self.body_len {
+ let frame = self.pending.take();
+ self.header_len = 0;
+ self.started = None;
+ Ok((used, frame))
+ } else {
+ Ok((used, None))
+ }
+ }
+
+ pub fn is_idle(&self) -> bool {
+ self.started.is_none() && !self.failed
+ }
+}
+
+/// A request is assembled completely before any input can be submitted.
+/// The reservation travels with the completed payload through its reply.
+pub struct Assembly {
+ total: usize,
+ bytes: Vec<u8>,
+ reservation: Reservation,
+}
+
+impl Assembly {
+ pub fn input(total: usize, budget: &RouteBudget) -> Result<Self> {
+ Self::new(total, MAX_INPUT_BYTES, budget)
+ }
+
+ pub fn text(total: usize, budget: &RouteBudget) -> Result<Self> {
+ Self::new(total, MAX_READ_BYTES, budget)
+ }
+
+ /// A reply's bytes join its request's reservation. The request already
+ /// paid the rate limit and holds a slot, so only its size can be refused.
+ pub fn reply_text(total: usize, mut reservation: Reservation) -> Result<Self> {
+ if total > MAX_READ_BYTES {
+ return Err(Error::TooLarge);
+ }
+ reservation.grow(total)?;
+ Ok(Self {
+ total,
+ bytes: Vec::with_capacity(total),
+ reservation,
+ })
+ }
+
+ fn new(total: usize, limit: usize, budget: &RouteBudget) -> Result<Self> {
+ if total > limit {
+ return Err(Error::TooLarge);
+ }
+ let reservation = budget.acquire(total)?;
+ Ok(Self {
+ total,
+ bytes: Vec::with_capacity(total),
+ reservation,
+ })
+ }
+
+ pub fn append(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
+ if offset != self.bytes.len()
+ || bytes.is_empty()
+ || bytes.len() > MAX_BLOCK
+ || bytes.len() > self.total - self.bytes.len()
+ {
+ return Err(Error::Protocol);
+ }
+ self.bytes.extend_from_slice(bytes);
+ Ok(())
+ }
+
+ pub fn finish(self) -> Result<Payload> {
+ if self.bytes.len() != self.total {
+ return Err(Error::Protocol);
+ }
+ std::str::from_utf8(&self.bytes).map_err(|_| Error::Protocol)?;
+ Ok(Payload {
+ bytes: self.bytes,
+ reservation: self.reservation,
+ })
+ }
+}
+
+pub struct Payload {
+ bytes: Vec<u8>,
+ reservation: Reservation,
+}
+
+impl Payload {
+ pub fn text(&self) -> &str {
+ // Validated once at assembly completion; bytes are never mutated.
+ std::str::from_utf8(&self.bytes).expect("validated Connect text")
+ }
+
+ pub fn reservation(&mut self) -> &mut Reservation {
+ &mut self.reservation
+ }
+}
+
+impl fmt::Debug for Payload {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Payload")
+ .field("bytes", &self.bytes.len())
+ .finish()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::budget::Budgets;
+ use crate::Id;
+
+ #[test]
+ fn every_split_decodes_without_losing_the_next_frame() {
+ let original = Frame::new(Kind::InputBlock, 12, b"example payload").unwrap();
+ let bytes = [original.header().as_slice(), original.body()].concat();
+ for split in 0..=bytes.len() {
+ let mut decoder = Decoder::default();
+ let (first, frame) = decoder.push(&bytes[..split], Tick::seconds(0)).unwrap();
+ assert_eq!(first, split);
+ let frame = match frame {
+ Some(frame) => frame,
+ None => decoder
+ .push(&bytes[split..], Tick::seconds(1))
+ .unwrap()
+ .1
+ .unwrap(),
+ };
+ assert_eq!(frame.body(), original.body());
+ assert!(decoder.is_idle());
+ }
+ }
+
+ #[test]
+ fn oversize_or_compressed_headers_fail_before_a_body_is_allocated() {
+ for compressed in [false, true] {
+ let mut header = Frame::new(Kind::Request, 1, b"").unwrap().header();
+ if compressed {
+ header[6] = 1;
+ } else {
+ header[16..].copy_from_slice(&u32::MAX.to_be_bytes());
+ }
+ let mut decoder = Decoder::default();
+ assert!(decoder.push(&header, Tick::seconds(0)).is_err());
+ assert!(decoder.pending.is_none());
+ assert!(decoder.push(&[], Tick::seconds(1)).is_err());
+ }
+ }
+
+ #[test]
+ fn trickling_progress_does_not_extend_frame_lifetime() {
+ let header = Frame::new(Kind::Request, 1, b"example").unwrap().header();
+ let mut decoder = Decoder::default();
+ for second in 0..5 {
+ assert!(decoder
+ .push(&header[second..second + 1], Tick::seconds(second as u64))
+ .is_ok());
+ }
+ assert!(matches!(
+ decoder.push(&header[5..], Tick::seconds(5)),
+ Err(Error::Timeout)
+ ));
+ }
+
+ #[test]
+ fn incomplete_reordered_or_invalid_utf8_input_is_never_released() {
+ let budgets = Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([1; 16])).unwrap();
+ let mut input = Assembly::input(4, &route).unwrap();
+ assert_eq!(input.append(1, b"x"), Err(Error::Protocol));
+ input.append(0, b"x").unwrap();
+ assert!(input.finish().is_err());
+ let mut input = Assembly::input(1, &route).unwrap();
+ input.append(0, &[0xff]).unwrap();
+ assert!(input.finish().is_err());
+ assert_eq!(budgets.retained().unwrap(), (0, 0));
+ }
+
+ #[test]
+ fn unicode_can_cross_block_boundaries_and_debug_is_redacted() {
+ let budgets = Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([1; 16])).unwrap();
+ let text = "example-\u{1f980}";
+ let mut input = Assembly::input(text.len(), &route).unwrap();
+ input.append(0, &text.as_bytes()[..10]).unwrap();
+ input.append(10, &text.as_bytes()[10..]).unwrap();
+ let payload = input.finish().unwrap();
+ assert_eq!(payload.text(), text);
+ assert!(!format!("{payload:?}").contains("example"));
+ let frame = Frame::new(Kind::InputBlock, 1, text.as_bytes()).unwrap();
+ assert!(!format!("{frame:?}").contains("example"));
+ }
+}
diff --git a/wezterm-client/Cargo.toml b/wezterm-client/Cargo.toml
index 23870105..d6eeeb40 100644
--- a/wezterm-client/Cargo.toml
+++ b/wezterm-client/Cargo.toml
@@ -29,6 +29,7 @@ rangeset.workspace = true
smol.workspace = true
termwiz.workspace = true
thinkterm-proto.workspace = true
+thinkterm-reverse-access = { path = "../thinkterm-reverse-access" }
thinkterm-session.workspace = true
thinkterm-update.workspace = true
thiserror.workspace = true
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index b2f13043..7ecfbdb9 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -192,6 +192,7 @@ pub struct Client {
/// loop checks it after every dead session, surfaces it in a visible
/// window, and stops.
fatal_connection_error: Arc<Mutex<Option<String>>>,
+ connect_transport: Arc<Mutex<Option<ConnectTransport>>>,
}
impl Client {
@@ -268,6 +269,7 @@ impl Client {
/// Retire this client, including an initial attach waiting on an update
/// decision. A replacement must get a new client and registration.
pub(crate) fn close(&self) {
+ self.connect_transport.lock().unwrap().take();
self.shutdown.close();
self.sender.close();
self.set_connection_phase(ClientConnectionPhase::Detached);
@@ -1585,6 +1587,188 @@ struct Reconnectable {
stream: Option<Box<dyn AsyncReadAndWrite>>,
tls_creds: Option<GetTlsCredsResponse>,
incoming_payload_limit: Option<usize>,
+ connect_transport: Arc<Mutex<Option<ConnectTransport>>>,
+}
+
+struct ConnectTransport {
+ session: wezterm_ssh::Session,
+ live: Arc<AtomicBool>,
+ command: String,
+ source: String,
+}
+
+impl std::fmt::Debug for ConnectTransport {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ConnectTransport(..)")
+ }
+}
+
+impl Drop for ConnectTransport {
+ fn drop(&mut self) {
+ self.live.store(false, Ordering::Release);
+ }
+}
+
+/// A channel opener obtained only from the authenticated, currently attached
+/// Connect transport. It cannot be reconstructed from a PDU or configuration.
+#[derive(Clone)]
+pub struct VerifiedConnectSession {
+ session: wezterm_ssh::Session,
+ live: std::sync::Weak<AtomicBool>,
+ command: String,
+ source: String,
+}
+
+impl VerifiedConnectSession {
+ pub fn is_alive(&self) -> bool {
+ self.live
+ .upgrade()
+ .is_some_and(|live| live.load(Ordering::Acquire))
+ }
+
+ pub fn source(&self) -> &str {
+ &self.source
+ }
+
+ pub async fn open_reverse_channel(&self) -> anyhow::Result<Box<dyn AsyncReadAndWrite>> {
+ anyhow::ensure!(self.is_alive(), "Connect session is no longer available");
+ let exec = self
+ .session
+ .exec(&self.command, None)
+ .or(async {
+ smol::Timer::after(Duration::from_secs(5)).await;
+ bail!("opening the Connect reverse channel timed out")
+ })
+ .await?;
+ anyhow::ensure!(self.is_alive(), "Connect session is no longer available");
+ let mut stderr = Async::new(SshStream {
+ stdin: exec.stderr.try_clone()?,
+ stdout: exec.stderr,
+ })?;
+ // Each direction on the descriptor it uses: `Async` makes that one
+ // nonblocking and waits on it. A write that blocks here would pass
+ // every deadline and hold the output guard, which Revoke needs.
+ let reader = Async::new(SshStream {
+ stdin: exec.stdout.try_clone()?,
+ stdout: exec.stdout,
+ })?;
+ let writer = Async::new(SshStream {
+ stdin: exec.stdin.try_clone()?,
+ stdout: exec.stdin,
+ })?;
+ let (stop, stopped) = bounded::<()>(1);
+ let state = Arc::new(ReverseChannelState {
+ failed: AtomicBool::new(false),
+ wake: futures::task::AtomicWaker::new(),
+ });
+ let worker_state = Arc::clone(&state);
+ smol::spawn(async move {
+ let result: std::io::Result<()> = async {
+ let mut remaining = 4096;
+ let mut buffer = [0; 512];
+ loop {
+ let count = stderr.read(&mut buffer).await?;
+ if count == 0 {
+ return Ok(());
+ }
+ if count > remaining {
+ return Err(std::io::ErrorKind::InvalidData.into());
+ }
+ remaining -= count;
+ }
+ }
+ .or(async {
+ let _ = stopped.recv().await;
+ Ok(())
+ })
+ .await;
+ if result.is_err() {
+ worker_state.failed.store(true, Ordering::Release);
+ worker_state.wake.wake();
+ }
+ })
+ .detach();
+ Ok(Box::new(ReverseSshStream {
+ reader,
+ writer,
+ child: Box::new(exec.child),
+ stop,
+ state,
+ }))
+ }
+}
+
+struct ReverseChannelState {
+ failed: AtomicBool,
+ wake: futures::task::AtomicWaker,
+}
+
+struct ReverseSshStream {
+ reader: Async<SshStream>,
+ writer: Async<SshStream>,
+ child: Box<wezterm_ssh::SshChildProcess>,
+ stop: Sender<()>,
+ state: Arc<ReverseChannelState>,
+}
+
+impl std::fmt::Debug for ReverseSshStream {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ReverseSshStream(..)")
+ }
+}
+
+impl AsyncRead for ReverseSshStream {
+ fn poll_read(
+ mut self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ buffer: &mut [u8],
+ ) -> std::task::Poll<std::io::Result<usize>> {
+ self.state.wake.register(cx.waker());
+ if self.state.failed.load(Ordering::Acquire) {
+ return std::task::Poll::Ready(Err(std::io::ErrorKind::InvalidData.into()));
+ }
+ std::pin::Pin::new(&mut self.reader).poll_read(cx, buffer)
+ }
+}
+
+impl AsyncWrite for ReverseSshStream {
+ fn poll_write(
+ mut self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ buffer: &[u8],
+ ) -> std::task::Poll<std::io::Result<usize>> {
+ self.state.wake.register(cx.waker());
+ if self.state.failed.load(Ordering::Acquire) {
+ return std::task::Poll::Ready(Err(std::io::ErrorKind::InvalidData.into()));
+ }
+ std::pin::Pin::new(&mut self.writer).poll_write(cx, buffer)
+ }
+ fn poll_flush(
+ mut self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<std::io::Result<()>> {
+ std::pin::Pin::new(&mut self.writer).poll_flush(cx)
+ }
+ fn poll_close(
+ mut self: std::pin::Pin<&mut Self>,
+ cx: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<std::io::Result<()>> {
+ std::pin::Pin::new(&mut self.writer).poll_close(cx)
+ }
+}
+
+#[async_trait(?Send)]
+impl AsyncReadAndWrite for ReverseSshStream {
+ async fn wait_for_readable(&self) -> anyhow::Result<()> {
+ Ok(self.reader.readable().await?)
+ }
+}
+
+impl Drop for ReverseSshStream {
+ fn drop(&mut self) {
+ self.stop.close();
+ let _ = portable_pty::ChildKiller::kill(self.child.as_mut());
+ }
}
struct SshStream {
@@ -1650,6 +1834,7 @@ impl Reconnectable {
stream,
tls_creds: None,
incoming_payload_limit: None,
+ connect_transport: Arc::new(Mutex::new(None)),
}
}
@@ -1794,6 +1979,21 @@ impl Reconnectable {
no_auto_start: bool,
) -> anyhow::Result<()> {
let ssh_config = mux::ssh::ssh_domain_to_ssh_config(&ssh_dom)?;
+ let reverse_source = ssh_config
+ .get("user")
+ .zip(ssh_config.get("hostname"))
+ .map(|(user, host)| {
+ format!(
+ "{}@{}:{}",
+ user,
+ host,
+ ssh_config.get("port").map(String::as_str).unwrap_or("22")
+ )
+ })
+ .filter(|source| {
+ source.len() <= 256
+ && thinkterm_reverse_access::protocol::display_text(source, 256) == *source
+ });
let sess =
ssh_connect_with_ui_and_password(ssh_config, ui, ssh_dom.stored_password.clone())?;
@@ -1855,6 +2055,22 @@ impl Reconnectable {
stdout: exec.stdout,
})?);
self.stream.replace(stream);
+ if ssh_dom.override_proxy_command.is_none()
+ && sess
+ .authentication_info()
+ .is_some_and(|info| info.is_verified_password_only())
+ && reverse_source.is_some()
+ {
+ *self.connect_transport.lock().unwrap() = Some(ConnectTransport {
+ session: sess,
+ live: Arc::new(AtomicBool::new(true)),
+ command: Self::remote_mux_command(
+ &ssh_dom.remote_wezterm_path,
+ "cli --prefer-mux --no-auto-start connect-reverse-proxy",
+ ),
+ source: reverse_source.unwrap(),
+ });
+ }
Ok(())
}
@@ -2191,6 +2407,7 @@ fn split_host_port(address: &str) -> Option<(&str, u16)> {
impl Client {
fn new(local_domain_id: Option<DomainId>, mut reconnectable: Reconnectable) -> Self {
+ let connect_transport = Arc::clone(&reconnectable.connect_transport);
let client_domain_config = reconnectable.config.clone();
let is_reconnectable = reconnectable.reconnectable();
let is_local = reconnectable.is_local();
@@ -2310,14 +2527,16 @@ impl Client {
})
.detach();
}
- if let Err(e) = client_thread(
+ let connection_result = client_thread(
&mut reconnectable,
local_domain_id,
generation,
&mut receiver,
&shutdown_rx,
&abort_rx,
- ) {
+ );
+ reconnectable.connect_transport.lock().unwrap().take();
+ if let Err(e) = connection_result {
*reader_abort.lock().unwrap() = None;
// A client let go of on purpose ends so: nothing to warn
// of, however often a command asks and lets go.
@@ -2661,9 +2880,25 @@ impl Client {
remote_os_release,
connection_generation,
fatal_connection_error,
+ connect_transport,
}
}
+ pub fn verified_connect_session(&self) -> Option<VerifiedConnectSession> {
+ if self.connection_phase() != ClientConnectionPhase::Ready || self.local_domain_id.is_none()
+ {
+ return None;
+ }
+ let transport = self.connect_transport.lock().ok()?;
+ let transport = transport.as_ref()?;
+ Some(VerifiedConnectSession {
+ session: transport.session.clone(),
+ live: Arc::downgrade(&transport.live),
+ command: transport.command.clone(),
+ source: transport.source.clone(),
+ })
+ }
+
/// Mark the connection as failed in a way no amount of retrying can fix.
/// The reconnect loop surfaces the reason and stops after the current
/// session dies.
@@ -3115,6 +3350,11 @@ impl Client {
GetPaneRenderableDimensionsResponse
);
rpc!(get_codec_version, GetCodecVersion, GetCodecVersionResponse);
+ rpc!(
+ get_connect_endpoint,
+ GetConnectEndpoint,
+ GetConnectEndpointResponse
+ );
rpc!(get_tls_creds, GetTlsCreds = (), GetTlsCredsResponse);
rpc!(web_token_mint, WebTokenMint, WebTokenMintResponse);
rpc!(web_token_list, WebTokenList = (), WebTokenListResponse);
diff --git a/wezterm-client/src/connect.rs b/wezterm-client/src/connect.rs
new file mode 100644
index 00000000..640e5fa6
--- /dev/null
+++ b/wezterm-client/src/connect.rs
@@ -0,0 +1,1481 @@
+use crate::client::{Client, ClientConnectionPhase, VerifiedConnectSession};
+use mux::connect::service::{Bound, Control, Controlled, Hello, RouterRoute};
+use mux::connect::{HostStatus, PaneChoice};
+use parking_lot::Mutex;
+use smol::channel::{bounded, Sender};
+use smol::future::FutureExt;
+use std::collections::{HashMap, HashSet};
+use std::sync::{Arc, Weak};
+use std::time::Duration;
+use thinkterm_reverse_access::budget::{Budgets, RouteBudget};
+use thinkterm_reverse_access::channel::{parse, Channel, Deadline, REPLY_MARGIN};
+use thinkterm_reverse_access::clock::{Clock, SystemClock, Tick};
+use thinkterm_reverse_access::exchange::{
+ discard_text, next_block, receive_input, receive_reply, send_payload, Refusable,
+};
+use thinkterm_reverse_access::ipc::LocalStream;
+use thinkterm_reverse_access::protocol::{Command, ExportSummary, Failure, Reply, TimedCommand};
+use thinkterm_reverse_access::wire::{Assembly, Frame, Kind, Payload};
+use thinkterm_reverse_access::{Error, GrantRef, GrantScope, Id, Result};
+
+#[derive(Clone)]
+pub struct Endpoint {
+ address: String,
+ server_id: String,
+}
+
+impl Endpoint {
+ pub async fn for_client(client: &Client) -> Result<Self> {
+ if !client.is_local {
+ return Err(Error::Unavailable);
+ }
+ let info = Deadline::after(Duration::from_secs(5))?
+ .run(async {
+ client
+ .get_connect_endpoint(codec::GetConnectEndpoint {})
+ .await
+ .map_err(|_| Error::Unavailable)
+ })
+ .await?;
+ if client.remote_server_id().as_deref() != Some(info.server_id.as_str()) {
+ return Err(Error::Unavailable);
+ }
+ Ok(Self {
+ address: info.address,
+ server_id: info.server_id,
+ })
+ }
+
+ pub fn in_process(mux: &Arc<mux::Mux>) -> Result<Self> {
+ Ok(Self {
+ address: mux.connect_service()?.name().into(),
+ server_id: mux.runtime_server_id().into(),
+ })
+ }
+
+ pub async fn stream(&self) -> Result<LocalStream> {
+ let stream = Deadline::after(Duration::from_secs(5))?
+ .run(LocalStream::connect(&self.address))
+ .await?;
+ let gui = if cfg!(windows) {
+ "thinkterm-gui.exe"
+ } else {
+ "thinkterm-gui"
+ };
+ let host = if cfg!(windows) {
+ "thinkterm-mux-server.exe"
+ } else {
+ "thinkterm-mux-server"
+ };
+ if !stream.peer().is_packaged(gui) && !stream.peer().is_packaged(host) {
+ return Err(Error::Unavailable);
+ }
+ Ok(stream)
+ }
+
+ async fn open(
+ &self,
+ hello: &Hello,
+ budget: &RouteBudget,
+ ) -> Result<(Channel<LocalStream>, Bound)> {
+ let mut channel = Channel::new(self.stream().await?, budget.acquire(1024 * 1024)?)?;
+ let deadline = Deadline::after(Duration::from_secs(5))?;
+ channel.write_json(Kind::Hello, 0, hello, &deadline).await?;
+ let bound: Bound = parse(&channel.read(Some(&deadline)).await?, Kind::Bound, 0)?;
+ if bound.server_id != self.server_id {
+ return Err(Error::Unavailable);
+ }
+ Ok((channel, bound))
+ }
+}
+
+fn budget() -> Result<RouteBudget> {
+ Budgets::process()?.open_route(Id::random()?)
+}
+
+pub struct RouterClient {
+ endpoint: Endpoint,
+ budget: RouteBudget,
+}
+
+impl RouterClient {
+ pub async fn new(client: &Client) -> Result<Self> {
+ Ok(Self {
+ endpoint: Endpoint::for_client(client).await?,
+ budget: budget()?,
+ })
+ }
+
+ pub async fn routes(&self) -> Result<Vec<RouterRoute>> {
+ let (mut channel, _) = self.endpoint.open(&Hello::Browse, &self.budget).await?;
+ let deadline = Deadline::request()?;
+ let routes: Vec<RouterRoute> =
+ parse(&channel.read(Some(&deadline)).await?, Kind::Reply, 1)?;
+ if routes.len() > thinkterm_reverse_access::MAX_ROUTES
+ || routes.iter().any(|route| {
+ route.name.len() > 64
+ || route.name.is_empty()
+ || route
+ .name
+ .chars()
+ .any(|c| !c.is_ascii_alphanumeric() && c != '-')
+ })
+ {
+ return Err(Error::Protocol);
+ }
+ channel
+ .write(&Frame::new(Kind::Cancel, 1, &[])?, &deadline)
+ .await?;
+ Ok(routes)
+ }
+
+ pub async fn request(
+ &self,
+ route: Id,
+ command: Command,
+ input: Option<&str>,
+ ) -> Result<(Reply, Option<Payload>)> {
+ let deadline = Deadline::request()?;
+ command.validate()?;
+ match (&command, input) {
+ (Command::Text { bytes, .. }, Some(input)) if *bytes == input.len() => {}
+ (Command::Text { .. }, _) => return Err(Error::Protocol),
+ (_, None) => {}
+ _ => return Err(Error::Protocol),
+ }
+ let (mut channel, bound) = deadline
+ .run(self.endpoint.open(&Hello::Request { route }, &self.budget))
+ .await?;
+ if bound.route != Some(route) {
+ return Err(Error::Unavailable);
+ }
+ let timed = TimedCommand::new(command, &deadline)?;
+ channel
+ .write_json(Kind::Request, 1, &timed, &deadline)
+ .await?;
+ if let Some(input) = input {
+ send_payload(
+ &mut channel,
+ input.as_bytes(),
+ 1,
+ Kind::InputBlock,
+ &deadline,
+ )
+ .await?;
+ }
+ let result = receive_reply(
+ &mut channel,
+ 1,
+ |bytes| Assembly::text(bytes, &self.budget),
+ &deadline,
+ )
+ .await??;
+ channel
+ .write(&Frame::new(Kind::Cancel, 1, &[])?, &deadline)
+ .await?;
+ Ok(result)
+ }
+
+ /// A list or a read changes nothing, so it can simply wait its turn when
+ /// the route is at its rate limit. Input is never sent twice this way.
+ pub async fn request_read(
+ &self,
+ route: Id,
+ command: Command,
+ ) -> Result<(Reply, Option<Payload>)> {
+ let deadline = Deadline::request()?;
+ loop {
+ let result = self.request(route, command.clone(), None).await?;
+ if !matches!(result.0, Reply::Failed(Failure::Busy)) {
+ return Ok(result);
+ }
+ deadline
+ .run(async {
+ smol::Timer::after(Duration::from_millis(150)).await;
+ Ok(())
+ })
+ .await?;
+ }
+ }
+
+ pub async fn exports(&self, route: Id) -> Result<Vec<ExportSummary>> {
+ let mut after = None;
+ let mut all = Vec::new();
+ loop {
+ let (reply, _) = self.request_read(route, Command::List { after }).await?;
+ let Reply::List { exports, more } = reply else {
+ return Err(Error::Unavailable);
+ };
+ if all.len() + exports.len() > thinkterm_reverse_access::MAX_TARGETS {
+ return Err(Error::TooLarge);
+ }
+ if exports.is_empty() && more {
+ return Err(Error::Protocol);
+ }
+ let next = exports.last().map(|item| item.export);
+ if next.is_some() && next == after {
+ return Err(Error::Replay);
+ }
+ after = next;
+ all.extend(exports);
+ if !more {
+ return Ok(all);
+ }
+ }
+ }
+}
+
+/// The host binding is checked against its live mux connection on every
+/// control heartbeat. A configuration flag alone cannot construct one.
+pub struct HostBinding {
+ endpoint: Endpoint,
+ client_id: mux::client::ClientId,
+ client: Option<(Client, u64)>,
+ mux: Option<Weak<mux::Mux>>,
+}
+
+impl HostBinding {
+ pub fn in_process(mux: &Arc<mux::Mux>) -> Result<Self> {
+ Ok(Self {
+ endpoint: Endpoint::in_process(mux)?,
+ client_id: mux
+ .active_identity()
+ .ok_or(Error::Unavailable)?
+ .as_ref()
+ .clone(),
+ client: None,
+ mux: Some(Arc::downgrade(mux)),
+ })
+ }
+
+ pub async fn local_session(client: Client) -> Result<Self> {
+ if !client.is_local_session_host() || !client.is_local {
+ return Err(Error::Unavailable);
+ }
+ let generation = client.connection_generation();
+ let endpoint = Endpoint::for_client(&client).await?;
+ Ok(Self {
+ endpoint,
+ client_id: client.client_id.clone(),
+ client: Some((client, generation)),
+ mux: None,
+ })
+ }
+
+ fn alive(&self) -> bool {
+ if let Some((client, generation)) = &self.client {
+ client.connection_phase() == ClientConnectionPhase::Ready
+ && client.connection_generation() == *generation
+ && client.remote_server_id().as_deref() == Some(self.endpoint.server_id.as_str())
+ } else {
+ self.mux
+ .as_ref()
+ .and_then(Weak::upgrade)
+ .is_some_and(|mux| mux.runtime_server_id() == self.endpoint.server_id)
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+pub struct ExportState {
+ pub choices: Vec<PaneChoice>,
+ pub status: HostStatus,
+ pub error: Option<Error>,
+ pub closed: bool,
+}
+
+pub struct Exporter {
+ commands: Sender<Control>,
+ state: Arc<Mutex<ExportState>>,
+ output: Arc<OutputGuard>,
+ _task: smol::Task<()>,
+}
+
+impl Exporter {
+ pub async fn start(
+ session: VerifiedConnectSession,
+ host: HostBinding,
+ language: String,
+ ) -> Result<Self> {
+ Self::start_scoped(session, host, GrantScope::SelectedTerminals, language).await
+ }
+
+ pub async fn start_all_local(
+ session: VerifiedConnectSession,
+ host: HostBinding,
+ language: String,
+ ) -> Result<Self> {
+ Self::start_scoped(session, host, GrantScope::AllLocalTerminals, language).await
+ }
+
+ async fn start_scoped(
+ session: VerifiedConnectSession,
+ host: HostBinding,
+ scope: GrantScope,
+ language: String,
+ ) -> Result<Self> {
+ if !session.is_alive() || !host.alive() {
+ return Err(Error::Unavailable);
+ }
+ let budget = budget()?;
+ let (mut control, bound) = host
+ .endpoint
+ .open(
+ &Hello::Manage {
+ server_id: host.endpoint.server_id.clone(),
+ client: host.client_id.clone(),
+ source: session.source().into(),
+ language,
+ },
+ &budget,
+ )
+ .await?;
+ let route = bound.route.ok_or(Error::Protocol)?;
+ let mut sequence = 0u64;
+ let choices = if scope == GrantScope::SelectedTerminals {
+ load_choices(&mut control, &mut sequence).await?
+ } else {
+ Vec::new()
+ };
+ let state = Arc::new(Mutex::new(ExportState {
+ choices,
+ ..ExportState::default()
+ }));
+ let worker_state = Arc::clone(&state);
+ let output = Arc::new(OutputGuard::new()?);
+ let worker_output = Arc::clone(&output);
+ let (commands, receiver) = bounded(4);
+ let task = smol::spawn(async move {
+ let mut bridge: Option<smol::Task<()>> = None;
+ let (failed, failure) = bounded(1);
+ let result: Result<()> = async {
+ loop {
+ let command = async { receiver.recv().await.map_err(|_| Error::Unavailable) }
+ .or(async {
+ smol::Timer::after(Duration::from_secs(1)).await;
+ Ok(Control::Status)
+ })
+ .or(async {
+ failure.recv().await.map_err(|_| Error::Unavailable)?;
+ Err(Error::Unavailable)
+ })
+ .await?;
+ if !session.is_alive() || !host.alive() {
+ return Err(Error::Unavailable);
+ }
+ if matches!(command, Control::Choices { .. }) {
+ let choices = load_choices(&mut control, &mut sequence).await?;
+ worker_state.lock().choices = choices;
+ continue;
+ }
+ sequence = sequence.checked_add(1).ok_or(Error::Replay)?;
+ let before = worker_output.clock.now()?;
+ let response = control_request(&mut control, sequence, &command).await?;
+ let has_grants = {
+ let mut state = worker_state.lock();
+ match response {
+ Controlled::Status(status) => {
+ worker_output.update(before, &status)?;
+ state.status = status;
+ state.error = None;
+ }
+ Controlled::Choices { .. } => return Err(Error::Protocol),
+ Controlled::Failed(_) => state.error = Some(Error::Unavailable),
+ }
+ !state.status.grants.is_empty()
+ };
+ if has_grants && bridge.is_none() {
+ let (data, data_bound) =
+ host.endpoint.open(&Hello::Data { route }, &budget).await?;
+ if data_bound.route != Some(route) {
+ return Err(Error::Unavailable);
+ }
+ let session = session.clone();
+ let budget = budget.clone();
+ let failed = failed.clone();
+ let output = Arc::clone(&worker_output);
+ bridge = Some(smol::spawn(async move {
+ let _ = reverse_requests(session, data, budget, output).await;
+ let _ = failed.try_send(());
+ }));
+ } else if !has_grants && bridge.is_some() {
+ // Closing the dedicated SSH channel removes the server's
+ // route and cancels all queued requests there.
+ return Ok(());
+ }
+ }
+ }
+ .await;
+ worker_output.close();
+ drop(bridge);
+ let mut state = worker_state.lock();
+ state.closed = true;
+ state.status = HostStatus::default();
+ if !receiver.is_closed() {
+ state.error = result.err();
+ }
+ });
+ Ok(Self {
+ commands,
+ state,
+ output,
+ _task: task,
+ })
+ }
+
+ pub fn state(&self) -> ExportState {
+ self.state.lock().clone()
+ }
+ pub fn command(&self, command: Control) -> Result<()> {
+ if let Control::Revoke { grant } = &command {
+ self.output.revoke(*grant);
+ }
+ self.commands.try_send(command).map_err(|_| Error::Busy)
+ }
+ pub fn close(&self) {
+ self.output.close();
+ self.commands.close();
+ }
+}
+
+impl Drop for Exporter {
+ fn drop(&mut self) {
+ self.close();
+ }
+}
+
+struct OutputState {
+ closed: bool,
+ last: Tick,
+ lease: Tick,
+ /// When the newest status was asked for.
+ status: Tick,
+ grants: HashMap<Id, (GrantRef, GrantScope, Vec<(u64, Id)>, Tick)>,
+ denied: HashSet<Id>,
+}
+
+/// A conservative replica used only to discard bytes at the last GUI-to-SSH
+/// boundary. It cannot approve a grant. Host durations are anchored before
+/// the status request, so IPC latency can only shorten them.
+struct OutputGuard {
+ clock: Arc<dyn Clock>,
+ state: Mutex<OutputState>,
+}
+
+impl OutputGuard {
+ fn new() -> Result<Self> {
+ Self::with_clock(SystemClock::shared())
+ }
+
+ fn with_clock(clock: Arc<dyn Clock>) -> Result<Self> {
+ let now = clock.now()?;
+ Ok(Self {
+ clock,
+ state: Mutex::new(OutputState {
+ closed: false,
+ last: now,
+ lease: now,
+ status: now,
+ grants: HashMap::new(),
+ denied: HashSet::new(),
+ }),
+ })
+ }
+
+ fn update(&self, before: Tick, status: &HostStatus) -> Result<()> {
+ if status.grants.len() > thinkterm_reverse_access::MAX_GRANTS {
+ return Err(Error::TooLarge);
+ }
+ let mut state = self.state.lock();
+ if state.closed {
+ return Err(Error::Revoked);
+ }
+ let now = self.clock.now()?;
+ if now < state.last || now < before {
+ state.closed = true;
+ return Err(Error::Clock);
+ }
+ let mut grants = HashMap::new();
+ state
+ .denied
+ .retain(|id| status.grants.iter().any(|grant| grant.grant.id == *id));
+ for grant in &status.grants {
+ let limit = match grant.scope {
+ GrantScope::SelectedTerminals => thinkterm_reverse_access::MAX_TARGETS_PER_GRANT,
+ GrantScope::AllLocalTerminals => thinkterm_reverse_access::MAX_TARGETS,
+ };
+ if grant.targets.len() > limit
+ || grant.remaining_ms > thinkterm_reverse_access::MAX_DURATION_SECS * 1000
+ {
+ return Err(Error::TooLarge);
+ }
+ if state.denied.contains(&grant.grant.id) {
+ continue;
+ }
+ grants.insert(
+ grant.grant.id,
+ (
+ grant.grant,
+ grant.scope,
+ grant.targets.clone(),
+ before.after(Duration::from_millis(grant.remaining_ms))?,
+ ),
+ );
+ }
+ state.last = now;
+ state.lease = before.after(Duration::from_secs(4))?;
+ state.status = before;
+ state.grants = grants;
+ Ok(())
+ }
+
+ fn inspect<T>(
+ &self,
+ refs: &[(GrantRef, (u64, Id))],
+ action: impl FnOnce(bool) -> T,
+ ) -> Result<T> {
+ let mut state = self.state.lock();
+ let now = self.clock.now()?;
+ if now < state.last {
+ state.closed = true;
+ }
+ if state.closed || now >= state.lease {
+ return Err(Error::Revoked);
+ }
+ state.last = now;
+ let mut ready = true;
+ for (grant, target) in refs {
+ if state.denied.contains(&grant.id) {
+ return Err(Error::Revoked);
+ }
+ match state.grants.get(&grant.id) {
+ Some((current, scope, targets, end)) if current == grant => {
+ if now >= *end {
+ return Err(Error::Revoked);
+ }
+ if !targets.contains(target) {
+ if *scope == GrantScope::SelectedTerminals {
+ return Err(Error::Revoked);
+ }
+ // Added or captured again since the last status, or
+ // already gone. `synchronize` finds out which; a
+ // pane id says nothing, recapture keeps it.
+ ready = false;
+ }
+ }
+ Some((current, _, _, _)) if current.version > grant.version => {
+ return Err(Error::Revoked);
+ }
+ _ => ready = false,
+ }
+ }
+ Ok(action(ready))
+ }
+
+ /// `refs` come with a reply the host has already made. A status asked for
+ /// after this began describes the host since then: what it still does not
+ /// list is gone, not late.
+ async fn synchronize(&self, refs: &[(GrantRef, (u64, Id))], deadline: &Deadline) -> Result<()> {
+ let started = self.clock.now()?;
+ loop {
+ deadline.remaining()?;
+ if self.inspect(refs, |ready| ready)? {
+ return Ok(());
+ }
+ if self.state.lock().status > started {
+ return Err(Error::Revoked);
+ }
+ // Authentication can publish a grant between control heartbeats.
+ // Only a trusted status update can make its output ready.
+ deadline
+ .run(async {
+ smol::Timer::after(Duration::from_millis(20)).await;
+ Ok(())
+ })
+ .await?;
+ }
+ }
+
+ fn execute<T>(&self, refs: &[(GrantRef, (u64, Id))], write: impl FnOnce() -> T) -> Result<T> {
+ self.inspect(refs, |ready| {
+ if ready {
+ Ok(write())
+ } else {
+ Err(Error::Revoked)
+ }
+ })?
+ }
+
+ fn revoke(&self, grant: GrantRef) {
+ let mut state = self.state.lock();
+ state.grants.remove(&grant.id);
+ if state.denied.len() >= thinkterm_reverse_access::MAX_GRANTS {
+ state.closed = true;
+ } else {
+ state.denied.insert(grant.id);
+ }
+ }
+ fn close(&self) {
+ let mut state = self.state.lock();
+ state.closed = true;
+ state.grants.clear();
+ }
+}
+
+async fn control_request(
+ channel: &mut Channel<LocalStream>,
+ sequence: u64,
+ command: &Control,
+) -> Result<Controlled> {
+ let deadline = Deadline::request()?;
+ channel
+ .write_json(Kind::Request, sequence, command, &deadline)
+ .await?;
+ parse(&channel.read(Some(&deadline)).await?, Kind::Reply, sequence)
+}
+
+async fn load_choices(
+ channel: &mut Channel<LocalStream>,
+ sequence: &mut u64,
+) -> Result<Vec<PaneChoice>> {
+ let mut after = None;
+ let mut all = Vec::new();
+ // Bounded even if a compromised host supplies an endless cursor.
+ for _ in 0..32 {
+ *sequence = sequence.checked_add(1).ok_or(Error::Replay)?;
+ let Controlled::Choices { panes, after: next } =
+ control_request(channel, *sequence, &Control::Choices { after }).await?
+ else {
+ return Err(Error::Unavailable);
+ };
+ if panes.len() > 32
+ || all.len() + panes.len() > thinkterm_reverse_access::MAX_TARGETS
+ || panes.iter().any(|pane| pane.title.len() > 512)
+ || next.is_some_and(|next| after.is_some_and(|after| next <= after))
+ {
+ return Err(Error::TooLarge);
+ }
+ all.extend(panes);
+ if next.is_none() {
+ return Ok(all);
+ }
+ after = next;
+ }
+ Err(Error::TooLarge)
+}
+
+async fn reverse_requests(
+ session: VerifiedConnectSession,
+ mut host: Channel<LocalStream>,
+ budget: RouteBudget,
+ output: Arc<OutputGuard>,
+) -> Result<()> {
+ let stream = session
+ .open_reverse_channel()
+ .await
+ .map_err(|_| Error::Unavailable)?;
+ let mut channel = Channel::new(stream, budget.acquire(1024 * 1024)?)?;
+ let handshake = Deadline::after(Duration::from_secs(5))?;
+ channel
+ .write_json(
+ Kind::Hello,
+ 0,
+ &Hello::Register {
+ name: "desktop".into(),
+ },
+ &handshake,
+ )
+ .await?;
+ let _: Bound = parse(&channel.read(Some(&handshake)).await?, Kind::Bound, 0)?;
+ let mut previous = 0;
+ loop {
+ let frame = channel.read(None).await?;
+ let sequence = frame.sequence();
+ if sequence <= previous || sequence == u64::MAX || !session.is_alive() {
+ return Err(Error::Replay);
+ }
+ previous = sequence;
+ let timed: TimedCommand = parse(&frame, Kind::Request, sequence)?;
+ let (command, deadline) = timed.receive()?;
+ let payload = receive_input(&mut channel, &command, sequence, &budget, &deadline).await?;
+ let disconnected = channel.watch_peer();
+ forward_request(
+ &mut channel,
+ &mut host,
+ &output,
+ command,
+ payload,
+ sequence,
+ &deadline,
+ )
+ .or(disconnected)
+ .await?;
+ }
+}
+
+/// Carry one request to the host and its reply back. A reply refused here
+/// holds no terminal data, so it needs no guard. An error means a channel is
+/// no longer in step and the bridge ends.
+async fn forward_request<S, H>(
+ channel: &mut Channel<S>,
+ host: &mut Channel<H>,
+ output: &OutputGuard,
+ command: Command,
+ payload: Refusable<Option<Payload>>,
+ sequence: u64,
+ deadline: &Deadline,
+) -> Result<()>
+where
+ S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin,
+ H: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin,
+{
+ let ready = payload.and_then(|payload| {
+ let forwarded = deadline.earlier(REPLY_MARGIN)?;
+ let timed = TimedCommand::new(command.clone(), &forwarded)?;
+ Ok((payload, forwarded, timed))
+ });
+ let (payload, forwarded, timed) = match ready {
+ Ok(ready) => ready,
+ Err(error) => return refuse(channel, sequence, error, deadline).await,
+ };
+ host.write_json(Kind::Request, sequence, &timed, &forwarded)
+ .await?;
+ if let Some(payload) = payload {
+ send_payload(
+ host,
+ payload.text().as_bytes(),
+ sequence,
+ Kind::InputBlock,
+ &forwarded,
+ )
+ .await?;
+ }
+ // Forward each already bounded frame without retaining terminal objects
+ // or assembling an extra copy of a read result in the GUI.
+ let frame = host.read(Some(deadline)).await?;
+ let reply: Reply = parse(&frame, Kind::Reply, sequence)?;
+ let refs = match &reply {
+ Reply::List { exports, .. } if exports.len() <= 32 => exports
+ .iter()
+ .map(|item| {
+ (
+ item.export.grant,
+ (item.export.target.pane, item.export.target.incarnation),
+ )
+ })
+ .collect::<Vec<_>>(),
+ Reply::Text { .. } => match &command {
+ Command::Read { export, .. } => vec![(
+ export.grant,
+ (export.target.pane, export.target.incarnation),
+ )],
+ _ => return Err(Error::Protocol),
+ },
+ Reply::List { .. } => return Err(Error::TooLarge),
+ _ => Vec::new(),
+ };
+ let expected = match reply {
+ Reply::Text { bytes } if bytes <= thinkterm_reverse_access::MAX_READ_BYTES => bytes,
+ Reply::Text { .. } => return Err(Error::TooLarge),
+ _ => 0,
+ };
+ if let Err(error) = output.synchronize(&refs, &forwarded).await {
+ refuse(channel, sequence, error, deadline).await?;
+ return discard_text(host, 0, expected, sequence, deadline).await;
+ }
+ channel
+ .write_guarded(&frame, deadline, |write| output.execute(&refs, write))
+ .await?;
+ let mut received = 0;
+ while received < expected {
+ let frame = host.read(Some(deadline)).await?;
+ let Some(bytes) = next_block(&frame, Kind::TextBlock, sequence, received, expected)? else {
+ return channel.write(&frame, deadline).await;
+ };
+ received += bytes.len();
+ // The host starts no block in the last REPLY_MARGIN of `forwarded`.
+ // What it sent before can still be queued here, and on a slow
+ // connection forwarding that would run out of `deadline` partway
+ // through a frame, which ends the bridge. Stopping with the host also
+ // lets it finish the frame it is writing.
+ let host_stopped = !forwarded.remaining().is_ok_and(|left| left > REPLY_MARGIN);
+ if host_stopped || output.execute(&refs, || ()).is_err() {
+ channel
+ .write(&Frame::new(Kind::Cancel, sequence, &[])?, deadline)
+ .await?;
+ return discard_text(host, received, expected, sequence, deadline).await;
+ }
+ channel
+ .write_guarded(&frame, deadline, |write| output.execute(&refs, write))
+ .await?;
+ }
+ Ok(())
+}
+
+async fn refuse<S: futures::io::AsyncRead + futures::io::AsyncWrite + Unpin>(
+ channel: &mut Channel<S>,
+ sequence: u64,
+ error: Error,
+ deadline: &Deadline,
+) -> Result<()> {
+ let reply = Reply::Failed(error.into());
+ channel
+ .write_json(Kind::Reply, sequence, &reply, deadline)
+ .await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use futures::io::{AsyncRead, AsyncWrite};
+ use futures::FutureExt as _;
+ use std::io;
+ use std::pin::Pin;
+ use std::sync::atomic::{AtomicU64, Ordering};
+ use std::task::{Context, Poll};
+ use thinkterm_reverse_access::Permission;
+
+ struct TestClock {
+ origin: Tick,
+ millis: AtomicU64,
+ }
+ impl Clock for TestClock {
+ fn now(&self) -> Result<Tick> {
+ self.origin
+ .after(Duration::from_millis(self.millis.load(Ordering::Acquire)))
+ }
+ }
+ impl TestClock {
+ fn set(&self, millis: u64) {
+ self.millis.store(millis, Ordering::Release);
+ }
+ }
+
+ fn target(pane: u64) -> (u64, Id) {
+ (pane, Id::from_bytes([3; 16]))
+ }
+
+ async fn write_reply<S: AsyncRead + AsyncWrite + Unpin>(
+ output: &OutputGuard,
+ channel: &mut Channel<S>,
+ frame: &Frame,
+ refs: &[(GrantRef, (u64, Id))],
+ deadline: &Deadline,
+ ) -> Result<()> {
+ output.synchronize(refs, deadline).await?;
+ channel
+ .write_guarded(frame, deadline, |write| output.execute(refs, write))
+ .await
+ }
+
+ fn fixture() -> (OutputGuard, Arc<TestClock>, HostStatus, GrantRef) {
+ let clock = Arc::new(TestClock {
+ origin: SystemClock::shared().now().unwrap(),
+ millis: AtomicU64::new(0),
+ });
+ let output = OutputGuard::with_clock(clock.clone()).unwrap();
+ let grant = GrantRef {
+ id: Id::from_bytes([1; 16]),
+ version: 1,
+ };
+ let status = HostStatus {
+ grants: vec![mux::connect::ActiveGrant {
+ grant,
+ scope: GrantScope::SelectedTerminals,
+ targets: vec![target(42)],
+ permission: Permission::ReadAndInput,
+ remaining_ms: 2000,
+ }],
+ ..HostStatus::default()
+ };
+ (output, clock, status, grant)
+ }
+
+ struct RecordingStream {
+ bytes: Arc<Mutex<Vec<u8>>>,
+ pause: bool,
+ }
+
+ impl AsyncRead for RecordingStream {
+ fn poll_read(
+ self: Pin<&mut Self>,
+ _: &mut Context<'_>,
+ _: &mut [u8],
+ ) -> Poll<io::Result<usize>> {
+ Poll::Pending
+ }
+ }
+
+ impl AsyncWrite for RecordingStream {
+ fn poll_write(
+ self: Pin<&mut Self>,
+ _: &mut Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ if self.pause && !self.bytes.lock().is_empty() {
+ return Poll::Pending;
+ }
+ let count = bytes.len().min(3);
+ self.bytes.lock().extend_from_slice(&bytes[..count]);
+ Poll::Ready(Ok(count))
+ }
+ fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ }
+
+ fn recording_channel(pause: bool) -> (Channel<RecordingStream>, Arc<Mutex<Vec<u8>>>) {
+ let bytes = Arc::new(Mutex::new(Vec::new()));
+ let budgets = Budgets::new().unwrap();
+ let route = budgets.open_route(Id::from_bytes([9; 16])).unwrap();
+ let channel = Channel::new(
+ RecordingStream {
+ bytes: bytes.clone(),
+ pause,
+ },
+ route.acquire(1024 * 1024).unwrap(),
+ )
+ .unwrap();
+ (channel, bytes)
+ }
+
+ #[test]
+ fn all_local_output_waits_for_new_targets_and_rejects_replaced_incarnations() {
+ let (output, clock, mut status, grant) = fixture();
+ status.grants[0].scope = GrantScope::AllLocalTerminals;
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let (mut channel, bytes) = recording_channel(false);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ let refs = [(grant, target(43))];
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ assert!(bytes.lock().is_empty());
+ status.grants[0].targets.push(target(43));
+ output.update(clock.now().unwrap(), &status).unwrap();
+ assert_eq!(pending.await, Ok(()));
+ });
+ status.grants[0].targets.retain(|target| target.0 != 43);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ assert_eq!(output.execute(&refs, || ()), Err(Error::Revoked));
+ status.grants[0].targets.push((43, Id::from_bytes([4; 16])));
+ output.update(clock.now().unwrap(), &status).unwrap();
+ // A newer status than this reply's turn settles it as gone.
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ clock.set(1000);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ assert_eq!(pending.await, Err(Error::Revoked));
+ });
+ assert_eq!(output.execute(&refs, || ()), Err(Error::Revoked));
+ assert!(output
+ .execute(&[(grant, (43, Id::from_bytes([4; 16])))], || ())
+ .is_ok());
+ }
+
+ #[test]
+ fn a_recaptured_pane_waits_for_status_instead_of_ending_the_bridge() {
+ let (output, clock, mut status, grant) = fixture();
+ status.grants[0].scope = GrantScope::AllLocalTerminals;
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let (mut channel, bytes) = recording_channel(false);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ // The host moved on from incarnation [3; 16] before this status.
+ let recaptured = (42, Id::from_bytes([4; 16]));
+ let refs = [(grant, recaptured)];
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ assert!(bytes.lock().is_empty());
+ status.grants[0].targets = vec![recaptured];
+ clock.set(500);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ assert_eq!(pending.await, Ok(()));
+ });
+ }
+
+ #[test]
+ fn all_local_output_does_not_extend_expiry_while_waiting_for_membership() {
+ let (output, clock, mut status, grant) = fixture();
+ status.grants[0].scope = GrantScope::AllLocalTerminals;
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let (mut channel, bytes) = recording_channel(false);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ let refs = [(grant, target(43))];
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ clock.set(2000);
+ assert_eq!(pending.await, Err(Error::Revoked));
+ });
+ assert!(bytes.lock().is_empty());
+ }
+
+ #[test]
+ fn maximum_all_local_status_fits_a_bounded_control_frame() {
+ let (output, clock, mut status, _) = fixture();
+ let grant = &mut status.grants[0];
+ grant.scope = GrantScope::AllLocalTerminals;
+ grant.targets = (0..thinkterm_reverse_access::MAX_TARGETS)
+ .map(|index| (u64::MAX - index as u64, Id::from_bytes([255; 16])))
+ .collect();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let response = Controlled::Status(status.clone());
+ thinkterm_reverse_access::channel::json_frame(Kind::Reply, 1, &response).unwrap();
+ status.grants[0].targets.push(target(42));
+ assert_eq!(
+ output.update(clock.now().unwrap(), &status),
+ Err(Error::TooLarge)
+ );
+ }
+
+ #[test]
+ fn new_and_renewed_replies_wait_for_trusted_status_before_writing() {
+ for renewal in [false, true] {
+ let (output, clock, mut status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let next = if renewal {
+ GrantRef {
+ version: 2,
+ ..grant
+ }
+ } else {
+ GrantRef {
+ id: Id::from_bytes([2; 16]),
+ ..grant
+ }
+ };
+ let (mut channel, bytes) = recording_channel(false);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ let refs = [(next, target(42))];
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ assert!(bytes.lock().is_empty());
+ if renewal {
+ status.grants[0].grant = next;
+ } else {
+ let mut added = status.grants[0].clone();
+ added.grant = next;
+ status.grants.push(added);
+ }
+ output.update(clock.now().unwrap(), &status).unwrap();
+ assert_eq!(pending.await, Ok(()));
+ });
+ let mut expected = frame.header().to_vec();
+ expected.extend_from_slice(frame.body());
+ assert_eq!(*bytes.lock(), expected);
+ if renewal {
+ assert_eq!(
+ output.execute(&[(grant, target(42))], || ()),
+ Err(Error::Revoked)
+ );
+ } else {
+ assert!(output.execute(&[(grant, target(42))], || ()).is_ok());
+ }
+ }
+ }
+
+ #[test]
+ fn output_synchronization_keeps_revocation_expiry_and_lease_failures_closed() {
+ for failure in 0..5 {
+ let (output, clock, mut status, grant) = fixture();
+ clock.set(100);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let next = GrantRef {
+ id: Id::from_bytes([2; 16]),
+ ..grant
+ };
+ let refs = [(next, target(42)), (grant, target(42))];
+ let (mut channel, bytes) = recording_channel(false);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ assert!(bytes.lock().is_empty());
+ match failure {
+ 0 => {
+ output.revoke(next);
+ let mut added = status.grants[0].clone();
+ added.grant = next;
+ status.grants.push(added);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ }
+ 1 => output.close(),
+ 2 => clock.set(99),
+ 3 => clock.set(2100),
+ 4 => clock.set(4100),
+ _ => unreachable!(),
+ }
+ assert_eq!(pending.await, Err(Error::Revoked));
+ });
+ assert!(bytes.lock().is_empty());
+ }
+ }
+
+ #[test]
+ fn output_synchronization_keeps_the_original_request_deadline() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let next = GrantRef {
+ version: 2,
+ ..grant
+ };
+ let (mut channel, bytes) = recording_channel(false);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ let result = smol::block_on(write_reply(
+ &output,
+ &mut channel,
+ &frame,
+ &[(next, target(42))],
+ &Deadline::after(Duration::from_millis(10)).unwrap(),
+ ));
+ assert_eq!(result, Err(Error::Timeout));
+ assert!(bytes.lock().is_empty());
+ }
+
+ #[test]
+ fn synchronized_output_still_checks_every_partial_write() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let (mut channel, bytes) = recording_channel(true);
+ let frame = Frame::new(Kind::Reply, 1, b"example").unwrap();
+ let refs = [(grant, target(42))];
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let mut pending =
+ Box::pin(write_reply(&output, &mut channel, &frame, &refs, &deadline));
+ assert!(futures::poll!(&mut pending).is_pending());
+ assert_eq!(bytes.lock().len(), 3);
+ output.revoke(grant);
+ assert_eq!(pending.await, Err(Error::Revoked));
+ });
+ assert_eq!(bytes.lock().len(), 3);
+ }
+
+ #[test]
+ fn output_replica_includes_status_latency_in_expiration() {
+ let (output, clock, status, grant) = fixture();
+ let before = clock.now().unwrap();
+ clock.set(1500);
+ output.update(before, &status).unwrap();
+ assert!(output.execute(&[(grant, target(42))], || ()).is_ok());
+ clock.set(2000);
+ assert!(output
+ .execute(&[(grant, target(42))], || panic!("expired output was sent"))
+ .is_err());
+ }
+
+ #[test]
+ fn pending_status_cannot_restore_a_locally_revoked_grant() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ output.revoke(grant);
+ clock.set(500);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ assert!(output
+ .execute(&[(grant, target(42))], || panic!("revoked output was sent"))
+ .is_err());
+ assert!(output
+ .execute(&[(grant, target(43))], || panic!("wrong pane was sent"))
+ .is_err());
+ }
+
+ #[test]
+ fn output_replica_needs_a_live_control_lease_and_exact_version() {
+ let (output, clock, mut status, grant) = fixture();
+ status.grants[0].remaining_ms = 60000;
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let stale = GrantRef {
+ version: 2,
+ ..grant
+ };
+ assert!(output.execute(&[(stale, target(42))], || ()).is_err());
+ clock.set(4000);
+ assert!(output.execute(&[(grant, target(42))], || ()).is_err());
+ output.close();
+ assert!(output.update(clock.now().unwrap(), &status).is_err());
+ }
+
+ /// The router's end and the host's end of one bridge, over real sockets.
+ #[cfg(unix)]
+ mod bridge {
+ use super::*;
+ use std::os::unix::net::UnixStream;
+ use thinkterm_reverse_access::protocol::{ExportRef, ReadOptions};
+ use thinkterm_reverse_access::Target;
+
+ type Socket = smol::Async<UnixStream>;
+ const SEQUENCE: u64 = 7;
+
+ struct Ends {
+ near_router: Channel<Socket>,
+ near_host: Channel<Socket>,
+ router: Channel<Socket>,
+ host: Channel<Socket>,
+ _budgets: Budgets,
+ }
+
+ fn ends() -> Ends {
+ let budgets = Budgets::new().unwrap();
+ let budget = budgets.open_route(Id::from_bytes([9; 16])).unwrap();
+ let channel = |socket| Channel::new(socket, budget.acquire(1024 * 1024).unwrap());
+ let (near_router, router) = Socket::pair().unwrap();
+ let (near_host, host) = Socket::pair().unwrap();
+ Ends {
+ near_router: channel(near_router).unwrap(),
+ near_host: channel(near_host).unwrap(),
+ router: channel(router).unwrap(),
+ host: channel(host).unwrap(),
+ _budgets: budgets,
+ }
+ }
+
+ fn read_command(grant: GrantRef, pane: u64) -> Command {
+ Command::Read {
+ export: ExportRef {
+ grant,
+ target: Target {
+ pane,
+ incarnation: Id::from_bytes([3; 16]),
+ owner: Id::from_bytes([5; 16]),
+ },
+ },
+ options: ReadOptions::default(),
+ }
+ }
+
+ async fn serve_text(host: &mut Channel<Socket>, text: &[u8], deadline: &Deadline) {
+ let frame = host.read(Some(deadline)).await.unwrap();
+ assert_eq!(frame.sequence(), SEQUENCE);
+ let reply = Reply::Text { bytes: text.len() };
+ host.write_json(Kind::Reply, SEQUENCE, &reply, deadline)
+ .await
+ .unwrap();
+ send_payload(host, text, SEQUENCE, Kind::TextBlock, deadline)
+ .await
+ .unwrap();
+ }
+
+ #[test]
+ fn a_refused_reply_is_answered_and_its_text_consumed() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let mut ends = ends();
+ let deadline = Deadline::request().unwrap();
+ let text = "example".repeat(20_000);
+ smol::block_on(async {
+ let (forwarded, _) = smol::future::zip(
+ forward_request(
+ &mut ends.near_router,
+ &mut ends.near_host,
+ &output,
+ // A selected-terminal grant that never had this pane.
+ read_command(grant, 43),
+ Ok(None),
+ SEQUENCE,
+ &deadline,
+ ),
+ serve_text(&mut ends.host, text.as_bytes(), &deadline),
+ )
+ .await;
+ forwarded.unwrap();
+ let frame = ends.router.read(Some(&deadline)).await.unwrap();
+ let reply: Reply = parse(&frame, Kind::Reply, SEQUENCE).unwrap();
+ assert!(matches!(reply, Reply::Failed(_)));
+ // Both channels are at a frame boundary.
+ assert!(ends.near_host.watch_peer().now_or_never().is_none());
+ assert!(ends.near_router.watch_peer().now_or_never().is_none());
+ });
+ }
+
+ #[test]
+ fn a_reply_refused_partway_is_abandoned_between_blocks() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let mut ends = ends();
+ let deadline = Deadline::request().unwrap();
+ let text = "example".repeat(20_000);
+ smol::block_on(async {
+ let router = &mut ends.router;
+ let (forwarded, _) = smol::future::zip(
+ forward_request(
+ &mut ends.near_router,
+ &mut ends.near_host,
+ &output,
+ read_command(grant, 42),
+ Ok(None),
+ SEQUENCE,
+ &deadline,
+ ),
+ smol::future::zip(
+ serve_text(&mut ends.host, text.as_bytes(), &deadline),
+ async {
+ let frame = router.read(Some(&deadline)).await.unwrap();
+ let reply: Reply = parse(&frame, Kind::Reply, SEQUENCE).unwrap();
+ assert!(matches!(reply, Reply::Text { .. }));
+ let frame = router.read(Some(&deadline)).await.unwrap();
+ assert_eq!(frame.kind(), Kind::TextBlock);
+ output.revoke(grant);
+ loop {
+ let frame = router.read(Some(&deadline)).await.unwrap();
+ if frame.kind() == Kind::Cancel {
+ assert_eq!(frame.sequence(), SEQUENCE);
+ break;
+ }
+ assert_eq!(frame.kind(), Kind::TextBlock);
+ }
+ },
+ ),
+ )
+ .await;
+ forwarded.unwrap();
+ assert!(ends.near_host.watch_peer().now_or_never().is_none());
+ });
+ }
+
+ #[test]
+ fn a_reply_past_the_hosts_time_is_abandoned_between_blocks() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let mut ends = ends();
+ // The host stops starting blocks after the first 300 ms of these.
+ let deadline = Deadline::after(2 * REPLY_MARGIN + Duration::from_millis(300)).unwrap();
+ let block = |offset: u32, text: &[u8]| {
+ let body = [&offset.to_be_bytes()[..], text].concat();
+ Frame::new(Kind::TextBlock, SEQUENCE, &body).unwrap()
+ };
+ smol::block_on(async {
+ let host = &mut ends.host;
+ let (forwarded, _) = smol::future::zip(
+ forward_request(
+ &mut ends.near_router,
+ &mut ends.near_host,
+ &output,
+ read_command(grant, 42),
+ Ok(None),
+ SEQUENCE,
+ &deadline,
+ ),
+ async {
+ host.read(Some(&deadline)).await.unwrap();
+ let reply = Reply::Text { bytes: 100_000 };
+ host.write_json(Kind::Reply, SEQUENCE, &reply, &deadline)
+ .await
+ .unwrap();
+ host.write(&block(0, b"example"), &deadline).await.unwrap();
+ smol::Timer::after(Duration::from_millis(350)).await;
+ host.write(&block(7, b"example"), &deadline).await.unwrap();
+ host.write(&Frame::new(Kind::Cancel, SEQUENCE, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ },
+ )
+ .await;
+ forwarded.unwrap();
+ let read = Deadline::request().unwrap();
+ let frame = ends.router.read(Some(&read)).await.unwrap();
+ let reply: Reply = parse(&frame, Kind::Reply, SEQUENCE).unwrap();
+ assert!(matches!(reply, Reply::Text { .. }));
+ let frame = ends.router.read(Some(&read)).await.unwrap();
+ assert_eq!(frame.kind(), Kind::TextBlock);
+ let frame = ends.router.read(Some(&read)).await.unwrap();
+ assert_eq!(frame.kind(), Kind::Cancel);
+ assert!(ends.near_host.watch_peer().now_or_never().is_none());
+ });
+ }
+
+ #[test]
+ fn a_host_that_abandons_its_text_is_passed_on() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let mut ends = ends();
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ let host = &mut ends.host;
+ let (forwarded, _) = smol::future::zip(
+ forward_request(
+ &mut ends.near_router,
+ &mut ends.near_host,
+ &output,
+ read_command(grant, 42),
+ Ok(None),
+ SEQUENCE,
+ &deadline,
+ ),
+ async {
+ host.read(Some(&deadline)).await.unwrap();
+ let reply = Reply::Text { bytes: 100_000 };
+ host.write_json(Kind::Reply, SEQUENCE, &reply, &deadline)
+ .await
+ .unwrap();
+ send_payload(host, b"example", SEQUENCE, Kind::TextBlock, &deadline)
+ .await
+ .unwrap();
+ host.write(&Frame::new(Kind::Cancel, SEQUENCE, &[]).unwrap(), &deadline)
+ .await
+ .unwrap();
+ },
+ )
+ .await;
+ forwarded.unwrap();
+ ends.router.read(Some(&deadline)).await.unwrap();
+ ends.router.read(Some(&deadline)).await.unwrap();
+ let frame = ends.router.read(Some(&deadline)).await.unwrap();
+ assert_eq!(frame.kind(), Kind::Cancel);
+ });
+ }
+
+ #[test]
+ fn input_refused_on_arrival_never_reaches_the_host() {
+ let (output, clock, status, grant) = fixture();
+ output.update(clock.now().unwrap(), &status).unwrap();
+ let mut ends = ends();
+ let deadline = Deadline::request().unwrap();
+ smol::block_on(async {
+ forward_request(
+ &mut ends.near_router,
+ &mut ends.near_host,
+ &output,
+ read_command(grant, 42),
+ Err(Error::Busy),
+ SEQUENCE,
+ &deadline,
+ )
+ .await
+ .unwrap();
+ let frame = ends.router.read(Some(&deadline)).await.unwrap();
+ let reply: Reply = parse(&frame, Kind::Reply, SEQUENCE).unwrap();
+ assert!(matches!(reply, Reply::Failed(Failure::Busy)));
+ assert!(ends.host.watch_peer().now_or_never().is_none());
+ });
+ }
+ }
+
+ #[test]
+ fn a_backwards_clock_permanently_closes_the_output_guard() {
+ let (output, clock, status, grant) = fixture();
+ clock.set(1000);
+ output.update(clock.now().unwrap(), &status).unwrap();
+ clock.set(999);
+ assert!(output.execute(&[(grant, target(42))], || ()).is_err());
+ clock.set(1001);
+ assert!(output.execute(&[(grant, target(42))], || ()).is_err());
+ }
+}
diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs
index 699019e5..a249f1e3 100644
--- a/wezterm-client/src/domain.rs
+++ b/wezterm-client/src/domain.rs
@@ -2579,6 +2579,12 @@ impl ClientDomain {
self.inner()?.client.remote_os_release()
}
+ pub fn connect_client(&self) -> Option<crate::client::Client> {
+ let inner = self.inner()?;
+ (inner.client.connection_phase() == ClientConnectionPhase::Ready)
+ .then(|| inner.client.clone())
+ }
+
pub(crate) fn inner(&self) -> Option<Arc<ClientInner>> {
self.inner.lock().unwrap().as_ref().map(Arc::clone)
}
diff --git a/wezterm-client/src/lib.rs b/wezterm-client/src/lib.rs
index daca0d5b..d3aa75e2 100644
--- a/wezterm-client/src/lib.rs
+++ b/wezterm-client/src/lib.rs
@@ -1,4 +1,5 @@
pub mod client;
+pub mod connect;
mod connection_io;
pub mod discovery;
pub mod domain;
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index 56eff058..f044464b 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -46,6 +46,7 @@ cc.workspace = true
embed-resource.workspace = true
[dependencies]
+thinkterm-reverse-access = { path = "../thinkterm-reverse-access" }
thinkterm-tailnet = { workspace = true, optional = true }
thinkterm-import-herdr.workspace = true
thinkterm-import.workspace = true
diff --git a/wezterm-gui/src/connect_access.rs b/wezterm-gui/src/connect_access.rs
new file mode 100644
index 00000000..88c3f12f
--- /dev/null
+++ b/wezterm-gui/src/connect_access.rs
@@ -0,0 +1,300 @@
+//! User-initiated reverse Connect grants. No configuration, Lua or mux PDU
+//! entry point invokes this controller.
+
+use mux::domain::DomainId;
+use mux::Mux;
+use parking_lot::Mutex;
+use std::collections::BTreeMap;
+use std::time::Duration;
+use thinkterm_reverse_access::{Error, GrantScope, Permission, Result};
+use wezterm_client::connect::{ExportState, Exporter, HostBinding};
+use wezterm_client::domain::ClientDomain;
+use window::Window;
+
+pub use mux::connect::service::Control;
+
+pub struct Source {
+ pub id: DomainId,
+ pub name: String,
+ pub eligible: bool,
+}
+pub struct HostChoice {
+ pub id: Option<DomainId>,
+ pub name: String,
+}
+
+pub fn sources() -> Vec<Source> {
+ let mut sources = Vec::new();
+ for domain in Mux::get().iter_domains() {
+ let Some(client_domain) = domain.downcast_ref::<ClientDomain>() else {
+ continue;
+ };
+ if client_domain.ssh_domain_config().is_none() {
+ continue;
+ }
+ // A domain exists for every host in the SSH configuration.
+ let Some(client) = client_domain.connect_client() else {
+ continue;
+ };
+ let eligible = client.verified_connect_session().is_some();
+ sources.push(Source {
+ id: domain.domain_id(),
+ name: thinkterm_reverse_access::protocol::display_text(domain.domain_name(), 96),
+ eligible,
+ });
+ }
+ sources.sort_by_key(|source| source.id);
+ sources
+}
+
+pub fn hosts() -> Vec<HostChoice> {
+ let mut hosts = Vec::new();
+ for domain in Mux::get().iter_domains() {
+ let Some(client_domain) = domain.downcast_ref::<ClientDomain>() else {
+ continue;
+ };
+ if client_domain.is_local_session_host()
+ && client_domain.unix_socket_path().is_some()
+ && client_domain.connect_client().is_some()
+ {
+ hosts.push(HostChoice {
+ id: Some(domain.domain_id()),
+ name: crate::i18n::tr("settings-reverse-local-sessions"),
+ });
+ }
+ }
+ hosts.sort_by_key(|host| host.id);
+ hosts.push(HostChoice {
+ id: None,
+ name: crate::i18n::tr("settings-reverse-this-window"),
+ });
+ hosts
+}
+
+struct Entry {
+ source_id: DomainId,
+ host_id: Option<DomainId>,
+ source: String,
+ host: String,
+ exporter: Option<Exporter>,
+ error: Option<Error>,
+ starting: bool,
+ initial: Option<Control>,
+}
+
+#[derive(Default)]
+struct State {
+ next: u64,
+ entries: BTreeMap<u64, Entry>,
+}
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static POLL: crate::page_poll::PollTimer = crate::page_poll::PollTimer::new();
+
+fn with_state<T>(action: impl FnOnce(&mut State) -> T) -> T {
+ action(STATE.lock().get_or_insert_with(State::default))
+}
+
+#[derive(Clone)]
+pub struct View {
+ pub id: u64,
+ pub source_id: DomainId,
+ pub source: String,
+ pub host: String,
+ pub state: ExportState,
+ pub starting: bool,
+}
+
+pub fn views() -> Vec<View> {
+ with_state(|state| {
+ state
+ .entries
+ .iter()
+ .map(|(id, entry)| {
+ let mut view = entry
+ .exporter
+ .as_ref()
+ .map(Exporter::state)
+ .unwrap_or_default();
+ if entry.error.is_some() {
+ view.error = entry.error;
+ }
+ View {
+ id: *id,
+ source_id: entry.source_id,
+ source: entry.source.clone(),
+ host: entry.host.clone(),
+ state: view,
+ starting: entry.starting,
+ }
+ })
+ .collect()
+ })
+}
+
+pub fn arm(window: Window) {
+ if with_state(|state| !state.entries.is_empty()) {
+ POLL.arm(window, Duration::from_secs(1));
+ }
+}
+
+pub fn begin(source_id: DomainId, host_id: Option<DomainId>) -> Result<u64> {
+ begin_scoped(source_id, host_id, GrantScope::SelectedTerminals, None)
+}
+
+pub fn begin_all_local(source_id: DomainId, permission: Permission, seconds: u64) -> Result<u64> {
+ let default_id = Mux::get().default_domain().domain_id();
+ let hosts = hosts();
+ let host_id = hosts
+ .iter()
+ .find(|host| host.id == Some(default_id))
+ .or_else(|| hosts.first())
+ .and_then(|host| host.id);
+ begin_scoped(
+ source_id,
+ host_id,
+ GrantScope::AllLocalTerminals,
+ Some(Control::ApproveAllLocal {
+ permission,
+ seconds,
+ renewal: None,
+ }),
+ )
+}
+
+fn begin_scoped(
+ source_id: DomainId,
+ host_id: Option<DomainId>,
+ scope: GrantScope,
+ initial: Option<Control>,
+) -> Result<u64> {
+ if let Some(id) = with_state(|state| {
+ state.entries.iter().find_map(|(id, entry)| {
+ (entry.source_id == source_id
+ && entry.host_id == host_id
+ && (entry.starting
+ || entry
+ .exporter
+ .as_ref()
+ .is_some_and(|exporter| !exporter.state().closed)))
+ .then_some(*id)
+ })
+ }) {
+ return Ok(id);
+ }
+ let mux = Mux::get();
+ let domain = mux.get_domain(source_id).ok_or(Error::Unavailable)?;
+ let session = domain
+ .downcast_ref::<ClientDomain>()
+ .and_then(ClientDomain::connect_client)
+ .and_then(|client| client.verified_connect_session())
+ .ok_or(Error::Unavailable)?;
+ let source = thinkterm_reverse_access::protocol::display_text(domain.domain_name(), 96);
+ let (host_client, host_name) = match host_id {
+ Some(id) => {
+ let domain = mux.get_domain(id).ok_or(Error::Unavailable)?;
+ let domain = domain
+ .downcast_ref::<ClientDomain>()
+ .ok_or(Error::Unavailable)?;
+ if !domain.is_local_session_host() || domain.unix_socket_path().is_none() {
+ return Err(Error::Unavailable);
+ }
+ (
+ Some(domain.connect_client().ok_or(Error::Unavailable)?),
+ crate::i18n::tr("settings-reverse-local-sessions"),
+ )
+ }
+ None => (None, crate::i18n::tr("settings-reverse-this-window")),
+ };
+ let id = with_state(|state| {
+ if state.entries.len() >= thinkterm_reverse_access::MAX_ROUTES {
+ return Err(Error::Busy);
+ }
+ state.next = state.next.checked_add(1).ok_or(Error::Busy)?;
+ state.entries.insert(
+ state.next,
+ Entry {
+ source_id,
+ host_id,
+ source,
+ host: host_name,
+ exporter: None,
+ error: None,
+ starting: true,
+ initial,
+ },
+ );
+ Ok(state.next)
+ })?;
+ promise::spawn::spawn_into_main_thread(async move {
+ let result = async {
+ let binding = match host_client {
+ Some(client) => HostBinding::local_session(client).await?,
+ None => HostBinding::in_process(&mux)?,
+ };
+ let language = crate::i18n::current_locale().to_string();
+ let exporter = match scope {
+ GrantScope::SelectedTerminals => Exporter::start(session, binding, language).await,
+ GrantScope::AllLocalTerminals => {
+ Exporter::start_all_local(session, binding, language).await
+ }
+ }?;
+ let initial =
+ with_state(|state| state.entries.get_mut(&id).map(|entry| entry.initial.take()))
+ .ok_or(Error::Unavailable)?;
+ if let Some(command) = initial {
+ exporter.command(command)?;
+ }
+ Ok(exporter)
+ }
+ .await;
+ with_state(|state| {
+ if let Some(entry) = state.entries.get_mut(&id) {
+ entry.starting = false;
+ match result {
+ Ok(exporter) => entry.exporter = Some(exporter),
+ Err(error) => entry.error = Some(error),
+ }
+ }
+ });
+ crate::settings_window::invalidate_open_settings_window();
+ })
+ .detach();
+ Ok(id)
+}
+
+pub fn command(id: u64, command: Control) -> Result<()> {
+ with_state(|state| {
+ let entry = state.entries.get_mut(&id).ok_or(Error::Unavailable)?;
+ if entry.starting && matches!(command, Control::Cancel) {
+ entry.initial = None;
+ return Ok(());
+ }
+ entry
+ .exporter
+ .as_ref()
+ .ok_or(Error::Unavailable)?
+ .command(command)
+ })
+}
+
+pub fn close(id: u64) {
+ with_state(|state| {
+ state.entries.remove(&id);
+ });
+}
+
+/// Leaving the editor cancels its unfinished authentication. Active grants
+/// stay visible in the process-wide list until expiry or explicit revocation.
+pub fn leave(id: u64) {
+ with_state(|state| {
+ if let Some(entry) = state.entries.get(&id) {
+ if let Some(exporter) = &entry.exporter {
+ if !exporter.state().status.grants.is_empty() {
+ let _ = exporter.command(Control::Cancel);
+ return;
+ }
+ }
+ }
+ state.entries.remove(&id);
+ });
+}
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index a531c325..020bdaa5 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -40,6 +40,7 @@ mod bottom_quotes;
mod bounded_file;
mod colorease;
mod commands;
+mod connect_access;
mod customglyph;
mod download;
mod editor_projects;
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index bbc01367..0b036bba 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -1778,13 +1778,37 @@ impl NativeServerTerminals {
pub(crate) const ALL: [Self; 3] = [Self::Off, Self::Read, Self::Type];
}
-#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub(crate) struct NativeAgentsSettings {
/// A build without a choice a newer one made falls back to off rather
/// than failing the file.
#[serde(deserialize_with = "choice_or_default")]
pub(crate) server_terminals: NativeServerTerminals,
+ #[serde(deserialize_with = "reverse_minutes")]
+ pub(crate) reverse_access_minutes: u16,
+}
+
+impl Default for NativeAgentsSettings {
+ fn default() -> Self {
+ Self {
+ server_terminals: NativeServerTerminals::Off,
+ reverse_access_minutes: 30,
+ }
+ }
+}
+
+/// A value outside the range reads as the default, and the file is kept: see
+/// [`choice_or_default`].
+fn reverse_minutes<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<u16, D::Error> {
+ let raw = serde_json::Value::deserialize(deserializer)?;
+ match u16::deserialize(&raw) {
+ Ok(value @ 1..=120) => Ok(value),
+ _ => {
+ log::warn!("reverse access duration {raw} is not 1 to 120 minutes; using the default");
+ Ok(NativeAgentsSettings::default().reverse_access_minutes)
+ }
+ }
}
/// How far the programs here may reach servers' terminals. Through the
@@ -3477,6 +3501,19 @@ mod tests {
assert!(settings.sharing.enabled);
}
+ #[test]
+ fn a_reverse_access_duration_out_of_range_costs_only_itself() {
+ let agents = |json: &str| -> NativeAgentsSettings { serde_json::from_str(json).unwrap() };
+ assert_eq!(agents("{}").reverse_access_minutes, 30);
+ assert_eq!(agents(r#"{"reverse_access_minutes": 45}"#).reverse_access_minutes, 45);
+ for bad in ["0", "121", "-1", "70000", "\"long\"", "null"] {
+ let json = format!(r#"{{"reverse_access_minutes": {bad}, "server_terminals": "type"}}"#);
+ let settings = agents(&json);
+ assert_eq!(settings.reverse_access_minutes, 30, "{bad}");
+ assert_eq!(settings.server_terminals, NativeServerTerminals::Type, "{bad}");
+ }
+ }
+
#[test]
fn the_right_sidebar_starts_as_it_was_left_while_that_is_remembered() {
let chrome = |json: &str| -> NativeChromeSettings { serde_json::from_str(json).unwrap() };
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index b7ca1d09..9eb46d61 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -55,6 +55,7 @@ mod session_import;
mod editor_import;
mod import;
mod keymap;
+mod connect_access;
pub(crate) use import::EDITORS_SOURCE;
use import::{ImportButton, ImportSource, ImportStep};
@@ -2311,6 +2312,20 @@ enum SettingsAction {
SetWindowTabs(crate::native_settings::NativeWindowTabs),
SetServerPlacement(crate::native_settings::NativeServerPlacement),
SetServerTerminals(crate::native_settings::NativeServerTerminals),
+ ReverseSourceMenu,
+ ReverseHostMenu,
+ ReverseSource(mux::domain::DomainId),
+ ReverseHost(Option<mux::domain::DomainId>),
+ ReverseSetup,
+ ReversePane(u64),
+ ReversePermission(bool),
+ ReverseApprove,
+ ReverseRefresh,
+ ReverseClose(u64),
+ ReverseCancel(u64),
+ ReverseRevoke(u64, thinkterm_reverse_access::GrantRef),
+ ReverseRenew(u64, thinkterm_reverse_access::GrantRef),
+ ReverseMinutes(i8),
SetTerminalShade(crate::native_settings::NativeShade),
SetThreadIcons(crate::native_settings::NativeThreadIcons),
SetThreadStatus(crate::native_settings::NativeThreadStatus),
@@ -2451,6 +2466,8 @@ enum SettingsDrag {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SettingsDropdown {
+ ReverseSource,
+ ReverseHost,
Language,
MainRenderer,
/// What a see-through window shows behind it, on macOS.
@@ -3990,6 +4007,7 @@ struct SettingsWindow {
chrome_palette: UiPalette,
selected: SettingsSection,
agents_expanded: Option<&'static str>,
+ reverse_access: connect_access::UiState,
native_settings: ThinkTermNativeSettings,
active_main_renderer: NativeRendererBackend,
ui: SettingsUiState,
@@ -4165,6 +4183,7 @@ impl SettingsWindow {
),
selected: initial_section(),
agents_expanded: initial_expanded_agent(),
+ reverse_access: connect_access::UiState::default(),
native_settings,
active_main_renderer,
ui,
@@ -4312,6 +4331,7 @@ impl SettingsWindow {
return;
}
self.cleaned_up = true;
+ self.leave_reverse_editor();
self.commit_focused_input();
// Closed mid-drag: what the windows are previewing is what is kept.
if matches!(self.ui.drag, Some(SettingsDrag::WindowOpacity)) {
@@ -4584,6 +4604,10 @@ impl SettingsWindow {
| SettingsAction::SetCommandPaletteHotkey(_)
| SettingsAction::ToggleWebLinkTtlMenu
| SettingsAction::SetWebLinkTtl(_)
+ | SettingsAction::ReverseSourceMenu
+ | SettingsAction::ReverseHostMenu
+ | SettingsAction::ReverseSource(_)
+ | SettingsAction::ReverseHost(_)
| SettingsAction::TogglePluginBackgroundMenu(_)
| SettingsAction::SetPluginBackground(..)
| SettingsAction::EditorImport(
@@ -6311,6 +6335,9 @@ impl SettingsWindow {
}
fn enter_section(&mut self, section: SettingsSection) {
+ if section != SettingsSection::Agents {
+ self.leave_reverse_editor();
+ }
self.selected = section;
self.ui.content_scroll.reset();
self.ui.open_dropdown = None;
@@ -6729,6 +6756,20 @@ impl SettingsWindow {
self.apply_server_placement(placement)
}
SettingsAction::SetServerTerminals(reach) => self.apply_server_terminals(reach),
+ action @ (SettingsAction::ReverseSourceMenu
+ | SettingsAction::ReverseHostMenu
+ | SettingsAction::ReverseSource(_)
+ | SettingsAction::ReverseHost(_)
+ | SettingsAction::ReverseSetup
+ | SettingsAction::ReversePane(_)
+ | SettingsAction::ReversePermission(_)
+ | SettingsAction::ReverseApprove
+ | SettingsAction::ReverseRefresh
+ | SettingsAction::ReverseClose(_)
+ | SettingsAction::ReverseCancel(_)
+ | SettingsAction::ReverseRevoke(..)
+ | SettingsAction::ReverseRenew(..)
+ | SettingsAction::ReverseMinutes(_)) => self.apply_reverse_action(action),
SettingsAction::SetTerminalShade(shade) => self.apply_window_areas(
"settings-terminal-shade",
localized_shade_label(shade),
@@ -12607,7 +12648,9 @@ impl SettingsWindow {
)?;
let (status_card_y, _) = self.settings_card_geometry(section_y, 0);
let status_bottom = self.paint_agent_status_card(layers, x, status_card_y, max_width)?;
- let status_bottom = self.paint_server_terminals_card(layers, x, status_bottom, max_width)?;
+ let status_bottom =
+ self.paint_server_terminals_card(layers, x, status_bottom, max_width)?;
+ let status_bottom = self.paint_reverse_access_card(layers, x, status_bottom, max_width)?;
let integrations_title_y = status_bottom + self.settings_section_card_gap();
let integrations_card_y = integrations_title_y + self.settings_section_card_gap();
let integrations_first_row_y = integrations_card_y + self.settings_card_top_padding();
@@ -20554,6 +20597,8 @@ impl SettingsWindow {
/// and whether it is the current one.
fn dropdown_menu_options(&self, dropdown: SettingsDropdown) -> Vec<(String, SettingsAction, bool)> {
match dropdown {
+ SettingsDropdown::ReverseSource => self.reverse_source_options(),
+ SettingsDropdown::ReverseHost => self.reverse_host_options(),
SettingsDropdown::Language => self.language_menu_options(),
SettingsDropdown::MacGlass => self.mac_glass_menu_options(),
SettingsDropdown::MainRenderer => self.main_renderer_menu_options(),
diff --git a/wezterm-gui/src/settings_window/connect_access.rs b/wezterm-gui/src/settings_window/connect_access.rs
new file mode 100644
index 00000000..f4d14da1
--- /dev/null
+++ b/wezterm-gui/src/settings_window/connect_access.rs
@@ -0,0 +1,647 @@
+use super::*;
+use crate::connect_access as controller;
+use std::collections::BTreeSet;
+use thinkterm_reverse_access::{Error as AccessError, GrantScope, Permission};
+
+// Keep the selected-terminal editor available for a future UI iteration.
+const SELECT_TERMINALS_IN_UI: bool = false;
+
+#[derive(Default)]
+pub(super) struct UiState {
+ source: Option<mux::domain::DomainId>,
+ host: Option<mux::domain::DomainId>,
+ host_chosen: bool,
+ editor: Option<u64>,
+ panes: BTreeSet<u64>,
+ input: bool,
+}
+
+impl SettingsWindow {
+ pub(super) fn leave_reverse_editor(&mut self) {
+ if let Some(id) = self.reverse_access.editor.take() {
+ controller::leave(id);
+ }
+ self.reverse_access.panes.clear();
+ }
+
+ pub(super) fn reverse_source_options(&self) -> Vec<(String, SettingsAction, bool)> {
+ controller::sources()
+ .into_iter()
+ .map(|source| {
+ let label = if source.eligible {
+ source.name
+ } else {
+ format!(
+ "{} — {}",
+ source.name,
+ crate::i18n::tr("settings-reverse-ineligible-short")
+ )
+ };
+ (
+ label,
+ SettingsAction::ReverseSource(source.id),
+ self.reverse_access.source == Some(source.id),
+ )
+ })
+ .collect()
+ }
+
+ pub(super) fn reverse_host_options(&self) -> Vec<(String, SettingsAction, bool)> {
+ controller::hosts()
+ .into_iter()
+ .map(|host| {
+ (
+ host.name,
+ SettingsAction::ReverseHost(host.id),
+ self.reverse_access.host == host.id,
+ )
+ })
+ .collect()
+ }
+
+ pub(super) fn apply_reverse_action(&mut self, action: SettingsAction) {
+ use controller::Control;
+ let result = (|| -> thinkterm_reverse_access::Result<()> {
+ match action {
+ SettingsAction::ReverseSourceMenu | SettingsAction::ReverseHostMenu => {
+ let menu = if action == SettingsAction::ReverseSourceMenu {
+ SettingsDropdown::ReverseSource
+ } else {
+ SettingsDropdown::ReverseHost
+ };
+ self.ui.open_dropdown = (self.ui.open_dropdown != Some(menu)).then_some(menu);
+ }
+ SettingsAction::ReverseSource(source) => {
+ self.leave_reverse_editor();
+ self.reverse_access.source = Some(source);
+ self.ui.open_dropdown = None;
+ }
+ SettingsAction::ReverseHost(host) => {
+ self.leave_reverse_editor();
+ self.reverse_access.host = host;
+ self.reverse_access.host_chosen = true;
+ self.ui.open_dropdown = None;
+ }
+ SettingsAction::ReverseSetup => {
+ self.leave_reverse_editor();
+ let source = self.reverse_access.source.ok_or(AccessError::Unavailable)?;
+ self.reverse_access.editor = Some(if SELECT_TERMINALS_IN_UI {
+ controller::begin(source, self.reverse_access.host)?
+ } else {
+ controller::begin_all_local(
+ source,
+ if self.reverse_access.input {
+ Permission::ReadAndInput
+ } else {
+ Permission::Read
+ },
+ u64::from(self.native_settings.agents.reverse_access_minutes) * 60,
+ )?
+ });
+ }
+ SettingsAction::ReversePane(pane) => {
+ self.cancel_reverse_authentication();
+ if !self.reverse_access.panes.remove(&pane) {
+ if self.reverse_access.panes.len()
+ >= thinkterm_reverse_access::MAX_TARGETS_PER_GRANT
+ {
+ return Err(AccessError::TooLarge);
+ }
+ self.reverse_access.panes.insert(pane);
+ }
+ }
+ SettingsAction::ReversePermission(input) => {
+ self.cancel_reverse_authentication();
+ self.reverse_access.input = input;
+ }
+ SettingsAction::ReverseApprove => {
+ let id = self.reverse_access.editor.ok_or(AccessError::Unavailable)?;
+ if SELECT_TERMINALS_IN_UI && self.reverse_access.panes.is_empty() {
+ return Err(AccessError::Unavailable);
+ }
+ controller::command(
+ id,
+ if SELECT_TERMINALS_IN_UI {
+ Control::Approve {
+ panes: self.reverse_access.panes.iter().copied().collect(),
+ permission: if self.reverse_access.input {
+ Permission::ReadAndInput
+ } else {
+ Permission::Read
+ },
+ seconds: u64::from(
+ self.native_settings.agents.reverse_access_minutes,
+ ) * 60,
+ renewal: None,
+ }
+ } else {
+ Control::ApproveAllLocal {
+ permission: if self.reverse_access.input {
+ Permission::ReadAndInput
+ } else {
+ Permission::Read
+ },
+ seconds: u64::from(
+ self.native_settings.agents.reverse_access_minutes,
+ ) * 60,
+ renewal: None,
+ }
+ },
+ )?;
+ }
+ SettingsAction::ReverseRefresh => {
+ self.cancel_reverse_authentication();
+ self.reverse_access.panes.clear();
+ controller::command(
+ self.reverse_access.editor.ok_or(AccessError::Unavailable)?,
+ Control::Choices { after: None },
+ )?;
+ }
+ SettingsAction::ReverseClose(id) => {
+ controller::close(id);
+ if self.reverse_access.editor == Some(id) {
+ self.reverse_access.editor = None;
+ self.reverse_access.panes.clear();
+ }
+ }
+ SettingsAction::ReverseCancel(id) => controller::command(id, Control::Cancel)?,
+ SettingsAction::ReverseRevoke(id, grant) => {
+ controller::command(id, Control::Revoke { grant })?
+ }
+ SettingsAction::ReverseRenew(id, grant) => {
+ let view = controller::views()
+ .into_iter()
+ .find(|view| view.id == id)
+ .ok_or(AccessError::Unavailable)?;
+ let grant = view
+ .state
+ .status
+ .grants
+ .into_iter()
+ .find(|active| active.grant == grant)
+ .ok_or(AccessError::Unavailable)?;
+ controller::command(
+ id,
+ if grant.scope == GrantScope::SelectedTerminals {
+ Control::Approve {
+ panes: grant.targets.iter().map(|target| target.0).collect(),
+ permission: grant.permission,
+ seconds: u64::from(
+ self.native_settings.agents.reverse_access_minutes,
+ ) * 60,
+ renewal: Some(grant.grant),
+ }
+ } else {
+ Control::ApproveAllLocal {
+ permission: grant.permission,
+ seconds: u64::from(
+ self.native_settings.agents.reverse_access_minutes,
+ ) * 60,
+ renewal: Some(grant.grant),
+ }
+ },
+ )?;
+ }
+ SettingsAction::ReverseMinutes(change) => {
+ let mut settings = crate::native_settings::load();
+ settings.agents.reverse_access_minutes = if change == 0 {
+ 30
+ } else {
+ (i32::from(settings.agents.reverse_access_minutes) + i32::from(change))
+ .clamp(1, 120) as u16
+ };
+ crate::native_settings::save(&settings)
+ .map_err(|_| AccessError::Unavailable)?;
+ self.set_native_settings(settings);
+ }
+ _ => return Err(AccessError::Protocol),
+ }
+ Ok(())
+ })();
+ if result.is_err() {
+ self.status = crate::i18n::tr("settings-reverse-error");
+ }
+ }
+
+ fn cancel_reverse_authentication(&self) {
+ if let Some(id) = self.reverse_access.editor {
+ let _ = controller::command(id, controller::Control::Cancel);
+ }
+ }
+
+ pub(super) fn paint_reverse_access_card(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator<'_>,
+ x: f32,
+ above: f32,
+ width: f32,
+ ) -> anyhow::Result<f32> {
+ let sources = controller::sources();
+ let hosts = controller::hosts();
+ if !sources
+ .iter()
+ .any(|source| Some(source.id) == self.reverse_access.source)
+ {
+ self.reverse_access.source = sources
+ .iter()
+ .find(|source| source.eligible)
+ .or_else(|| sources.first())
+ .map(|source| source.id);
+ }
+ if !self.reverse_access.host_chosen {
+ self.reverse_access.host = hosts.first().and_then(|host| host.id);
+ self.reverse_access.host_chosen = true;
+ }
+ let views = controller::views();
+ if !SELECT_TERMINALS_IN_UI && self.reverse_access.editor.is_none() {
+ self.reverse_access.editor = views
+ .iter()
+ .find(|view| {
+ Some(view.source_id) == self.reverse_access.source && !view.state.closed
+ })
+ .map(|view| view.id);
+ }
+ if let Some(window) = self.window.clone() {
+ controller::arm(window);
+ }
+ let selected = sources
+ .iter()
+ .find(|source| Some(source.id) == self.reverse_access.source);
+ let source_label = selected
+ .map(|source| source.name.clone())
+ .unwrap_or_else(|| crate::i18n::tr("settings-reverse-no-connection"));
+ let host_label = hosts
+ .iter()
+ .find(|host| host.id == self.reverse_access.host)
+ .map(|host| host.name.clone())
+ .unwrap_or_else(|| crate::i18n::tr("settings-reverse-unavailable"));
+ let eligible = selected.is_some_and(|source| source.eligible);
+ let row_x = x + self.ui_px(36.0);
+ let row_width = width - self.ui_px(72.0);
+ let heading = crate::i18n::tr("settings-reverse-heading");
+ let y = self.paint_card_heading(layers, x, above, width, &heading)?;
+ // Still being tried, and said so after its heading, as sharing is.
+ let body_font = Rc::clone(&self.body_font);
+ let heading_width = self.measure_text_width(&body_font, &heading).min(width);
+ self.paint_beta_badge(
+ layers,
+ x + heading_width + self.ui_px(14.0),
+ above + self.settings_section_card_gap(),
+ x + width,
+ )?;
+ self.paint_card_as(
+ layers,
+ x,
+ y,
+ width,
+ CardLayout {
+ description_lines: 4,
+ ..self.card_layout()
+ },
+ |this, layers, top| {
+ let mut rows = RowCursor::new(top, this);
+ rows.add(this.paint_label_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-intro"),
+ &crate::i18n::tr("settings-reverse-description"),
+ false,
+ )?);
+ let minutes = this.native_settings.agents.reverse_access_minutes;
+ rows.add(this.paint_font_size_stepper_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-duration"),
+ &crate::i18n::tr("settings-reverse-duration-description"),
+ f64::from(minutes),
+ Some(&settings_tr(
+ "settings-reverse-minutes",
+ &[("minutes", minutes.to_string())],
+ )),
+ SettingsAction::ReverseMinutes(0),
+ SettingsAction::ReverseMinutes(-1),
+ SettingsAction::ReverseMinutes(1),
+ rows.rule(),
+ )?);
+ rows.add(this.paint_choice_dropdown_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ rows.rule(),
+ SettingsDropdown::ReverseSource,
+ SettingsAction::ReverseSourceMenu,
+ "settings-reverse-source",
+ source_label,
+ )?);
+ if !SELECT_TERMINALS_IN_UI
+ && !views.iter().any(|view| {
+ Some(view.id) == this.reverse_access.editor
+ && !view.state.status.grants.is_empty()
+ })
+ {
+ let options = vec![
+ (
+ crate::i18n::tr("settings-reverse-read"),
+ SettingsAction::ReversePermission(false),
+ ),
+ (
+ crate::i18n::tr("settings-reverse-input"),
+ SettingsAction::ReversePermission(true),
+ ),
+ ];
+ rows.add(this.paint_segmented_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-permission"),
+ &crate::i18n::tr("settings-reverse-permission-description"),
+ &options,
+ usize::from(this.reverse_access.input),
+ rows.rule(),
+ )?);
+ }
+ if eligible {
+ if SELECT_TERMINALS_IN_UI {
+ rows.add(this.paint_choice_dropdown_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ rows.rule(),
+ SettingsDropdown::ReverseHost,
+ SettingsAction::ReverseHostMenu,
+ "settings-reverse-host",
+ host_label,
+ )?);
+ }
+ if this.reverse_access.editor.is_none() {
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr(if SELECT_TERMINALS_IN_UI {
+ "settings-reverse-select"
+ } else {
+ "settings-reverse-all-local"
+ }),
+ &crate::i18n::tr(if SELECT_TERMINALS_IN_UI {
+ "settings-reverse-select-description"
+ } else {
+ "settings-reverse-all-description"
+ }),
+ &crate::i18n::tr(if SELECT_TERMINALS_IN_UI {
+ "settings-reverse-choose"
+ } else {
+ "settings-reverse-authenticate"
+ }),
+ SettingsAction::ReverseSetup,
+ rows.rule(),
+ )?);
+ }
+ } else {
+ rows.add(this.paint_label_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr(if selected.is_some() {
+ "settings-reverse-ineligible-short"
+ } else {
+ "settings-reverse-all-local"
+ }),
+ &crate::i18n::tr(if selected.is_some() {
+ "settings-reverse-ineligible"
+ } else {
+ "settings-reverse-connect-first"
+ }),
+ rows.rule(),
+ )?);
+ }
+ if let Some(view) = views
+ .iter()
+ .find(|view| Some(view.id) == this.reverse_access.editor)
+ {
+ let active: BTreeSet<_> = view
+ .state
+ .status
+ .grants
+ .iter()
+ .flat_map(|grant| grant.targets.iter().map(|target| target.0))
+ .collect();
+ this.reverse_access
+ .panes
+ .retain(|pane| !active.contains(pane));
+ if view.starting {
+ rows.add(this.paint_label_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-loading"),
+ "",
+ rows.rule(),
+ )?);
+ } else if !view.state.closed
+ && view.state.error.is_none()
+ && (SELECT_TERMINALS_IN_UI || view.state.status.grants.is_empty())
+ {
+ if SELECT_TERMINALS_IN_UI {
+ for pane in &view.state.choices {
+ if active.contains(&pane.pane) {
+ continue;
+ }
+ rows.add(this.paint_toggle_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &settings_tr(
+ "settings-reverse-pane",
+ &[("pane", pane.pane.to_string())],
+ ),
+ &pane.title,
+ this.reverse_access.panes.contains(&pane.pane),
+ SettingsAction::ReversePane(pane.pane),
+ rows.rule(),
+ )?);
+ }
+ }
+ if SELECT_TERMINALS_IN_UI {
+ let options = vec![
+ (
+ crate::i18n::tr("settings-reverse-read"),
+ SettingsAction::ReversePermission(false),
+ ),
+ (
+ crate::i18n::tr("settings-reverse-input"),
+ SettingsAction::ReversePermission(true),
+ ),
+ ];
+ rows.add(this.paint_segmented_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-permission"),
+ &crate::i18n::tr("settings-reverse-permission-description"),
+ &options,
+ usize::from(this.reverse_access.input),
+ rows.rule(),
+ )?);
+ }
+ if (!SELECT_TERMINALS_IN_UI || !this.reverse_access.panes.is_empty())
+ && !view.state.status.authenticating
+ {
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr(if SELECT_TERMINALS_IN_UI {
+ "settings-reverse-approve"
+ } else {
+ "settings-reverse-all-local"
+ }),
+ &crate::i18n::tr("settings-reverse-approve-description"),
+ &crate::i18n::tr("settings-reverse-authenticate"),
+ SettingsAction::ReverseApprove,
+ rows.rule(),
+ )?);
+ }
+ if SELECT_TERMINALS_IN_UI {
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-refresh"),
+ &crate::i18n::tr("settings-reverse-refresh-description"),
+ &crate::i18n::tr("settings-reverse-refresh-button"),
+ SettingsAction::ReverseRefresh,
+ rows.rule(),
+ )?);
+ }
+ }
+ }
+ for view in &views {
+ let heading = if SELECT_TERMINALS_IN_UI {
+ format!("{} · {}", view.source, view.host)
+ } else {
+ view.source.clone()
+ };
+ if view.state.status.authenticating {
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &heading,
+ &crate::i18n::tr("settings-reverse-authenticating"),
+ &crate::i18n::tr("settings-reverse-cancel"),
+ SettingsAction::ReverseCancel(view.id),
+ rows.rule(),
+ )?);
+ }
+ for grant in &view.state.status.grants {
+ let seconds = grant.remaining_ms / 1000;
+ let scope = settings_tr(
+ if grant.scope == GrantScope::AllLocalTerminals {
+ "settings-reverse-all-active"
+ } else {
+ "settings-reverse-active"
+ },
+ &[
+ ("count", grant.targets.len().to_string()),
+ (
+ "panes",
+ grant
+ .targets
+ .iter()
+ .map(|target| target.0.to_string())
+ .collect::<Vec<_>>()
+ .join(", "),
+ ),
+ ("time", format!("{}:{:02}", seconds / 60, seconds % 60)),
+ (
+ "permission",
+ crate::i18n::tr(if grant.permission == Permission::Read {
+ "settings-reverse-read"
+ } else {
+ "settings-reverse-input"
+ }),
+ ),
+ ],
+ );
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &heading,
+ &scope,
+ &crate::i18n::tr("settings-reverse-revoke"),
+ SettingsAction::ReverseRevoke(view.id, grant.grant),
+ rows.rule(),
+ )?);
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &crate::i18n::tr("settings-reverse-renew"),
+ &crate::i18n::tr("settings-reverse-renew-description"),
+ &crate::i18n::tr("settings-reverse-authenticate"),
+ SettingsAction::ReverseRenew(view.id, grant.grant),
+ rows.rule(),
+ )?);
+ }
+ if view.state.closed
+ || view.state.error.is_some()
+ || view.state.status.error.is_some()
+ {
+ let message =
+ crate::i18n::tr(if view.state.closed && view.state.error.is_none() {
+ "settings-reverse-ended"
+ } else {
+ "settings-reverse-error"
+ });
+ if view.state.status.grants.is_empty() {
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &heading,
+ &message,
+ &crate::i18n::tr("settings-reverse-dismiss"),
+ SettingsAction::ReverseClose(view.id),
+ rows.rule(),
+ )?);
+ } else {
+ // The grant is fine: only this message goes.
+ rows.add(this.paint_action_setting_row(
+ layers,
+ row_x,
+ rows.y,
+ row_width,
+ &heading,
+ &message,
+ &crate::i18n::tr("settings-reverse-dismiss"),
+ SettingsAction::ReverseCancel(view.id),
+ rows.rule(),
+ )?);
+ }
+ }
+ }
+ Ok(rows.bottom)
+ },
+ )
+ }
+}
diff --git a/wezterm-mux-server-impl/src/handoff.rs b/wezterm-mux-server-impl/src/handoff.rs
index 04f2b9d7..63916d51 100644
--- a/wezterm-mux-server-impl/src/handoff.rs
+++ b/wezterm-mux-server-impl/src/handoff.rs
@@ -774,6 +774,7 @@ struct Capture {
panes: Vec<(HandoffPane, PaneObjects)>,
topology: Vec<HandoffWindow>,
paused: Vec<PausedReader>,
+ connect: mux::ConnectSuspension,
}
fn serve_inner(stream: &mut UnixStream, socket_path: &Path) -> anyhow::Result<()> {
@@ -859,6 +860,7 @@ fn serve_inner(stream: &mut UnixStream, socket_path: &Path) -> anyhow::Result<()
for paused in capture.paused {
paused.keep();
}
+ capture.connect.keep();
Ok(())
}
@@ -920,6 +922,7 @@ where
/// Runs on the main thread, where the mux is read.
fn capture(pid_file: bool) -> anyhow::Result<Capture> {
let mux = Mux::get();
+ let connect = mux.suspend_connect();
let local_domain = mux.default_domain().domain_id();
let mut paused = Vec::new();
let mut panes = Vec::new();
@@ -929,8 +932,11 @@ fn capture(pid_file: bool) -> anyhow::Result<Capture> {
for pane in mux.iter_panes() {
let pane_id = pane.pane_id();
let parts = match pane.downcast_ref::<LocalPane>() {
- Some(local) if pane.domain_id() == local_domain => travelling_parts(local)
- .with_context(|| format!("pane {pane_id} cannot be handed over"))?,
+ Some(local) if pane.domain_id() == local_domain => {
+ local.quiesce_connect_input()?;
+ travelling_parts(local)
+ .with_context(|| format!("pane {pane_id} cannot be handed over"))?
+ }
_ => None,
};
let Some(parts) = parts else {
@@ -1010,6 +1016,7 @@ fn capture(pid_file: bool) -> anyhow::Result<Capture> {
panes,
topology,
paused,
+ connect,
})
}
diff --git a/wezterm-mux-server-impl/src/session_import/pty.rs b/wezterm-mux-server-impl/src/session_import/pty.rs
index 509f8328..809c286a 100644
--- a/wezterm-mux-server-impl/src/session_import/pty.rs
+++ b/wezterm-mux-server-impl/src/session_import/pty.rs
@@ -1,11 +1,12 @@
use anyhow::{Context, Result};
-use portable_pty::{MasterPty, PtySize};
+use portable_pty::unix::NonblockingInput;
+use portable_pty::{MasterPty, PtySize, TryInputWriter};
use rustix::event::{poll, PollFd, PollFlags};
use std::fs::File;
use std::io::{self, Read, Write};
use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
use std::path::PathBuf;
-use std::sync::Mutex;
+use std::sync::{Arc, Mutex};
/// Duplicates are reserved before commit; dropping them only closes them.
/// Unlike UnixMasterWriter, these files never inject EOF when dropped.
@@ -15,6 +16,7 @@ pub struct ImportedPty {
master: OwnedFd,
reader: Mutex<Option<File>>,
writer: Mutex<Option<File>>,
+ input: Mutex<Option<Arc<NonblockingInput>>>,
}
struct ImportedWriter(File);
@@ -95,6 +97,7 @@ impl ImportedPty {
master,
reader: Mutex::new(Some(reader)),
writer: Mutex::new(Some(writer)),
+ input: Mutex::new(None),
})
}
}
@@ -142,6 +145,25 @@ impl MasterPty for ImportedPty {
)))
}
+ /// `ImportedReader` and `ImportedWriter` already work either way.
+ fn try_input_writer(&self) -> Result<Box<dyn TryInputWriter>> {
+ let mut input = self.input.lock().unwrap();
+ if let Some(input) = input.as_ref() {
+ return Ok(input.writer());
+ }
+ let created = NonblockingInput::new(&self.master)?;
+ let writer = created.writer();
+ *input = Some(created);
+ Ok(writer)
+ }
+
+ fn quiesce_input(&self) -> Result<()> {
+ if let Some(input) = self.input.lock().unwrap().take() {
+ input.close()?;
+ }
+ Ok(())
+ }
+
fn as_raw_fd(&self) -> Option<RawFd> {
Some(self.master.as_raw_fd())
}
diff --git a/wezterm-mux-server-impl/src/session_import/tests.rs b/wezterm-mux-server-impl/src/session_import/tests.rs
index bb8de061..fac0d231 100644
--- a/wezterm-mux-server-impl/src/session_import/tests.rs
+++ b/wezterm-mux-server-impl/src/session_import/tests.rs
@@ -327,3 +327,46 @@ fn a_shell_is_known_by_its_program_name() {
assert!(!names_a_shell(&program), "{:?}", program);
}
}
+
+/// Delegated input works from the start, without changing how the imported
+/// reader and writer behave, and a handoff ends it.
+#[test]
+fn imported_terminal_takes_delegated_input_until_handed_off() {
+ let pty = nix::pty::openpty(None, None).unwrap();
+ let mut attributes = nix::sys::termios::tcgetattr(&pty.slave).unwrap();
+ nix::sys::termios::cfmakeraw(&mut attributes);
+ nix::sys::termios::tcsetattr(
+ &pty.slave,
+ nix::sys::termios::SetArg::TCSANOW,
+ &attributes,
+ )
+ .unwrap();
+ let master = pty::ImportedPty::prepare(pty.master).unwrap();
+ let mut regular = portable_pty::MasterPty::take_writer(&master).unwrap();
+ let mut reader = portable_pty::MasterPty::try_clone_reader(&master).unwrap();
+ let mut delegated = portable_pty::MasterPty::try_input_writer(&master).unwrap();
+ assert_eq!(delegated.try_write(b"typed").unwrap(), 5);
+ regular.write_all(b"after").unwrap();
+ let mut slave = std::fs::File::from(pty.slave);
+ let mut bytes = [0; 10];
+ slave.read_exact(&mut bytes).unwrap();
+ assert_eq!(&bytes, b"typedafter");
+
+ // Reading does not fail on the descriptor having turned nonblocking.
+ let read = std::thread::spawn(move || {
+ let mut bytes = [0; 5];
+ reader.read_exact(&mut bytes).unwrap();
+ bytes
+ });
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ slave.write_all(b"reply").unwrap();
+ assert_eq!(&read.join().unwrap(), b"reply");
+
+ portable_pty::MasterPty::quiesce_input(&master).unwrap();
+ assert_eq!(
+ delegated.try_write(b"stale").unwrap_err().kind(),
+ std::io::ErrorKind::BrokenPipe
+ );
+ let mut next = portable_pty::MasterPty::try_input_writer(&master).unwrap();
+ assert_eq!(next.try_write(b"next").unwrap(), 4);
+}
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index 4025ed62..8d53c649 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -1567,6 +1567,20 @@ impl SessionHandler {
spawn_into_main_thread(push_pane_changes_when_free(pane_id, sender, per_pane)).detach();
}
+ fn connect_endpoint(&self) -> anyhow::Result<Pdu> {
+ if !matches!(self.peer, ConnectionPeer::Local) {
+ anyhow::bail!("Connect local endpoint is unavailable");
+ }
+ let mux = Mux::get();
+ let service = mux.connect_service()?;
+ Ok(Pdu::GetConnectEndpointResponse(
+ GetConnectEndpointResponse {
+ server_id: mux.runtime_server_id().to_string(),
+ address: service.name().to_string(),
+ },
+ ))
+ }
+
pub fn process_one(&mut self, decoded: DecodedPdu) {
let start = Instant::now();
let sender = self.to_write_tx.clone();
@@ -2997,6 +3011,8 @@ impl SessionHandler {
}
}
+ Pdu::GetConnectEndpoint(_) => send_response(self.connect_endpoint()),
+
// Carried to the plugin host unread; see plugin_relay.
Pdu::PluginFrame(PluginFrame { data }) => {
if data.is_empty() {
@@ -3473,6 +3489,7 @@ impl SessionHandler {
| Pdu::SearchScrollbackResponse { .. }
| Pdu::GetLinesResponse { .. }
| Pdu::GetCodecVersionResponse { .. }
+ | Pdu::GetConnectEndpointResponse { .. }
| Pdu::WindowWorkspaceChanged { .. }
| Pdu::GetTlsCredsResponse { .. }
| Pdu::WebTokenMintResponse { .. }
diff --git a/wezterm-mux-server-impl/tests/session_import.rs b/wezterm-mux-server-impl/tests/session_import.rs
index c0e5eda6..a679346c 100644
--- a/wezterm-mux-server-impl/tests/session_import.rs
+++ b/wezterm-mux-server-impl/tests/session_import.rs
@@ -549,8 +549,10 @@ async fn scenario(local_id: mux::domain::DomainId) -> Result<()> {
}
assert_eq!(mux.iter_panes().len(), 1);
let existing_thread = result.tree.projects[0].threads[0].id.clone();
- live_scenario(existing_thread.clone(), true).await?;
- live_scenario(existing_thread, false).await?;
+ // Each fixture owns several clients and complete wire messages. Keep
+ // these nested futures off the caller's test-thread stack.
+ Box::pin(live_scenario(existing_thread.clone(), true)).await?;
+ Box::pin(live_scenario(existing_thread, false)).await?;
Ok(())
}
diff --git a/wezterm-ssh/Cargo.toml b/wezterm-ssh/Cargo.toml
index 6c43869a..9d25a98b 100644
--- a/wezterm-ssh/Cargo.toml
+++ b/wezterm-ssh/Cargo.toml
@@ -52,6 +52,8 @@ env_logger.workspace = true
k9.workspace = true
predicates.workspace = true
rstest.workspace = true
+russh = { version = "0.63.3", default-features = false, features = ["ring"] }
shell-words.workspace = true
termwiz.workspace = true
+tokio = { workspace = true, features = ["rt-multi-thread", "macros", "net", "time"] }
whoami.workspace = true
diff --git a/wezterm-ssh/src/auth.rs b/wezterm-ssh/src/auth.rs
index 22997fcd..648368a1 100644
--- a/wezterm-ssh/src/auth.rs
+++ b/wezterm-ssh/src/auth.rs
@@ -1,3 +1,4 @@
+use crate::authentication::{AuthenticationBackend, AuthenticationMethod, AuthenticationProgress};
use crate::session::SessionEvent;
use anyhow::Context;
use smol::channel::{bounded, Sender};
@@ -28,7 +29,12 @@ impl AuthenticationEvent {
impl crate::sessioninner::SessionInner {
#[cfg(feature = "ssh2")]
- fn agent_auth(&mut self, sess: &ssh2::Session, user: &str) -> anyhow::Result<bool> {
+ fn agent_auth(
+ &mut self,
+ sess: &ssh2::Session,
+ user: &str,
+ progress: &mut AuthenticationProgress,
+ ) -> anyhow::Result<bool> {
if let Some(only) = self.config.get("identitiesonly") {
if only == "yes" {
log::trace!("Skipping agent auth because identitiesonly=yes");
@@ -45,7 +51,13 @@ impl crate::sessioninner::SessionInner {
agent.list_identities()?;
let identities = agent.identities()?;
for identity in identities {
- if agent.userauth(user, &identity).is_ok() {
+ let result = agent.userauth(user, &identity);
+ progress.observe_ssh2(
+ AuthenticationMethod::PublicKey,
+ result.is_ok(),
+ sess.authenticated(),
+ );
+ if result.is_ok() {
return Ok(true);
}
}
@@ -59,6 +71,7 @@ impl crate::sessioninner::SessionInner {
sess: &ssh2::Session,
user: &str,
host: &str,
+ progress: &mut AuthenticationProgress,
) -> anyhow::Result<bool> {
use std::path::{Path, PathBuf};
@@ -78,7 +91,13 @@ impl crate::sessioninner::SessionInner {
};
// We try with no passphrase first, in case the key is unencrypted
- match sess.userauth_pubkey_file(user, pubkey, &file, None) {
+ let result = sess.userauth_pubkey_file(user, pubkey, &file, None);
+ progress.observe_ssh2(
+ AuthenticationMethod::PublicKey,
+ result.is_ok(),
+ sess.authenticated(),
+ );
+ match result {
Ok(_) => {
log::info!("pubkey_file immediately ok for {}", file.display());
return Ok(true);
@@ -113,7 +132,14 @@ impl crate::sessioninner::SessionInner {
let passphrase = &answers[0];
- match sess.userauth_pubkey_file(user, pubkey, &file, Some(passphrase)) {
+ let result =
+ sess.userauth_pubkey_file(user, pubkey, &file, Some(passphrase));
+ progress.observe_ssh2(
+ AuthenticationMethod::PublicKey,
+ result.is_ok(),
+ sess.authenticated(),
+ );
+ match result {
Ok(_) => {
return Ok(true);
}
@@ -129,9 +155,17 @@ impl crate::sessioninner::SessionInner {
}
#[cfg(feature = "libssh-rs")]
- pub fn authenticate_libssh(&mut self, sess: &libssh_rs::Session) -> anyhow::Result<()> {
+ pub fn authenticate_libssh(
+ &mut self,
+ sess: &libssh_rs::Session,
+ ) -> anyhow::Result<AuthenticationProgress> {
use std::collections::HashMap;
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::Arc;
let tx = self.tx_event.clone();
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::LibSsh);
+ let cancelled = Arc::new(AtomicBool::new(false));
+ let callback_cancelled = Arc::clone(&cancelled);
// Set the callback for pubkey auth
sess.set_auth_callback(move |prompt, echo, _verify, identity| {
@@ -148,17 +182,26 @@ impl crate::sessioninner::SessionInner {
}],
reply,
}))
- .unwrap();
-
- let mut answers = smol::block_on(answers.recv())
- .context("waiting for authentication answers from user")
- .unwrap();
- Ok(answers.remove(0))
+ .map_err(|_| {
+ callback_cancelled.store(true, Ordering::Relaxed);
+ libssh_rs::Error::fatal("authentication prompt channel closed")
+ })?;
+
+ let answers = smol::block_on(answers.recv()).map_err(|_| {
+ callback_cancelled.store(true, Ordering::Relaxed);
+ libssh_rs::Error::fatal("authentication answer channel closed")
+ })?;
+ answers.into_iter().next().ok_or_else(|| {
+ callback_cancelled.store(true, Ordering::Relaxed);
+ libssh_rs::Error::fatal("user cancelled authentication")
+ })
});
use libssh_rs::{AuthMethods, AuthStatus};
- match sess.userauth_none(None)? {
- AuthStatus::Success => return Ok(()),
+ let status = sess.userauth_none(None)?;
+ progress.observe_libssh(AuthenticationMethod::None, status);
+ match status {
+ AuthStatus::Success => return Ok(progress),
_ => {}
}
@@ -167,8 +210,14 @@ impl crate::sessioninner::SessionInner {
let mut status_by_method = HashMap::new();
if auth_methods.contains(AuthMethods::PUBLIC_KEY) {
- match sess.userauth_public_key_auto(None, None)? {
- AuthStatus::Success => return Ok(()),
+ let result = sess.userauth_public_key_auto(None, None);
+ if cancelled.load(Ordering::Relaxed) {
+ anyhow::bail!("user cancelled authentication");
+ }
+ let status = result?;
+ progress.observe_libssh(AuthenticationMethod::PublicKey, status);
+ match status {
+ AuthStatus::Success => return Ok(progress),
AuthStatus::Partial => continue,
status => {
status_by_method.insert(AuthMethods::PUBLIC_KEY, status);
@@ -178,8 +227,10 @@ impl crate::sessioninner::SessionInner {
if auth_methods.contains(AuthMethods::INTERACTIVE) {
loop {
- match sess.userauth_keyboard_interactive(None, None)? {
- AuthStatus::Success => return Ok(()),
+ let status = sess.userauth_keyboard_interactive(None, None)?;
+ progress.observe_libssh(AuthenticationMethod::KeyboardInteractive, status);
+ match status {
+ AuthStatus::Success => return Ok(progress),
AuthStatus::Info => {
let info = sess.userauth_keyboard_interactive_info()?;
@@ -230,15 +281,19 @@ impl crate::sessioninner::SessionInner {
}],
reply,
}))
- .unwrap();
-
- let mut answers = smol::block_on(answers.recv())
- .context("waiting for authentication answers from user")
- .unwrap();
- let pw = answers.remove(0);
+ .context("sending Authenticate request to user")?;
- match sess.userauth_password(None, Some(&pw))? {
- AuthStatus::Success => return Ok(()),
+ let answers = smol::block_on(answers.recv())
+ .context("waiting for authentication answers from user")?;
+ let pw = answers
+ .into_iter()
+ .next()
+ .ok_or_else(|| anyhow::anyhow!("user cancelled authentication"))?;
+
+ let status = sess.userauth_password(None, Some(&pw))?;
+ progress.observe_libssh(AuthenticationMethod::Password, status);
+ match status {
+ AuthStatus::Success => return Ok(progress),
AuthStatus::Partial => continue,
status => anyhow::bail!("password auth status: {:?}", status),
}
@@ -258,12 +313,13 @@ impl crate::sessioninner::SessionInner {
sess: &ssh2::Session,
user: &str,
host: &str,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<AuthenticationProgress> {
use std::collections::HashSet;
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::Ssh2);
loop {
if sess.authenticated() {
- return Ok(());
+ return Ok(progress);
}
// Re-query the auth methods on each loop as a successful method
@@ -271,13 +327,17 @@ impl crate::sessioninner::SessionInner {
// auth may then unlock 2fac)
let methods: HashSet<&str> = sess.auth_methods(&user)?.split(',').collect();
log::trace!("ssh auth methods: {:?}", methods);
+ if sess.authenticated() {
+ progress.observe_ssh2(AuthenticationMethod::None, true, true);
+ return Ok(progress);
+ }
if !sess.authenticated() && methods.contains("publickey") {
- if self.agent_auth(sess, user)? {
+ if self.agent_auth(sess, user, &mut progress)? {
continue;
}
- if self.pubkey_auth(sess, user, host)? {
+ if self.pubkey_auth(sess, user, host, &mut progress)? {
continue;
}
}
@@ -303,7 +363,13 @@ impl crate::sessioninner::SessionInner {
anyhow::bail!("user cancelled authentication");
}
- if let Err(err) = sess.userauth_password(user, &answers[0]) {
+ let result = sess.userauth_password(user, &answers[0]);
+ progress.observe_ssh2(
+ AuthenticationMethod::Password,
+ result.is_ok(),
+ sess.authenticated(),
+ );
+ if let Err(err) = result {
log::error!("while attempting password auth: {}", err);
}
}
@@ -356,7 +422,13 @@ impl crate::sessioninner::SessionInner {
tx_event: &self.tx_event,
};
- if let Err(err) = sess.userauth_keyboard_interactive(user, &mut helper) {
+ let result = sess.userauth_keyboard_interactive(user, &mut helper);
+ progress.observe_ssh2(
+ AuthenticationMethod::KeyboardInteractive,
+ result.is_ok(),
+ sess.authenticated(),
+ );
+ if let Err(err) = result {
log::error!("while attempting keyboard-interactive auth: {}", err);
}
}
diff --git a/wezterm-ssh/src/authentication.rs b/wezterm-ssh/src/authentication.rs
new file mode 100644
index 00000000..883d71b5
--- /dev/null
+++ b/wezterm-ssh/src/authentication.rs
@@ -0,0 +1,259 @@
+/// The backend that observed an SSH authentication exchange.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AuthenticationBackend {
+ LibSsh,
+ Ssh2,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AuthenticationMethod {
+ None,
+ PublicKey,
+ Password,
+ KeyboardInteractive,
+}
+
+const MAX_AUTHENTICATION_STEPS: usize = 16;
+
+/// Read-only evidence from one session's handshake, without credentials or
+/// prompt text. This is not user consent and does not establish liveness.
+/// Consumers must use the record on the session that owns their channel.
+#[derive(Debug)]
+pub struct AuthenticationInfo {
+ backend: AuthenticationBackend,
+ methods: Vec<AuthenticationMethod>,
+ complete: bool,
+ host_verified: bool,
+}
+
+impl AuthenticationInfo {
+ pub fn backend(&self) -> AuthenticationBackend {
+ self.backend
+ }
+
+ /// Successful and partially successful steps, in observation order.
+ /// If `is_complete` is false, other steps may be missing.
+ pub fn methods(&self) -> &[AuthenticationMethod] {
+ &self.methods
+ }
+
+ pub fn is_complete(&self) -> bool {
+ self.complete
+ }
+
+ pub fn host_is_verified(&self) -> bool {
+ self.host_verified
+ }
+
+ /// Method eligibility only: this must never create or extend a grant.
+ pub fn is_verified_password_only(&self) -> bool {
+ self.host_verified
+ && self.complete
+ && !self.methods.is_empty()
+ && self
+ .methods
+ .iter()
+ .all(|method| *method == AuthenticationMethod::Password)
+ }
+}
+
+pub(crate) struct AuthenticationProgress {
+ info: AuthenticationInfo,
+}
+
+impl AuthenticationProgress {
+ pub(crate) fn new(backend: AuthenticationBackend) -> Self {
+ Self {
+ info: AuthenticationInfo {
+ backend,
+ methods: Vec::new(),
+ complete: true,
+ host_verified: false,
+ },
+ }
+ }
+
+ fn accepted(&mut self, method: AuthenticationMethod) {
+ if self.info.methods.len() < MAX_AUTHENTICATION_STEPS {
+ self.info.methods.push(method);
+ } else {
+ self.info.complete = false;
+ }
+ }
+
+ #[cfg(feature = "libssh-rs")]
+ pub(crate) fn observe_libssh(
+ &mut self,
+ method: AuthenticationMethod,
+ status: libssh_rs::AuthStatus,
+ ) {
+ match status {
+ libssh_rs::AuthStatus::Success | libssh_rs::AuthStatus::Partial => {
+ self.accepted(method);
+ }
+ libssh_rs::AuthStatus::Denied
+ | libssh_rs::AuthStatus::Info
+ | libssh_rs::AuthStatus::Again => {}
+ }
+ }
+
+ #[cfg(feature = "ssh2")]
+ pub(crate) fn observe_ssh2(
+ &mut self,
+ method: AuthenticationMethod,
+ succeeded: bool,
+ authenticated: bool,
+ ) {
+ if succeeded && authenticated {
+ self.accepted(method);
+ } else {
+ // libssh2 reports USERAUTH_FAILURE without exposing its partial
+ // success flag. A rejected attempt cannot safely be discarded.
+ self.info.complete = false;
+ }
+ }
+
+ pub(crate) fn finish(mut self, host_verified: bool) -> AuthenticationInfo {
+ self.info.host_verified = host_verified;
+ if self.info.methods.is_empty() {
+ self.info.complete = false;
+ }
+ self.info
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn missing_evidence_or_host_verification_never_qualifies() {
+ for backend in [AuthenticationBackend::LibSsh, AuthenticationBackend::Ssh2] {
+ assert!(!AuthenticationProgress::new(backend)
+ .finish(true)
+ .is_verified_password_only());
+ let mut progress = AuthenticationProgress::new(backend);
+ progress.accepted(AuthenticationMethod::Password);
+ assert!(!progress.finish(false).is_verified_password_only());
+ }
+ }
+
+ #[test]
+ fn recording_is_bounded_and_overflow_cannot_qualify() {
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::LibSsh);
+ for _ in 0..MAX_AUTHENTICATION_STEPS + 100 {
+ progress.accepted(AuthenticationMethod::Password);
+ }
+ let info = progress.finish(true);
+ assert_eq!(info.methods().len(), MAX_AUTHENTICATION_STEPS);
+ assert!(!info.is_complete());
+ assert!(!info.is_verified_password_only());
+ }
+
+ #[test]
+ fn a_new_handshake_does_not_inherit_the_previous_chain() {
+ let mut first = AuthenticationProgress::new(AuthenticationBackend::LibSsh);
+ first.accepted(AuthenticationMethod::Password);
+ assert!(first.finish(true).is_verified_password_only());
+ assert!(!AuthenticationProgress::new(AuthenticationBackend::LibSsh)
+ .finish(true)
+ .is_verified_password_only());
+ }
+
+ #[cfg(feature = "libssh-rs")]
+ #[test]
+ fn libssh_distinguishes_rejection_from_partial_public_key_success() {
+ use libssh_rs::AuthStatus;
+ for (status, eligible) in [(AuthStatus::Denied, true), (AuthStatus::Partial, false)] {
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::LibSsh);
+ progress.observe_libssh(AuthenticationMethod::PublicKey, status);
+ progress.observe_libssh(AuthenticationMethod::Password, AuthStatus::Success);
+ let info = progress.finish(true);
+ assert!(info.is_complete());
+ assert_eq!(info.is_verified_password_only(), eligible);
+ }
+ }
+
+ #[cfg(feature = "libssh-rs")]
+ #[test]
+ fn libssh_interactive_prompts_do_not_turn_into_password_evidence() {
+ use libssh_rs::AuthStatus;
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::LibSsh);
+ progress.observe_libssh(AuthenticationMethod::KeyboardInteractive, AuthStatus::Info);
+ progress.observe_libssh(
+ AuthenticationMethod::KeyboardInteractive,
+ AuthStatus::Partial,
+ );
+ progress.observe_libssh(AuthenticationMethod::Password, AuthStatus::Success);
+ let info = progress.finish(true);
+ assert_eq!(
+ info.methods(),
+ &[
+ AuthenticationMethod::KeyboardInteractive,
+ AuthenticationMethod::Password
+ ]
+ );
+ assert!(!info.is_verified_password_only());
+ }
+
+ #[cfg(feature = "libssh-rs")]
+ #[test]
+ fn libssh_accepts_only_verified_password_chains() {
+ use libssh_rs::AuthStatus;
+ for method in [
+ AuthenticationMethod::None,
+ AuthenticationMethod::PublicKey,
+ AuthenticationMethod::KeyboardInteractive,
+ AuthenticationMethod::Password,
+ ] {
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::LibSsh);
+ progress.observe_libssh(method, AuthStatus::Success);
+ let info = progress.finish(true);
+ assert_eq!(info.backend(), AuthenticationBackend::LibSsh);
+ assert!(info.host_is_verified());
+ assert_eq!(
+ info.is_verified_password_only(),
+ method == AuthenticationMethod::Password
+ );
+ }
+ }
+
+ #[cfg(feature = "ssh2")]
+ #[test]
+ fn ssh2_ambiguous_prior_attempts_cannot_be_erased_by_password_success() {
+ for method in [
+ AuthenticationMethod::PublicKey,
+ AuthenticationMethod::KeyboardInteractive,
+ AuthenticationMethod::Password,
+ ] {
+ for (succeeded, authenticated) in [(false, false), (true, false), (false, true)] {
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::Ssh2);
+ progress.observe_ssh2(method, succeeded, authenticated);
+ progress.observe_ssh2(AuthenticationMethod::Password, true, true);
+ let info = progress.finish(true);
+ assert!(!info.is_complete());
+ assert!(!info.is_verified_password_only());
+ }
+ }
+ }
+
+ #[cfg(feature = "ssh2")]
+ #[test]
+ fn ssh2_accepts_only_observed_password_success() {
+ for method in [
+ AuthenticationMethod::None,
+ AuthenticationMethod::PublicKey,
+ AuthenticationMethod::KeyboardInteractive,
+ AuthenticationMethod::Password,
+ ] {
+ let mut progress = AuthenticationProgress::new(AuthenticationBackend::Ssh2);
+ progress.observe_ssh2(method, true, true);
+ let info = progress.finish(true);
+ assert_eq!(info.backend(), AuthenticationBackend::Ssh2);
+ assert_eq!(
+ info.is_verified_password_only(),
+ method == AuthenticationMethod::Password
+ );
+ }
+ }
+}
diff --git a/wezterm-ssh/src/authentication_tests.rs b/wezterm-ssh/src/authentication_tests.rs
new file mode 100644
index 00000000..9e161d09
--- /dev/null
+++ b/wezterm-ssh/src/authentication_tests.rs
@@ -0,0 +1,491 @@
+//! Real SSH exchanges against a loopback-only, synthetic account. Client
+//! configuration, host trust and throwaway identities stay in a temporary
+//! directory; neither backend reads the user's SSH configuration or keys.
+
+use crate::authentication::{AuthenticationBackend, AuthenticationInfo, AuthenticationMethod};
+use crate::session::{SessionEvent, SessionShutdown};
+use crate::sessioninner::SessionInner;
+use crate::ConfigMap;
+use anyhow::Context;
+use filedescriptor::socketpair;
+use russh::keys::ssh_key::private::Ed25519Keypair;
+use russh::keys::{PrivateKey, PublicKey};
+use russh::server::{Auth, Handler};
+use russh::{MethodKind, MethodSet};
+use smol::channel::{bounded, Receiver};
+use std::borrow::Cow;
+use std::collections::HashMap;
+use std::io::{BufRead, BufReader};
+use std::net::{Ipv4Addr, SocketAddr};
+use std::os::unix::fs::PermissionsExt;
+use std::path::Path;
+use std::process::{Child, ChildStdout, Command, Stdio};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, Instant};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum Scenario {
+ Password,
+ Interactive,
+ PublicKeyThenPassword,
+ RejectedKeyThenPassword,
+ PasswordThenInteractive,
+ EncryptedKey,
+}
+
+struct TestServer {
+ scenario: Scenario,
+ first_step: bool,
+ credential_attempts: Arc<AtomicUsize>,
+}
+
+fn methods(methods: &[MethodKind]) -> MethodSet {
+ methods.into()
+}
+
+impl TestServer {
+ fn available_methods(&self) -> MethodSet {
+ use MethodKind::*;
+ match (self.scenario, self.first_step) {
+ (Scenario::Interactive, _) | (Scenario::PasswordThenInteractive, true) => {
+ methods(&[KeyboardInteractive])
+ }
+ (Scenario::PublicKeyThenPassword, false)
+ | (Scenario::RejectedKeyThenPassword, false)
+ | (Scenario::EncryptedKey, false) => methods(&[PublicKey, Password]),
+ _ => methods(&[Password]),
+ }
+ }
+}
+
+impl Handler for TestServer {
+ type Error = russh::Error;
+
+ async fn auth_none(&mut self, _: &str) -> Result<Auth, Self::Error> {
+ Ok(Auth::Reject {
+ proceed_with_methods: Some(self.available_methods()),
+ partial_success: false,
+ })
+ }
+
+ async fn auth_publickey(&mut self, _: &str, _: &PublicKey) -> Result<Auth, Self::Error> {
+ self.credential_attempts.fetch_add(1, Ordering::SeqCst);
+ self.first_step = true;
+ Ok(Auth::Reject {
+ proceed_with_methods: Some(methods(&[MethodKind::Password])),
+ partial_success: self.scenario == Scenario::PublicKeyThenPassword,
+ })
+ }
+
+ async fn auth_password(&mut self, _: &str, password: &str) -> Result<Auth, Self::Error> {
+ self.credential_attempts.fetch_add(1, Ordering::SeqCst);
+ assert!(password == "example-password");
+ if self.scenario == Scenario::PasswordThenInteractive {
+ self.first_step = true;
+ Ok(Auth::Reject {
+ proceed_with_methods: Some(methods(&[MethodKind::KeyboardInteractive])),
+ partial_success: true,
+ })
+ } else {
+ Ok(Auth::Accept)
+ }
+ }
+
+ async fn auth_keyboard_interactive<'a>(
+ &'a mut self,
+ _: &str,
+ _: &str,
+ response: Option<russh::server::Response<'a>>,
+ ) -> Result<Auth, Self::Error> {
+ if let Some(mut response) = response {
+ self.credential_attempts.fetch_add(1, Ordering::SeqCst);
+ assert!(response
+ .next()
+ .is_some_and(|value| value.as_ref() == b"example-password"));
+ Ok(Auth::Accept)
+ } else {
+ Ok(Auth::Partial {
+ name: Cow::Borrowed("Example authentication"),
+ instructions: Cow::Borrowed(""),
+ prompts: Cow::Owned(vec![(Cow::Borrowed("Password: "), false)]),
+ })
+ }
+ }
+}
+
+fn test_inner(root: &Path) -> (SessionInner, Receiver<SessionEvent>) {
+ let (tx_event, events) = bounded(8);
+ let (_requests, rx_req) = bounded(8);
+ let (_write, sender_read) = socketpair().unwrap();
+ let config = ConfigMap::from([
+ (
+ "identityfile".into(),
+ root.join("identity").to_str().unwrap().into(),
+ ),
+ ("identitiesonly".into(), "yes".into()),
+ (
+ "userknownhostsfile".into(),
+ root.join("known_hosts").to_str().unwrap().into(),
+ ),
+ ]);
+ (
+ SessionInner {
+ config,
+ tx_event,
+ rx_req,
+ channels: HashMap::new(),
+ files: HashMap::new(),
+ dirs: HashMap::new(),
+ next_channel_id: 1,
+ next_file_id: 1,
+ sender_read,
+ session_was_dropped: false,
+ shown_accept_env_error: false,
+ last_keep_alive: Instant::now(),
+ keep_alive: None,
+ shutdown: Arc::new(SessionShutdown::default()),
+ authentication: Arc::new(OnceLock::new()),
+ },
+ events,
+ )
+}
+
+fn backends() -> Vec<AuthenticationBackend> {
+ vec![
+ #[cfg(feature = "libssh-rs")]
+ AuthenticationBackend::LibSsh,
+ #[cfg(feature = "ssh2")]
+ AuthenticationBackend::Ssh2,
+ ]
+}
+
+struct PartialAuthServer {
+ child: Child,
+ output: BufReader<ChildStdout>,
+}
+
+impl PartialAuthServer {
+ fn start(root: &Path, scenario: Scenario) -> (Self, SocketAddr) {
+ let python = std::env::var_os("THINKTERM_AUTH_TEST_PYTHON")
+ .expect("set THINKTERM_AUTH_TEST_PYTHON to a virtualenv Python with Paramiko");
+ let mut child = Command::new(python)
+ .arg(
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/authentication-server.py"),
+ )
+ .arg(match scenario {
+ Scenario::PublicKeyThenPassword => "key-password",
+ Scenario::PasswordThenInteractive => "password-interactive",
+ _ => unreachable!(),
+ })
+ .env_clear()
+ .env("HOME", root)
+ .env("PYTHONDONTWRITEBYTECODE", "1")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .spawn()
+ .unwrap();
+ let output = BufReader::new(child.stdout.take().unwrap());
+ let mut server = Self { child, output };
+ let mut port = String::new();
+ server.output.read_line(&mut port).unwrap();
+ let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port.trim().parse::<u16>().unwrap()));
+ (server, address)
+ }
+
+ fn attempts(&mut self) -> usize {
+ let mut attempts = String::new();
+ self.output.read_line(&mut attempts).unwrap();
+ assert!(self.child.wait().unwrap().success());
+ attempts.trim().parse().unwrap()
+ }
+}
+
+impl Drop for PartialAuthServer {
+ fn drop(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+async fn exchange(
+ backend: AuthenticationBackend,
+ scenario: Scenario,
+ trust_host: bool,
+ cancel_password: bool,
+) -> (anyhow::Result<AuthenticationInfo>, usize) {
+ let directory = assert_fs::TempDir::new().unwrap();
+ // Synthetic, public test material, generated without external key files.
+ let server_key = PrivateKey::from(Ed25519Keypair::from_seed(&[1; 32]));
+ let client_key = PrivateKey::from(Ed25519Keypair::from_seed(&[2; 32]));
+ std::fs::write(
+ directory.path().join("identity"),
+ client_key
+ .to_openssh(russh::keys::ssh_key::LineEnding::LF)
+ .unwrap()
+ .as_bytes(),
+ )
+ .unwrap();
+ std::fs::set_permissions(
+ directory.path().join("identity"),
+ std::fs::Permissions::from_mode(0o600),
+ )
+ .unwrap();
+ if scenario == Scenario::EncryptedKey {
+ assert!(Command::new("ssh-keygen")
+ .args(["-p", "-P", "", "-N", "example-passphrase", "-f"])
+ .arg(directory.path().join("identity"))
+ .stdin(Stdio::null())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .unwrap()
+ .success());
+ }
+ std::fs::write(directory.path().join("known_hosts"), "").unwrap();
+ let (mut inner, events) = test_inner(directory.path());
+ let root = directory.path().to_path_buf();
+ let attempts = Arc::new(AtomicUsize::new(0));
+ let handler = TestServer {
+ scenario,
+ first_step: false,
+ credential_attempts: attempts.clone(),
+ };
+ let config = Arc::new(russh::server::Config {
+ keys: vec![server_key],
+ methods: handler.available_methods(),
+ auth_rejection_time: Duration::ZERO,
+ auth_rejection_time_initial: Some(Duration::ZERO),
+ inactivity_timeout: Some(Duration::from_secs(5)),
+ ..Default::default()
+ });
+ // russh 0.63.3 clears partial_success in its password/public-key server
+ // paths. Use an independent server for those wire-level cases.
+ let (server, mut partial_server, address) = if matches!(
+ scenario,
+ Scenario::PublicKeyThenPassword | Scenario::PasswordThenInteractive
+ ) {
+ let (server, address) = PartialAuthServer::start(directory.path(), scenario);
+ (None, Some(server), address)
+ } else {
+ let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
+ .await
+ .unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ let (stream, _) = listener.accept().await.unwrap();
+ if let Ok(session) = russh::server::run_stream(config, stream, handler).await {
+ let _ = session.await;
+ }
+ });
+ (Some(server), None, address)
+ };
+ let answers = tokio::spawn(async move {
+ let mut prompt_count = 0;
+ while let Ok(event) = events.recv().await {
+ match event {
+ SessionEvent::HostVerify(event) => event.answer(trust_host).await.unwrap(),
+ SessionEvent::Authenticate(event) => {
+ if cancel_password {
+ assert_eq!(
+ prompt_count, 0,
+ "authentication continued after cancellation"
+ );
+ }
+ prompt_count += 1;
+ let values = if cancel_password {
+ vec![]
+ } else {
+ vec!["example-password".to_string(); event.prompts.len()]
+ };
+ event.answer(values).await.unwrap();
+ }
+ _ => {}
+ }
+ }
+ });
+ let client = tokio::task::spawn_blocking(move || -> anyhow::Result<AuthenticationInfo> {
+ match backend {
+ #[cfg(feature = "libssh-rs")]
+ AuthenticationBackend::LibSsh => {
+ use libssh_rs::SshOption;
+ let session = libssh_rs::Session::new()?;
+ session.set_option(SshOption::ProcessConfig(false))?;
+ session.set_option(SshOption::SshDir(Some(root.to_str().unwrap().into())))?;
+ session.set_option(SshOption::KnownHosts(Some(
+ root.join("known_hosts").to_str().unwrap().into(),
+ )))?;
+ session.set_option(SshOption::GlobalKnownHosts(Some(
+ root.join("global_known_hosts").to_str().unwrap().into(),
+ )))?;
+ session.set_option(SshOption::IdentityAgent(Some(
+ root.join("no-agent").to_str().unwrap().into(),
+ )))?;
+ session.set_option(SshOption::AddIdentity(
+ root.join("identity").to_str().unwrap().into(),
+ ))?;
+ session.set_option(SshOption::Hostname(Ipv4Addr::LOCALHOST.to_string()))?;
+ session.set_option(SshOption::Port(address.port()))?;
+ session.set_option(SshOption::User(Some("example".into())))?;
+ session.set_option(SshOption::Timeout(Duration::from_secs(3)))?;
+ session.connect()?;
+ let verified =
+ inner.host_verification_libssh(&session, "localhost", address.port())?;
+ Ok(inner.authenticate_libssh(&session)?.finish(verified))
+ }
+ #[cfg(feature = "ssh2")]
+ AuthenticationBackend::Ssh2 => {
+ let stream =
+ std::net::TcpStream::connect_timeout(&address, Duration::from_secs(3))?;
+ let mut session = ssh2::Session::new()?;
+ session.set_timeout(3000);
+ session.set_tcp_stream(stream);
+ session.handshake()?;
+ let verified =
+ inner.host_verification(&session, "localhost", address.port(), "localhost")?;
+ Ok(inner
+ .authenticate(&session, "example", "localhost")?
+ .finish(verified))
+ }
+ #[allow(unreachable_patterns)]
+ _ => unreachable!(),
+ }
+ });
+ let result = tokio::time::timeout(Duration::from_secs(10), client)
+ .await
+ .context("authentication test exceeded its deadline")
+ .unwrap()
+ .unwrap();
+ answers.await.unwrap();
+ if let Some(server) = server {
+ server.abort();
+ let _ = server.await;
+ }
+ let attempts = if let Some(server) = partial_server.as_mut() {
+ assert!(
+ result.is_ok(),
+ "partial-authentication client failed: {:?}",
+ result
+ );
+ server.attempts()
+ } else {
+ attempts.load(Ordering::SeqCst)
+ };
+ (result, attempts)
+}
+
+#[tokio::test]
+async fn real_password_exchange_has_verified_connection_evidence() {
+ for backend in backends() {
+ let (result, attempts) = exchange(backend, Scenario::Password, true, false).await;
+ let info = result.unwrap();
+ assert_eq!(info.backend(), backend);
+ assert_eq!(info.methods(), &[AuthenticationMethod::Password]);
+ assert!(info.is_verified_password_only());
+ assert_eq!(attempts, 1);
+ }
+}
+
+#[tokio::test]
+async fn real_password_prompt_can_be_keyboard_interactive() {
+ for backend in backends() {
+ let (result, _) = exchange(backend, Scenario::Interactive, true, false).await;
+ let info = result.unwrap();
+ assert_eq!(info.methods(), &[AuthenticationMethod::KeyboardInteractive]);
+ assert!(!info.is_verified_password_only());
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires THINKTERM_AUTH_TEST_PYTHON with Paramiko; see docs/thinkterm/connect-reverse-access-implementation.md"]
+async fn real_partial_public_key_success_cannot_qualify_as_password_only() {
+ for backend in backends() {
+ let (result, attempts) =
+ exchange(backend, Scenario::PublicKeyThenPassword, true, false).await;
+ let info = result.unwrap();
+ assert!(attempts >= 2);
+ assert!(!info.is_verified_password_only());
+ if backend == AuthenticationBackend::LibSsh {
+ assert!(info.is_complete());
+ assert_eq!(
+ info.methods(),
+ &[
+ AuthenticationMethod::PublicKey,
+ AuthenticationMethod::Password
+ ]
+ );
+ } else {
+ assert!(!info.is_complete());
+ }
+ }
+}
+
+#[tokio::test]
+async fn real_rejected_public_key_is_only_eligible_with_complete_evidence() {
+ for backend in backends() {
+ let (result, attempts) =
+ exchange(backend, Scenario::RejectedKeyThenPassword, true, false).await;
+ let info = result.unwrap();
+ assert!(attempts >= 2);
+ assert_eq!(
+ info.is_verified_password_only(),
+ backend == AuthenticationBackend::LibSsh
+ );
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires THINKTERM_AUTH_TEST_PYTHON with Paramiko; see docs/thinkterm/connect-reverse-access-implementation.md"]
+async fn real_password_followed_by_another_factor_does_not_qualify() {
+ for backend in backends() {
+ let (result, attempts) =
+ exchange(backend, Scenario::PasswordThenInteractive, true, false).await;
+ let info = result.unwrap();
+ assert_eq!(attempts, 2);
+ assert!(!info.is_verified_password_only());
+ if backend == AuthenticationBackend::LibSsh {
+ assert_eq!(
+ info.methods(),
+ &[
+ AuthenticationMethod::Password,
+ AuthenticationMethod::KeyboardInteractive
+ ]
+ );
+ } else {
+ assert!(!info.is_complete());
+ }
+ }
+}
+
+#[tokio::test]
+async fn declining_host_trust_never_attempts_credentials() {
+ for backend in backends() {
+ let (result, attempts) = exchange(backend, Scenario::Password, false, false).await;
+ assert!(result.is_err());
+ assert_eq!(attempts, 0);
+ }
+}
+
+#[tokio::test]
+async fn cancelling_password_produces_no_authentication_record() {
+ for backend in backends() {
+ let (result, attempts) = exchange(backend, Scenario::Password, true, true).await;
+ assert!(result.is_err());
+ assert_eq!(attempts, 0);
+ }
+}
+
+#[cfg(feature = "libssh-rs")]
+#[tokio::test]
+async fn cancelling_key_decryption_does_not_fall_back_to_password() {
+ let (result, attempts) = exchange(
+ AuthenticationBackend::LibSsh,
+ Scenario::EncryptedKey,
+ true,
+ true,
+ )
+ .await;
+ assert!(result.is_err());
+ assert_eq!(attempts, 0);
+}
diff --git a/wezterm-ssh/src/host.rs b/wezterm-ssh/src/host.rs
index 55b22b79..996b7702 100644
--- a/wezterm-ssh/src/host.rs
+++ b/wezterm-ssh/src/host.rs
@@ -32,13 +32,13 @@ impl crate::sessioninner::SessionInner {
sess: &libssh_rs::Session,
hostname: &str,
port: u16,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<bool> {
let key = sess
.get_server_public_key()?
.get_public_key_hash_hexa(libssh_rs::PublicKeyHashType::Sha256)?;
match sess.is_known_server()? {
- libssh_rs::KnownHosts::Ok => Ok(()),
+ libssh_rs::KnownHosts::Ok => Ok(true),
libssh_rs::KnownHosts::NotFound | libssh_rs::KnownHosts::Unknown => {
let (reply, confirm) = bounded(1);
self.tx_event
@@ -60,7 +60,8 @@ impl crate::sessioninner::SessionInner {
anyhow::bail!("user declined to trust host");
}
- Ok(sess.update_known_hosts_file()?)
+ sess.update_known_hosts_file()?;
+ Ok(true)
}
libssh_rs::KnownHosts::Changed => {
let mut file = None;
@@ -133,7 +134,7 @@ impl crate::sessioninner::SessionInner {
remote_host_name: &str,
port: u16,
remote_address: &str,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<bool> {
use anyhow::anyhow;
use std::io::Write;
use std::path::Path;
@@ -147,6 +148,7 @@ impl crate::sessioninner::SessionInner {
.split_whitespace()
.map(|s| s.to_string());
+ let mut verified = false;
for file in known_hosts_files {
let file = Path::new(&file);
@@ -187,7 +189,7 @@ impl crate::sessioninner::SessionInner {
.ok_or_else(|| anyhow!("failed to get host fingerprint"))?;
match known_hosts.check_port(&remote_host_name, port, key) {
- ssh2::CheckResult::Match => {}
+ ssh2::CheckResult::Match => verified = true,
ssh2::CheckResult::NotFound => {
let (reply, confirm) = bounded(1);
self.tx_event
@@ -222,6 +224,7 @@ impl crate::sessioninner::SessionInner {
known_hosts
.write_file(&file, ssh2::KnownHostFileKind::OpenSSH)
.with_context(|| format!("writing known_hosts file {}", file.display()))?;
+ verified = true;
}
ssh2::CheckResult::Mismatch => {
let failed = HostVerificationFailed {
@@ -240,6 +243,6 @@ impl crate::sessioninner::SessionInner {
}
}
- Ok(())
+ Ok(verified)
}
}
diff --git a/wezterm-ssh/src/lib.rs b/wezterm-ssh/src/lib.rs
index 789bc994..189a452d 100644
--- a/wezterm-ssh/src/lib.rs
+++ b/wezterm-ssh/src/lib.rs
@@ -3,6 +3,9 @@ compile_error!("Either libssh-rs or ssh2 must be enabled!");
mod addresses;
mod auth;
+mod authentication;
+#[cfg(all(test, unix))]
+mod authentication_tests;
mod channelwrap;
mod config;
mod dirwrap;
@@ -18,6 +21,7 @@ mod through;
pub use addresses::OTHER_ADDRESSES;
pub use auth::*;
+pub use authentication::{AuthenticationBackend, AuthenticationInfo, AuthenticationMethod};
pub use config::*;
pub use host::*;
pub use pty::*;
diff --git a/wezterm-ssh/src/session.rs b/wezterm-ssh/src/session.rs
index 1cc5d674..0a0abb02 100644
--- a/wezterm-ssh/src/session.rs
+++ b/wezterm-ssh/src/session.rs
@@ -1,4 +1,5 @@
use crate::auth::*;
+use crate::authentication::AuthenticationInfo;
use crate::config::ConfigMap;
use crate::host::*;
use crate::pty::*;
@@ -12,7 +13,7 @@ use std::collections::HashMap;
use std::io::Write;
use std::net::Shutdown;
use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
#[derive(Debug)]
@@ -89,6 +90,7 @@ pub(crate) struct Exec {
pub struct Session {
tx: SessionSender,
shutdown: Arc<SessionShutdown>,
+ authentication: Arc<OnceLock<AuthenticationInfo>>,
}
/// Shutting down a duplicate interrupts even a backend blocked in its
@@ -137,6 +139,13 @@ impl Drop for Session {
}
impl Session {
+ /// Available before `SessionEvent::Authenticated` is delivered. It is
+ /// populated only by this session's handshake and never by configuration
+ /// or a caller-supplied authentication event. It is not a live grant.
+ pub fn authentication_info(&self) -> Option<&AuthenticationInfo> {
+ self.authentication.get()
+ }
+
/// Abort this session, including open channels and pending requests.
/// All clones refer to the same connection; ordinary drop still lets
/// its existing channels finish.
@@ -169,6 +178,7 @@ impl Session {
let now = Instant::now();
let shutdown = Arc::new(SessionShutdown::default());
+ let authentication = Arc::new(OnceLock::new());
let mut inner = SessionInner {
config,
@@ -185,12 +195,14 @@ impl Session {
last_keep_alive: now,
keep_alive,
shutdown: Arc::clone(&shutdown),
+ authentication: Arc::clone(&authentication),
};
std::thread::spawn(move || inner.run());
Ok((
Self {
tx: session_sender,
shutdown,
+ authentication,
},
rx_event,
))
diff --git a/wezterm-ssh/src/sessioninner.rs b/wezterm-ssh/src/sessioninner.rs
index 72d19b6a..248dda38 100644
--- a/wezterm-ssh/src/sessioninner.rs
+++ b/wezterm-ssh/src/sessioninner.rs
@@ -1,3 +1,4 @@
+use crate::authentication::AuthenticationInfo;
use crate::channelwrap::ChannelWrap;
use crate::config::ConfigMap;
use crate::dirwrap::DirWrap;
@@ -21,7 +22,7 @@ use smol::channel::{bounded, Receiver, Sender, TryRecvError};
use socket2::Socket;
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write};
-use std::sync::Arc;
+use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
#[derive(Debug)]
@@ -65,6 +66,7 @@ pub(crate) struct SessionInner {
pub last_keep_alive: Instant,
pub keep_alive: Option<Duration>,
pub shutdown: Arc<SessionShutdown>,
+ pub authentication: Arc<OnceLock<AuthenticationInfo>>,
}
impl Drop for SessionInner {
@@ -153,7 +155,6 @@ impl SessionInner {
.unwrap_or("false")
== "true";
if verbose {
-
/// libssh logs to stderr, but on Windows in the GUI there isn't a valid
/// stderr for it to log to.
/// So, we redirect logging via our own log callback and pipe it via
@@ -234,8 +235,11 @@ impl SessionInner {
.try_send(SessionEvent::Banner(Some(banner)))
.context("notifying user of banner")?;
- self.host_verification_libssh(&sess, &hostname, port)?;
- self.authenticate_libssh(&sess)?;
+ let host_verified = self.host_verification_libssh(&sess, &hostname, port)?;
+ let authentication = self.authenticate_libssh(&sess)?.finish(host_verified);
+ self.authentication
+ .set(authentication)
+ .map_err(|_| anyhow!("SSH authentication was already recorded"))?;
if let Some(reached) = &reached {
crate::addresses::remember_reached(&hostname, port, reached);
}
@@ -373,11 +377,16 @@ impl SessionInner {
.try_send(SessionEvent::Banner(sess.banner().map(|s| s.to_string())))
.context("notifying user of banner")?;
- self.host_verification(&sess, &hostname, port, &remote_address)
+ let host_verified = self
+ .host_verification(&sess, &hostname, port, &remote_address)
.context("host verification")?;
- self.authenticate(&sess, &user, &hostname)
+ let authentication = self
+ .authenticate(&sess, &user, &hostname)
.context("authentication")?;
+ self.authentication
+ .set(authentication.finish(host_verified))
+ .map_err(|_| anyhow!("SSH authentication was already recorded"))?;
if let Some(reached) = &reached {
crate::addresses::remember_reached(&hostname, port, reached);
}
diff --git a/wezterm-ssh/tests/fixtures/authentication-server.py b/wezterm-ssh/tests/fixtures/authentication-server.py
new file mode 100644
index 00000000..4d7d63cc
--- /dev/null
+++ b/wezterm-ssh/tests/fixtures/authentication-server.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""One synthetic SSH exchange, for testing the partial-success wire flag.
+
+Requires Paramiko in an isolated virtual environment. No real accounts,
+configuration files or keys are loaded. stdout carries only a port and count.
+"""
+
+import socket
+import sys
+import threading
+import time
+
+import paramiko
+
+
+class Server(paramiko.ServerInterface):
+ def __init__(self, scenario):
+ self.scenario = scenario
+ self.first_step = False
+ self.attempts = 0
+ self.authenticated = False
+
+ def get_allowed_auths(self, username):
+ if self.scenario == "key-password":
+ return "password" if self.first_step else "publickey,password"
+ return "keyboard-interactive" if self.first_step else "password"
+
+ def check_auth_publickey(self, username, key):
+ assert username == "example"
+ self.attempts += 1
+ self.first_step = True
+ return paramiko.AUTH_PARTIALLY_SUCCESSFUL
+
+ def check_auth_password(self, username, password):
+ assert username == "example" and password == "example-password"
+ self.attempts += 1
+ if self.scenario == "key-password":
+ self.authenticated = self.first_step
+ return paramiko.AUTH_SUCCESSFUL if self.first_step else paramiko.AUTH_FAILED
+ self.first_step = True
+ return paramiko.AUTH_PARTIALLY_SUCCESSFUL
+
+ def check_auth_interactive(self, username, submethods):
+ assert username == "example" and self.first_step
+ return paramiko.InteractiveQuery("Example authentication", "", ("Password: ", False))
+
+ def check_auth_interactive_response(self, responses):
+ assert responses == ["example-password"]
+ self.attempts += 1
+ self.authenticated = True
+ return paramiko.AUTH_SUCCESSFUL
+
+
+def main():
+ assert sys.argv[1:] in (["key-password"], ["password-interactive"])
+ server = Server(sys.argv[1])
+ # Throwaway host identity exists only in this process.
+ host_key = paramiko.RSAKey.generate(2048)
+ with socket.socket() as listener:
+ listener.settimeout(10)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ print(listener.getsockname()[1], flush=True)
+ peer, _ = listener.accept()
+ with peer, paramiko.Transport(peer) as transport:
+ transport.add_server_key(host_key)
+ # The synchronous waiter checks disconnect before its completion
+ # event. A fast successful client can otherwise look like a KEX
+ # failure after it has already finished authentication and exited.
+ transport.start_server(event=threading.Event(), server=server)
+ deadline = time.monotonic() + 10
+ while transport.is_active() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert server.authenticated, "synthetic SSH authentication did not complete"
+ print(server.attempts, flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.toml
index 070a9d07..95490820 100644
--- a/wezterm/Cargo.toml
+++ b/wezterm/Cargo.toml
@@ -22,6 +22,8 @@ default = ["tailnet"]
tailnet = ["dep:thinkterm-tailnet"]
[dependencies]
+futures.workspace = true
+thinkterm-reverse-access = { path = "../thinkterm-reverse-access" }
base64 = { workspace = true, features = ["std"] }
thinkterm-tailnet = { workspace = true, optional = true }
anyhow.workspace = true
diff --git a/wezterm/src/cli/get_text.rs b/wezterm/src/cli/get_text.rs
index ce9dddf9..a717a4a1 100644
--- a/wezterm/src/cli/get_text.rs
+++ b/wezterm/src/cli/get_text.rs
@@ -87,6 +87,45 @@ impl GetText {
client: Client,
pushes: Option<smol::channel::Receiver<Pdu>>,
) -> anyhow::Result<()> {
+ if self
+ .pane
+ .as_deref()
+ .is_some_and(crate::cli::reverse::looks_like_target)
+ && self.text_format() != TextFormat::Text
+ {
+ return Err(
+ crate::cli::UsageError("reverse access supports plain text only".into()).into(),
+ );
+ }
+ if let Some(target) = crate::cli::reverse::resolve(&client, self.pane.as_deref()).await? {
+ use thinkterm_reverse_access::protocol::{Command, ReadOptions, Reply};
+ let (reply, payload) = target
+ .router
+ .request_read(
+ target.route,
+ Command::Read {
+ export: target.export,
+ options: ReadOptions {
+ start: self.start_line.map(|n| n as i64),
+ end: self.end_line.map(|n| n as i64),
+ trim: self.trim,
+ unwrap: self.unwrap,
+ },
+ },
+ )
+ .await?;
+ match (reply, payload) {
+ (Reply::Text { .. }, Some(text)) => {
+ std::io::stdout()
+ .lock()
+ .write_all(text.text().as_bytes())
+ .map_err(crate::stdout_error)?;
+ return Ok(());
+ }
+ (Reply::Failed(failure), _) => anyhow::bail!("reverse read failed: {:?}", failure),
+ _ => anyhow::bail!("invalid reverse read response"),
+ }
+ }
let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
client,
self.pane_id,
diff --git a/wezterm/src/cli/list.rs b/wezterm/src/cli/list.rs
index f293da9a..adef3744 100644
--- a/wezterm/src/cli/list.rs
+++ b/wezterm/src/cli/list.rs
@@ -43,8 +43,22 @@ impl ListCommand {
} else {
self.format
};
+ let reverse = crate::cli::reverse::list(&client).await.unwrap_or_default();
match format {
- CliOutputFormatKind::Json => crate::cli::print_json(&output_items)?,
+ CliOutputFormatKind::Json => {
+ #[derive(serde::Serialize)]
+ #[serde(untagged)]
+ enum Item<'a> {
+ Local(&'a CliListResultItem),
+ Reverse(&'a crate::cli::reverse::Listed),
+ }
+ let items: Vec<_> = output_items
+ .iter()
+ .map(Item::Local)
+ .chain(reverse.iter().map(Item::Reverse))
+ .collect();
+ crate::cli::print_json(&items)?;
+ }
CliOutputFormatKind::Table => {
let cols = vec![
Column {
@@ -82,7 +96,7 @@ impl ListCommand {
alignment: Alignment::Left,
},
];
- let data = output_items
+ let mut data = output_items
.iter()
.map(|output_item| {
vec![
@@ -97,6 +111,18 @@ impl ListCommand {
]
})
.collect::<Vec<_>>();
+ data.extend(reverse.iter().map(|item| {
+ vec![
+ String::new(),
+ String::new(),
+ item.pane_id.clone(),
+ String::new(),
+ String::new(),
+ item.title.clone(),
+ String::new(),
+ item.label.clone(),
+ ]
+ }));
tabulate_output(&cols, &data, &mut std::io::stdout().lock())
.map_err(crate::stdout_error)?;
}
diff --git a/wezterm/src/cli/mod.rs b/wezterm/src/cli/mod.rs
index 77b4e4ac..3ddbf38f 100644
--- a/wezterm/src/cli/mod.rs
+++ b/wezterm/src/cli/mod.rs
@@ -20,6 +20,7 @@ mod move_pane_to_new_tab;
mod proxy;
mod rename_workspace;
mod restore_output;
+mod reverse;
mod send_key;
mod send_text;
mod set_pane_label;
@@ -208,6 +209,9 @@ enum CliSubCommand {
#[command(name = "proxy", about = "start rpc proxy pipe")]
Proxy(proxy::ProxyCommand),
+ #[command(name = "connect-reverse-proxy", hide = true)]
+ ConnectReverseProxy(reverse::Proxy),
+
#[command(name = "tlscreds", about = "obtain tls credentials")]
TlsCreds(tls_creds::TlsCredsCommand),
@@ -490,6 +494,7 @@ async fn run_cli_async(opts: &crate::Opt, cli: CliCommand) -> anyhow::Result<()>
CliSubCommand::GetText(cmd) => cmd.run(client, palette_pushes).await,
CliSubCommand::SpawnCommand(cmd) => cmd.run(client, &crate::init_config(opts)?).await,
CliSubCommand::Proxy(cmd) => cmd.run(client, &crate::init_config(opts)?).await,
+ CliSubCommand::ConnectReverseProxy(cmd) => cmd.run(client).await,
CliSubCommand::TlsCreds(cmd) => cmd.run(client).await,
CliSubCommand::WebServer(cmd) => cmd.run(client).await,
CliSubCommand::WebToken(cmd) => cmd.run(client).await,
diff --git a/wezterm/src/cli/reverse.rs b/wezterm/src/cli/reverse.rs
new file mode 100644
index 00000000..9a0d58ce
--- /dev/null
+++ b/wezterm/src/cli/reverse.rs
@@ -0,0 +1,178 @@
+use super::{NoSuchTarget, UsageError};
+use anyhow::{anyhow, bail};
+use clap::Parser;
+use smol::future::FutureExt;
+use smol::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
+use thinkterm_reverse_access::protocol::{Command, ExportRef, InputResult, InputStatus, Reply};
+use thinkterm_reverse_access::{Id, Permission};
+use wezterm_client::client::Client;
+use wezterm_client::connect::{Endpoint, RouterClient};
+
+#[derive(Debug, Clone, Parser)]
+pub struct Proxy {}
+
+impl Proxy {
+ pub async fn run(&self, client: Client) -> anyhow::Result<()> {
+ let stream = Endpoint::for_client(&client).await?.stream().await?;
+ drop(client);
+ let (mut reader, mut writer) = futures::io::AsyncReadExt::split(stream);
+ let mut input = smol::Unblock::with_capacity(8192, std::io::stdin());
+ let mut output = smol::Unblock::with_capacity(8192, std::io::stdout());
+ pump(&mut input, &mut writer)
+ .or(pump(&mut reader, &mut output))
+ .await?;
+ Ok(())
+ }
+}
+
+async fn pump<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
+ reader: &mut R,
+ writer: &mut W,
+) -> std::io::Result<()> {
+ let mut bytes = [0; 8192];
+ loop {
+ let count = reader.read(&mut bytes).await?;
+ if count == 0 {
+ return Ok(());
+ }
+ writer.write_all(&bytes[..count]).await?;
+ writer.flush().await?;
+ }
+}
+
+#[derive(serde::Serialize)]
+pub struct Listed {
+ pub pane_id: String,
+ pub machine: String,
+ pub label: String,
+ pub title: String,
+ pub reverse_access: bool,
+ pub permission: Permission,
+ pub remaining_ms: u64,
+}
+
+pub async fn list(client: &Client) -> anyhow::Result<Vec<Listed>> {
+ let router = RouterClient::new(client).await?;
+ let mut listed = Vec::new();
+ for route in router.routes().await? {
+ // One expired or disconnected desktop must not hide other routes.
+ let Ok(exports) = router.exports(route.id).await else {
+ continue;
+ };
+ for item in exports {
+ listed.push(Listed {
+ pane_id: format!("{}/{}", route.name, item.export.target.pane),
+ machine: route.name.clone(),
+ label: item.name,
+ title: item.title,
+ reverse_access: true,
+ permission: item.permission,
+ remaining_ms: item.remaining_ms,
+ });
+ }
+ }
+ Ok(listed)
+}
+
+pub struct Target {
+ pub router: RouterClient,
+ pub route: Id,
+ pub export: ExportRef,
+ permission: Permission,
+}
+
+pub fn looks_like_target(name: &str) -> bool {
+ let Some((machine, _)) = name.trim().split_once('/') else {
+ return false;
+ };
+ let Some(suffix) = machine.strip_prefix("desktop-") else {
+ return false;
+ };
+ suffix.len() == 8 && suffix.bytes().all(|b| b.is_ascii_hexdigit())
+}
+
+pub async fn resolve(client: &Client, name: Option<&str>) -> anyhow::Result<Option<Target>> {
+ let Some(name) = name.filter(|name| looks_like_target(name)) else {
+ return Ok(None);
+ };
+ let (machine, pane) = name
+ .trim()
+ .split_once('/')
+ .ok_or_else(|| UsageError("invalid reverse target".into()))?;
+ let router = RouterClient::new(client).await?;
+ let routes = router.routes().await?;
+ let matching: Vec<_> = routes
+ .into_iter()
+ .filter(|route| route.name == machine)
+ .collect();
+ let [route] = matching.as_slice() else {
+ return Err(NoSuchTarget("reverse terminal is unavailable or ambiguous".into()).into());
+ };
+ let exports = router.exports(route.id).await?;
+ let matching: Vec<_> = exports
+ .into_iter()
+ .filter(|item| {
+ pane.parse::<u64>().ok() == Some(item.export.target.pane) || item.name == pane
+ })
+ .collect();
+ let [export] = matching.as_slice() else {
+ return Err(NoSuchTarget("reverse terminal is unavailable or ambiguous".into()).into());
+ };
+ if super::target::local_match(client, name).await? {
+ return Err(NoSuchTarget(
+ "the reverse terminal name also identifies a local terminal".into(),
+ )
+ .into());
+ }
+ Ok(Some(Target {
+ route: route.id,
+ export: export.export,
+ permission: export.permission,
+ router,
+ }))
+}
+
+pub fn input_result(reply: Reply) -> anyhow::Result<()> {
+ match reply {
+ Reply::Input(InputResult { status: InputStatus::Submitted, .. }) => Ok(()),
+ Reply::Input(result) => bail!("input {:?}: {} bytes submitted; Enter submitted: {}; paste may be open: {}. Do not retry automatically",
+ result.status, result.bytes, result.enter_submitted, result.paste_may_be_open),
+ Reply::Failed(failure) => bail!("reverse input was rejected: {:?}", failure),
+ _ => Err(anyhow!("invalid reverse input response; input outcome is unknown")),
+ }
+}
+
+/// The desktop refuses this too, and without a reason, as it does anything it
+/// refuses. The listing has already told this caller the permission, so saying
+/// what is wrong gives nothing away. The desktop's check is still the one that
+/// counts: this copy can be a moment old.
+fn check_input_allowed(permission: Permission) -> anyhow::Result<()> {
+ if permission != Permission::ReadAndInput {
+ bail!("this reverse terminal is read-only; nothing was sent");
+ }
+ Ok(())
+}
+
+pub async fn send(target: Target, command: Command, input: Option<&str>) -> anyhow::Result<()> {
+ check_input_allowed(target.permission)?;
+ let (reply, _) = target
+ .router
+ .request(target.route, command, input)
+ .await
+ .map_err(|error| {
+ anyhow!("reverse input outcome is unknown ({error}); do not retry automatically")
+ })?;
+ input_result(reply)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn input_on_read_only_access_says_so() {
+ assert!(check_input_allowed(Permission::ReadAndInput).is_ok());
+ let refused = check_input_allowed(Permission::Read).unwrap_err();
+ assert!(refused.to_string().contains("read-only"));
+ }
+}
diff --git a/wezterm/src/cli/send_key.rs b/wezterm/src/cli/send_key.rs
index 734d3ef7..62929bf3 100644
--- a/wezterm/src/cli/send_key.rs
+++ b/wezterm/src/cli/send_key.rs
@@ -55,6 +55,54 @@ impl SendKey {
.collect::<anyhow::Result<Vec<_>>>()
.map_err(|err| UsageError(format!("{err:#}")))?;
+ if self.wait
+ && self
+ .pane
+ .as_deref()
+ .is_some_and(crate::cli::reverse::looks_like_target)
+ {
+ return Err(UsageError("reverse access does not support --wait".into()).into());
+ }
+ if let Some(target) = crate::cli::reverse::resolve(&client, self.pane.as_deref()).await? {
+ use thinkterm_reverse_access::protocol::{Command, Key};
+ if events.len() > thinkterm_reverse_access::MAX_KEYS {
+ return Err(UsageError("reverse input is limited to 64 keys".into()).into());
+ }
+ let keys = events
+ .into_iter()
+ .map(|event| {
+ let name = match event.key {
+ KeyCode::Char(c) => c.to_string(),
+ KeyCode::Enter => "enter".into(),
+ KeyCode::Tab => "tab".into(),
+ KeyCode::Escape => "escape".into(),
+ KeyCode::Backspace => "backspace".into(),
+ KeyCode::Delete => "delete".into(),
+ KeyCode::UpArrow => "up".into(),
+ KeyCode::DownArrow => "down".into(),
+ KeyCode::LeftArrow => "left".into(),
+ KeyCode::RightArrow => "right".into(),
+ KeyCode::Home => "home".into(),
+ KeyCode::End => "end".into(),
+ KeyCode::PageUp => "pageup".into(),
+ KeyCode::PageDown => "pagedown".into(),
+ KeyCode::Insert => "insert".into(),
+ KeyCode::Function(n) => format!("f{n}"),
+ _ => return Err(UsageError("unsupported reverse key".into())),
+ };
+ Ok(Key {
+ name,
+ modifiers: event.modifiers.bits(),
+ })
+ })
+ .collect::<Result<Vec<_>, UsageError>>()?;
+ let command = Command::Keys {
+ export: target.export,
+ keys,
+ };
+ return crate::cli::reverse::send(target, command, None).await;
+ }
+
if !self.wait {
let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
client,
diff --git a/wezterm/src/cli/send_text.rs b/wezterm/src/cli/send_text.rs
index c70d97c0..8c06fc3a 100644
--- a/wezterm/src/cli/send_text.rs
+++ b/wezterm/src/cli/send_text.rs
@@ -3,8 +3,8 @@ use clap::Parser;
use codec::{InputSerial, SendKeyDown};
use mux::pane::PaneId;
use std::io::Read;
-use std::time::Duration;
use termwiz::input::{KeyCode, KeyEvent, Modifiers};
+use thinkterm_reverse_access::protocol::enter_delay;
use wezterm_client::client::Client;
#[derive(Debug, Parser, Clone)]
@@ -36,6 +36,31 @@ pub struct SendText {
impl SendText {
pub async fn run(self, client: Client) -> anyhow::Result<()> {
+ if let Some(target) = crate::cli::reverse::resolve(&client, self.pane.as_deref()).await? {
+ let text = match self.text {
+ Some(text) => text,
+ None => {
+ let mut text = String::new();
+ std::io::stdin()
+ .take((thinkterm_reverse_access::MAX_INPUT_BYTES + 1) as u64)
+ .read_to_string(&mut text)
+ .context("reading reverse input")?;
+ text
+ }
+ };
+ if text.len() > thinkterm_reverse_access::MAX_INPUT_BYTES {
+ return Err(
+ crate::cli::UsageError("reverse input is limited to 64 KiB".into()).into(),
+ );
+ }
+ let command = thinkterm_reverse_access::protocol::Command::Text {
+ export: target.export,
+ bytes: text.len(),
+ no_paste: self.no_paste,
+ enter: self.enter,
+ };
+ return crate::cli::reverse::send(target, command, Some(&text)).await;
+ }
let (client, pane_id) = crate::cli::target::resolve_reaching_servers(
client,
self.pane_id,
@@ -86,13 +111,6 @@ impl SendText {
}
}
-/// How long `--enter` waits after `len` bytes of text: a moment, and a
-/// little more for a long text a program takes longer to read, up to two
-/// seconds.
-fn enter_delay(len: usize) -> Duration {
- Duration::from_millis((300 + len as u64 / 1024 * 50).min(2000))
-}
-
#[cfg(test)]
mod tests {
use super::enter_delay;
diff --git a/wezterm/src/cli/target.rs b/wezterm/src/cli/target.rs
index 62f2c379..402d6184 100644
--- a/wezterm/src/cli/target.rs
+++ b/wezterm/src/cli/target.rs
@@ -13,12 +13,29 @@ pub async fn resolve(
pane_id: Option<PaneId>,
pane: Option<&str>,
) -> anyhow::Result<PaneId> {
+ if pane.is_some_and(crate::cli::reverse::looks_like_target) {
+ return Err(UsageError("this operation does not support reverse terminals".into()).into());
+ }
match pane {
Some(name) => find(client, name).await,
None => client.resolve_pane_id(pane_id).await,
}
}
+pub(super) async fn local_match(client: &Client, name: &str) -> anyhow::Result<bool> {
+ let panes = candidates(client).await?;
+ Ok(local_match_in(&panes, name.trim()))
+}
+
+fn local_match_in(panes: &[Candidate], name: &str) -> bool {
+ let id = as_pane_id(name);
+ // A name claimed by several panes still conflicts with a reverse
+ // target, including a thread name that needs further disambiguation.
+ panes
+ .iter()
+ .any(|pane| id == Some(pane.pane_id) || names(pane, name, true))
+}
+
/// The pane `pane` names, and the client that reaches it: a pane of this
/// machine's through `client`; one that is not, but on a server as
/// `MACHINE/NAME` names it, through the window this machine has open, which
@@ -381,6 +398,39 @@ mod tests {
]
}
+ #[test]
+ fn local_reverse_name_collisions_include_ambiguous_labels() {
+ let name = "desktop-0123abcd/21";
+ let mut panes = vec![pane(1, Some(name), "w-a", None)];
+ assert!(local_match_in(&panes, name));
+ panes.push(pane(2, Some("DESKTOP-0123ABCD/21"), "w-b", None));
+ assert!(choose(&panes, name, None).is_err());
+ assert!(local_match_in(&panes, name));
+ assert!(local_match_in(&panes, "DESKTOP-0123ABCD/21"));
+ assert!(!local_match_in(&panes, "desktop-0123abcd/22"));
+ assert!(!local_match_in(&[], name));
+ }
+
+ #[test]
+ fn local_reverse_name_collisions_include_shared_thread_names_and_labels() {
+ let name = "desktop-0123abcd/21";
+ let panes = vec![
+ pane(1, None, "w-a", Some(name)),
+ pane(2, None, "w-a", Some(name)),
+ ];
+ assert!(choose(&panes, name, None).is_err());
+ assert!(local_match_in(&panes, name));
+ let panes = vec![
+ pane(1, Some("21"), "w-a", Some("desktop-0123abcd")),
+ pane(2, Some("21"), "w-b", Some("desktop-0123abcd")),
+ ];
+ assert!(choose(&panes, name, None).is_err());
+ assert!(local_match_in(&panes, name));
+ assert!(local_match_in(&panes, "1"));
+ assert!(!local_match_in(&panes, "3"));
+ assert!(!local_match_in(&panes, "zsh"));
+ }
+
#[test]
fn a_label_held_once_names_its_pane() {
assert_eq!(choose(&panes(), "build", None), Ok(4));