Public Access
Free the terminal from the Hosts screen, and fill the room it left
The WebView sat inside the Hosts grid, so navigating to Files or the keychain hid every open terminal and the strip that named them. A connection you had opened was invisible from four of the five screens. The window now has two surfaces rather than one: a nav rail that says which page you are on, and a terminal strip that is always there and switches the whole content area to a shell. Screen keeps meaning "which page" and never becomes a sixth kind of page, which is why this is two properties instead of one enum with a terminal member in it. Every screen lives inside one wrapper panel that collapses when a terminal is showing. That is not tidiness — the WebView hosts a Win32 child window that composites above everything Avalonia draws, so a screen left visible over its rectangle is a screen sliced in half, and this window has shipped that defect once already. One decision point, IsTerminalShowing, and a nested panel rather than five compound bindings nobody would remember to extend. The focus choreography is the part no test in this repo can see. Every reveal path now focuses in the same turn the WebView appeared, so all three of them post at DispatcherPriority.Loaded and let the native control re-push its bounds first. Going the other way had a real bug: the screen-changed branch called a bare Focus() where it had to release the keyboard from the native child, so switching from a terminal to Files silently ate the first keystrokes. Rare before this commit and the primary gesture after it. The tab strip grew a cross inside each tab, a plus that opens the quick-connect palette, and middle-click close. Nested buttons are correct here: Avalonia handles a left press on the cross and deliberately does not handle other buttons, which is exactly what lets middle-click bubble up from the cross as well as the tab. The test is PointerUpdateKind rather than IsMiddleButtonPressed, because the latter reports button state and is also true for a left press made while the middle button happens to be held. The handler is on the tab and not the strip, so the background closes nothing by construction. Plus opens the palette rather than a flyout, since a menu dropping into the WebView's rectangle may or may not composite above a child HWND and this repo does not make rendering claims it has not photographed. Everything a user reads now says keychain. The wire, the database and the cryptographic spec still say vault, deliberately: renaming those is a migration and a protocol change for a word. That split is written down rather than left to be rediscovered as an inconsistency. Four things that were squeezed into the keychain's category rail, or into nothing at all, now have screens. Pinned host keys get one, with fingerprints never truncated and a filter that matches them, because comparing what you have against what the operator published is the whole workflow; the approved date is read out of the item's UUIDv7 rather than added as a column, and says so, since it means first approval and not last use. Keys can be generated in the client, which needed the openssh-key-v1 container written by hand — there is no BCL or NSec helper, and the PKCS#8 route is unverified in the SSH library this uses. The armour carries no passphrase: encrypting it needs bcrypt_pbkdf, which is Blowfish with a swizzle, in a project whose crypto is otherwise entirely libsodium, for a protection the key's own remarks argue is redundant inside a vault. Generation fills the existing editor and stops, so SAVE stays the one thing that writes. ~/.ssh/config can be imported behind a preview that is ticked per row and writes nothing until the button; IdentityFile records the path and imports the key material only on an explicit opt-in, because reading somebody's private key into a vault is precisely the act this product exists to make deliberate. Match blocks and ProxyJump are reported rather than obeyed — one cannot be evaluated statically and the other has nothing behind it to route with, and a preview that implied otherwise would be worse than one that admits it. Files can be dragged in all four directions that are honestly available. Remote to Explorer does not ship and is not pretended to: the shell wants the bytes during the drop, which needs a virtual file and a native COM data object, outside what Avalonia offers. Note for the next person that Avalonia 12 replaced the drag model outright — DataObject and DataFormats are no-op stubs and IDataObject is not in the reference assembly, so every tutorial written for 11 does not compile here. Hosts can be grouped, flat and never nested. A parent id merged as a scalar lets two offline clients each re-parent A under B and B under A, producing a cycle inside an encrypted payload that no server can police and every reader would have to detect for ever. Membership lives in that payload rather than in the one plaintext concession ADR 0001 allows, whose test is that the relay cannot function without it — nothing on the server reads a group, so what plaintext would hand over is a clustering of the estate for nothing. The plaintext column reserved for it is dropped, provably always null, and the server now refuses a client that sends one; it was never populated, was copied on apply, and was not cleared on delete, so a group id would have outlived the host it described. Snippets insert through xterm rather than through the pump, because xterm is the only thing that knows whether the remote has bracketed paste on, and that is what makes a shell treat embedded newlines as text instead of as execute. The host process moves opaque bytes and never parses output, so it would have to guess, and guessing wrong runs every line. Running is off by default and the copy says the text goes into whatever is there — the terminal has no notion of being at a prompt, and may be in vi or at a password prompt with echo off, so the Enter the user presses themselves is the entire safety property. Connections and keychain changes are recorded as synced encrypted items, which is what makes them auditable by a team later and costs the server knowledge of connection rate and timing from row counts alone. ADR 0001 already concedes it cannot hide that class of metadata; the trade is now written into it rather than left implicit. A connection entry is written once, at close, which is what makes a synced log tractable: nothing to merge, one outbox row, no chance of colliding with itself. Live sessions come from memory, not from the log. The write is void by contract and posts to a bounded channel, because putting an encrypt-and-write on the teardown path of every session is how closing the application comes to take four seconds. A ticket opened before a lock still closes afterwards, since a shell outlives the vault. The activity log hooks the one generic repository every kind writes through, so it cannot miss a caller — which is also why the log kinds themselves declare they are not audited, or the first entry would write an entry about writing an entry. It records the names of the fields that changed and never their values; a log with an old password in it would be a plaintext credential store with no vault around it. Retention is 90 days or 5,000 entries, whichever bites first, pruned on the sync loop rather than on a second timer. That log traffic then broke the status line, which is worth recording because the fix is a shape and not a patch: background sync counted its own log rows as pushed items, so the quiet rule stopped being quiet and every action's message was overwritten a second later by a sync report. The report now separates log rows from user items and the rule reads the latter. S3 buckets appear as a remote in the file browser, behind the same interface an SFTP session implements, so the queue and both panes did not have to learn what they are talking to. Uploads go through a pipe, because the queue wants to write and the SDK wants to read; memory is then bounded by the part size instead of buffering a file to disk twice. Finally, the Windows device key store moved out of the session project, which was the one thing keeping it from being portable — everything else in it is platform-neutral, and a Windows CNG dependency in the middle of the vault code meant a second head could not reference it without dragging Windows along. The seam that made the move free was already there. docs/android-port.md is the audit behind that: what ports, what does not, in order of cost, the four decisions taken, and an inventory of every screen and state the interface has to carry, written so a design can be made from it directly. dotnet build, dotnet test and dotnet format --verify-no-changes are all clean: 1240 tests at zero warnings, including the end-to-end suite against real containers. The manual checks that headless Avalonia cannot make — the drag from Explorer, a generated key against a real host, twelve tabs at the minimum window width — are listed in docs/manual-checks.md and are still outstanding.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Reading an OpenSSH client configuration and turning it into hosts this application can store.
|
||||
|
||||
Its own project rather than a folder in DodoSSH.Client.Domain, which holds decrypted item shapes and
|
||||
their codecs and has no package references at all. A parser, a resolver and a file-system walk are a
|
||||
different concern with different dependencies, and keeping them apart is what lets the whole of the
|
||||
parsing be tested with no Avalonia, no SQLite and no disk.
|
||||
-->
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DodoSSH.Client.Domain\DodoSSH.Client.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="DodoSSH.Client.Import.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,102 @@
|
||||
using DodoSSH.Client.Domain;
|
||||
|
||||
namespace DodoSSH.Client.Import;
|
||||
|
||||
/// <summary>
|
||||
/// One host an <c>ssh_config</c> describes, resolved and ready to be looked at.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Deliberately not a <see cref="HostSecret"/>. This is a candidate somebody has not agreed to import yet,
|
||||
/// and it carries things a stored host has no field for — the identity file's path, the jump alias by name,
|
||||
/// and the warnings that go beside a row in the preview.
|
||||
/// </remarks>
|
||||
/// <param name="Alias">
|
||||
/// The name from the <c>Host</c> line, which is what the user types after <c>ssh</c> and so the name they
|
||||
/// will recognise.
|
||||
/// </param>
|
||||
/// <param name="Hostname">
|
||||
/// What <c>HostName</c> said, or the alias when it said nothing — which is OpenSSH's own default and the
|
||||
/// reason <c>Host db.internal</c> with no other directive works.
|
||||
/// </param>
|
||||
/// <param name="Username">What <c>User</c> said, if anything.</param>
|
||||
/// <param name="Port">What <c>Port</c> said, defaulting to 22.</param>
|
||||
/// <param name="IdentityFiles">Every <c>IdentityFile</c> path, in the order they were given.</param>
|
||||
/// <param name="ProxyJump">The <c>ProxyJump</c> value verbatim, if any.</param>
|
||||
/// <param name="Options">Everything else, as SSH directives.</param>
|
||||
/// <param name="Warnings">What could not be represented, per host.</param>
|
||||
public sealed record ImportedHost(
|
||||
string Alias,
|
||||
string Hostname,
|
||||
string? Username,
|
||||
int Port,
|
||||
IReadOnlyList<string> IdentityFiles,
|
||||
string? ProxyJump,
|
||||
HostOptions Options,
|
||||
IReadOnlyList<string> Warnings)
|
||||
{
|
||||
/// <summary>The address this would dial, for a preview row.</summary>
|
||||
public string Address => Username is { Length: > 0 } user
|
||||
? $"{user}@{Hostname}:{Port}"
|
||||
: $"{Hostname}:{Port}";
|
||||
|
||||
/// <summary>Turns this into the host that would be stored.</summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>The identity file becomes a note and a directive, not a key.</b> Reading somebody's
|
||||
/// <c>~/.ssh/id_ed25519</c> into a keychain is exactly the act this product exists to make deliberate,
|
||||
/// and doing it as a side effect of "import my config" is the wrong default. The path is recorded so it
|
||||
/// is not lost; importing the material is a separate, per-row choice.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>ProxyJump records intent and changes nothing about connecting.</b> The SSH layer has no jump
|
||||
/// hosts — <c>ISshConnection</c> offers <c>OpenShellAsync</c> and nothing else, and
|
||||
/// <c>SshConnectionRequest</c> has no route field. So it is kept as a directive and a note, and the
|
||||
/// preview says so; a bastion topology that imported and quietly did not route would be worse than one
|
||||
/// that was not imported.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public HostSecret ToSecret()
|
||||
{
|
||||
var options = new List<HostOption>(Options);
|
||||
var notes = new List<string>();
|
||||
|
||||
if (IdentityFiles.Count > 0)
|
||||
{
|
||||
options.Add(new HostOption("IdentityFile", IdentityFiles[0]));
|
||||
|
||||
notes.Add(IdentityFiles.Count == 1
|
||||
? $"ssh_config used the key at {IdentityFiles[0]}."
|
||||
: $"ssh_config listed {IdentityFiles.Count} keys, the first being {IdentityFiles[0]}.");
|
||||
}
|
||||
|
||||
if (ProxyJump is { Length: > 0 } jump)
|
||||
{
|
||||
options.Add(new HostOption("ProxyJump", jump));
|
||||
notes.Add($"ssh_config reached this through {jump}. DodoSSH does not route through a jump host yet.");
|
||||
}
|
||||
|
||||
return new HostSecret
|
||||
{
|
||||
Label = Alias,
|
||||
Hostname = Hostname,
|
||||
Port = Port,
|
||||
Username = Username,
|
||||
Notes = notes.Count == 0 ? null : string.Join(" ", notes),
|
||||
Options = HostOptions.Create(options),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Everything an <c>ssh_config</c> yielded: the hosts it can offer, and what it could not.
|
||||
/// </summary>
|
||||
/// <param name="Hosts">The importable candidates, in file order.</param>
|
||||
/// <param name="SkippedPatterns">
|
||||
/// <c>Host</c> patterns that are patterns rather than names. They contribute defaults and are not
|
||||
/// importable: a bookmark called <c>*.internal</c> is one nothing can dial.
|
||||
/// </param>
|
||||
/// <param name="Warnings">Document-level notes, including the parser's own.</param>
|
||||
public sealed record SshConfigImport(
|
||||
IReadOnlyList<ImportedHost> Hosts,
|
||||
IReadOnlyList<string> SkippedPatterns,
|
||||
IReadOnlyList<string> Warnings);
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace DodoSSH.Client.Import;
|
||||
|
||||
/// <summary>One <c>Keyword Value</c> line, with the keyword as written.</summary>
|
||||
/// <param name="Keyword">The directive name. SSH keywords are case-insensitive; the case here is the file's.</param>
|
||||
/// <param name="Value">Everything after the keyword, unquoted but otherwise verbatim.</param>
|
||||
public sealed record SshConfigDirective(string Keyword, string Value);
|
||||
|
||||
/// <summary>
|
||||
/// One <c>Host</c> block: the patterns it applies to and the directives under it.
|
||||
/// </summary>
|
||||
/// <param name="Patterns">
|
||||
/// Every token on the <c>Host</c> line. One line can name several — <c>Host web1 web2 web3</c> — and any of
|
||||
/// them may be a pattern rather than a name.
|
||||
/// </param>
|
||||
/// <param name="Directives">The directives under it, in file order.</param>
|
||||
public sealed record SshConfigBlock(
|
||||
IReadOnlyList<string> Patterns,
|
||||
IReadOnlyList<SshConfigDirective> Directives);
|
||||
|
||||
/// <summary>
|
||||
/// A parsed <c>ssh_config</c>, plus what could not be honoured.
|
||||
/// </summary>
|
||||
/// <param name="Blocks">Every <c>Host</c> block, in the order OpenSSH would read them.</param>
|
||||
/// <param name="Warnings">
|
||||
/// What was skipped or flattened, in the words the preview will show. Everything this parser cannot
|
||||
/// represent ends up here rather than being dropped quietly — a config that half-imported without saying so
|
||||
/// is worse than one that refused.
|
||||
/// </param>
|
||||
public sealed record SshConfigDocument(
|
||||
IReadOnlyList<SshConfigBlock> Blocks,
|
||||
IReadOnlyList<string> Warnings);
|
||||
@@ -0,0 +1,80 @@
|
||||
namespace DodoSSH.Client.Import;
|
||||
|
||||
/// <summary>
|
||||
/// Finds and reads the user's OpenSSH client configuration.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The only type here that touches a disk, which is what keeps <see cref="SshConfigParser"/> and
|
||||
/// <see cref="SshConfigResolver"/> testable against strings.
|
||||
/// </remarks>
|
||||
public sealed class SshConfigLocator
|
||||
{
|
||||
private readonly string sshDirectory;
|
||||
|
||||
/// <param name="sshDirectory">
|
||||
/// Where to look. Defaults to <c>~/.ssh</c>, which is the location on Windows as well as everywhere
|
||||
/// else — OpenSSH on Windows uses the profile directory, not <c>%APPDATA%</c>.
|
||||
/// </param>
|
||||
public SshConfigLocator(string? sshDirectory = null) =>
|
||||
this.sshDirectory = sshDirectory ?? Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
".ssh");
|
||||
|
||||
/// <summary>The file this would read.</summary>
|
||||
public string ConfigPath => Path.Combine(sshDirectory, "config");
|
||||
|
||||
/// <summary>Whether there is anything to read.</summary>
|
||||
public bool Exists => File.Exists(ConfigPath);
|
||||
|
||||
/// <summary>Reads and resolves the configuration.</summary>
|
||||
/// <exception cref="FileNotFoundException">There is no configuration file.</exception>
|
||||
public async Task<SshConfigImport> ReadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var text = await File.ReadAllTextAsync(ConfigPath, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return SshConfigResolver.Resolve(SshConfigParser.Parse(text, ReadIncluded));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads every file an <c>Include</c> pattern names.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A relative pattern resolves against <c>~/.ssh</c>, which is OpenSSH's rule for the user file. Glob
|
||||
/// characters are handled by enumerating the directory rather than by matching by hand — a pattern like
|
||||
/// <c>conf.d/*.conf</c> is the common shape and is what the enumeration overload is for.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Everything here swallows its own failures and returns nothing. An <c>Include</c> naming a file that
|
||||
/// does not exist is not an error to OpenSSH, and an unreadable one is a reason to import less rather
|
||||
/// than a reason to import nothing — the parser records the shortfall in its warnings either way.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private IReadOnlyList<string> ReadIncluded(string pattern)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rooted = Path.IsPathRooted(pattern) ? pattern : Path.Combine(sshDirectory, pattern);
|
||||
var directory = Path.GetDirectoryName(rooted);
|
||||
var mask = Path.GetFileName(rooted);
|
||||
|
||||
if (string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(mask) || !Directory.Exists(directory))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return [.. Directory
|
||||
.EnumerateFiles(directory, mask, SearchOption.TopDirectoryOnly)
|
||||
.Order(StringComparer.Ordinal)
|
||||
.Select(File.ReadAllText)];
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace DodoSSH.Client.Import;
|
||||
|
||||
/// <summary>
|
||||
/// Reads an OpenSSH client configuration into blocks and directives.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Pure, and takes its include reader as a parameter.</b> That is what makes <c>Include</c> — the one
|
||||
/// directive whose behaviour depends on the file system — testable without a file system, and it keeps the
|
||||
/// recursion depth cap and the cycle detection here, next to the recursion, rather than in whatever happens
|
||||
/// to be doing the reading.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Deliberately not a complete implementation of ssh_config, and the gaps are reported rather than
|
||||
/// hidden.</b> <c>Match</c> blocks are not evaluated: <c>Match exec</c> runs a command, <c>Match host</c>
|
||||
/// depends on what is being connected to, and <c>Match final</c> depends on the result of everything else —
|
||||
/// none of which is knowable while looking at a file. Token expansion beyond <c>~</c>,
|
||||
/// <c>CanonicalizeHostname</c> and negated patterns are all out of scope for the same reason: this is an
|
||||
/// importer producing bookmarks somebody will check, not a second SSH client.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class SshConfigParser
|
||||
{
|
||||
/// <summary>How deep <c>Include</c> may nest before this gives up.</summary>
|
||||
/// <remarks>
|
||||
/// OpenSSH's own limit is 16. Matching it means a config this refuses is one <c>ssh</c> refuses too,
|
||||
/// which is a better answer than a different arbitrary number.
|
||||
/// </remarks>
|
||||
private const int MaximumIncludeDepth = 16;
|
||||
|
||||
/// <summary>
|
||||
/// Parses configuration text.
|
||||
/// </summary>
|
||||
/// <param name="text">The file's contents.</param>
|
||||
/// <param name="includeReader">
|
||||
/// Resolves an <c>Include</c> pattern to the contents of every file it names, in order. Return an empty
|
||||
/// sequence for a pattern that matches nothing, which is what OpenSSH does — an <c>Include</c> naming no
|
||||
/// file is not an error.
|
||||
/// </param>
|
||||
public static SshConfigDocument Parse(string text, Func<string, IReadOnlyList<string>>? includeReader = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
|
||||
var blocks = new List<SshConfigBlock>();
|
||||
var warnings = new List<string>();
|
||||
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
ParseInto(text, includeReader, blocks, warnings, visited, depth: 0);
|
||||
|
||||
return new SshConfigDocument(blocks, warnings);
|
||||
}
|
||||
|
||||
private static void ParseInto(
|
||||
string text,
|
||||
Func<string, IReadOnlyList<string>>? includeReader,
|
||||
List<SshConfigBlock> blocks,
|
||||
List<string> warnings,
|
||||
HashSet<string> visited,
|
||||
int depth)
|
||||
{
|
||||
List<string>? patterns = null;
|
||||
var directives = new List<SshConfigDirective>();
|
||||
|
||||
// A Match block is "everything until the next Host or Match", and while one is open its directives
|
||||
// are dropped rather than attributed to whatever block came before — which is what a naive parser
|
||||
// does, and it silently gives one host another host's settings.
|
||||
var insideMatch = false;
|
||||
var matchBlocks = 0;
|
||||
|
||||
foreach (var raw in text.Split('\n'))
|
||||
{
|
||||
var (keyword, value) = Tokenise(raw);
|
||||
|
||||
if (keyword is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Is(keyword, "Host"))
|
||||
{
|
||||
Flush(blocks, patterns, directives);
|
||||
|
||||
patterns = SplitPatterns(value);
|
||||
directives = [];
|
||||
insideMatch = false;
|
||||
}
|
||||
else if (Is(keyword, "Match"))
|
||||
{
|
||||
Flush(blocks, patterns, directives);
|
||||
|
||||
patterns = null;
|
||||
directives = [];
|
||||
insideMatch = true;
|
||||
matchBlocks++;
|
||||
}
|
||||
else if (insideMatch)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
else if (Is(keyword, "Include"))
|
||||
{
|
||||
// Flushed first, so the included file's blocks land between this block and the next — which
|
||||
// is where OpenSSH puts them, and it matters because the first value seen for a keyword is
|
||||
// the one that wins.
|
||||
Flush(blocks, patterns, directives);
|
||||
patterns = null;
|
||||
directives = [];
|
||||
|
||||
Include(value, includeReader, blocks, warnings, visited, depth);
|
||||
}
|
||||
else
|
||||
{
|
||||
directives.Add(new SshConfigDirective(keyword, value));
|
||||
}
|
||||
}
|
||||
|
||||
Flush(blocks, patterns, directives);
|
||||
|
||||
WarnAboutMatchBlocks(matchBlocks, warnings);
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Counted rather than listed. What a reader needs is that some of their file was not honoured and why;
|
||||
/// naming each <c>Match</c> condition would be repeating the file back at them.
|
||||
/// </remarks>
|
||||
private static void WarnAboutMatchBlocks(int matchBlocks, List<string> warnings)
|
||||
{
|
||||
if (matchBlocks == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
warnings.Add(string.Create(
|
||||
CultureInfo.CurrentCulture,
|
||||
$"{matchBlocks} Match block(s) were ignored. Whether one applies depends on what is being connected to, or on a command's output, so it cannot be decided from the file alone."));
|
||||
}
|
||||
|
||||
private static bool Is(string keyword, string name) =>
|
||||
string.Equals(keyword, name, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static void Include(
|
||||
string pattern,
|
||||
Func<string, IReadOnlyList<string>>? includeReader,
|
||||
List<SshConfigBlock> blocks,
|
||||
List<string> warnings,
|
||||
HashSet<string> visited,
|
||||
int depth)
|
||||
{
|
||||
if (includeReader is null)
|
||||
{
|
||||
warnings.Add($"Include {pattern} was skipped: nothing was supplied to read included files.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (depth >= MaximumIncludeDepth)
|
||||
{
|
||||
warnings.Add($"Include {pattern} was skipped: includes are nested more than {MaximumIncludeDepth} deep.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Cycles are the reason this is a set rather than a counter. A file that includes itself — directly
|
||||
// or through a chain — would otherwise recurse until the depth cap, importing the same hosts sixteen
|
||||
// times before stopping, which reads as a bug in the importer rather than in the config.
|
||||
if (!visited.Add(pattern))
|
||||
{
|
||||
warnings.Add($"Include {pattern} was skipped: it is already being read further up.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var included in includeReader(pattern))
|
||||
{
|
||||
ParseInto(included, includeReader, blocks, warnings, visited, depth + 1);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
visited.Remove(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Flush(
|
||||
List<SshConfigBlock> blocks,
|
||||
List<string>? patterns,
|
||||
List<SshConfigDirective> directives)
|
||||
{
|
||||
if (patterns is { Count: > 0 })
|
||||
{
|
||||
blocks.Add(new SshConfigBlock(patterns, directives));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits one line into a keyword and a value, or nothing.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// OpenSSH accepts <c>Keyword Value</c>, <c>Keyword=Value</c> and <c>Keyword = Value</c>, allows leading
|
||||
/// whitespace, treats <c>#</c> as a comment, and lets a value be double-quoted. The quoting is what this
|
||||
/// has to get right rather than approximately right: <c>IdentityFile "~/my keys/id_ed25519"</c> is one
|
||||
/// path, and splitting it on whitespace produces two that do not exist.
|
||||
/// </remarks>
|
||||
private static (string? Keyword, string Value) Tokenise(string line)
|
||||
{
|
||||
// A BOM on the first line, and CR on every line of a CRLF file. Both are invisible and both would
|
||||
// otherwise end up inside the first keyword, where nothing matches them.
|
||||
var trimmed = line.Trim('', '\r').Trim();
|
||||
|
||||
if (trimmed.Length == 0 || trimmed[0] == '#')
|
||||
{
|
||||
return (null, string.Empty);
|
||||
}
|
||||
|
||||
var separator = trimmed.AsSpan().IndexOfAny(" \t=");
|
||||
|
||||
if (separator < 0)
|
||||
{
|
||||
return (trimmed, string.Empty);
|
||||
}
|
||||
|
||||
var keyword = trimmed[..separator];
|
||||
var rest = trimmed[separator..].TrimStart(' ', '\t');
|
||||
|
||||
if (rest.StartsWith('='))
|
||||
{
|
||||
rest = rest[1..].TrimStart(' ', '\t');
|
||||
}
|
||||
|
||||
return (keyword, Unquote(rest));
|
||||
}
|
||||
|
||||
private static string Unquote(string value)
|
||||
{
|
||||
var trimmed = value.Trim();
|
||||
|
||||
return trimmed.Length >= 2 && trimmed[0] == '"' && trimmed[^1] == '"'
|
||||
? trimmed[1..^1]
|
||||
: trimmed;
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Each token unquoted separately, because <c>Host "my server" other</c> is two patterns and one of them
|
||||
/// contains a space.
|
||||
/// </remarks>
|
||||
private static List<string> SplitPatterns(string value)
|
||||
{
|
||||
var patterns = new List<string>();
|
||||
var span = value.AsSpan();
|
||||
var index = 0;
|
||||
|
||||
while (index < span.Length)
|
||||
{
|
||||
while (index < span.Length && char.IsWhiteSpace(span[index]))
|
||||
{
|
||||
index++;
|
||||
}
|
||||
|
||||
if (index >= span.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
int end;
|
||||
|
||||
if (span[index] == '"')
|
||||
{
|
||||
index++;
|
||||
end = index;
|
||||
|
||||
while (end < span.Length && span[end] != '"')
|
||||
{
|
||||
end++;
|
||||
}
|
||||
|
||||
patterns.Add(span[index..end].ToString());
|
||||
index = end + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
end = index;
|
||||
|
||||
while (end < span.Length && !char.IsWhiteSpace(span[end]))
|
||||
{
|
||||
end++;
|
||||
}
|
||||
|
||||
patterns.Add(span[index..end].ToString());
|
||||
index = end;
|
||||
}
|
||||
|
||||
return patterns;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
using System.Buffers;
|
||||
using System.Globalization;
|
||||
using DodoSSH.Client.Domain;
|
||||
|
||||
namespace DodoSSH.Client.Import;
|
||||
|
||||
/// <summary>
|
||||
/// Turns parsed blocks into the hosts an import can offer.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>First value wins.</b> That is the actual OpenSSH rule and it is not the intuitive one — a later
|
||||
/// <c>Host *</c> block supplies defaults for keywords nothing earlier set, and cannot override a keyword an
|
||||
/// earlier block already set. Getting it backwards produces an import where every host has the wildcard
|
||||
/// block's username.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>A block whose patterns are all wildcards contributes defaults and is not itself importable.</b>
|
||||
/// <c>Host *.internal</c> is a rule about names, not a machine — a bookmark by that name could not be
|
||||
/// dialled. Those are reported so the preview can say what was used and not imported, rather than leaving
|
||||
/// somebody to wonder why six blocks produced four hosts.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class SshConfigResolver
|
||||
{
|
||||
private static readonly SearchValues<char> PatternCharacters = SearchValues.Create("*?!");
|
||||
|
||||
/// <summary>Resolves every importable host in a parsed configuration.</summary>
|
||||
public static SshConfigImport Resolve(SshConfigDocument document)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(document);
|
||||
|
||||
var hosts = new List<ImportedHost>();
|
||||
var skipped = new List<string>();
|
||||
var warnings = new List<string>(document.Warnings);
|
||||
|
||||
foreach (var pattern in document.Blocks.SelectMany(block => block.Patterns).Where(IsPattern))
|
||||
{
|
||||
if (!skipped.Contains(pattern, StringComparer.Ordinal))
|
||||
{
|
||||
skipped.Add(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var alias in document.Blocks.SelectMany(block => block.Patterns).Where(name => !IsPattern(name)))
|
||||
{
|
||||
if (hosts.Any(host => string.Equals(host.Alias, alias, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
hosts.Add(Resolve(alias, document));
|
||||
}
|
||||
|
||||
if (skipped.Count > 0)
|
||||
{
|
||||
var named = string.Join(", ", skipped);
|
||||
|
||||
warnings.Add(string.Create(
|
||||
CultureInfo.CurrentCulture,
|
||||
$"{skipped.Count} pattern block(s) — {named} — supplied defaults but were not imported as hosts. A pattern names a rule, not a machine."));
|
||||
}
|
||||
|
||||
return new SshConfigImport(hosts, skipped, warnings);
|
||||
}
|
||||
|
||||
private static ImportedHost Resolve(string alias, SshConfigDocument document)
|
||||
{
|
||||
// Case-insensitive, because SSH keywords are and HostOption.NameComparer already says so. Two
|
||||
// spellings of ServerAliveInterval reaching HostOptions.Create would be a duplicate-name throw.
|
||||
var settled = new Dictionary<string, string>(HostOption.NameComparer);
|
||||
var identityFiles = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
|
||||
Settle(alias, document, settled, identityFiles, warnings);
|
||||
|
||||
var port = ResolvePort(settled, warnings);
|
||||
var hostname = Take(settled, "HostName") ?? alias;
|
||||
var username = Take(settled, "User");
|
||||
var proxyJump = Take(settled, "ProxyJump");
|
||||
|
||||
if (Take(settled, "ProxyCommand") is { } proxyCommand)
|
||||
{
|
||||
// Not put into Options: it would look like a setting that does something. Nothing in this
|
||||
// application runs a ProxyCommand, and a directive sitting in a host's editor implying otherwise
|
||||
// is worse than a sentence saying it was dropped.
|
||||
warnings.Add($"ProxyCommand was dropped: nothing here runs one. It was '{proxyCommand}'.");
|
||||
}
|
||||
|
||||
return new ImportedHost(
|
||||
alias,
|
||||
hostname,
|
||||
username,
|
||||
port,
|
||||
identityFiles,
|
||||
proxyJump,
|
||||
HostOptions.Create(settled.Select(entry => new HostOption(entry.Key, entry.Value))),
|
||||
warnings);
|
||||
}
|
||||
|
||||
/// <summary>Walks every block that applies to an alias, keeping the first value for each keyword.</summary>
|
||||
private static void Settle(
|
||||
string alias,
|
||||
SshConfigDocument document,
|
||||
Dictionary<string, string> settled,
|
||||
List<string> identityFiles,
|
||||
List<string> warnings)
|
||||
{
|
||||
var duplicates = new HashSet<string>(HostOption.NameComparer);
|
||||
|
||||
foreach (var block in document.Blocks.Where(block => block.Patterns.Any(pattern => Matches(pattern, alias))))
|
||||
{
|
||||
foreach (var directive in block.Directives)
|
||||
{
|
||||
// IdentityFile is the one keyword that legitimately repeats — ssh tries each in turn — so it
|
||||
// accumulates instead of settling, and is not reported as a duplicate.
|
||||
if (string.Equals(directive.Keyword, "IdentityFile", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
identityFiles.Add(ExpandHome(directive.Value));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!settled.TryAdd(directive.Keyword, directive.Value))
|
||||
{
|
||||
duplicates.Add(directive.Keyword);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var keyword in duplicates.Order(HostOption.NameComparer))
|
||||
{
|
||||
// HostOptions is unique by name and cannot hold a repeat, which is a stated M1 limitation whose
|
||||
// own remarks require the import path to surface it rather than quietly keep one. The first is
|
||||
// kept because that is what ssh would have used.
|
||||
warnings.Add($"{keyword} was set more than once; the first value was kept.");
|
||||
}
|
||||
}
|
||||
|
||||
private static int ResolvePort(Dictionary<string, string> settled, List<string> warnings)
|
||||
{
|
||||
if (Take(settled, "Port") is not { } portText)
|
||||
{
|
||||
return HostSecret.DefaultPort;
|
||||
}
|
||||
|
||||
if (int.TryParse(portText, CultureInfo.InvariantCulture, out var parsed) && parsed is > 0 and <= 65535)
|
||||
{
|
||||
return parsed;
|
||||
}
|
||||
|
||||
warnings.Add($"Port '{portText}' is not a usable port number; 22 was used.");
|
||||
|
||||
return HostSecret.DefaultPort;
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Removed as it is read, so a keyword that maps onto a first-class field does not <em>also</em> end up
|
||||
/// in <c>Options</c>. A host carrying both a <c>Port</c> of 2222 and a <c>Port</c> directive saying 2222
|
||||
/// has two places to change it and one of them will be forgotten.
|
||||
/// </remarks>
|
||||
private static string? Take(Dictionary<string, string> settled, string keyword)
|
||||
{
|
||||
if (!settled.Remove(keyword, out var value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return string.IsNullOrWhiteSpace(value) ? null : value;
|
||||
}
|
||||
|
||||
private static bool IsPattern(string name) => name.AsSpan().ContainsAny(PatternCharacters);
|
||||
|
||||
/// <summary>
|
||||
/// Whether a <c>Host</c> pattern applies to an alias.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <c>*</c> and <c>?</c> only. Negation is not implemented — a <c>!</c> pattern is treated as not
|
||||
/// matching, which errs towards importing a host with fewer defaults rather than towards silently
|
||||
/// applying a block the user had excluded.
|
||||
/// </remarks>
|
||||
private static bool Matches(string pattern, string alias)
|
||||
{
|
||||
if (pattern.StartsWith('!'))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return !pattern.AsSpan().ContainsAny(PatternCharacters)
|
||||
? string.Equals(pattern, alias, StringComparison.OrdinalIgnoreCase)
|
||||
: Glob(pattern.AsSpan(), alias.AsSpan());
|
||||
}
|
||||
|
||||
private static bool Glob(ReadOnlySpan<char> pattern, ReadOnlySpan<char> value)
|
||||
{
|
||||
if (pattern.IsEmpty)
|
||||
{
|
||||
return value.IsEmpty;
|
||||
}
|
||||
|
||||
if (pattern[0] == '*')
|
||||
{
|
||||
for (var skip = 0; skip <= value.Length; skip++)
|
||||
{
|
||||
if (Glob(pattern[1..], value[skip..]))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (value.IsEmpty)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return (pattern[0] == '?' || char.ToUpperInvariant(pattern[0]) == char.ToUpperInvariant(value[0]))
|
||||
&& Glob(pattern[1..], value[1..]);
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// Tilde only. <c>%h</c>, <c>%p</c> and the rest are left alone: they are expanded per connection
|
||||
/// against values this importer does not have, and a path with a literal <c>%h</c> in it is at least
|
||||
/// visibly unexpanded rather than wrong.
|
||||
/// </remarks>
|
||||
private static string ExpandHome(string path)
|
||||
{
|
||||
if (!path.StartsWith("~/", StringComparison.Ordinal) && !path.StartsWith("~\\", StringComparison.Ordinal))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
|
||||
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
|
||||
return Path.Combine(home, path[2..]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"version": 2,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Meziantou.Analyzer": {
|
||||
"type": "Direct",
|
||||
"requested": "[3.0.137, )",
|
||||
"resolved": "3.0.137",
|
||||
"contentHash": "48n8WsokyefLOZt2qGPpk+hjfF9rQRa7MGK+8hMS6sO22QuIDtBztfbXV7RtVfX7JKjUwDI9e06I8aeCc5XZzQ=="
|
||||
},
|
||||
"Microsoft.CodeAnalysis.BannedApiAnalyzers": {
|
||||
"type": "Direct",
|
||||
"requested": "[5.6.0, )",
|
||||
"resolved": "5.6.0",
|
||||
"contentHash": "Kcobt3pnOdO0A+6CKiMHZdTEluJpsfxiV20axtZdmfBQnDmiWTKPJADlgAfdTuKNAnVarrkJa0UEGwuOo91muw=="
|
||||
},
|
||||
"dodossh.client.domain": {
|
||||
"type": "Project"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user