Files
DodoSSH/src/DodoSSH.Client.Ssh/SshConnection.cs
T
jaap-jan e2733e5cbc
ci / build and test (push) Successful in 3m28s
ci / android head (push) Successful in 4m48s
ci / desktop nightly (push) Successful in 1m17s
ci / api image (push) Successful in 28s
Notice when a shell ends, say which way it ended, and offer the way back
A terminal whose machine rebooted stayed green for ever. Not "went stale and
recovered late" — for ever: the tab claimed CONNECTED, the elapsed timer went
on counting, and the only thing that ever corrected it was closing the
application. That is the defect this fixes, and it turned out to be two
separate failures wearing one symptom.

◆ THE HANG IS IN SSH.NET, AND KEEP-ALIVE ALONE WOULD NOT HAVE FIXED IT.

ShellStream ends a blocked read from exactly two places: its channel being
closed, and the session raising Disconnected. A shell that exits gives the
first. But Session raises Disconnected from one method only — OnDisconnectReceived,
for a server that politely says goodbye — and a socket that simply fails goes
down a different path entirely: RaiseError fires the error event, sets the
disconnecting flag and disposes the socket, without ever raising Disconnected.
So the stream was never disposed, its Monitor.Wait was never pulsed, and the
read blocked until the process ended. The transport was gone, the client knew
the transport was gone, and nothing woke the one thread that was waiting.

That is why the first attempt at a test for this sat at thirty seconds and
failed. Both halves are needed and neither is sufficient:

  - Keep-alive makes the failure HAPPEN. An idle SSH session is a socket
    nobody writes to, and TCP has no way to discover that the far end has gone
    without writing to it — nothing was asked, so nothing could fail. Thirty
    seconds, matching OpenSSH's own ServerAliveInterval examples. It is the
    write that matters and not a reply: SSH_MSG_IGNORE need not be answered,
    so this is traffic rather than a heartbeat with a deadline, and there is
    no timeout invented here to be wrong about a slow link.

  - Disposing the stream from the error handler makes it ARRIVE. Queued to the
    thread pool and not done inline, which is not tidiness: this runs on
    SSH.NET's message-listener thread, and closing a channel waits for the
    server's close — processed by that same thread — so an inline dispose is
    the listener thread waiting on itself.

SFTP gets the keep-alive too. Its operations are request/response and bounded
by ConnectionInfo.Timeout already, so it needs no equivalent wake-up.

◆ exit AND reboot ARE TOLD APART BY A LATCH, BECAUSE THE OBVIOUS WAY IS A RACE.

Wait for the read to end and then ask whether the transport is still up, and
against a real server the answer is wrong about half the time: this was the
only channel on the connection, so sshd hangs up a millisecond after closing
it. By the time anything could ask, the transport is gone either way — and a
poll would report every ordinary `exit` as a dropped connection.

So ISshShellSession.TransportFailure is set at the moment SSH.NET raises the
failure, which its own ordering puts strictly before the disconnect that wakes
the read. A read that has just returned zero consults a settled value: set if
the transport failed, still null if the remote merely closed the channel. The
pump turns that into a TerminalSessionOutcome — RemoteClosed, ConnectionLost,
ClosedLocally — carried on SessionEnded, which used to hand over a session id
and nothing else. A subscriber cannot work this out afterwards; by the time it
hears, there is no transport left to interrogate.

Deliberately no fourth value for "the remote rebooted". Nothing on the wire
distinguishes a reboot from a cable being pulled, and a name this client
cannot check would be a guess dressed as a fact.

◆ WHAT IS DRAWN, AND WHY IT IS NOT DRAWN OVER THE PANE.

The status bar says DISCONNECTED or SHELL EXITED where it used to say NOT
CONNECTED for both — a word that is honest about a tab still dialling and
useless about one whose shell has stopped. Red for the first and grey for the
second: one is a machine that stopped answering and the other is work
finished, and crying wolf on the ordinary end of every session is its own bug.
The tab strip's dot gains the same fourth state, on both heads.

Under the terminal, a strip carrying the reason and two buttons. It takes its
own Auto grid row rather than overlaying the renderer, and that is forced
rather than chosen: the WebView is a native child view composited above
everything Avalonia draws, so the alternative is collapsing the terminal — and
the scrollback is precisely what the user wants to read, because the last
thing the remote said is usually why it went. terminal.js already writes the
same sentence into the pane; this is the copy that does not scroll away.

RECONNECT reuses the tab in place, which is what the word means to somebody
who pressed it: the terminal they were working in comes back, where it was.
It dials through the vault's ordinary connect path, so every refusal — a key
that has left the keychain, an unknown host key, a group default that has
changed since — is decided in the one place that already decides them; what
this adds is which tab the attempt belongs to. The old session is closed as
part of it, because a dead shell still holds an authenticated connection this
process has stopped reading, and its pane still holds an xterm, a scrollback
and a WebGL context, of which a browser hands out about sixteen.

Two refusals it makes rather than pretending: a host reached by typing an
address has no keychain entry to redial, and one that wants a password typed
goes to the keychain with the sheet raised rather than being dialled with an
empty box. Both say so on the strip where the button was pressed, not only in
the vault's status on a screen that surface is not.

TRY AGAIN appears on a refused connection for the same reason, and it is worth
as much: the commonest refusal is a host that was not up yet.

◆ WHAT IS ACTUALLY VERIFIED.

Two tests against a real sshd in a container. `exit` is reported as the remote
closing the session — the one a polling implementation fails, and a fake shell
cannot show it because a fake has no server behind it deciding to hang up. And
a live shell losing its transport is reported as a lost connection, produced
by dialling through a plain TCP relay the test owns and then cutting it; the
container is shared by the collection, so killing sshd was never an option.

The first draft of that second test used LoopbackProxyTests' SOCKS forward and
timed out: disconnecting the carrier of a ForwardedPortDynamic does not close
the loopback socket it accepted. Recorded in the test, because it is a
property of SSH.NET's forwarder rather than of anything here, and it is not
what a dying machine looks like.

What no test reproduces is the waiting. A relay that closes sends a FIN, so
the socket reports itself at once; a machine switched off sends nothing, and
finding that out is the keep-alive's business and the OS's retransmit budget's
— neither of which a test can hurry along without a clock this code does not
own. A reboot is prompt in practice because the machine comes back and RSTs.

Beside those: three pump outcomes, three workspace announcements, and seven
shell-flow tests covering the drop, the clean exit, reuse of the tab, retry
after a refusal, and both ways a reconnect can honestly come to nothing.

Also fixed in passing: SshNetShellSession.IsOpen read ShellStream.CanRead,
which is documented as always true — the stream stays readable after disposal
so buffered output can be drained — so it had answered "yes" for every shell
that ever existed. It reads CanWrite now. And MainWindowViewModel's session-
ended handler moved from Dispatcher.UIThread.Post to the injected post
delegate, which is what makes any of the shell half testable at all; the
remark listing the three unreachable posts is one shorter.
2026-08-24 10:36:15 +02:00

247 lines
12 KiB
C#

namespace DodoSSH.Client.Ssh;
/// <summary>How to authenticate to a host.</summary>
/// <remarks>
/// Always decrypted from the vault immediately before use and never persisted outside it. Because
/// SSH terminates on the client, using a credential requires its plaintext here — which is exactly
/// why the <c>Connect</c> permission is a UI hint and not an enforceable boundary. See ADR 0001.
/// </remarks>
public abstract record SshCredential;
/// <summary>Password authentication, and keyboard-interactive where the server prefers it.</summary>
public sealed record SshPasswordCredential(string Password) : SshCredential;
/// <summary>Public-key authentication.</summary>
/// <param name="PrivateKeyPem">The private key in PEM form, as stored in the vault.</param>
/// <param name="Passphrase">Passphrase protecting the key, when it has one.</param>
public sealed record SshPrivateKeyCredential(byte[] PrivateKeyPem, string? Passphrase) : SshCredential;
/// <summary>
/// A SOCKS5 proxy on this machine's loopback interface, through which a host is reached.
/// </summary>
/// <param name="Port">The port it is listening on.</param>
/// <remarks>
/// <para>
/// ◆ <b>A port and nothing else, so a proxy anywhere but loopback cannot be expressed.</b> Both things
/// that will produce one of these listen on <c>127.0.0.1</c> — SSH.NET's own dynamic forward over a
/// bastion, and the bridge that will front the server relay — and a SOCKS proxy bound to any other
/// interface is an open proxy into whatever network the machine is on, for as long as the shell is up.
/// Leaving the host out of this type is what makes that unrepresentable rather than merely unlikely; it is
/// the same reason <c>AuthenticationChoice</c> carries a kind beside its id.
/// </para>
/// <para>
/// <b>SOCKS5 rather than a plain pipe, and that is what keeps host key pinning honest.</b> The target's
/// real name and port stay in <see cref="SshConnectionRequest.Host"/> and <see cref="SshConnectionRequest.Port"/>
/// and travel to the proxy in the CONNECT request, so the connection is *about* the target throughout —
/// nothing downstream has to be told that the address dialled is not the address being spoken to. A dumb
/// pipe would have meant handing SSH.NET <c>127.0.0.1</c> and remembering, everywhere else, that it was a
/// stand-in. See the gate in <c>SshNetConnectionFactory</c>, which pins what this request names.
/// </para>
/// <para>
/// Nothing in this assembly opens one. The proxy is somebody else's — a forward on a bastion connection,
/// or the relay bridge — and its lifetime belongs to whoever opened it, which must outlast the connection
/// made through it. See <c>docs/reaching-a-host-you-cannot-dial.md</c>.
/// </para>
/// </remarks>
public sealed record SshLoopbackProxy(int Port);
/// <summary>Everything needed to reach one host.</summary>
/// <param name="Host">Hostname or address.</param>
/// <param name="Port">Port.</param>
/// <param name="Username">Remote account.</param>
/// <param name="Credential">How to authenticate.</param>
/// <param name="ConnectTimeout">How long to wait for the transport and handshake.</param>
/// <param name="Proxy">
/// A loopback SOCKS5 proxy to reach <paramref name="Host"/> through, or null to dial it directly.
/// <para>
/// Last and optional, so that every existing caller — which is every connection this product makes today —
/// keeps meaning exactly what it did. A host that can be dialled is still dialled.
/// </para>
/// </param>
public sealed record SshConnectionRequest(
string Host,
int Port,
string Username,
SshCredential Credential,
TimeSpan? ConnectTimeout = null,
SshLoopbackProxy? Proxy = null);
/// <summary>
/// How a shell session came to an end.
/// </summary>
/// <remarks>
/// <para>
/// Three, because they are the three a user would answer differently. A shell that exited is over and there
/// is nothing wrong; a connection that was lost is a machine that may well still be there, and is the one
/// worth offering to dial again; a session this client ended is a tab being closed, which nobody needs told.
/// </para>
/// <para>
/// ◆ <b>Deliberately not a fourth for "the remote rebooted".</b> Nothing on the wire distinguishes a reboot
/// from a cable being pulled — both are a transport that stops answering — and a name this client cannot
/// check would be a guess dressed as a fact. <see cref="ConnectionLost"/> is what is actually known.
/// </para>
/// </remarks>
public enum SshSessionEnd
{
/// <summary>
/// The remote ended it in an orderly way: the shell exited, or the server hung up cleanly.
/// </summary>
/// <remarks>
/// What <c>exit</c> and <c>logout</c> produce, and what a login shell being killed produces. The channel
/// closed while the transport under it was still healthy.
/// </remarks>
RemoteClosed = 0,
/// <summary>
/// The transport failed underneath it, with no channel close first.
/// </summary>
/// <remarks>
/// A reboot, a network that went away, an <c>sshd</c> that was killed, a laptop lid. See
/// <see cref="ISshShellSession.TransportFailure"/> for how this is told apart from
/// <see cref="RemoteClosed"/> without a race.
/// </remarks>
ConnectionLost = 1,
/// <summary>This client ended it: a tab was closed, a reconnect began, or the process is shutting down.</summary>
ClosedLocally = 2,
}
/// <summary>An interactive shell over a pseudo-terminal.</summary>
public interface ISshShellSession : IAsyncDisposable
{
/// <summary>Whether the channel is still usable.</summary>
bool IsOpen { get; }
/// <summary>
/// Why the transport under this shell went away, or null if it did not.
/// </summary>
/// <remarks>
/// <para>
/// ◆ <b>A latched value rather than a question asked afterwards, and that is the whole point of it.</b>
/// The obvious way to tell <c>exit</c> from a dropped connection is to wait for the read to report the end
/// of the shell and then ask whether the transport is still up — and it is wrong about half the time,
/// because a server whose only channel just closed hangs the connection up a millisecond later. The
/// answer to that question races the teardown; this does not.
/// </para>
/// <para>
/// What makes it safe is an ordering SSH.NET guarantees: a transport failure is raised on its
/// message-listener thread <em>before</em> that thread goes on to disconnect the session, and it is the
/// disconnect that wakes a blocked read. So a read that has just returned zero can consult this and get a
/// settled answer — set if the transport failed, still null if the remote merely closed the channel.
/// </para>
/// <para>
/// The message rather than the exception: this is read to be shown to somebody, and nothing above this
/// interface branches on a type.
/// </para>
/// </remarks>
string? TransportFailure { get; }
/// <summary>Reads whatever output is available, blocking until at least one byte arrives.</summary>
/// <returns>Bytes read, or 0 once the remote closes the channel.</returns>
ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken);
/// <summary>Sends keystrokes to the remote.</summary>
ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken);
/// <summary>
/// Tells the remote the terminal has been resized.
/// </summary>
/// <remarks>
/// Verified to reach the remote against a real sshd; see <c>PtyAndResizeSpikeTests</c>. Sizes
/// that are not <see cref="TerminalSize.IsUsable"/> are dropped rather than forwarded.
/// </remarks>
void Resize(TerminalSize size);
}
/// <summary>An authenticated connection to one host.</summary>
public interface ISshConnection : IAsyncDisposable
{
/// <summary>Whether the transport is still up.</summary>
bool IsConnected { get; }
/// <summary>The host key that was accepted for this connection.</summary>
HostKeyPresentation HostKey { get; }
/// <summary>
/// The negotiated server-to-client encryption algorithm, e.g. <c>aes256-gcm@openssh.com</c>.
/// </summary>
/// <remarks>
/// <para>
/// Read once, immediately after the handshake, off SSH.NET's own <c>ConnectionInfo.CurrentServerEncryption</c>.
/// The only event that could make this stale is a rekey, and SSH.NET raises no event for one and exposes no
/// way to ask again — there is nothing behind this property to go and re-read. A captured value is therefore
/// not a snapshot that might drift; it is the only value there has ever been a moment to observe.
/// </para>
/// <para>
/// <b>Server-to-client, not client-to-server.</b> SSH negotiates the two directions independently and a
/// server is free to choose differently for each, so the two can in principle disagree. This is the
/// direction the bytes drawn on a terminal pane travelled in, which is the fact a status bar showing what
/// the screen is made of should be naming.
/// </para>
/// </remarks>
string Cipher { get; }
/// <summary>Opens an interactive shell with a pseudo-terminal.</summary>
Task<ISshShellSession> OpenShellAsync(TerminalSize size, CancellationToken cancellationToken);
}
/// <summary>
/// How far a connection being made has got.
/// </summary>
/// <remarks>
/// <para>
/// These are the boundaries a client can actually observe, and there are deliberately no others. SSH.NET
/// runs the whole handshake inside one <c>ConnectAsync</c> and raises exactly one event from the middle of
/// it — <c>HostKeyReceived</c>, once the key exchange has produced a key to show. That event is the only
/// interior moment there is, so it is the only interior phase named here: everything before it is
/// <see cref="Reaching"/> and everything after it is <see cref="Authenticating"/>.
/// </para>
/// <para>
/// ◆ <b>Nothing here is a guess about elapsed time or a fraction of the way through.</b> Each value is
/// reported at the instant the thing it names actually starts, which is what makes it safe for a screen to
/// draw as fact. A phase that took no measurable time is reported anyway and simply passes at once — that
/// is a true account of a fast handshake, not a step that was skipped. See the transfer strip's own remark
/// in TransfersScreen.axaml for why this design does not invent furniture for states it cannot measure.
/// </para>
/// </remarks>
public enum SshConnectionPhase
{
/// <summary>Resolving the name, opening the socket, and exchanging keys. Before any key is known.</summary>
Reaching = 0,
/// <summary>The server has offered a host key, and its trust is being decided.</summary>
CheckingHostKey = 1,
/// <summary>The key was accepted. The credential is being offered.</summary>
Authenticating = 2,
/// <summary>Authenticated. A pseudo-terminal and a shell channel are being opened.</summary>
OpeningShell = 3,
}
/// <summary>Opens connections, enforcing host key trust before authenticating.</summary>
public interface ISshConnectionFactory
{
/// <summary>
/// Connects and authenticates.
/// </summary>
/// <param name="request">What to connect to, as whom, and with what.</param>
/// <param name="progress">
/// Told each phase as it begins, or null to report nothing. Called from whichever thread the handshake
/// is on — SSH.NET raises host key verification on its own — so an implementation that touches a UI must
/// marshal for itself.
/// </param>
/// <param name="cancellationToken">Abandons the attempt.</param>
/// <exception cref="SshHostKeyUnknownException">
/// The host has no pinned key. The caller must show the fingerprint, and only on explicit
/// confirmation record it via <see cref="IKnownHostStore.TrustAsync"/> and retry.
/// </exception>
/// <exception cref="SshHostKeyMismatchException">
/// The presented key differs from the pin. There is no retry path: this is a hard block.
/// </exception>
Task<ISshConnection> ConnectAsync(
SshConnectionRequest request,
IProgress<SshConnectionPhase>? progress,
CancellationToken cancellationToken);
}