using System.Globalization; namespace DodoSSH.Client.Ssh; /// What kind of thing a remote directory entry is. /// /// Taken from the attributes a listing already carries, which are lstat attributes: a symbolic link /// reports as a link whatever it points at. Resolving each one would be a round trip per entry, so /// stays its own answer and the caller finds out what it leads to by /// trying to list it — see . /// public enum SftpEntryKind { /// An ordinary file. File = 0, /// A directory. Directory = 1, /// A symbolic link, to something this listing did not resolve. SymbolicLink = 2, /// A socket, device, pipe or anything else that is not one of the three above. Other = 3, } /// One entry in a remote directory. /// The entry's own name, with no path. /// The absolute path, which is what every operation takes. /// What it is. /// Size in bytes. Meaningless for anything that is not a file, and zero there. /// When it was last written. /// The mode as drwxr-xr-x; see . /// /// 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. /// public sealed record SftpEntry( string Name, string FullPath, SftpEntryKind Kind, long Length, DateTimeOffset LastWriteTimeUtc, string Permissions) { /// Whether this is somewhere the file browser can navigate into. /// /// 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. /// public bool IsNavigable => Kind is SftpEntryKind.Directory or SftpEntryKind.SymbolicLink; } /// /// Renders POSIX permission bits the way ls -l does. /// /// /// Nothing in this repository formatted a mode before, and the design's file listing has a PERMS /// column. It is written from the individual bits rather than from an octal mode because that is the shape /// SFTP hands over — ISftpFile 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. /// /// The setuid, setgid and sticky bits are not shown. SFTP's own file attributes carry them, SSH.NET does not /// surface them on ISftpFile, and a column that showed rwx where rws was true would be /// worse than one that never claims to render them. /// /// public static class PosixMode { /// Formats one entry's mode, kind character included. 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 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 triple, bool read, bool write, bool execute) { triple[0] = read ? 'r' : '-'; triple[1] = write ? 'w' : '-'; triple[2] = execute ? 'x' : '-'; } } } /// /// Remote paths, which are POSIX paths whatever this client is running on. /// /// /// Not . The BCL's path helpers use the local platform's separator, so on Windows /// Path.Combine("/var", "log") yields /var\log — 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. /// public static class SftpPath { /// The root of a remote filesystem. public const string Root = "/"; /// Joins a directory and a name. public static string Combine(string directory, string name) { ArgumentException.ThrowIfNullOrEmpty(directory); return directory.EndsWith('/') ? directory + name : directory + "/" + name; } /// The directory holding a path, or the path itself when it is already the root. 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], }; } /// The last segment of a path, or the root when that is all there is. /// /// 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. /// 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; } /// Whether a path is already anchored at the root. public static bool IsAbsolute(string path) => path.StartsWith('/'); /// /// The segments of a path, for a breadcrumb trail. /// /// /// 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. /// 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; } } /// /// A file-transfer session on one host. /// /// /// /// This is a connection, not a channel. The obvious shape would have been /// ISshConnection.OpenSftpAsync, opening the SFTP subsystem beside the shell on the transport that is /// already up — which is what SSH itself allows and what docs/design-import-gaps.md assumed it would /// take. SSH.NET does not offer it: SftpClient derives from BaseClient and owns its own /// transport, and there is no supported way to hand it an existing SshClient's session. So opening one /// of these authenticates again. /// /// /// 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. is a /// connect, and host key trust is checked on it exactly as it is for a shell. /// /// /// 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. /// /// public interface ISftpSession : IAsyncDisposable { /// Whether the transport is still up. bool IsConnected { get; } /// The host key that was accepted for this session. HostKeyPresentation HostKey { get; } /// /// Where the session starts, which is the account's home directory. /// /// /// 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. /// string HomeDirectory { get; } /// /// Lists a directory. /// /// /// . and .. 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. /// /// The path is not a directory, or is not readable. Task> ListAsync(string path, CancellationToken cancellationToken); /// What one path is, or null when nothing is there. Task StatAsync(string path, CancellationToken cancellationToken); /// /// Opens a remote file for reading, starting at an offset. /// /// The file. /// Where to start, which is what makes an interrupted download resumable. /// Abandons the open. Task OpenReadAsync(string path, long offset, CancellationToken cancellationToken); /// /// Opens a remote file for writing, starting at an offset. /// /// /// 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. /// /// The file. /// Where to start, which is what makes an interrupted upload resumable. /// Abandons the open. Task OpenWriteAsync(string path, long offset, CancellationToken cancellationToken); /// Creates one directory, whose parent must exist. Task CreateDirectoryAsync(string path, CancellationToken cancellationToken); /// /// Deletes a file, or an empty directory. /// /// /// 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. /// Task DeleteAsync(string path, CancellationToken cancellationToken); /// Renames or moves a path within the same host. Task RenameAsync(string fromPath, string toPath, CancellationToken cancellationToken); } /// /// Something on the remote filesystem could not be reached, and the server said why. /// /// /// 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 — SftpPathNotFoundException, /// SftpPermissionDeniedException, and a bare SshException for the rest — and the path is not on /// all of them. /// public sealed class SftpPathException(string path, string message, Exception? innerException = null) : Exception(message, innerException) { /// The path the failure was about. public string Path { get; } = path; } /// Opens file-transfer sessions. /// /// Declared beside and implemented by the same type, because both start /// with the same handshake and the same host key decision. See for why this is a /// separate connect rather than a channel on a connection that already exists. /// public interface ISftpSessionFactory { /// /// Connects, authenticates, and starts the SFTP subsystem. /// /// /// The host has no pinned key. Resolved exactly as it is for a shell: show the fingerprint, record it on /// explicit confirmation, and retry. /// /// /// The presented key differs from the pin. There is no retry path. /// Task OpenSftpAsync(SshConnectionRequest request, CancellationToken cancellationToken); } /// Formats a byte count the way a file browser shows one. /// /// 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. /// public static class ByteSize { private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"]; /// Formats a byte count to three significant figures. 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]}"); } }