Add the SSH session layer and the terminal data plane

The throughput harness the plan requires before any UI, plus the SSH
plumbing under it. 94 new tests, no WebView involved.

Credit-based flow control is what makes `yes` survivable. A terminal renders
at 60 Hz at best while a remote produces output as fast as the network
allows, and the difference has to accumulate somewhere or be refused.
Credit is reserved *before* reading, never after: because the pump cannot
read more than the renderer has room for, the coalescing buffer is bounded
by the window rather than by how fast the remote can talk. When credit runs
out the pump stops reading, SSH's own receive window closes, and the remote
sshd blocks -- backpressure to the source with no custom protocol.

Verified by falsification, not just by passing: with the credit gate removed
three tests fail, including the throughput harness's bounded-memory
assertion. Acknowledgements are clamped because they cross into JavaScript,
where a buggy or hostile page could otherwise claim to have rendered a
gigabyte and talk the host into an unbounded read.

Host key trust is enforced by *failing* the connection rather than
prompting inside the handshake. SSH.NET raises verification synchronously,
so consulting the user there would block the handshake on a UI round trip
and deadlock the first time the prompt needed the UI thread. Unknown host
and changed key become distinct exceptions the caller resolves
asynchronously. A mismatch has no retry path at all: a dialog offering to
continue is how users are trained to click through the one warning that
actually indicates interception. A legitimately rebuilt server is handled by
removing the pin in settings, away from the moment of connecting.

The data plane serves the renderer page from the same loopback listener as
the socket, which makes Origin predictable -- always http://127.0.0.1:{port}
-- where a WebView virtual-host mapping would give a different origin per
backend and nothing to validate. The token is substituted at serve time, so
it never touches disk and never appears in a URL. Being clear about what
that buys: not protection from a process running as this user, which can
read our memory anyway, but from a page in the user's browser attempting
WebSocket connections to loopback ports, which is a real and routine thing.

Two bugs the tests caught. The accept loop handled connections serially, so
an upgraded WebSocket parked it inside the receive loop and every later
request went unanswered -- the page's own script among them. The suite hung
rather than failed, which is how I found it. And SHA-1 is unavoidable here:
RFC 6455 mandates it for Sec-WebSocket-Accept, where it authenticates
nothing. Suppressed narrowly with that reasoning; the alternative,
HttpListener.AcceptWebSocketAsync, throws PlatformNotSupportedException off
Windows.
This commit is contained in:
2026-07-28 21:58:55 +02:00
parent 94f66be5e8
commit eb354bcdd9
19 changed files with 3216 additions and 0 deletions
+152
View File
@@ -0,0 +1,152 @@
namespace DodoSSH.Client.Terminal;
/// <summary>
/// Credit-based flow control over one terminal session's output.
/// </summary>
/// <remarks>
/// <para>
/// This is what makes <c>yes</c> survivable. A terminal emulator renders at 60 Hz at best, while a
/// remote process can produce output as fast as the network allows. Without a limit the difference
/// accumulates somewhere — an unbounded queue in the client, or an ever-growing scrollback — and the
/// application's memory grows until it dies.
/// </para>
/// <para>
/// The mechanism: the renderer is granted a window of bytes it is allowed to be behind by. Each byte
/// sent to it consumes credit; each byte it reports having actually rendered returns credit. When
/// credit reaches zero the pump <b>stops reading the SSH channel</b>. That closes SSH's own receive
/// window, which makes the remote <c>sshd</c> block on write, which propagates the backpressure all
/// the way to the process producing the output. Nothing buffers without bound because nothing is read
/// that cannot be delivered.
/// </para>
/// <para>
/// The window has to be large enough that a normal burst never stalls and small enough to bound
/// memory. 256 KiB is roughly a screenful of dense output many times over, and it caps a session's
/// in-flight cost at a quarter of a megabyte.
/// </para>
/// </remarks>
public sealed class CreditWindow
{
/// <summary>Default window size: 256 KiB.</summary>
public const int DefaultWindowBytes = 256 * 1024;
private readonly Lock gate = new();
private readonly int windowBytes;
/// <summary>Signalled whenever credit becomes available.</summary>
private TaskCompletionSource available = CreateSignal();
private int outstanding;
/// <param name="windowBytes">How many unrendered bytes the renderer may be behind by.</param>
public CreditWindow(int windowBytes = DefaultWindowBytes)
{
ArgumentOutOfRangeException.ThrowIfLessThan(windowBytes, 1);
this.windowBytes = windowBytes;
}
/// <summary>Bytes sent but not yet reported as rendered.</summary>
public int Outstanding
{
get
{
lock (gate)
{
return outstanding;
}
}
}
/// <summary>Bytes that may be sent right now.</summary>
public int Available
{
get
{
lock (gate)
{
return windowBytes - outstanding;
}
}
}
/// <summary>
/// Reserves up to <paramref name="wanted"/> bytes of credit, returning how many were granted.
/// </summary>
/// <remarks>
/// A partial grant rather than all-or-nothing. Refusing to send 40 KiB because only 30 KiB of
/// credit remains would stall a session that could have made progress, and the caller has to
/// handle short writes regardless.
/// </remarks>
/// <returns>Bytes reserved, which is zero when the window is full.</returns>
public int TryReserve(int wanted)
{
ArgumentOutOfRangeException.ThrowIfLessThan(wanted, 0);
lock (gate)
{
var granted = Math.Min(wanted, windowBytes - outstanding);
outstanding += granted;
return granted;
}
}
/// <summary>
/// Returns credit for bytes the renderer has reported rendering.
/// </summary>
/// <remarks>
/// Clamped rather than trusted. The acknowledgement crosses a process boundary into JavaScript, so
/// a buggy or tampered page could acknowledge more than it was ever sent; letting that drive
/// <c>outstanding</c> negative would hand it an unbounded window and reintroduce exactly the
/// failure this class exists to prevent.
/// </remarks>
public void Return(int rendered)
{
ArgumentOutOfRangeException.ThrowIfLessThan(rendered, 0);
lock (gate)
{
outstanding -= Math.Min(rendered, outstanding);
// Released inside the lock so a waiter cannot miss the transition, and completed
// asynchronously so a continuation cannot run while the lock is held.
available.TrySetResult();
available = CreateSignal();
}
}
/// <summary>Waits until at least one byte of credit is available.</summary>
public async ValueTask WaitForCreditAsync(CancellationToken cancellationToken)
{
while (true)
{
Task signal;
lock (gate)
{
if (windowBytes - outstanding > 0)
{
return;
}
signal = available.Task;
}
await signal.WaitAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Discards all outstanding credit, for a session being torn down.</summary>
public void Reset()
{
lock (gate)
{
outstanding = 0;
available.TrySetResult();
available = CreateSignal();
}
}
private static TaskCompletionSource CreateSignal() =>
new(TaskCreationOptions.RunContinuationsAsynchronously);
}
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
The terminal data plane. Avalonia-free and WebView-free on purpose: the throughput and
backpressure behaviour is the part most likely to be wrong, and it has to be testable
without a UI toolkit or a browser engine. ITerminalHost is the seam the app plugs into.
-->
<ItemGroup>
<ProjectReference Include="../DodoSSH.Client.Ssh/DodoSSH.Client.Ssh.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="DodoSSH.Client.Terminal.Tests" />
</ItemGroup>
</Project>
@@ -0,0 +1,31 @@
namespace DodoSSH.Client.Terminal;
/// <summary>One file the renderer needs.</summary>
/// <param name="ContentType">MIME type, including a charset for text.</param>
/// <param name="Content">The bytes to serve.</param>
public sealed record TerminalAsset(string ContentType, byte[] Content);
/// <summary>
/// Supplies the renderer's HTML, JavaScript and CSS.
/// </summary>
/// <remarks>
/// An abstraction so the data plane does not depend on Avalonia's resource system, which keeps the
/// whole transport testable with in-memory assets. The application implements this over
/// <c>AvaloniaResource</c>; tests hand over a dictionary.
/// </remarks>
public interface ITerminalAssetProvider
{
/// <summary>
/// Returns the asset for a request path, or null if there is none.
/// </summary>
/// <param name="path">Absolute request path, beginning with a slash.</param>
TerminalAsset? Find(string path);
}
/// <summary>Assets held in a dictionary.</summary>
public sealed class InMemoryTerminalAssetProvider(IReadOnlyDictionary<string, TerminalAsset> assets)
: ITerminalAssetProvider
{
/// <inheritdoc />
public TerminalAsset? Find(string path) => assets.GetValueOrDefault(path);
}
@@ -0,0 +1,535 @@
using System.Buffers.Text;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
namespace DodoSSH.Client.Terminal;
/// <summary>
/// Serves the renderer page and carries terminal frames, over one loopback socket.
/// </summary>
/// <remarks>
/// <para>
/// The data plane is a socket rather than the WebView's JavaScript bridge. The bridge is UI-thread
/// bound string evaluation with no backpressure signal, which at terminal throughput means thousands
/// of script evaluations per second on the thread that also has to paint. A socket gives ordering,
/// binary payloads and flow control for free.
/// </para>
/// <para>
/// The page is served from the same listener as the socket, which is what makes the <c>Origin</c>
/// header predictable — it is always <c>http://127.0.0.1:{port}</c>. Loading the page through a
/// WebView virtual-host mapping instead would produce a different origin on each backend and give
/// nothing to validate against.
/// </para>
/// <para>
/// <b>What the token and origin check actually defend against.</b> Not a hostile process running as
/// the same user: that process can already read this one's memory, so nothing here is a boundary
/// against it. They defend against a web page in the user's browser, which can and does attempt
/// WebSocket connections to loopback ports, and against a second copy of the application
/// accidentally attaching to the wrong terminal. Both are real; neither is stopped by the socket
/// being loopback alone.
/// </para>
/// </remarks>
public sealed class TerminalDataPlane : ITerminalTransport, IAsyncDisposable
{
/// <summary>Subprotocol the renderer must request.</summary>
public const string SubProtocol = "dodossh.terminal.v1";
/// <summary>Path the renderer page is served from.</summary>
public const string PagePath = "/terminal";
/// <summary>Path the WebSocket upgrade is accepted on.</summary>
public const string SocketPath = "/socket";
/// <summary>Placeholder in the page that is replaced with the connection token.</summary>
public const string TokenPlaceholder = "__DODOSSH_TOKEN__";
/// <summary>Placeholder in the page that is replaced with the socket URL.</summary>
public const string SocketUrlPlaceholder = "__DODOSSH_SOCKET__";
/// <summary>RFC 6455 §1.3: the fixed GUID mixed into the handshake response.</summary>
private const string HandshakeGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private const int MaximumRequestBytes = 16 * 1024;
private const int ReceiveBufferBytes = 64 * 1024;
private readonly TcpListener listener;
private readonly ITerminalAssetProvider assets;
private readonly Dictionary<uint, TerminalSessionPump> pumps = [];
private readonly Lock pumpGate = new();
private readonly SemaphoreSlim sendGate = new(1, 1);
private readonly CancellationTokenSource lifetime = new();
private readonly TaskCompletionSource rendererAttached =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private WebSocket? socket;
private int accepted;
private int disposed;
/// <param name="assets">Where the renderer's files come from.</param>
public TerminalDataPlane(ITerminalAssetProvider assets)
{
ArgumentNullException.ThrowIfNull(assets);
this.assets = assets;
Token = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32));
listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
Port = ((IPEndPoint)listener.LocalEndpoint).Port;
}
/// <summary>The port the OS assigned.</summary>
public int Port { get; }
/// <summary>The single-use connection token embedded in the served page.</summary>
public string Token { get; }
/// <summary>Where the WebView should navigate.</summary>
public Uri PageUrl => new(
string.Create(CultureInfo.InvariantCulture, $"http://127.0.0.1:{Port}{PagePath}"),
UriKind.Absolute);
/// <summary>Completes once the renderer has attached its socket.</summary>
public Task RendererAttached => rendererAttached.Task;
/// <summary>Registers a session so inbound frames can be routed to it.</summary>
public void Register(uint sessionId, TerminalSessionPump pump)
{
ArgumentNullException.ThrowIfNull(pump);
lock (pumpGate)
{
pumps[sessionId] = pump;
}
}
/// <summary>Forgets a session that has ended.</summary>
public void Unregister(uint sessionId)
{
lock (pumpGate)
{
pumps.Remove(sessionId);
}
}
/// <summary>Accepts connections until disposed.</summary>
public async Task RunAsync(CancellationToken cancellationToken)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
lifetime.Token);
while (!linked.Token.IsCancellationRequested)
{
TcpClient client;
try
{
client = await listener.AcceptTcpClientAsync(linked.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
// Each connection on its own task, and deliberately not awaited. An upgraded WebSocket
// lives for the whole session, so handling connections in sequence would leave the accept
// loop parked inside the receive loop and every later request unanswered — the page's
// script and stylesheet among them. Concurrency needs no coordination here because the
// single-attach guard is an interlocked exchange.
_ = HandleConnectionAsync(client, linked.Token);
}
}
private async Task HandleConnectionAsync(TcpClient client, CancellationToken cancellationToken)
{
try
{
await HandleAsync(client, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
when (exception is IOException or SocketException or WebSocketException
or OperationCanceledException or ObjectDisposedException)
{
// A renderer that went away mid-handshake, or a shutdown in progress. Ordinary.
}
finally
{
client.Dispose();
}
}
/// <inheritdoc />
public async ValueTask SendAsync(ReadOnlyMemory<byte> frame, CancellationToken cancellationToken)
{
var current = socket;
if (current is null || current.State != WebSocketState.Open)
{
// Dropped rather than queued. A terminal whose renderer has gone has nothing to catch up
// on, and buffering for one that may never return is the unbounded growth the credit
// window exists to prevent.
return;
}
// WebSocket forbids concurrent sends, and every session shares this one socket.
await sendGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await current
.SendAsync(frame, WebSocketMessageType.Binary, endOfMessage: true, cancellationToken)
.ConfigureAwait(false);
}
finally
{
sendGate.Release();
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref disposed, 1) == 1)
{
return;
}
await lifetime.CancelAsync().ConfigureAwait(false);
rendererAttached.TrySetCanceled();
listener.Dispose();
socket?.Dispose();
sendGate.Dispose();
lifetime.Dispose();
}
private async Task HandleAsync(TcpClient client, CancellationToken cancellationToken)
{
var stream = client.GetStream();
await using var streamScope = stream.ConfigureAwait(false);
var request = await ReadRequestAsync(stream, cancellationToken).ConfigureAwait(false);
if (request is null)
{
return;
}
if (string.Equals(request.Path, SocketPath, StringComparison.Ordinal))
{
await UpgradeAsync(stream, request, cancellationToken).ConfigureAwait(false);
return;
}
await ServeAssetAsync(stream, request.Path, cancellationToken).ConfigureAwait(false);
}
private async Task ServeAssetAsync(Stream stream, string path, CancellationToken cancellationToken)
{
var asset = assets.Find(path);
if (asset is null)
{
await WriteResponseAsync(stream, "404 Not Found", "text/plain", "Not found"u8.ToArray(), cancellationToken)
.ConfigureAwait(false);
return;
}
var content = asset.Content;
if (string.Equals(path, PagePath, StringComparison.Ordinal))
{
// The token and socket URL are substituted at serve time rather than being written into
// the file, so the token never touches disk and never appears in a URL that could reach a
// log or a browser history.
var text = Encoding.UTF8.GetString(content)
.Replace(TokenPlaceholder, Token, StringComparison.Ordinal)
.Replace(
SocketUrlPlaceholder,
string.Create(CultureInfo.InvariantCulture, $"ws://127.0.0.1:{Port}{SocketPath}"),
StringComparison.Ordinal);
content = Encoding.UTF8.GetBytes(text);
}
await WriteResponseAsync(stream, "200 OK", asset.ContentType, content, cancellationToken)
.ConfigureAwait(false);
}
private async Task UpgradeAsync(
Stream stream,
HttpRequestLine request,
CancellationToken cancellationToken)
{
if (!IsAcceptableUpgrade(request))
{
await WriteResponseAsync(
stream, "403 Forbidden", "text/plain", "Rejected"u8.ToArray(), cancellationToken)
.ConfigureAwait(false);
return;
}
if (Interlocked.Exchange(ref accepted, 1) == 1)
{
// One renderer, one socket. A second attach would be either a bug or something else on the
// machine having found the port.
await WriteResponseAsync(
stream, "409 Conflict", "text/plain", "Already attached"u8.ToArray(), cancellationToken)
.ConfigureAwait(false);
return;
}
var key = request.Headers.GetValueOrDefault("sec-websocket-key")!;
var accept = ComputeHandshakeAccept(key);
var handshake =
"HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + accept + "\r\n"
+ "Sec-WebSocket-Protocol: " + SubProtocol + "\r\n\r\n";
await stream.WriteAsync(Encoding.ASCII.GetBytes(handshake), cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
// The handshake is ours; the framing is the BCL's. Hand-rolling masking, fragmentation and
// control frames would be a great deal of code for no gain.
using var webSocket = WebSocket.CreateFromStream(
stream,
new WebSocketCreationOptions
{
IsServer = true,
SubProtocol = SubProtocol,
KeepAliveInterval = TimeSpan.FromSeconds(30),
});
socket = webSocket;
rendererAttached.TrySetResult();
await ReceiveLoopAsync(webSocket, cancellationToken).ConfigureAwait(false);
}
/// <remarks>
/// The origin is checked because a page in the user's browser can attempt a WebSocket connection to
/// a loopback port, and the token because that page could otherwise simply guess the path. Neither
/// defends against a process running as this user; that one can read our memory regardless.
/// </remarks>
private bool IsAcceptableUpgrade(HttpRequestLine request)
{
var origin = request.Headers.GetValueOrDefault("origin");
var expectedOrigin = string.Create(CultureInfo.InvariantCulture, $"http://127.0.0.1:{Port}");
if (!string.Equals(origin, expectedOrigin, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (request.Headers.GetValueOrDefault("sec-websocket-key") is null)
{
return false;
}
var protocols = request.Headers.GetValueOrDefault("sec-websocket-protocol") ?? string.Empty;
var offered = protocols
.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
if (!offered.Contains(SubProtocol, StringComparer.Ordinal))
{
return false;
}
// Carried as a subprotocol rather than a query parameter, which keeps it out of anything that
// logs URLs.
var presented = offered.FirstOrDefault(p => p.StartsWith("token.", StringComparison.Ordinal));
return presented is not null
&& CryptographicOperations.FixedTimeEquals(
Encoding.ASCII.GetBytes(presented["token.".Length..]),
Encoding.ASCII.GetBytes(Token));
}
private async Task ReceiveLoopAsync(WebSocket webSocket, CancellationToken cancellationToken)
{
var buffer = new byte[ReceiveBufferBytes];
while (webSocket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
{
var result = await webSocket
.ReceiveAsync(buffer.AsMemory(), cancellationToken)
.ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
return;
}
if (!result.EndOfMessage)
{
// A frame larger than the receive buffer. Terminal input and acknowledgements are tiny,
// so this is either a bug or something hostile; dropping is the safe response.
continue;
}
Dispatch(buffer.AsSpan(0, result.Count));
}
}
private void Dispatch(ReadOnlySpan<byte> frame)
{
if (!TerminalFrame.TryRead(frame, out var opcode, out var sessionId, out var payload))
{
return;
}
TerminalSessionPump? pump;
lock (pumpGate)
{
pump = pumps.GetValueOrDefault(sessionId);
}
if (pump is null)
{
// A frame for a session that has already ended. Ordinary during teardown.
return;
}
switch ((TerminalClientOpcode)opcode)
{
case TerminalClientOpcode.Input:
// Fire and forget: a blocked write must not stall acknowledgements for other sessions
// sharing this socket.
_ = pump.WriteInputAsync(payload.ToArray(), lifetime.Token).AsTask();
break;
case TerminalClientOpcode.Acknowledge:
if (TerminalFrame.TryReadAcknowledgement(payload, out var rendered))
{
pump.Acknowledge(rendered);
}
break;
case TerminalClientOpcode.Resize:
if (TerminalFrame.TryReadResize(payload, out var size))
{
pump.Resize(size);
}
break;
default:
// Unknown opcode from a newer page than this host. Ignored rather than fatal.
break;
}
}
/// <summary>
/// Computes the <c>Sec-WebSocket-Accept</c> value RFC 6455 §4.2.2 requires.
/// </summary>
/// <remarks>
/// <para>
/// SHA-1 is mandated by the specification and is not doing security work here. The value proves
/// only that the server understood the WebSocket handshake rather than being a plain HTTP server
/// that echoed the request; it authenticates nothing and protects no data. Substituting SHA-256
/// would simply make the handshake fail with every client in existence.
/// </para>
/// <para>
/// The alternative that avoids SHA-1 in our own code is
/// <c>HttpListener.AcceptWebSocketAsync</c>, which throws <c>PlatformNotSupportedException</c>
/// off Windows — so it would trade a documented suppression for a platform restriction.
/// </para>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Security",
"CA5350:Do Not Use Weak Cryptographic Algorithms",
Justification = "RFC 6455 mandates SHA-1 for the handshake; it carries no security property.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"ApiDesign",
"RS0030:Do not use banned APIs",
Justification = "RFC 6455 mandates SHA-1 for the handshake; it carries no security property.")]
private static string ComputeHandshakeAccept(string key) =>
Convert.ToBase64String(SHA1.HashData(Encoding.ASCII.GetBytes(key + HandshakeGuid)));
private static async Task WriteResponseAsync(
Stream stream,
string status,
string contentType,
byte[] body,
CancellationToken cancellationToken)
{
var header =
"HTTP/1.1 " + status + "\r\n"
+ "Content-Type: " + contentType + "\r\n"
+ "Content-Length: " + body.Length.ToString(CultureInfo.InvariantCulture) + "\r\n"
// The page carries a connection token, so it must never be cached anywhere.
+ "Cache-Control: no-store\r\n"
+ "Connection: close\r\n\r\n";
await stream.WriteAsync(Encoding.ASCII.GetBytes(header), cancellationToken).ConfigureAwait(false);
await stream.WriteAsync(body, cancellationToken).ConfigureAwait(false);
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
private static async Task<HttpRequestLine?> ReadRequestAsync(
Stream stream,
CancellationToken cancellationToken)
{
var buffer = new byte[MaximumRequestBytes];
var count = 0;
while (count < buffer.Length)
{
var read = await stream
.ReadAsync(buffer.AsMemory(count), cancellationToken)
.ConfigureAwait(false);
if (read == 0)
{
break;
}
count += read;
if (Encoding.ASCII.GetString(buffer, 0, count).Contains("\r\n\r\n", StringComparison.Ordinal))
{
break;
}
}
var lines = Encoding.ASCII.GetString(buffer, 0, count).Split("\r\n");
var parts = lines[0].Split(' ');
if (parts.Length < 2 || !string.Equals(parts[0], "GET", StringComparison.Ordinal))
{
return null;
}
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var line in lines.Skip(1))
{
if (line.Length == 0)
{
break;
}
var separator = line.IndexOf(':', StringComparison.Ordinal);
if (separator > 0)
{
headers[line[..separator].Trim()] = line[(separator + 1)..].Trim();
}
}
var path = parts[1];
var query = path.IndexOf('?', StringComparison.Ordinal);
return new HttpRequestLine(query < 0 ? path : path[..query], headers);
}
private sealed record HttpRequestLine(string Path, IReadOnlyDictionary<string, string> Headers);
}
@@ -0,0 +1,181 @@
using System.Buffers.Binary;
namespace DodoSSH.Client.Terminal;
/// <summary>Frames the host sends to the renderer.</summary>
public enum TerminalServerOpcode : byte
{
/// <summary>Not a legal value.</summary>
Unspecified = 0,
/// <summary>Terminal output. Payload is raw bytes for <c>term.write</c>.</summary>
Output = 1,
/// <summary>A session has been created; the renderer should attach a terminal to it.</summary>
SessionOpened = 2,
/// <summary>A session has ended. Payload is a UTF-8 reason for the user.</summary>
SessionClosed = 3,
}
/// <summary>Frames the renderer sends to the host.</summary>
public enum TerminalClientOpcode : byte
{
/// <summary>Not a legal value.</summary>
Unspecified = 0,
/// <summary>Keystrokes. Payload is raw bytes for the remote.</summary>
Input = 1,
/// <summary>
/// Bytes actually rendered. Payload is a big-endian <see cref="uint"/>, returning credit.
/// </summary>
Acknowledge = 2,
/// <summary>The terminal was resized. Payload is four big-endian <see cref="ushort"/> values.</summary>
Resize = 3,
}
/// <summary>
/// The wire format between the host process and the renderer page.
/// </summary>
/// <remarks>
/// <para>
/// Binary frames over a loopback WebSocket, not the WebView's JavaScript bridge. The official bridge
/// is UI-thread-bound string evaluation: at 10 MB/s in 4 KiB chunks that is roughly 2,500 script
/// evaluations per second on the thread that also has to paint, with base64's 33% overhead on top and
/// — decisively — no backpressure signal at all. A socket gives flow control for free.
/// </para>
/// <para>
/// Every frame carries a session id because one WebView hosts every terminal. A WebView2 instance is
/// a separate browser process, so one per tab would mean twenty renderer processes and hundreds of
/// megabytes for a normal working set of tabs.
/// </para>
/// <para>
/// Fixed 5-byte header, big-endian, no length prefix: WebSocket already delimits messages, so adding
/// our own length would be a second source of truth about where a frame ends.
/// </para>
/// </remarks>
public static class TerminalFrame
{
/// <summary>Opcode plus session id.</summary>
public const int HeaderLength = 1 + sizeof(uint);
/// <summary>Writes a frame into <paramref name="destination"/> and returns its length.</summary>
public static int Write(
Span<byte> destination,
byte opcode,
uint sessionId,
ReadOnlySpan<byte> payload)
{
var total = HeaderLength + payload.Length;
if (destination.Length < total)
{
throw new ArgumentException(
$"Need {total} bytes for the frame, got {destination.Length}.",
nameof(destination));
}
destination[0] = opcode;
BinaryPrimitives.WriteUInt32BigEndian(destination[1..], sessionId);
payload.CopyTo(destination[HeaderLength..]);
return total;
}
/// <summary>Allocates and writes a frame.</summary>
public static byte[] Create(byte opcode, uint sessionId, ReadOnlySpan<byte> payload)
{
var frame = new byte[HeaderLength + payload.Length];
Write(frame, opcode, sessionId, payload);
return frame;
}
/// <summary>
/// Reads a frame's header and payload.
/// </summary>
/// <remarks>
/// Returns false rather than throwing on anything malformed. These frames arrive from a WebView
/// page — a different process running code we shipped but do not control at runtime — so a bad
/// frame is untrusted input to be dropped, not an exceptional condition.
/// </remarks>
public static bool TryRead(
ReadOnlySpan<byte> frame,
out byte opcode,
out uint sessionId,
out ReadOnlySpan<byte> payload)
{
opcode = 0;
sessionId = 0;
payload = default;
if (frame.Length < HeaderLength)
{
return false;
}
opcode = frame[0];
sessionId = BinaryPrimitives.ReadUInt32BigEndian(frame[1..]);
payload = frame[HeaderLength..];
return true;
}
/// <summary>Reads an <see cref="TerminalClientOpcode.Acknowledge"/> payload.</summary>
public static bool TryReadAcknowledgement(ReadOnlySpan<byte> payload, out uint rendered)
{
rendered = 0;
if (payload.Length != sizeof(uint))
{
return false;
}
rendered = BinaryPrimitives.ReadUInt32BigEndian(payload);
return true;
}
/// <summary>Reads a <see cref="TerminalClientOpcode.Resize"/> payload.</summary>
public static bool TryReadResize(ReadOnlySpan<byte> payload, out DodoSSH.Client.Ssh.TerminalSize size)
{
size = default;
if (payload.Length != sizeof(ushort) * 4)
{
return false;
}
size = new DodoSSH.Client.Ssh.TerminalSize(
BinaryPrimitives.ReadUInt16BigEndian(payload),
BinaryPrimitives.ReadUInt16BigEndian(payload[2..]),
BinaryPrimitives.ReadUInt16BigEndian(payload[4..]),
BinaryPrimitives.ReadUInt16BigEndian(payload[6..]));
return true;
}
/// <summary>Writes a <see cref="TerminalClientOpcode.Resize"/> payload. Used by tests and tooling.</summary>
public static byte[] CreateResizePayload(DodoSSH.Client.Ssh.TerminalSize size)
{
var payload = new byte[sizeof(ushort) * 4];
BinaryPrimitives.WriteUInt16BigEndian(payload, size.Columns);
BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(2), size.Rows);
BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(4), size.PixelWidth);
BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(6), size.PixelHeight);
return payload;
}
/// <summary>Writes an <see cref="TerminalClientOpcode.Acknowledge"/> payload.</summary>
public static byte[] CreateAcknowledgementPayload(uint rendered)
{
var payload = new byte[sizeof(uint)];
BinaryPrimitives.WriteUInt32BigEndian(payload, rendered);
return payload;
}
}
@@ -0,0 +1,308 @@
using System.Buffers;
using System.Text;
using System.Threading.Channels;
using DodoSSH.Client.Ssh;
namespace DodoSSH.Client.Terminal;
/// <summary>Where terminal frames are sent.</summary>
/// <remarks>
/// Implementations must serialise sends: a WebSocket does not permit concurrent writes, and the pump
/// deliberately does not know whether its transport is a socket, a test double or something else.
/// </remarks>
public interface ITerminalTransport
{
/// <summary>Sends one binary frame.</summary>
ValueTask SendAsync(ReadOnlyMemory<byte> frame, CancellationToken cancellationToken);
}
/// <summary>Tuning for one session's output path.</summary>
public sealed class TerminalPumpOptions
{
/// <summary>How many bytes to read from the channel at once.</summary>
public int ReadBufferBytes { get; init; } = 32 * 1024;
/// <summary>
/// How long to accumulate output before sending it.
/// </summary>
/// <remarks>
/// xterm cannot render faster than the display refreshes, so flushing more often than once a frame
/// is work whose result is overwritten before anyone sees it. 16 ms is one frame at 60 Hz, and the
/// added latency on an echoed keystroke is below the threshold of perception.
/// </remarks>
public TimeSpan FlushInterval { get; init; } = TimeSpan.FromMilliseconds(16);
/// <summary>How far behind the renderer may fall, in bytes.</summary>
public int WindowBytes { get; init; } = CreditWindow.DefaultWindowBytes;
}
/// <summary>
/// Moves bytes between one SSH shell channel and the renderer, under flow control.
/// </summary>
/// <remarks>
/// <para>
/// Credit is reserved before reading, never after. That ordering is the whole design: because the pump
/// cannot read more than the renderer has room for, the coalescing buffer is bounded by the credit
/// window rather than by how fast the remote can talk. Reserving after reading would leave an
/// unbounded queue between the socket and the screen, which is the failure mode this exists to
/// prevent.
/// </para>
/// <para>
/// When credit runs out the pump stops reading. SSH's own receive window then closes, the remote
/// <c>sshd</c> blocks on write, and the process producing output blocks in turn — backpressure all the
/// way to the source, with no custom protocol.
/// </para>
/// </remarks>
public sealed class TerminalSessionPump : IAsyncDisposable
{
private readonly uint sessionId;
private readonly ISshShellSession session;
private readonly ITerminalTransport transport;
private readonly TimeProvider clock;
private readonly TerminalPumpOptions options;
private readonly Channel<byte[]> pending = Channel.CreateUnbounded<byte[]>(
new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });
private readonly CancellationTokenSource lifetime = new();
private int disposed;
/// <param name="sessionId">Identifies this session in every frame.</param>
/// <param name="session">The shell channel.</param>
/// <param name="transport">Where frames go.</param>
/// <param name="clock">Time source, so the flush interval is testable.</param>
/// <param name="options">Tuning, or null for the defaults.</param>
public TerminalSessionPump(
uint sessionId,
ISshShellSession session,
ITerminalTransport transport,
TimeProvider clock,
TerminalPumpOptions? options = null)
{
ArgumentNullException.ThrowIfNull(session);
ArgumentNullException.ThrowIfNull(transport);
ArgumentNullException.ThrowIfNull(clock);
this.sessionId = sessionId;
this.session = session;
this.transport = transport;
this.clock = clock;
this.options = options ?? new TerminalPumpOptions();
Credits = new CreditWindow(this.options.WindowBytes);
}
/// <summary>This session's flow-control window.</summary>
public CreditWindow Credits { get; }
/// <summary>Total bytes read from the remote, for the throughput harness.</summary>
public long BytesRead { get; private set; }
/// <summary>Total frames sent to the renderer, for the throughput harness.</summary>
public long FramesSent { get; private set; }
/// <summary>
/// Runs until the remote closes the channel or the token is cancelled.
/// </summary>
/// <remarks>
/// The read and flush loops are separate tasks because a read blocks until bytes arrive: combining
/// them would mean output sitting unflushed until the next byte happened to show up, so a prompt
/// would appear only after the user pressed a key.
/// </remarks>
public async Task RunAsync(CancellationToken cancellationToken)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
cancellationToken,
lifetime.Token);
await SendAsync(TerminalServerOpcode.SessionOpened, default, linked.Token).ConfigureAwait(false);
var reader = ReadLoopAsync(linked.Token);
var flusher = FlushLoopAsync(linked.Token);
string reason;
try
{
await reader.ConfigureAwait(false);
reason = "The remote closed the session.";
}
catch (OperationCanceledException)
{
reason = "The session was closed.";
}
catch (Exception exception)
{
reason = exception.Message;
}
// Stop the flusher, but only after draining what the reader already produced — the last thing
// a remote writes is often the most important, and dropping it makes a clean exit look like a
// crash.
pending.Writer.TryComplete();
try
{
await flusher.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Cancelled during shutdown; the drain below is best-effort anyway.
}
await SendAsync(
TerminalServerOpcode.SessionClosed,
Encoding.UTF8.GetBytes(reason),
CancellationToken.None)
.ConfigureAwait(false);
}
/// <summary>Forwards keystrokes to the remote.</summary>
public ValueTask WriteInputAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken) =>
session.WriteAsync(data, cancellationToken);
/// <summary>Tells the remote the terminal was resized.</summary>
public void Resize(TerminalSize size) => session.Resize(size);
/// <summary>Returns credit for bytes the renderer reported rendering.</summary>
public void Acknowledge(uint rendered) =>
Credits.Return(rendered > int.MaxValue ? int.MaxValue : (int)rendered);
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref disposed, 1) == 1)
{
return;
}
await lifetime.CancelAsync().ConfigureAwait(false);
// Unblocks anything waiting on credit that will now never be acknowledged.
Credits.Reset();
pending.Writer.TryComplete();
lifetime.Dispose();
await session.DisposeAsync().ConfigureAwait(false);
}
private async Task ReadLoopAsync(CancellationToken cancellationToken)
{
var buffer = ArrayPool<byte>.Shared.Rent(options.ReadBufferBytes);
try
{
while (!cancellationToken.IsCancellationRequested)
{
await Credits.WaitForCreditAsync(cancellationToken).ConfigureAwait(false);
var granted = Credits.TryReserve(options.ReadBufferBytes);
if (granted == 0)
{
continue;
}
int read;
try
{
read = await session
.ReadAsync(buffer.AsMemory(0, granted), cancellationToken)
.ConfigureAwait(false);
}
catch
{
Credits.Return(granted);
throw;
}
// Hand back what was reserved but not used, so a short read does not permanently
// shrink the window.
Credits.Return(granted - read);
if (read == 0)
{
return;
}
BytesRead += read;
await pending.Writer.WriteAsync(buffer[..read], cancellationToken).ConfigureAwait(false);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private async Task FlushLoopAsync(CancellationToken cancellationToken)
{
var segments = new List<byte[]>();
while (await pending.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
{
if (!pending.Reader.TryRead(out var first))
{
continue;
}
segments.Clear();
segments.Add(first);
// Coalesce for one frame's worth of time, then send everything at once. Whatever the
// remote produced in that window becomes a single write to the terminal.
await Task.Delay(options.FlushInterval, clock, cancellationToken).ConfigureAwait(false);
while (pending.Reader.TryRead(out var more))
{
segments.Add(more);
}
await SendOutputAsync(segments, cancellationToken).ConfigureAwait(false);
}
// The channel completed. Anything the reader wrote before finishing still has to go out.
segments.Clear();
while (pending.Reader.TryRead(out var trailing))
{
segments.Add(trailing);
}
if (segments.Count > 0)
{
await SendOutputAsync(segments, CancellationToken.None).ConfigureAwait(false);
}
}
private async ValueTask SendOutputAsync(List<byte[]> segments, CancellationToken cancellationToken)
{
var total = 0;
foreach (var segment in segments)
{
total += segment.Length;
}
var frame = new byte[TerminalFrame.HeaderLength + total];
TerminalFrame.Write(frame, (byte)TerminalServerOpcode.Output, sessionId, default);
var offset = TerminalFrame.HeaderLength;
foreach (var segment in segments)
{
segment.CopyTo(frame, offset);
offset += segment.Length;
}
FramesSent++;
await transport.SendAsync(frame, cancellationToken).ConfigureAwait(false);
}
private async ValueTask SendAsync(
TerminalServerOpcode opcode,
ReadOnlyMemory<byte> payload,
CancellationToken cancellationToken)
{
FramesSent++;
await transport
.SendAsync(TerminalFrame.Create((byte)opcode, sessionId, payload.Span), cancellationToken)
.ConfigureAwait(false);
}
}
@@ -0,0 +1,54 @@
{
"version": 2,
"dependencies": {
"net10.0": {
"Meziantou.Analyzer": {
"type": "Direct",
"requested": "[3.0.134, )",
"resolved": "3.0.134",
"contentHash": "tTYCcYKyOko3TMNxmxmA9nakbcHVUgglENmCMIhzIjl9y9FBZO/0tWSxTGC74Sp198FmWih5S5KkjQRBg5ePkQ=="
},
"Microsoft.CodeAnalysis.BannedApiAnalyzers": {
"type": "Direct",
"requested": "[5.6.0, )",
"resolved": "5.6.0",
"contentHash": "Kcobt3pnOdO0A+6CKiMHZdTEluJpsfxiV20axtZdmfBQnDmiWTKPJADlgAfdTuKNAnVarrkJa0UEGwuOo91muw=="
},
"Microsoft.Extensions.DependencyInjection.Abstractions": {
"type": "Transitive",
"resolved": "8.0.2",
"contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg=="
},
"Microsoft.Extensions.Logging.Abstractions": {
"type": "Transitive",
"resolved": "8.0.3",
"contentHash": "dL0QGToTxggRLMYY4ZYX5AMwBb+byQBd/5dMiZE07Nv73o6I5Are3C7eQTh7K2+A4ct0PVISSr7TZANbiNb2yQ==",
"dependencies": {
"Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2"
}
},
"dodossh.client.ssh": {
"type": "Project",
"dependencies": {
"SSH.NET": "[2025.1.0, )"
}
},
"BouncyCastle.Cryptography": {
"type": "CentralTransitive",
"requested": "[2.6.2, )",
"resolved": "2.6.2",
"contentHash": "7oWOcvnntmMKNzDLsdxAYqApt+AjpRpP2CShjMfIa3umZ42UQMvH0tl1qAliYPNYO6vTdcGMqnRrCPmsfzTI1w=="
},
"SSH.NET": {
"type": "CentralTransitive",
"requested": "[2025.1.0, )",
"resolved": "2025.1.0",
"contentHash": "jrnbtf0ItVaXAe6jE8X/kSLa6uC+0C+7W1vepcnRQB/rD88qy4IxG7Lf1FIbWmkoc4iVXv0pKrz+Wc6J4ngmHw==",
"dependencies": {
"BouncyCastle.Cryptography": "2.6.2",
"Microsoft.Extensions.Logging.Abstractions": "8.0.3"
}
}
}
}
}