Files
DodoSSH/src/DodoSSH.Client.Ssh/SshNetSftpSession.cs
T
jaap-jan 04faef6597 Move files to and from a host over SFTP
M2's file transfer, built bottom-up: an SFTP session on the SSH layer, a
transfer queue in a project of its own, and the two-pane browser the design
asked for replacing the screen that said it did not exist. Remote listings
carry names, sizes, modification times and a real drwxr-xr-x — nothing in this
repository could render a POSIX mode before — and the queue moves one file at a
time with progress, throughput and resume.

The design import assumed this would be an SFTP subsystem channel on
ISshConnection, beside the shell on a transport that is already up. SSH.NET
does not offer that: SftpClient derives from BaseClient and owns its own
transport, and there is no supported way to hand it an SshClient's session. So
file transfer opens a second authenticated connection, and it is named for
that rather than dressed up as a channel — OpenSftpAsync is on
ISftpSessionFactory, not on a connection. The difference is visible to a user:
the host records a second login, and a host whose password is typed each time
asks for it again on this screen. It goes through the same host key gate, the
same pin and the same two refusals a shell does, so a fingerprint approved for
a terminal is approved here and one approved here reaches the other machines
with the next sync. docs/design-import-gaps.md is corrected, and marked as the
one row where what shipped differs from what it predicted.

Nothing is written at its final name until it is complete. Every transfer goes
to a .dodossh-part file beside its destination and is renamed into place at the
end, so an interrupted transfer can never be mistaken for a finished one —
which matters most for what this screen is actually for, which is copying a
build artefact onto a server and then running it. A destination that already
exists is refused outright rather than overwritten: the queue has no way to
ask, and silently replacing a file somebody's process is serving is the worse
of the two failures. The remote pane has DELETE and MKDIR so that refusal is
not a dead end. A test against the container pins the assumption underneath all
of this — that SFTP's rename does not clobber.

Resume works within a run of the application and not across a restart, and the
limit is deliberate rather than unfinished. Nothing records which source wrote
a part file, and resuming one on the strength of its name matching is how a
corrupt artefact gets delivered with nothing reporting a failure; a part file
found at startup is started over. Making it survive a restart needs the
preferences store this client still has not got. The offset a resume starts at
is the part file's own length rather than the transfer's recorded progress: a
cancellation can land between a write completing and the counter moving, and
only one of those two is a fact about the bytes that are there.

The queue and its connection outlive a lock, as shells do. LockAsync already
argues that locking must not destroy work in flight — it is what somebody does
when they walk away from the machine, which is exactly when a long transfer is
most likely to be running — so TransfersViewModel is created once and the vault
is attached on unlock and detached on lock. What locking takes is the host
list, and it has to: those rows carry decrypted secrets.

DodoSSH.Client.Transfer is a new project rather than more of Client.Ssh. The
two answer different questions — one is about reaching a host, the other about
moving bytes and what to do when moving them stops halfway — and this is the
only client project that deliberately touches the local filesystem.

Three defects the tests found, none of which review would have. SftpPath.Name
answered an empty string for the root. NavigateRemoteAsync wrapped itself in
the busy guard, so navigating from inside another command did nothing at all
and the remote pane simply stayed empty after connecting, with no failure
anywhere to explain it. And opening an SFTP session per test made two
handshakes per test — this client learns a host key by being refused — which
pushed the SSH assembly past sshd's MaxStartups and failed a different few
unrelated tests each run; the session is shared through the fixture now, with
the reason written where the next person will hit it.

1004 tests green across 18 projects, 24 of them new: the SFTP subsystem against
the OpenSSH container, the queue against a real temporary directory and a fake
host, and three more layout measurements because a screen this window has never
laid out is a screen never checked.

Not verified: the screen has not been looked at running. The layout harness
measures it at the window's minimum in three shapes, which is the class of
defect that has shipped here before, but reaching it in the application needs
the compose stack, the migrations, the API and a browser sign-in. What is still
absent — the status bar's transfer count, dragging between the panes,
transferring a directory, and sftp over a bastion — is in
docs/design-import-gaps.md.
2026-07-31 11:07:29 +02:00

251 lines
9.4 KiB
C#

using Renci.SshNet;
using Renci.SshNet.Common;
using Renci.SshNet.Sftp;
namespace DodoSSH.Client.Ssh;
/// <summary>An SSH.NET-backed file-transfer session.</summary>
/// <remarks>
/// Thin on purpose. Everything above this reasons about <see cref="SftpEntry"/> and <see cref="Stream"/>,
/// which is what keeps the transfer queue and the file browser testable without a server — and the one thing
/// this type does beyond forwarding calls is translate SSH.NET's several path failures into the single one a
/// caller can act on.
/// </remarks>
internal sealed class SshNetSftpSession(SftpClient client, HostKeyPresentation hostKey, string homeDirectory)
: ISftpSession
{
/// <inheritdoc />
public bool IsConnected => client.IsConnected;
/// <inheritdoc />
public HostKeyPresentation HostKey { get; } = hostKey;
/// <inheritdoc />
public string HomeDirectory { get; } = homeDirectory;
/// <inheritdoc />
public async Task<IReadOnlyList<SftpEntry>> ListAsync(string path, CancellationToken cancellationToken)
{
var entries = new List<SftpEntry>();
try
{
await foreach (var file in client
.ListDirectoryAsync(path, cancellationToken)
.ConfigureAwait(false))
{
// Every directory has these and no user is choosing between them. The way up is the
// breadcrumb trail, which cannot be mistaken for a file.
if (file.Name is "." or "..")
{
continue;
}
entries.Add(Describe(file));
}
}
catch (Exception exception) when (IsPathFailure(exception))
{
throw Translate(path, exception);
}
// Directories first and then by name, which is the order a file browser shows and the order that
// saves every caller sorting it again. Ordinal, because a remote filesystem's names are bytes the
// server never claimed a culture for, and a listing whose order depended on this machine's locale
// would put the same directory in two orders on two of a user's machines.
entries.Sort(static (left, right) => left.Kind == right.Kind
? string.CompareOrdinal(left.Name, right.Name)
: Rank(left.Kind).CompareTo(Rank(right.Kind)));
return entries;
}
/// <inheritdoc />
public async Task<SftpEntry?> StatAsync(string path, CancellationToken cancellationToken)
{
try
{
var file = await client.GetAsync(path, cancellationToken).ConfigureAwait(false);
return Describe(file);
}
catch (SftpPathNotFoundException)
{
// Absent is an answer rather than a failure. Every caller here is asking whether something is
// already there, and turning "no" into an exception would put a try/catch at each of them.
return null;
}
catch (Exception exception) when (IsPathFailure(exception))
{
throw Translate(path, exception);
}
}
/// <inheritdoc />
public Task<Stream> OpenReadAsync(string path, long offset, CancellationToken cancellationToken) =>
OpenAsync(path, FileMode.Open, FileAccess.Read, offset, cancellationToken);
/// <inheritdoc />
public Task<Stream> OpenWriteAsync(string path, long offset, CancellationToken cancellationToken) =>
OpenAsync(path, FileMode.OpenOrCreate, FileAccess.Write, offset, cancellationToken);
/// <inheritdoc />
public async Task CreateDirectoryAsync(string path, CancellationToken cancellationToken)
{
try
{
await client.CreateDirectoryAsync(path, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception) when (IsPathFailure(exception))
{
throw Translate(path, exception);
}
}
/// <inheritdoc />
public async Task DeleteAsync(string path, CancellationToken cancellationToken)
{
try
{
// One call for both kinds: SSH.NET stats the path and issues rmdir or remove accordingly. A
// non-empty directory fails here, which is the refusal this interface promises.
await client.DeleteAsync(path, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception) when (IsPathFailure(exception))
{
throw Translate(path, exception);
}
}
/// <inheritdoc />
public async Task RenameAsync(string fromPath, string toPath, CancellationToken cancellationToken)
{
try
{
await client.RenameFileAsync(fromPath, toPath, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception) when (IsPathFailure(exception))
{
// Named for the destination, which is what the caller chose and what a collision is about. The
// source is a path the transfer queue made up.
throw Translate(toPath, exception);
}
}
/// <inheritdoc />
public ValueTask DisposeAsync()
{
client.Dispose();
return ValueTask.CompletedTask;
}
/// <remarks>
/// Seeking after the open rather than asking for an appending mode. <c>FileMode.Append</c> would give the
/// right position for an upload and nothing for a download, and a resume has to be able to start at an
/// offset that is <em>not</em> the end — a part file whose tail was written by an interrupted transfer is
/// exactly that case, and the queue truncates to a known-good length before resuming.
/// </remarks>
private async Task<Stream> OpenAsync(
string path,
FileMode mode,
FileAccess access,
long offset,
CancellationToken cancellationToken)
{
ArgumentOutOfRangeException.ThrowIfNegative(offset);
SftpFileStream stream;
try
{
stream = await client.OpenAsync(path, mode, access, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception) when (IsPathFailure(exception))
{
throw Translate(path, exception);
}
if (offset == 0)
{
return stream;
}
try
{
stream.Seek(offset, SeekOrigin.Begin);
}
catch
{
await stream.DisposeAsync().ConfigureAwait(false);
throw;
}
return stream;
}
/// <summary>Directories first, then links, then everything else.</summary>
private static int Rank(SftpEntryKind kind) => kind switch
{
SftpEntryKind.Directory => 0,
SftpEntryKind.SymbolicLink => 1,
_ => 2,
};
private static SftpEntry Describe(ISftpFile file)
{
// Checked in this order because the predicates are not exclusive: a symbolic link to a directory
// answers true to both, and calling that a directory would hide the fact that opening it depends on
// the server resolving a link. Asking about the link first is the honest reading of an lstat.
var kind = file switch
{
{ IsSymbolicLink: true } => SftpEntryKind.SymbolicLink,
{ IsDirectory: true } => SftpEntryKind.Directory,
{ IsRegularFile: true } => SftpEntryKind.File,
_ => SftpEntryKind.Other,
};
return new SftpEntry(
file.Name,
file.FullName,
kind,
// Only a file's length means anything. A directory's is the size of its own inode, which is a
// number no user has ever wanted in a SIZE column.
kind is SftpEntryKind.File ? file.Length : 0,
new DateTimeOffset(file.LastWriteTimeUtc, TimeSpan.Zero),
PosixMode.Format(
kind,
file.OwnerCanRead,
file.OwnerCanWrite,
file.OwnerCanExecute,
file.GroupCanRead,
file.GroupCanWrite,
file.GroupCanExecute,
file.OthersCanRead,
file.OthersCanWrite,
file.OthersCanExecute));
}
/// <remarks>
/// <see cref="SshException"/> covers the SFTP-specific types as well, since both derive from it. It is
/// deliberately wide: the SFTP protocol returns a status code and a server-supplied message for
/// everything from a missing file to a full disk, and SSH.NET surfaces most of them as a bare
/// <see cref="SshException"/> carrying that message. What must <em>not</em> be caught is cancellation and
/// the ordinary failures of this process, which is why this is a predicate rather than a bare catch.
/// </remarks>
private static bool IsPathFailure(Exception exception) =>
exception is SshException or IOException or UnauthorizedAccessException;
private static SftpPathException Translate(string path, Exception exception) => exception switch
{
SftpPathNotFoundException => new SftpPathException(path, $"{path} is not there.", exception),
SftpPermissionDeniedException => new SftpPathException(
path, $"The server refused access to {path}.", exception),
// The server's own words. They are the only description of a full disk, a quota or a read-only mount
// that this client could produce, and inventing a friendlier sentence would lose them.
_ => new SftpPathException(path, $"{path}: {exception.Message}", exception),
};
}