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.
This commit is contained in:
2026-07-31 11:07:29 +02:00
parent 94e11f5e38
commit 04faef6597
32 changed files with 4933 additions and 53 deletions
+357
View File
@@ -0,0 +1,357 @@
using System.Globalization;
namespace DodoSSH.Client.Ssh;
/// <summary>What kind of thing a remote directory entry is.</summary>
/// <remarks>
/// Taken from the attributes a listing already carries, which are <c>lstat</c> attributes: a symbolic link
/// reports as a link whatever it points at. Resolving each one would be a round trip per entry, so
/// <see cref="SftpEntryKind.SymbolicLink"/> stays its own answer and the caller finds out what it leads to by
/// trying to list it — see <see cref="ISftpSession.ListAsync"/>.
/// </remarks>
public enum SftpEntryKind
{
/// <summary>An ordinary file.</summary>
File = 0,
/// <summary>A directory.</summary>
Directory = 1,
/// <summary>A symbolic link, to something this listing did not resolve.</summary>
SymbolicLink = 2,
/// <summary>A socket, device, pipe or anything else that is not one of the three above.</summary>
Other = 3,
}
/// <summary>One entry in a remote directory.</summary>
/// <param name="Name">The entry's own name, with no path.</param>
/// <param name="FullPath">The absolute path, which is what every operation takes.</param>
/// <param name="Kind">What it is.</param>
/// <param name="Length">Size in bytes. Meaningless for anything that is not a file, and zero there.</param>
/// <param name="LastWriteTimeUtc">When it was last written.</param>
/// <param name="Permissions">The mode as <c>drwxr-xr-x</c>; see <see cref="PosixMode"/>.</param>
/// <remarks>
/// A record of what the server said rather than a handle. Nothing here holds a channel open, so a listing can
/// be kept on a screen after the session behind it has gone — which is what the transfers screen does while a
/// connection is being re-established.
/// </remarks>
public sealed record SftpEntry(
string Name,
string FullPath,
SftpEntryKind Kind,
long Length,
DateTimeOffset LastWriteTimeUtc,
string Permissions)
{
/// <summary>Whether this is somewhere the file browser can navigate into.</summary>
/// <remarks>
/// True for a symbolic link as well as a directory, because a link to a directory is the ordinary way a
/// remote filesystem is laid out and refusing to open one would make those paths unreachable. A link to a
/// file fails the listing instead, which is the caller's cue that it was not a directory after all.
/// </remarks>
public bool IsNavigable => Kind is SftpEntryKind.Directory or SftpEntryKind.SymbolicLink;
}
/// <summary>
/// Renders POSIX permission bits the way <c>ls -l</c> does.
/// </summary>
/// <remarks>
/// Nothing in this repository formatted a mode before, and the design's file listing has a <c>PERMS</c>
/// column. It is written from the individual bits rather than from an octal mode because that is the shape
/// SFTP hands over — <c>ISftpFile</c> exposes nine booleans and a set of kind predicates, and reassembling
/// them into an octal number only to take it apart again would be a round trip through a representation
/// neither end uses.
/// <para>
/// The setuid, setgid and sticky bits are not shown. SFTP's own file attributes carry them, SSH.NET does not
/// surface them on <c>ISftpFile</c>, and a column that showed <c>rwx</c> where <c>rws</c> was true would be
/// worse than one that never claims to render them.
/// </para>
/// </remarks>
public static class PosixMode
{
/// <summary>Formats one entry's mode, kind character included.</summary>
public static string Format(
SftpEntryKind kind,
bool ownerRead,
bool ownerWrite,
bool ownerExecute,
bool groupRead,
bool groupWrite,
bool groupExecute,
bool othersRead,
bool othersWrite,
bool othersExecute)
{
Span<char> mode = stackalloc char[10];
mode[0] = kind switch
{
SftpEntryKind.Directory => 'd',
SftpEntryKind.SymbolicLink => 'l',
SftpEntryKind.File => '-',
_ => '?',
};
Write(mode[1..4], ownerRead, ownerWrite, ownerExecute);
Write(mode[4..7], groupRead, groupWrite, groupExecute);
Write(mode[7..10], othersRead, othersWrite, othersExecute);
return new string(mode);
static void Write(Span<char> triple, bool read, bool write, bool execute)
{
triple[0] = read ? 'r' : '-';
triple[1] = write ? 'w' : '-';
triple[2] = execute ? 'x' : '-';
}
}
}
/// <summary>
/// Remote paths, which are POSIX paths whatever this client is running on.
/// </summary>
/// <remarks>
/// <b>Not <see cref="Path"/>.</b> The BCL's path helpers use the local platform's separator, so on Windows
/// <c>Path.Combine("/var", "log")</c> yields <c>/var\log</c> — a path the remote will not resolve and which
/// fails as "no such file" somewhere the user cannot see the backslash. Every remote path in this codebase
/// goes through here.
/// </remarks>
public static class SftpPath
{
/// <summary>The root of a remote filesystem.</summary>
public const string Root = "/";
/// <summary>Joins a directory and a name.</summary>
public static string Combine(string directory, string name)
{
ArgumentException.ThrowIfNullOrEmpty(directory);
return directory.EndsWith('/') ? directory + name : directory + "/" + name;
}
/// <summary>The directory holding a path, or the path itself when it is already the root.</summary>
public static string Parent(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
var trimmed = path.Length > 1 ? path.TrimEnd('/') : path;
var slash = trimmed.LastIndexOf('/');
return slash switch
{
< 0 => Root,
0 => Root,
_ => trimmed[..slash],
};
}
/// <summary>The last segment of a path, or the root when that is all there is.</summary>
/// <remarks>
/// The root names itself. Taking the text after its only separator leaves an empty string, which as a
/// heading or a tab label is a blank where a path should be.
/// </remarks>
public static string Name(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
var trimmed = path.Length > 1 ? path.TrimEnd('/') : path;
var slash = trimmed.LastIndexOf('/');
var name = slash < 0 ? trimmed : trimmed[(slash + 1)..];
return name.Length == 0 ? Root : name;
}
/// <summary>Whether a path is already anchored at the root.</summary>
public static bool IsAbsolute(string path) => path.StartsWith('/');
/// <summary>
/// The segments of a path, for a breadcrumb trail.
/// </summary>
/// <returns>
/// Each segment paired with the absolute path that reaches it, root first. An empty list for the root
/// itself, which has no segment to name.
/// </returns>
public static IReadOnlyList<(string Name, string Path)> Trail(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
var trail = new List<(string, string)>();
var walked = string.Empty;
foreach (var segment in path.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
walked = Combine(walked.Length == 0 ? Root : walked, segment);
trail.Add((segment, walked));
}
return trail;
}
}
/// <summary>
/// A file-transfer session on one host.
/// </summary>
/// <remarks>
/// <para>
/// <b>This is a connection, not a channel.</b> The obvious shape would have been
/// <c>ISshConnection.OpenSftpAsync</c>, opening the SFTP subsystem beside the shell on the transport that is
/// already up — which is what SSH itself allows and what <c>docs/design-import-gaps.md</c> assumed it would
/// take. SSH.NET does not offer it: <c>SftpClient</c> derives from <c>BaseClient</c> and owns its own
/// transport, and there is no supported way to hand it an existing <c>SshClient</c>'s session. So opening one
/// of these authenticates again.
/// </para>
/// <para>
/// It is named for that rather than dressed up as a channel, because the difference is visible to a user: the
/// host sees a second login, a one-time password would be asked for twice, and closing every terminal on a
/// host does not close its file browser. <see cref="ISshConnectionFactory.OpenSftpAsync"/> is a
/// <em>connect</em>, and host key trust is checked on it exactly as it is for a shell.
/// </para>
/// <para>
/// One session is one channel, and everything on it shares that channel's window — so the queue that drives
/// this runs one transfer at a time. That is a throughput decision rather than a safety one: two large
/// transfers over one channel do not go faster than one, they arrive later and both at once. Browsing while a
/// transfer runs is fine, and is the point of not opening a session per transfer.
/// </para>
/// </remarks>
public interface ISftpSession : IAsyncDisposable
{
/// <summary>Whether the transport is still up.</summary>
bool IsConnected { get; }
/// <summary>The host key that was accepted for this session.</summary>
HostKeyPresentation HostKey { get; }
/// <summary>
/// Where the session starts, which is the account's home directory.
/// </summary>
/// <remarks>
/// Absolute, because the server resolves it during the handshake. It is the only path this layer knows
/// without asking, and it is what a file browser should open on.
/// </remarks>
string HomeDirectory { get; }
/// <summary>
/// Lists a directory.
/// </summary>
/// <remarks>
/// <c>.</c> and <c>..</c> are dropped: every remote directory has them, no user is choosing between them,
/// and the way up is a breadcrumb rather than a row. Ordered directories first and then by name, which is
/// what a file browser has to show and what saves every caller sorting it again.
/// </remarks>
/// <exception cref="SftpPathException">The path is not a directory, or is not readable.</exception>
Task<IReadOnlyList<SftpEntry>> ListAsync(string path, CancellationToken cancellationToken);
/// <summary>What one path is, or null when nothing is there.</summary>
Task<SftpEntry?> StatAsync(string path, CancellationToken cancellationToken);
/// <summary>
/// Opens a remote file for reading, starting at an offset.
/// </summary>
/// <param name="path">The file.</param>
/// <param name="offset">Where to start, which is what makes an interrupted download resumable.</param>
/// <param name="cancellationToken">Abandons the open.</param>
Task<Stream> OpenReadAsync(string path, long offset, CancellationToken cancellationToken);
/// <summary>
/// Opens a remote file for writing, starting at an offset.
/// </summary>
/// <remarks>
/// Creates the file when it is not there, and does not truncate one that is — an offset of zero over an
/// existing file overwrites from the beginning and leaves any tail beyond what is written. Callers are
/// expected to write to a path nothing else holds; the transfer queue writes to a part file for exactly
/// this reason.
/// </remarks>
/// <param name="path">The file.</param>
/// <param name="offset">Where to start, which is what makes an interrupted upload resumable.</param>
/// <param name="cancellationToken">Abandons the open.</param>
Task<Stream> OpenWriteAsync(string path, long offset, CancellationToken cancellationToken);
/// <summary>Creates one directory, whose parent must exist.</summary>
Task CreateDirectoryAsync(string path, CancellationToken cancellationToken);
/// <summary>
/// Deletes a file, or an empty directory.
/// </summary>
/// <remarks>
/// Deliberately not recursive. A recursive remote delete is the one operation on this screen that can
/// destroy something no undo reaches, and offering it behind the same button as deleting one file is how
/// that happens by accident. A non-empty directory fails, and says so.
/// </remarks>
Task DeleteAsync(string path, CancellationToken cancellationToken);
/// <summary>Renames or moves a path within the same host.</summary>
Task RenameAsync(string fromPath, string toPath, CancellationToken cancellationToken);
}
/// <summary>
/// Something on the remote filesystem could not be reached, and the server said why.
/// </summary>
/// <remarks>
/// One exception for the whole surface rather than one per operation, because there is exactly one thing a
/// caller does with any of them: show the message beside the path it was about. SSH.NET raises several
/// unrelated types for what a user experiences as one condition — <c>SftpPathNotFoundException</c>,
/// <c>SftpPermissionDeniedException</c>, and a bare <c>SshException</c> for the rest — and the path is not on
/// all of them.
/// </remarks>
public sealed class SftpPathException(string path, string message, Exception? innerException = null)
: Exception(message, innerException)
{
/// <summary>The path the failure was about.</summary>
public string Path { get; } = path;
}
/// <summary>Opens file-transfer sessions.</summary>
/// <remarks>
/// Declared beside <see cref="ISshConnectionFactory"/> and implemented by the same type, because both start
/// with the same handshake and the same host key decision. See <see cref="ISftpSession"/> for why this is a
/// separate connect rather than a channel on a connection that already exists.
/// </remarks>
public interface ISftpSessionFactory
{
/// <summary>
/// Connects, authenticates, and starts the SFTP subsystem.
/// </summary>
/// <exception cref="SshHostKeyUnknownException">
/// The host has no pinned key. Resolved exactly as it is for a shell: show the fingerprint, record it on
/// explicit confirmation, and retry.
/// </exception>
/// <exception cref="SshHostKeyMismatchException">
/// The presented key differs from the pin. There is no retry path.
/// </exception>
Task<ISftpSession> OpenSftpAsync(SshConnectionRequest request, CancellationToken cancellationToken);
}
/// <summary>Formats a byte count the way a file browser shows one.</summary>
/// <remarks>
/// Here rather than in the view model because the transfer queue's own progress reporting needs the same
/// wording, and two spellings of "1.4 MB" in one window reads as two different measurements.
/// </remarks>
public static class ByteSize
{
private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"];
/// <summary>Formats a byte count to three significant figures.</summary>
public static string Format(long bytes)
{
if (bytes < 1024)
{
return string.Create(CultureInfo.InvariantCulture, $"{bytes} B");
}
double scaled = bytes;
var unit = 0;
while (scaled >= 1024 && unit < Units.Length - 1)
{
scaled /= 1024;
unit++;
}
// One decimal below ten, none above: "9.4 MB" and "512 MB" are both three characters of information,
// and "512.3 MB" is a precision the number does not have by the time it is that large.
return scaled < 10
? string.Create(CultureInfo.InvariantCulture, $"{scaled:0.0} {Units[unit]}")
: string.Create(CultureInfo.InvariantCulture, $"{scaled:0} {Units[unit]}");
}
}
@@ -13,10 +13,22 @@ namespace DodoSSH.Client.Ssh;
/// blocking the handshake on a UI round trip. Anything the comparison cannot settle becomes an
/// exception the caller resolves asynchronously.
/// </remarks>
public sealed class SshNetConnectionFactory(IKnownHostStore knownHosts) : ISshConnectionFactory
public sealed class SshNetConnectionFactory(IKnownHostStore knownHosts)
: ISshConnectionFactory, ISftpSessionFactory
{
private static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(15);
/// <summary>
/// How much of a file SSH.NET reads or writes per SFTP request.
/// </summary>
/// <remarks>
/// SSH.NET's default is 32 KiB, which is a request per 32 KiB and a round trip's latency between each on
/// a link the window would happily keep full. 64 KiB is the largest an OpenSSH server accepts without
/// negotiation, so it is the ceiling rather than a guess — anything above it is answered with a shorter
/// read, which SSH.NET handles but which buys nothing.
/// </remarks>
private const uint SftpBufferSize = 64 * 1024;
/// <inheritdoc />
public async Task<ISshConnection> ConnectAsync(
SshConnectionRequest request,
@@ -25,6 +37,62 @@ public sealed class SshNetConnectionFactory(IKnownHostStore knownHosts) : ISshCo
ArgumentNullException.ThrowIfNull(request);
var client = new SshClient(BuildConnectionInfo(request));
var gate = await ConnectThroughHostKeyGateAsync(client, request, cancellationToken)
.ConfigureAwait(false);
return new SshNetConnection(client, gate.Presented!);
}
/// <inheritdoc />
/// <remarks>
/// A second connection to the host rather than a second channel on one that may already be open — see
/// <see cref="ISftpSession"/> for why SSH.NET leaves no choice. Everything that guards a shell guards this
/// too, because it is the same handshake: the same host key gate, the same pin, the same two refusals.
/// </remarks>
public async Task<ISftpSession> OpenSftpAsync(
SshConnectionRequest request,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
var client = new SftpClient(BuildConnectionInfo(request)) { BufferSize = SftpBufferSize };
var gate = await ConnectThroughHostKeyGateAsync(client, request, cancellationToken)
.ConfigureAwait(false);
// Read once, here, rather than per call. SftpClient.WorkingDirectory canonicalises against the server
// on first read, so leaving it to the property would put a round trip behind something that reads
// like a field — and the session's own remark promises this is the one path known without asking.
string home;
try
{
home = client.WorkingDirectory;
}
catch
{
client.Dispose();
throw;
}
return new SshNetSftpSession(client, gate.Presented!, home);
}
/// <summary>
/// Runs the handshake with host key trust attached, and translates a refusal this factory caused.
/// </summary>
/// <remarks>
/// Shared by the shell and the file-transfer paths over <c>BaseClient</c>, which is where SSH.NET puts
/// both <c>ConnectAsync</c> and <c>HostKeyReceived</c>. The alternative was the same twelve lines twice,
/// and the half worth getting wrong is the translation: without it a user who has never seen a host is
/// told the connection was lost.
/// </remarks>
private async Task<HostKeyGate> ConnectThroughHostKeyGateAsync(
BaseClient client,
SshConnectionRequest request,
CancellationToken cancellationToken)
{
var gate = new HostKeyGate(knownHosts, request, cancellationToken);
client.HostKeyReceived += gate.OnHostKeyReceived;
@@ -47,7 +115,7 @@ public sealed class SshNetConnectionFactory(IKnownHostStore knownHosts) : ISshCo
throw;
}
return new SshNetConnection(client, gate.Presented!);
return gate;
}
/// <summary>
+250
View File
@@ -0,0 +1,250 @@
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),
};
}