From 9f9f1054ee324e1f29f444b7768a9823f7f973d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:06:24 +0000 Subject: [PATCH 1/2] Turn MSSP WEBSOCKET into WebSocket endpoints, measured A game's MSSP WEBSOCKET variable names the addresses a web client can use. It was stored as a field and nothing else, so no game in the catalogue had a websocket endpoint and a client listing games could not offer one. Each declared ws:// or wss:// URL is now handshaken after an answered probe, through the opt-out gate and the scope guard (dialled at the addresses it ruled on), offering no subprotocol, since websockify and MUME's Apache both refuse one they do not know. An address that upgrades becomes an endpoint (kind websocket, or the new wss) with its path; one that does not writes nothing. An address another game holds, or one of this game's telnet addresses, is left as it is. The API's endpoint gains `path` (null except on a websocket); a wss endpoint is kind "websocket" with tlsMeasured true. The game page and plain text show the URL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- migrations/0045_websocket_endpoint.sql | 28 +++ src/MUI.Catalog/Games/Views.cs | 19 +- .../Persistence/Games/NpgsqlEndpointStore.cs | 12 +- src/MUI.Catalog/Persistence/Games/Records.cs | 20 +- .../Queries/NpgsqlGameQueries.GamePage.cs | 9 +- src/MUI.Catalog/Persistence/SqlEnums.cs | 2 + src/MUI.Crawl/WebSocket/WebSocketAddress.cs | 129 ++++++++++++ src/MUI.Crawl/WebSocket/WebSocketProbe.cs | 133 +++++++++++++ src/MUI.Crawler.Cli/Program.cs | 10 +- src/MUI.Crawler/Crawl/CrawlCycle.cs | 11 +- .../Crawl/WebSocketEndpointWriter.cs | 123 ++++++++++++ .../CrawlerServiceCollectionExtensions.cs | 5 + src/MUI.Web/Api/ApiMapper.cs | 3 +- src/MUI.Web/Api/ApiModels.cs | 5 +- src/MUI.Web/Components/Copy/PreviewCopy.cs | 7 +- src/MUI.Web/Components/Pages/Game.razor | 5 +- .../Components/Pages/GameStructuredData.cs | 10 +- src/MUI.Web/Components/Pages/PlainText.cs | 10 +- src/MUI.Web/Fixtures/FixtureGameQueries.cs | 13 +- .../Queries/GameQueriesPostgresTests.cs | 43 ++++ .../WebSocket/WebSocketAddressesTests.cs | 92 +++++++++ .../WebSocket/WebSocketProbeTests.cs | 186 ++++++++++++++++++ .../Crawl/WebSocketEndpointPostgresTests.cs | 169 ++++++++++++++++ .../MUI.Crawler.Tests/Support/CrawlCycles.cs | 13 +- tests/MUI.Web.Tests/Api/GameApiTests.cs | 18 ++ 25 files changed, 1048 insertions(+), 27 deletions(-) create mode 100644 migrations/0045_websocket_endpoint.sql create mode 100644 src/MUI.Crawl/WebSocket/WebSocketAddress.cs create mode 100644 src/MUI.Crawl/WebSocket/WebSocketProbe.cs create mode 100644 src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs create mode 100644 tests/MUI.Crawl.Tests/WebSocket/WebSocketAddressesTests.cs create mode 100644 tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs create mode 100644 tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs diff --git a/migrations/0045_websocket_endpoint.sql b/migrations/0045_websocket_endpoint.sql new file mode 100644 index 00000000..2b3c3ed6 --- /dev/null +++ b/migrations/0045_websocket_endpoint.sql @@ -0,0 +1,28 @@ +-- game_endpoint gains a path, and a kind for a WebSocket behind TLS. +-- +-- A WebSocket endpoint is a URL, not a host and port: MUME answers at wss://mume.org/ws-play/, and +-- the path is as much the address as the port is. 'websocket' was in the vocabulary from 0005 and +-- never written; 'wss' is added beside it rather than a tls flag on every row, because for telnet the +-- kind already says whether a TLS handshake completed ('tls'), and a WebSocket should say the same +-- thing the same way. The CHECK ties the two together: a WebSocket kind always has a path, and no +-- other kind has one. +-- +-- The address stays (host, port) for identity (game_endpoint_address_idx). Two games behind one +-- gateway on one host and port, told apart only by path, would collide on it; no such pair has been +-- observed, and the writer refuses an address another game holds rather than taking it. +ALTER TABLE game_endpoint ADD COLUMN path text; + +-- Nothing has written 'websocket' yet, but a row that did would otherwise fail the CHECK below. +UPDATE game_endpoint SET path = '/' WHERE kind = 'websocket' AND path IS NULL; + +ALTER TABLE game_endpoint DROP CONSTRAINT game_endpoint_kind_vocabulary; +ALTER TABLE game_endpoint ADD CONSTRAINT game_endpoint_kind_vocabulary + CHECK (kind IN ('telnet', 'tls', 'websocket', 'wss', 'http')); + +ALTER TABLE game_endpoint ADD CONSTRAINT game_endpoint_path_only_on_websockets + CHECK ((path IS NOT NULL) = (kind IN ('websocket', 'wss'))); + +-- What a request line can carry and nothing else: a leading slash, printable ASCII without spaces, +-- and a bound. The value comes from a game's MSSP, so it is somebody else's text. +ALTER TABLE game_endpoint ADD CONSTRAINT game_endpoint_path_is_a_path + CHECK (path IS NULL OR (path ~ '^/[!-~]*$' AND length(path) <= 256)); diff --git a/src/MUI.Catalog/Games/Views.cs b/src/MUI.Catalog/Games/Views.cs index f4459083..e29ff914 100644 --- a/src/MUI.Catalog/Games/Views.cs +++ b/src/MUI.Catalog/Games/Views.cs @@ -264,6 +264,11 @@ public sealed record ReferralNeighbour( /// carried through rather than re-derived from the dates, so a surface cannot invent a threshold the /// writer does not share. /// +/// +/// telnet, tls or websocket. A WebSocket behind TLS is websocket with +/// set, the way a telnet one is tls. +/// +/// A WebSocket's request path (/ws-play/); null for every other kind. public sealed record GameEndpointView( string Host, int Port, @@ -271,10 +276,22 @@ public sealed record GameEndpointView( bool TlsMeasured, DateTimeOffset FirstSeenAt, DateTimeOffset LastSeenAt, - string State) + string State, + string? Path = null) { /// Whether we still reach the game here. public bool IsCurrent => string.Equals(State, "active", StringComparison.Ordinal); + + /// Whether this is a WebSocket, which a telnet client cannot open. + public bool IsWebSocket => string.Equals(Kind, "websocket", StringComparison.Ordinal); + + /// + /// The URL a WebSocket client dials (wss://mume.org:443/ws-play/), or null for a telnet endpoint. + /// The port is always written: the catalogue measured it, and leaving the default implied is a guess. + /// + public string? Url => IsWebSocket + ? $"{(TlsMeasured ? "wss" : "ws")}://{(Host.Contains(':', StringComparison.Ordinal) ? $"[{Host}]" : Host)}:{Port.ToString(System.Globalization.CultureInfo.InvariantCulture)}{Path ?? "/"}" + : null; } public sealed record ChangeEntry(DateTimeOffset At, string Summary); diff --git a/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs b/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs index 2be56e7d..90adde52 100644 --- a/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs +++ b/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs @@ -9,7 +9,7 @@ public sealed class NpgsqlEndpointStore(NpgsqlDataSource source) : IEndpointStor { private const string Columns = """ game_id AS GameId, host AS Host, port AS Port, kind AS Kind, - first_seen_at AS FirstSeenAt, last_seen_at AS LastSeenAt, state AS State + first_seen_at AS FirstSeenAt, last_seen_at AS LastSeenAt, state AS State, path AS Path """; public async Task> ForGameAsync( @@ -99,10 +99,11 @@ public async Task UpsertAsync(GameEndpoint endpoint, CancellationToken cancellat // how long we have known the address, not how long the current answer has been true. await connection.ExecuteAsync(new CommandDefinition( """ - INSERT INTO game_endpoint (game_id, host, port, kind, first_seen_at, last_seen_at, state) - VALUES (@gameId, @host, @port, @kind, @firstSeenAt, @lastSeenAt, @state) + INSERT INTO game_endpoint (game_id, host, port, kind, first_seen_at, last_seen_at, state, path) + VALUES (@gameId, @host, @port, @kind, @firstSeenAt, @lastSeenAt, @state, @path) ON CONFLICT (game_id, host, port) DO UPDATE SET kind = EXCLUDED.kind, + path = EXCLUDED.path, last_seen_at = GREATEST(game_endpoint.last_seen_at, EXCLUDED.last_seen_at), state = EXCLUDED.state """, @@ -115,6 +116,7 @@ ON CONFLICT (game_id, host, port) DO UPDATE firstSeenAt = endpoint.FirstSeenAt.ToUniversalTime(), lastSeenAt = endpoint.LastSeenAt.ToUniversalTime(), state = SqlEnums.ToDb(endpoint.State), + path = endpoint.Path, }, cancellationToken: cancellationToken)); } @@ -135,8 +137,10 @@ private sealed class Row public string State { get; init; } = string.Empty; + public string? Path { get; init; } + public GameEndpoint ToRecord() => new( GameId, Host, Port, SqlEnums.ToEndpointKind(Kind), FirstSeenAt, LastSeenAt, - SqlEnums.ToEndpointState(State)); + SqlEnums.ToEndpointState(State), Path); } } diff --git a/src/MUI.Catalog/Persistence/Games/Records.cs b/src/MUI.Catalog/Persistence/Games/Records.cs index 1ee328fc..279336a2 100644 --- a/src/MUI.Catalog/Persistence/Games/Records.cs +++ b/src/MUI.Catalog/Persistence/Games/Records.cs @@ -53,7 +53,16 @@ public enum EndpointKind { Telnet, Tls, + + /// A WebSocket (ws://) carrying telnet. Always has a . WebSocket, + + /// + /// A WebSocket behind TLS (wss://): the handshake completed, as means for telnet. + /// Always has a . + /// + SecureWebSocket, + Http, } @@ -69,6 +78,10 @@ public enum EndpointState } /// An address a game answers on (spec §5.5). +/// +/// The request path of a WebSocket endpoint (/ws-play/), and null for every other kind: migration 0045's +/// CHECK holds the two together. +/// public sealed record GameEndpoint( Guid GameId, string Host, @@ -76,7 +89,12 @@ public sealed record GameEndpoint( EndpointKind Kind, DateTimeOffset FirstSeenAt, DateTimeOffset LastSeenAt, - EndpointState State); + EndpointState State, + string? Path = null) +{ + /// Whether this is a WebSocket, behind TLS or not. + public bool IsWebSocket => Kind is EndpointKind.WebSocket or EndpointKind.SecureWebSocket; +} /// /// Who measured an availability interval. diff --git a/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs b/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs index 9ee8387e..2efeb72f 100644 --- a/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs +++ b/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs @@ -150,11 +150,14 @@ private async Task PageAsync( .Select(e => new GameEndpointView( e.Host, e.Port, - SqlEnums.ToDb(e.Kind), - TlsMeasured: e.Kind is EndpointKind.Tls, + // The API's vocabulary keeps one word per protocol and says TLS beside it: a + // `wss` row reads as `websocket` with tlsMeasured, as a `tls` row is telnet's. + e.IsWebSocket ? SqlEnums.ToDb(EndpointKind.WebSocket) : SqlEnums.ToDb(e.Kind), + TlsMeasured: e.Kind is EndpointKind.Tls or EndpointKind.SecureWebSocket, e.FirstSeenAt, e.LastSeenAt, - SqlEnums.ToDb(e.State))) + SqlEnums.ToDb(e.State), + e.Path)) .ToList(), ConnectScreen: Winner(fields, InternalFields.ConnectScreen)?.Value, ConnectScreenSuppressed: string.Equals( diff --git a/src/MUI.Catalog/Persistence/SqlEnums.cs b/src/MUI.Catalog/Persistence/SqlEnums.cs index 6e78fe08..48a33f6a 100644 --- a/src/MUI.Catalog/Persistence/SqlEnums.cs +++ b/src/MUI.Catalog/Persistence/SqlEnums.cs @@ -210,6 +210,7 @@ public static class SqlEnums EndpointKind.Telnet => "telnet", EndpointKind.Tls => "tls", EndpointKind.WebSocket => "websocket", + EndpointKind.SecureWebSocket => "wss", EndpointKind.Http => "http", _ => throw Unmapped(kind), }; @@ -219,6 +220,7 @@ public static class SqlEnums "telnet" => EndpointKind.Telnet, "tls" => EndpointKind.Tls, "websocket" => EndpointKind.WebSocket, + "wss" => EndpointKind.SecureWebSocket, "http" => EndpointKind.Http, _ => throw Unread(value, nameof(EndpointKind)), }; diff --git a/src/MUI.Crawl/WebSocket/WebSocketAddress.cs b/src/MUI.Crawl/WebSocket/WebSocketAddress.cs new file mode 100644 index 00000000..f93646f4 --- /dev/null +++ b/src/MUI.Crawl/WebSocket/WebSocketAddress.cs @@ -0,0 +1,129 @@ +namespace MUI.Crawl; + +/// +/// One WebSocket address a game declared in its MSSP WEBSOCKET variable. +/// +/// +/// A declaration, not a measurement: nothing here says the address answers. It becomes a fact about +/// the game only once has completed a handshake there (rule 1). +/// +/// The host, lower-cased, IPv6 without brackets. +/// The port, the scheme's default where the URL named none. +/// True for wss. +/// The path and query, always starting with /. +public sealed record WebSocketAddress(string Host, int Port, bool Tls, string Path) +{ + /// The address as a URL, the port always written. + public Uri Uri => new( + $"{(Tls ? "wss" : "ws")}://{(Host.Contains(':', StringComparison.Ordinal) ? $"[{Host}]" : Host)}:{Port}{Path}"); +} + +/// +/// Reads the MSSP WEBSOCKET variable: one or more ws:// or wss:// URLs. +/// +/// +/// +/// The MSSP proposal lets the value be a comma-separated list, and MSSP lets the variable repeat; both +/// are read. A URL that is not one this site would show a reader is refused rather than tidied: +/// another scheme, user information (a login the game did not mean to publish), a fragment, a path +/// that is not plain printable ASCII, or one longer than . The same path +/// rule is the database's (migration 0045). +/// +/// +/// The value is server text, and so is every host it names: none of it is dialled before the opt-out +/// and scope gates have ruled on it. +/// +/// +public static class WebSocketAddresses +{ + /// The variable's name. + public const string Variable = "WEBSOCKET"; + + /// The longest path kept, the database's own limit. + public const int MaxPathLength = 256; + + /// How many addresses one report may name. More than this is noise, not a game. + public const int MaxAddresses = 4; + + /// Every address the report declares that this site would show, in order, once each. + public static IReadOnlyList From(IReadOnlyDictionary>? report) + { + if (report is null || !report.TryGetValue(Variable, out var values)) + { + return []; + } + + var found = new List(); + + foreach (var value in values) + { + foreach (var piece in value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + if (Parse(piece) is { } address && !found.Contains(address)) + { + found.Add(address); + + if (found.Count == MaxAddresses) + { + return found; + } + } + } + } + + return found; + } + + /// One URL, or null when it is not one this site would show. + public static WebSocketAddress? Parse(string? text) + { + if (string.IsNullOrWhiteSpace(text) || text.Length > MaxPathLength + 300) + { + return null; + } + + text = text.Trim(); + + // Anything outside printable ASCII is refused before Uri sees it, which would otherwise + // percent-encode it into something that looks like a path we chose. + foreach (var c in text) + { + if (c is < '!' or > '~') + { + return null; + } + } + + if (!Uri.TryCreate(text, UriKind.Absolute, out var uri)) + { + return null; + } + + var tls = uri.Scheme switch + { + "wss" => true, + "ws" => false, + _ => (bool?)null, + }; + + if (tls is null + || uri.UserInfo.Length > 0 + || text.Contains('#', StringComparison.Ordinal) + || uri.HostNameType is UriHostNameType.Unknown or UriHostNameType.Basic + || uri.Port is < 1 or > 65535) + { + return null; + } + + var path = uri.PathAndQuery; + + if (path.Length == 0 || path[0] != '/' || path.Length > MaxPathLength) + { + return null; + } + + var host = uri.HostNameType is UriHostNameType.IPv6 ? uri.Host.Trim('[', ']') : uri.Host; + + return new WebSocketAddress(host.ToLowerInvariant(), uri.Port, tls.Value, path); + } +} diff --git a/src/MUI.Crawl/WebSocket/WebSocketProbe.cs b/src/MUI.Crawl/WebSocket/WebSocketProbe.cs new file mode 100644 index 00000000..9580a9e7 --- /dev/null +++ b/src/MUI.Crawl/WebSocket/WebSocketProbe.cs @@ -0,0 +1,133 @@ +using System.Net; +using System.Net.Sockets; +using System.Net.WebSockets; + +namespace MUI.Crawl; + +/// What came of one WebSocket handshake. +/// True only when the server completed the upgrade. +/// Why not, for a log line. Never written to a game's record. +public sealed record WebSocketHandshake(bool Answered, string? Detail = null) +{ + public static readonly WebSocketHandshake Upgraded = new(true); +} + +/// +/// Completes a WebSocket handshake at an address, and says whether it did. +/// +/// +/// A seam so the crawler's writer is testable with no socket; is the one +/// that dials. +/// +public interface IWebSocketProbe +{ + /// + /// Dials at exactly , which the scope gate + /// has already ruled on, and asks for the upgrade. + /// + Task HandshakeAsync( + WebSocketAddress address, + IReadOnlyList addresses, + CancellationToken cancellationToken = default); +} + +/// +/// The handshake a MU* client's WebSocket would make, and nothing after it. +/// +/// +/// +/// No subprotocol is offered. The real bridges are strict about it: websockify answers 400 to a +/// name it does not know, and MUME's Apache answers 502 to telnet.mudstandards.org, while both +/// accept a handshake that names none. The question here is whether a client can reach the game at +/// this address, and offering a name the bridge refuses would record our choice of offer as the +/// game's failure (rule 5). +/// +/// +/// The socket goes to the addresses the scope gate ruled on, never to a second lookup of the +/// name — 's rule, and §7.2's. TLS still names the host, so SNI and the +/// certificate check are the host's. The certificate is checked: a reader's client would refuse one +/// that does not verify, so an address that needs it ignored is not an address to show them. +/// +/// +/// No proxy, no redirect followed (a WebSocket upgrade does not follow one), and the connection is +/// closed as soon as the upgrade is in: nothing is read and nothing is sent to the game. +/// +/// +public sealed class WebSocketProbe(TimeSpan? timeout = null) : IWebSocketProbe +{ + /// The whole handshake's budget, connect and TLS included. + public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(15); + + private readonly TimeSpan _timeout = timeout ?? DefaultTimeout; + + public async Task HandshakeAsync( + WebSocketAddress address, + IReadOnlyList addresses, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(address); + ArgumentNullException.ThrowIfNull(addresses); + + if (addresses.Count == 0) + { + return new WebSocketHandshake(false, "no address to dial"); + } + + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(_timeout); + + using var handler = new SocketsHttpHandler + { + UseProxy = false, + AllowAutoRedirect = false, + ConnectTimeout = _timeout, + ConnectCallback = async (context, token) => + { + var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + + try + { + await socket.ConnectAsync([.. addresses], address.Port, token).ConfigureAwait(false); + + return new NetworkStream(socket, ownsSocket: true); + } + catch + { + socket.Dispose(); + throw; + } + }, + }; + + using var invoker = new HttpMessageInvoker(handler); + using var socket = new ClientWebSocket(); + socket.Options.CollectHttpResponseDetails = true; + + try + { + await socket.ConnectAsync(address.Uri, invoker, budget.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return new WebSocketHandshake(false, $"no upgrade within {_timeout.TotalSeconds:0} s"); + } + catch (Exception error) when (error is WebSocketException or HttpRequestException or IOException or SocketException) + { + return new WebSocketHandshake( + false, + socket.HttpStatusCode != 0 ? $"HTTP {(int)socket.HttpStatusCode}" : error.Message); + } + + try + { + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, budget.Token).ConfigureAwait(false); + } + catch (Exception error) when (error is WebSocketException or OperationCanceledException or IOException) + { + // The upgrade is the measurement; how the close went is not. + socket.Abort(); + } + + return WebSocketHandshake.Upgraded; + } +} diff --git a/src/MUI.Crawler.Cli/Program.cs b/src/MUI.Crawler.Cli/Program.cs index 1c6919a2..d5cf2ee2 100644 --- a/src/MUI.Crawler.Cli/Program.cs +++ b/src/MUI.Crawler.Cli/Program.cs @@ -611,7 +611,15 @@ await fields.RecordChangeAsync( // Issue #185 — and it writes down what it declined to dial, for the same reason: an operator // running a cycle by hand is the reader most likely to want to know. new NpgsqlCrawlRefusalStore(source), - loggerFactory.CreateLogger()); + loggerFactory.CreateLogger(), + // The WebSocket addresses a game declares, written once one has upgraded. + new WebSocketEndpointWriter( + new WebSocketProbe(), + optOut, + new HostScopeGuard(hostResolver), + endpoints, + time, + loggerFactory.CreateLogger())); if (arguments.DryRun) { diff --git a/src/MUI.Crawler/Crawl/CrawlCycle.cs b/src/MUI.Crawler/Crawl/CrawlCycle.cs index 8da57bc2..91d14326 100644 --- a/src/MUI.Crawler/Crawl/CrawlCycle.cs +++ b/src/MUI.Crawler/Crawl/CrawlCycle.cs @@ -57,7 +57,11 @@ public sealed class CrawlCycle( // reads it — it exists so an operator can see an address that is otherwise indistinguishable // from a healthy target. ICrawlRefusalStore? refusals = null, - ILogger? logger = null) + ILogger? logger = null, + // The WebSocket addresses a game declares in MSSP, handshaken and written as endpoints. Optional: + // a crawl that cannot is a crawl doing slightly less. After the logger so the positional callers + // that pass one keep compiling. + WebSocketEndpointWriter? webSockets = null) { /// Probes everything that is due, and returns what the pass did. public async Task RunAsync(CancellationToken cancellationToken = default) @@ -468,6 +472,11 @@ private async Task StoreAsync( tally.Referred(intake); await SettleClaimsAsync(binding.GameId, result, cancellationToken); + + if (webSockets is not null) + { + await webSockets.ApplyAsync(binding.GameId, result, cancellationToken); + } } } diff --git a/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs b/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs new file mode 100644 index 00000000..6e920786 --- /dev/null +++ b/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs @@ -0,0 +1,123 @@ +using MUI.Catalog; +using MUI.Catalog.Persistence; +using MUI.Crawl; +using MUI.Discovery; + +using Microsoft.Extensions.Logging; + +namespace MUI.Crawler; + +/// +/// Turns the WebSocket addresses a game declared in MSSP into endpoints, once each has answered. +/// +/// +/// +/// Declared, then measured, then written. WEBSOCKET stays an MSSP field like any other +/// (the ingestor stores it verbatim); this writes an endpoint only for an address where a handshake +/// completed, so a game page lists a way in that worked, not one that was claimed (rule 1). A failed +/// handshake writes nothing, here or anywhere: an address that did not upgrade from our vantage +/// point is not shown, and nothing says it is down (rule 5). +/// +/// +/// Every address is server text, so each goes through the same two gates as a dial of the +/// crawl loop's own: the opt-out (§11) first, then the scope guard on the resolved addresses +/// (§7.2), whose answer is what the probe dials. There is no operator-seed exemption on this path. +/// +/// +/// An address belongs to one game, and keeps its kind. (host, port) is the identity +/// signal (§7.3), so a declaration naming an address another game holds is ignored rather than +/// written, and one naming a telnet or TLS endpoint of this game is ignored rather than turning it +/// into a WebSocket — that address answered telnet, which a declaration cannot overrule. +/// +/// +public sealed class WebSocketEndpointWriter( + IWebSocketProbe probe, + OptOutGate optOut, + IHostScopeGuard scope, + IEndpointStore endpoints, + TimeProvider time, + ILogger? logger = null) +{ + /// + /// Probes each address declared and writes the ones that answered. + /// + /// How many endpoints were written. + /// + /// Never throws for one address: a WebSocket endpoint is a detail of a game whose measurement has + /// already been stored, and must not cost the crawl loop the schedule it writes after this. + /// + public async Task ApplyAsync(Guid gameId, ProbeResult result, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(result); + + var written = 0; + + foreach (var address in WebSocketAddresses.From(result.Mssp)) + { + try + { + if (await ApplyOneAsync(gameId, address, cancellationToken)) + { + written++; + } + } + catch (Exception error) when (error is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + logger?.LogWarning(error, "WebSocket address {Address} declared by {Host}:{Port} threw", address.Uri, result.Host, result.Port); + } + } + + return written; + } + + private async Task ApplyOneAsync(Guid gameId, WebSocketAddress address, CancellationToken cancellationToken) + { + if (await optOut.RuleOnAsync(address.Host, address.Port, cancellationToken) is not null) + { + logger?.LogInformation("WebSocket address {Address} has opted out; not dialled", address.Uri); + return false; + } + + var existing = await endpoints.ByAddressAsync(address.Host, address.Port, cancellationToken); + + if (existing is not null && (existing.GameId != gameId || !existing.IsWebSocket)) + { + logger?.LogInformation( + "WebSocket address {Address} is already a {Kind} endpoint of game {Game}; left as it is", + address.Uri, existing.Kind, existing.GameId); + return false; + } + + var decision = await scope.InspectAsync(address.Host, cancellationToken); + + if (!decision.IsAllowed) + { + logger?.LogInformation("WebSocket address {Address} refused by scope: {Detail}", address.Uri, decision.Detail); + return false; + } + + var handshake = await probe.HandshakeAsync(address, decision.Addresses, cancellationToken); + + if (!handshake.Answered) + { + logger?.LogInformation("WebSocket address {Address} did not upgrade: {Detail}", address.Uri, handshake.Detail); + return false; + } + + var now = time.GetUtcNow(); + + await endpoints.UpsertAsync( + new GameEndpoint( + gameId, + address.Host, + address.Port, + address.Tls ? EndpointKind.SecureWebSocket : EndpointKind.WebSocket, + existing?.FirstSeenAt ?? now, + now, + EndpointState.Active, + address.Path), + cancellationToken); + + return true; + } +} diff --git a/src/MUI.Crawler/CrawlerServiceCollectionExtensions.cs b/src/MUI.Crawler/CrawlerServiceCollectionExtensions.cs index 31f3df8f..9f569bdd 100644 --- a/src/MUI.Crawler/CrawlerServiceCollectionExtensions.cs +++ b/src/MUI.Crawler/CrawlerServiceCollectionExtensions.cs @@ -237,6 +237,11 @@ public static IServiceCollection AddMuiCrawlerCore(this IServiceCollection servi services.TryAddSingleton(s => new NpgsqlEcosystemSnapshots( s.GetRequiredService())); + // The WebSocket addresses a game declares in MSSP: one handshake each, an endpoint for the + // ones that upgrade. Registered here so CrawlCycle's optional parameter is filled. + services.TryAddSingleton(_ => new WebSocketProbe()); + services.TryAddSingleton(); + services.TryAddSingleton(); // §5.3's third reason a transition is written: elapsed time. See CrawlGapGuard for why the diff --git a/src/MUI.Web/Api/ApiMapper.cs b/src/MUI.Web/Api/ApiMapper.cs index 9403fea8..15f7d111 100644 --- a/src/MUI.Web/Api/ApiMapper.cs +++ b/src/MUI.Web/Api/ApiMapper.cs @@ -192,7 +192,8 @@ public static CapabilityView Capability(CapabilityRow row, DateTimeOffset now) endpoint.TlsMeasured, endpoint.FirstSeenAt, endpoint.LastSeenAt, - endpoint.State); + endpoint.State, + endpoint.Path); public static FeedEntryView Feed(FeedEntry entry) => new( entry.Id, diff --git a/src/MUI.Web/Api/ApiModels.cs b/src/MUI.Web/Api/ApiModels.cs index bc57da78..1f24169b 100644 --- a/src/MUI.Web/Api/ApiModels.cs +++ b/src/MUI.Web/Api/ApiModels.cs @@ -98,6 +98,8 @@ public enum PlayerCountState /// An address, and how long it has answered there (spec §9). /// /// state is the catalogue's own word (active/stale/gone), not a threshold applied here, so this can't disagree with the page. +/// telnet, tls or websocket; a wss:// endpoint is websocket with tlsMeasured. +/// A WebSocket's request path, such as /ws-play/; absent for telnet. public sealed record EndpointView( string Host, int Port, @@ -105,7 +107,8 @@ public sealed record EndpointView( bool TlsMeasured, DateTimeOffset FirstSeenAt, DateTimeOffset LastSeenAt, - string State); + string State, + string? Path = null); public sealed record ChangeView(DateTimeOffset At, string Summary); diff --git a/src/MUI.Web/Components/Copy/PreviewCopy.cs b/src/MUI.Web/Components/Copy/PreviewCopy.cs index c40b0fb5..28664a88 100644 --- a/src/MUI.Web/Components/Copy/PreviewCopy.cs +++ b/src/MUI.Web/Components/Copy/PreviewCopy.cs @@ -208,7 +208,10 @@ public static string ForGame(string tag, GamePage page, DateTimeOffset now) /// Where you connect, which is the fact a reader most often wanted the page for. private static string? Address(GamePage page) { - var endpoint = page.Endpoints.FirstOrDefault(e => e.IsCurrent) ?? page.Endpoints.FirstOrDefault(); + var endpoint = page.Endpoints.FirstOrDefault(e => e.IsCurrent && !e.IsWebSocket) + ?? page.Endpoints.FirstOrDefault(e => !e.IsWebSocket) + ?? page.Endpoints.FirstOrDefault(e => e.IsCurrent) + ?? page.Endpoints.FirstOrDefault(); if (endpoint is null) { @@ -217,7 +220,7 @@ public static string ForGame(string tag, GamePage page, DateTimeOffset now) var codebase = page.Summary.Codebase is { } known ? $"{known} at " : string.Empty; - return $"{codebase}{endpoint.Host} {endpoint.Port.ToString(CultureInfo.InvariantCulture)}"; + return $"{codebase}{endpoint.Url ?? $"{endpoint.Host} {endpoint.Port.ToString(CultureInfo.InvariantCulture)}"}"; } /// diff --git a/src/MUI.Web/Components/Pages/Game.razor b/src/MUI.Web/Components/Pages/Game.razor index dd5a046d..33666cc6 100644 --- a/src/MUI.Web/Components/Pages/Game.razor +++ b/src/MUI.Web/Components/Pages/Game.razor @@ -95,8 +95,9 @@ else @foreach (var e in Page.Endpoints.OrderByDescending(e => e.IsCurrent).ThenBy(e => e.Port)) {

- @e.Host @e.Port - @if (e.TlsMeasured) + @* A WebSocket is a URL a web client dials, not a host and port to type into telnet. *@ + @(e.Url ?? $"{e.Host} {e.Port}") + @if (e.TlsMeasured && !e.IsWebSocket) { ● tls } diff --git a/src/MUI.Web/Components/Pages/GameStructuredData.cs b/src/MUI.Web/Components/Pages/GameStructuredData.cs index 472fd980..d65638fd 100644 --- a/src/MUI.Web/Components/Pages/GameStructuredData.cs +++ b/src/MUI.Web/Components/Pages/GameStructuredData.cs @@ -156,7 +156,12 @@ public static string For(GamePage page, Uri origin) /// private static JsonObject? Server(GamePage page) { - var endpoint = page.Endpoints.FirstOrDefault(e => e.IsCurrent) ?? page.Endpoints.FirstOrDefault(); + // Telnet first: a WebSocket's URL is not a telnet:// one, and a page that has both is better + // described by the address most clients can dial. + var endpoint = page.Endpoints.FirstOrDefault(e => e.IsCurrent && !e.IsWebSocket) + ?? page.Endpoints.FirstOrDefault(e => !e.IsWebSocket) + ?? page.Endpoints.FirstOrDefault(e => e.IsCurrent) + ?? page.Endpoints.FirstOrDefault(); if (endpoint is null) { @@ -166,7 +171,8 @@ public static string For(GamePage page, Uri origin) return new JsonObject { ["@type"] = "GameServer", - ["url"] = $"telnet://{endpoint.Host}:{endpoint.Port.ToString(CultureInfo.InvariantCulture)}", + ["url"] = endpoint.Url + ?? $"telnet://{endpoint.Host}:{endpoint.Port.ToString(CultureInfo.InvariantCulture)}", }; } diff --git a/src/MUI.Web/Components/Pages/PlainText.cs b/src/MUI.Web/Components/Pages/PlainText.cs index 1a61d942..fe6c0369 100644 --- a/src/MUI.Web/Components/Pages/PlainText.cs +++ b/src/MUI.Web/Components/Pages/PlainText.cs @@ -79,9 +79,13 @@ public static string Render( // to turn it off, not -servername to turn it on), and spelling it out again would put // the line past Columns for any ordinary hostname, which is what the eighty-column rule // is there to stop. - b.AppendLine(e.TlsMeasured - ? $"openssl s_client -crlf -connect {e.Host}:{e.Port}" - : $"telnet {e.Host} {e.Port}"); + // + // A WebSocket has no command a terminal reliably has, so it is the URL itself: what a + // reader pastes into a client that speaks it. + b.AppendLine(e.Url + ?? (e.TlsMeasured + ? $"openssl s_client -crlf -connect {e.Host}:{e.Port}" + : $"telnet {e.Host} {e.Port}")); } // How this site came to know about the game, and when. Rendered here as well as on the diff --git a/src/MUI.Web/Fixtures/FixtureGameQueries.cs b/src/MUI.Web/Fixtures/FixtureGameQueries.cs index 1fdfd964..132f5aa4 100644 --- a/src/MUI.Web/Fixtures/FixtureGameQueries.cs +++ b/src/MUI.Web/Fixtures/FixtureGameQueries.cs @@ -417,7 +417,13 @@ public Task> ForGameAsync( "aardwolf" => [Endpoint("aardmud.org", 4000, "telnet", tls: false, sinceDays: 4000)], "midnight-sun" => [Endpoint("midnightsun2.org", 3000, "telnet", tls: false, sinceDays: 1500)], "batmud" => [Endpoint("bat.org", 23, "telnet", tls: false, sinceDays: 5000)], - "ashen-court" => [Endpoint("ashen.example", 4000, "tls", tls: true, sinceDays: 600)], + "ashen-court" => + [ + Endpoint("ashen.example", 4000, "tls", tls: true, sinceDays: 600), + + // A WebSocket the game declared in MSSP and that upgraded (migration 0045). + Endpoint("ashen.example", 443, "websocket", tls: true, sinceDays: 30, path: "/play/"), + ], "hollow-bell" => [Endpoint("hollowbell.example", 4201, "telnet", tls: false, sinceDays: 2400)], "gaslight-row" => [Endpoint("gaslight.example", 4201, "telnet", tls: false, sinceDays: 3000)], "verdigris" => [Endpoint("verdigris.example", 6250, "telnet", tls: false, sinceDays: 800)], @@ -426,14 +432,15 @@ public Task> ForGameAsync( /// How long ago we last reached it, for an address the game has left. private static GameEndpointView Endpoint( - string host, int port, string kind, bool tls, int sinceDays, int? goneDays = null) => new( + string host, int port, string kind, bool tls, int sinceDays, int? goneDays = null, string? path = null) => new( host, port, kind, TlsMeasured: tls, Now.AddDays(-sinceDays), goneDays is { } left ? Now.AddDays(-left) : Now, - goneDays is null ? "active" : "gone"); + goneDays is null ? "active" : "gone", + path); private static string? Screen(GameSummary g) => g.Slug switch { diff --git a/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs b/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs index 51f921b5..c20d5b0f 100644 --- a/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs +++ b/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs @@ -949,6 +949,49 @@ await endpoints.UpsertAsync(new GameEndpoint( await Assert.That(page.Endpoints.Single(e => e.Port == 4201).TlsMeasured).IsFalse(); } + [Test] + public async Task AWebSocketEndpointIsShownWithItsPathAndWhetherItIsSecure() + { + await using var db = await PostgresFixture.MigratedAsync(); + var game = await Seed.GameAsync(db); + var endpoints = new NpgsqlEndpointStore(db.DataSource); + + await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 443, EndpointKind.SecureWebSocket, Now, Now, EndpointState.Active, "/ws-play/")); + await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 8080, EndpointKind.WebSocket, Now, Now, EndpointState.Active, "/")); + + var page = await QueriesOn(db).FindAsync("corvid"); + var secure = page!.Endpoints.Single(e => e.Port == 443); + var plain = page.Endpoints.Single(e => e.Port == 8080); + + // One kind word for a client to look for; TLS is the measurement beside it, as for telnet. + await Assert.That(secure.Kind).IsEqualTo("websocket"); + await Assert.That(secure.TlsMeasured).IsTrue(); + await Assert.That(secure.Path).IsEqualTo("/ws-play/"); + await Assert.That(secure.Url).IsEqualTo("wss://mume.org:443/ws-play/"); + await Assert.That(plain.TlsMeasured).IsFalse(); + await Assert.That(plain.Url).IsEqualTo("ws://mume.org:8080/"); + } + + [Test] + public async Task OnlyAWebSocketEndpointCarriesAPath() + { + await using var db = await PostgresFixture.MigratedAsync(); + var game = await Seed.GameAsync(db); + var endpoints = new NpgsqlEndpointStore(db.DataSource); + + await Assert.That(async () => await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 4242, EndpointKind.Telnet, Now, Now, EndpointState.Active, "/x"))) + .Throws(); + await Assert.That(async () => await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 443, EndpointKind.SecureWebSocket, Now, Now, EndpointState.Active, null))) + .Throws(); + await Assert.That(async () => await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 443, EndpointKind.SecureWebSocket, Now, Now, EndpointState.Active, "ws play"))) + .Throws(); + } + private static ActivityCell Cell(IReadOnlyList cells, DateTimeOffset at) => cells.Single(c => c.DayOfWeek == (int)at.UtcDateTime.DayOfWeek && c.Hour == at.UtcDateTime.Hour); diff --git a/tests/MUI.Crawl.Tests/WebSocket/WebSocketAddressesTests.cs b/tests/MUI.Crawl.Tests/WebSocket/WebSocketAddressesTests.cs new file mode 100644 index 00000000..480007cb --- /dev/null +++ b/tests/MUI.Crawl.Tests/WebSocket/WebSocketAddressesTests.cs @@ -0,0 +1,92 @@ +namespace MUI.Crawl.Tests.WebSocket; + +///

The MSSP WEBSOCKET variable, read as the two games that publish it write it. +public class WebSocketAddressesTests +{ + private static IReadOnlyDictionary> Report(params string[] values) + { + var report = new OrderedDictionary>(StringComparer.OrdinalIgnoreCase) + { + [WebSocketAddresses.Variable] = values, + }; + + return report; + } + + [Test] + public async Task MumesAddressIsReadWithItsPathAndTheSchemesPort() + { + var found = WebSocketAddresses.From(Report("wss://mume.org/ws-play/")); + + await Assert.That(found).Count().IsEqualTo(1); + await Assert.That(found[0]).IsEqualTo(new WebSocketAddress("mume.org", 443, true, "/ws-play/")); + await Assert.That(found[0].Uri.ToString()).IsEqualTo("wss://mume.org/ws-play/"); + } + + [Test] + public async Task AListIsReadInOrderOnceEach() + { + var found = WebSocketAddresses.From(Report( + "wss://last-outpost.com/ws/telnet/, ws://Last-Outpost.com:8080/ws", + "wss://last-outpost.com/ws/telnet/")); + + await Assert.That(found).Count().IsEqualTo(2); + await Assert.That(found[0].Path).IsEqualTo("/ws/telnet/"); + await Assert.That(found[1]).IsEqualTo(new WebSocketAddress("last-outpost.com", 8080, false, "/ws")); + } + + [Test] + public async Task ABareHostIsThePathSlash() + { + var found = WebSocketAddresses.Parse("ws://mud.example.org:4000"); + + await Assert.That(found).IsEqualTo(new WebSocketAddress("mud.example.org", 4000, false, "/")); + } + + [Test] + public async Task AnIpv6AddressIsKeptWithoutBracketsAndWrittenWithThem() + { + var found = WebSocketAddresses.Parse("wss://[2001:db8::1]:4443/play"); + + await Assert.That(found!.Host).IsEqualTo("2001:db8::1"); + await Assert.That(found.Uri.ToString()).IsEqualTo("wss://[2001:db8::1]:4443/play"); + } + + [Test] + [Arguments("https://mume.org/ws-play/")] + [Arguments("telnet://mume.org:4242")] + [Arguments("wss://user:secret@mume.org/ws")] + [Arguments("wss://mume.org/ws#here")] + [Arguments("wss://mume.org/ws play")] + [Arguments("wss://mume.org/wsé")] + [Arguments("mume.org/ws")] + [Arguments("1")] + [Arguments("")] + public async Task WhatThisSiteWouldNotShowIsRefusedNotTidied(string value) + { + await Assert.That(WebSocketAddresses.Parse(value)).IsNull(); + } + + [Test] + public async Task APathPastTheDatabasesLimitIsRefused() + { + var path = "/" + new string('a', WebSocketAddresses.MaxPathLength); + + await Assert.That(WebSocketAddresses.Parse($"wss://mume.org{path}")).IsNull(); + } + + [Test] + public async Task AReportNamingManyAddressesIsCut() + { + var values = Enumerable.Range(1, 10).Select(n => $"wss://mud{n}.example.org/").ToArray(); + + await Assert.That(WebSocketAddresses.From(Report(values))).Count().IsEqualTo(WebSocketAddresses.MaxAddresses); + } + + [Test] + public async Task NoVariableIsNoAddress() + { + await Assert.That(WebSocketAddresses.From(MsspReport.Empty)).IsEmpty(); + await Assert.That(WebSocketAddresses.From(null)).IsEmpty(); + } +} diff --git a/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs b/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs new file mode 100644 index 00000000..def8553d --- /dev/null +++ b/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs @@ -0,0 +1,186 @@ +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text; + +namespace MUI.Crawl.Tests.WebSocket; + +/// The handshake against a bridge on loopback that answers as the real ones do. +public class WebSocketProbeTests +{ + [Test] + public async Task ABridgeThatRefusesUnknownSubprotocolsUpgradesTheProbe() + { + // websockify answers 400 to a subprotocol it does not know; the probe offers none. + await using var bridge = Bridge.Start(refuseAnyOffer: true); + + var handshake = await new WebSocketProbe().HandshakeAsync( + new WebSocketAddress("localhost", bridge.Port, false, "/ws/telnet/"), + [IPAddress.Loopback]); + + await Assert.That(handshake.Answered).IsTrue(); + await Assert.That(bridge.Paths).Contains("/ws/telnet/"); + await Assert.That(bridge.Offers).Contains((string?)null); + } + + [Test] + public async Task ARefusedUpgradeSaysItsStatus() + { + await using var bridge = Bridge.Start(refuseEverything: true); + + var handshake = await new WebSocketProbe().HandshakeAsync( + new WebSocketAddress("localhost", bridge.Port, false, "/"), + [IPAddress.Loopback]); + + await Assert.That(handshake.Answered).IsFalse(); + await Assert.That(handshake.Detail).IsEqualTo("HTTP 400"); + } + + [Test] + public async Task TheSocketGoesToTheRuledAddressNotToTheName() + { + // The name does not resolve; the probe never asks. + await using var bridge = Bridge.Start(); + + var handshake = await new WebSocketProbe().HandshakeAsync( + new WebSocketAddress("unresolvable.invalid", bridge.Port, false, "/"), + [IPAddress.Loopback]); + + await Assert.That(handshake.Answered).IsTrue(); + } + + [Test] + public async Task ASilentServerRunsOutOfBudget() + { + using var silent = new TcpListener(IPAddress.Loopback, 0); + silent.Start(); + var port = ((IPEndPoint)silent.LocalEndpoint).Port; + + var handshake = await new WebSocketProbe(TimeSpan.FromMilliseconds(300)).HandshakeAsync( + new WebSocketAddress("localhost", port, false, "/"), + [IPAddress.Loopback]); + + await Assert.That(handshake.Answered).IsFalse(); + } + + [Test] + public async Task NoAddressIsNoDial() + { + var handshake = await new WebSocketProbe().HandshakeAsync( + new WebSocketAddress("localhost", 1, false, "/"), []); + + await Assert.That(handshake.Answered).IsFalse(); + } + + private sealed class Bridge : IAsyncDisposable + { + private readonly TcpListener _listener; + private readonly CancellationTokenSource _stop = new(); + private readonly Task _loop; + + private Bridge(TcpListener listener, bool refuseAnyOffer, bool refuseEverything) + { + _listener = listener; + _loop = Task.Run(() => AcceptAsync(refuseAnyOffer, refuseEverything)); + } + + public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; + + public List Paths { get; } = []; + + public List Offers { get; } = []; + + public static Bridge Start(bool refuseAnyOffer = false, bool refuseEverything = false) + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + return new Bridge(listener, refuseAnyOffer, refuseEverything); + } + + private async Task AcceptAsync(bool refuseAnyOffer, bool refuseEverything) + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (OperationCanceledException) + { + return; + } + + using (client) + { + var stream = client.GetStream(); + var request = await ReadHeadAsync(stream); + var lines = request.Split("\r\n"); + var path = lines[0].Split(' ')[1]; + string? Header(string name) => lines + .Where(l => l.StartsWith(name + ":", StringComparison.OrdinalIgnoreCase)) + .Select(l => l[(name.Length + 1)..].Trim()) + .FirstOrDefault(); + + var offer = Header("Sec-WebSocket-Protocol"); + lock (Paths) + { + Paths.Add(path); + Offers.Add(offer); + } + + string response; + + if (refuseEverything || (refuseAnyOffer && offer is not null)) + { + response = "HTTP/1.1 400 Invalid protocol selected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + } + else + { + var accept = Convert.ToBase64String(SHA1.HashData(Encoding.ASCII.GetBytes( + Header("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))); + response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + $"Sec-WebSocket-Accept: {accept}\r\n\r\n"; + } + + await stream.WriteAsync(Encoding.ASCII.GetBytes(response)); + + // Hold the socket long enough for the client's close frame. + var buffer = new byte[256]; + using var wait = new CancellationTokenSource(TimeSpan.FromSeconds(2)); + try + { + _ = await stream.ReadAsync(buffer, wait.Token); + } + catch (Exception) + { + // The close is not under test. + } + } + } + } + + private static async Task ReadHeadAsync(NetworkStream stream) + { + var text = new StringBuilder(); + var buffer = new byte[1]; + + while (!text.ToString().EndsWith("\r\n\r\n", StringComparison.Ordinal) + && await stream.ReadAsync(buffer) == 1) + { + text.Append((char)buffer[0]); + } + + return text.ToString(); + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + await _loop.ConfigureAwait(false); + _stop.Dispose(); + } + } +} diff --git a/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs b/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs new file mode 100644 index 00000000..97f4b9ff --- /dev/null +++ b/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs @@ -0,0 +1,169 @@ +using System.Collections.Concurrent; +using System.Net; + +using Dapper; + +using MUI.Crawl; +using MUI.Crawler.Persistence; +using MUI.Crawler.Tests.Support; +using MUI.Discovery; + +namespace MUI.Crawler.Tests; + +/// +/// The MSSP WEBSOCKET variable, through the crawl loop and into game_endpoint. +/// +/// +/// A declared address becomes an endpoint only once a handshake there completed (rule 1), and an +/// address that did not upgrade, opted out, or resolved somewhere we do not dial leaves nothing behind +/// on the game's record (rule 5). +/// +public class WebSocketEndpointPostgresTests +{ + private static ScriptedProbe Declaring(string value) => new(target => Probes.Answered( + host: target.Host, + port: target.Port, + mssp: Probes.Mssp(("NAME", "Multi-Users in Middle-earth"), ("WEBSOCKET", value)), + banner: "Welcome to MUME")); + + private sealed class Handshakes(bool answer) : IWebSocketProbe + { + public ConcurrentQueue<(WebSocketAddress Address, IReadOnlyList Addresses)> Asked { get; } = []; + + public Task HandshakeAsync( + WebSocketAddress address, + IReadOnlyList addresses, + CancellationToken cancellationToken = default) + { + Asked.Enqueue((address, addresses)); + return Task.FromResult(answer ? WebSocketHandshake.Upgraded : new WebSocketHandshake(false, "HTTP 502")); + } + } + + [Test] + public async Task ADeclaredAddressThatUpgradesIsAWebSocketEndpointWithItsPath() + { + await using var database = await PostgresFixture.MigratedAsync(); + var source = database.DataSource; + + await CrawlCycles.SeedAsync(source, new CrawlSeed("mume.org", 4242)); + var handshakes = new Handshakes(answer: true); + + await CrawlCycles.Build( + source, Declaring("wss://mume.org/ws-play/"), TimeProvider.System, + options: CrawlCycles.Confirming(), webSockets: handshakes) + .RunAsync(); + + await using var connection = await source.OpenConnectionAsync(); + var row = await connection.QuerySingleAsync<(string Kind, string Path, string State)>( + "SELECT kind, path, state FROM game_endpoint WHERE host = 'mume.org' AND port = 443"); + + await Assert.That(row.Kind).IsEqualTo("wss"); + await Assert.That(row.Path).IsEqualTo("/ws-play/"); + await Assert.That(row.State).IsEqualTo("active"); + + // On the same game as the telnet address it was declared by. + await Assert.That(await connection.ExecuteScalarAsync( + "SELECT count(DISTINCT game_id) FROM game_endpoint WHERE host = 'mume.org'")) + .IsEqualTo(1L); + + // And dialled at the address the scope guard ruled on, not at a second lookup. + await Assert.That(handshakes.Asked.Single().Addresses.Single()).IsEqualTo(IPAddress.Parse("198.51.100.7")); + } + + [Test] + public async Task AnAddressThatDidNotUpgradeLeavesNothing() + { + await using var database = await PostgresFixture.MigratedAsync(); + var source = database.DataSource; + + await CrawlCycles.SeedAsync(source, new CrawlSeed("mume.org", 4242)); + + var report = await CrawlCycles.Build( + source, Declaring("wss://mume.org/ws-play/"), TimeProvider.System, + options: CrawlCycles.Confirming(), webSockets: new Handshakes(answer: false)) + .RunAsync(); + + await Assert.That(report.Answered).IsEqualTo(1); + + await using var connection = await source.OpenConnectionAsync(); + + await Assert.That(await connection.ExecuteScalarAsync( + "SELECT count(*) FROM game_endpoint WHERE kind IN ('websocket', 'wss')")) + .IsEqualTo(0L); + + // The declaration itself is still the game's field, verbatim. + await Assert.That(await connection.ExecuteScalarAsync( + "SELECT count(*) FROM game_field WHERE field = 'WEBSOCKET'")) + .IsEqualTo(1L); + } + + [Test] + public async Task AnAddressThatResolvesInsideIsNeverDialled() + { + await using var database = await PostgresFixture.MigratedAsync(); + var source = database.DataSource; + + await CrawlCycles.SeedAsync(source, new CrawlSeed("mume.org", 4242)); + var handshakes = new Handshakes(answer: true); + + await CrawlCycles.Build( + source, Declaring("ws://metadata.example.org/"), TimeProvider.System, + resolver: new FakeHostResolver().Resolving("metadata.example.org", "169.254.169.254"), + options: CrawlCycles.Confirming(), webSockets: handshakes) + .RunAsync(); + + await Assert.That(handshakes.Asked).IsEmpty(); + } + + [Test] + public async Task AnAddressThatOptedOutIsNeverDialled() + { + await using var database = await PostgresFixture.MigratedAsync(); + var source = database.DataSource; + + await CrawlCycles.SeedAsync(source, new CrawlSeed("mume.org", 4242)); + await new NpgsqlCrawlOptOutRepository(source).RecordAsync( + new CrawlOptOut + { + Host = "mume.org", + Port = 443, + Source = OptOutSource.Request, + RecordedAt = DateTimeOffset.UtcNow, + LastConfirmedAt = DateTimeOffset.UtcNow, + Detail = "asked", + }, + default); + + var handshakes = new Handshakes(answer: true); + + await CrawlCycles.Build( + source, Declaring("wss://mume.org/ws-play/"), TimeProvider.System, + options: CrawlCycles.Confirming(), webSockets: handshakes) + .RunAsync(); + + await Assert.That(handshakes.Asked).IsEmpty(); + } + + [Test] + public async Task ADeclarationNamingTheGamesOwnTelnetAddressLeavesItTelnet() + { + await using var database = await PostgresFixture.MigratedAsync(); + var source = database.DataSource; + + await CrawlCycles.SeedAsync(source, new CrawlSeed("mume.org", 4242)); + var handshakes = new Handshakes(answer: true); + + await CrawlCycles.Build( + source, Declaring("ws://mume.org:4242/"), TimeProvider.System, + options: CrawlCycles.Confirming(), webSockets: handshakes) + .RunAsync(); + + await using var connection = await source.OpenConnectionAsync(); + + await Assert.That(await connection.ExecuteScalarAsync( + "SELECT kind FROM game_endpoint WHERE host = 'mume.org' AND port = 4242")) + .IsEqualTo("telnet"); + await Assert.That(handshakes.Asked).IsEmpty(); + } +} diff --git a/tests/MUI.Crawler.Tests/Support/CrawlCycles.cs b/tests/MUI.Crawler.Tests/Support/CrawlCycles.cs index 5597079c..cd366c97 100644 --- a/tests/MUI.Crawler.Tests/Support/CrawlCycles.cs +++ b/tests/MUI.Crawler.Tests/Support/CrawlCycles.cs @@ -24,7 +24,8 @@ public static CrawlCycle Build( IHostResolver? resolver = null, DiscoveryOptions? options = null, TimeSpan? grace = null, - IDnsTxtResolver? dns = null) + IDnsTxtResolver? dns = null, + IWebSocketProbe? webSockets = null) { var discovery = options ?? new DiscoveryOptions { @@ -85,7 +86,15 @@ public static CrawlCycle Build( payloads: null, // Issue #185 — a suite asserting what a cycle wrote has to be given the same register // the deployment has, or "a refusal left a record" is untestable here. - refusals: new NpgsqlCrawlRefusalStore(source)); + refusals: new NpgsqlCrawlRefusalStore(source), + webSockets: webSockets is null + ? null + : new WebSocketEndpointWriter( + webSockets, + new OptOutGate(new NpgsqlCrawlOptOutRepository(source), dns ?? new ScriptedDns(), time), + new HostScopeGuard(effectiveResolver), + endpoints, + time)); } /// Confirmation on, with no wait, so a suite asserts the behaviour and not the delay. diff --git a/tests/MUI.Web.Tests/Api/GameApiTests.cs b/tests/MUI.Web.Tests/Api/GameApiTests.cs index 82c99692..275ff31e 100644 --- a/tests/MUI.Web.Tests/Api/GameApiTests.cs +++ b/tests/MUI.Web.Tests/Api/GameApiTests.cs @@ -128,6 +128,24 @@ await Assert.That(game.GetProperty("connectScreen").GetProperty("text").GetStrin await Assert.That(game.GetProperty("availability").GetArrayLength()).IsGreaterThan(0); } + [Test] + public async Task AWebSocketEndpointCarriesItsPathAndATelnetOneCarriesNone() + { + // A client dials a WebSocket at host, port and path; TLS is tlsMeasured, as for telnet. + await using var host = await ApiHost.StartAsync(); + + var game = await Json.ElementAsync( + await host.Client.GetAsync($"{ApiRoutes.Games}/ashen-court")); + + var endpoints = game.GetProperty("endpoints").EnumerateArray().ToList(); + var socket = endpoints.Single(e => e.GetProperty("kind").GetString() == "websocket"); + var telnet = endpoints.Single(e => e.GetProperty("kind").GetString() == "tls"); + + await Assert.That(socket.GetProperty("path").GetString()).IsEqualTo("/play/"); + await Assert.That(socket.GetProperty("tlsMeasured").GetBoolean()).IsTrue(); + await Assert.That(telnet.GetProperty("path").ValueKind).IsEqualTo(System.Text.Json.JsonValueKind.Null); + } + /// A suppressed screen is withheld here as well as on the page (spec §11). [Test] public async Task AScreenItsOwnerAskedUsNotToRepublishIsNotRepublishedByTheApiEither() From 4715739c66ad852b73f12b944cf8b0bf00323c09 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 20:21:29 +0000 Subject: [PATCH 2/2] Record which WebSocket subprotocol a server chose A socket that upgraded says nothing about what a client must speak on it. Evennia 6.1 chooses terminal., gmcp. or json.mudstandards.org and never telnet., and with no choice made it talks its own JSON, so a telnet client that dialled an Evennia endpoint listed as "websocket" would send bytes Evennia reads as malformed JSON. The handshake now offers the four mudstandards.org names and keeps the one the server chose. A server that answers the offer with an HTTP refusal (websockify's 400, MUME's Apache 502) is asked again with no offer, so the stricter bridges still upgrade and are recorded with no subprotocol, as before. game_endpoint gains subprotocol (websocket kinds only, an RFC 6455 token), and the API's endpoint gains subProtocol. The game page shows the name beside the URL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Rqqt7SNv2XNNK6ro5YvSJP --- migrations/0045_websocket_endpoint.sql | 11 +++ src/MUI.Catalog/Games/Views.cs | 7 +- .../Persistence/Games/NpgsqlEndpointStore.cs | 12 ++- src/MUI.Catalog/Persistence/Games/Records.cs | 7 +- .../Queries/NpgsqlGameQueries.GamePage.cs | 3 +- src/MUI.Crawl/WebSocket/WebSocketProbe.cs | 80 ++++++++++++++++--- .../Crawl/WebSocketEndpointWriter.cs | 3 +- src/MUI.Web/Api/ApiMapper.cs | 3 +- src/MUI.Web/Api/ApiModels.cs | 8 +- src/MUI.Web/Components/Pages/Game.razor | 5 ++ src/MUI.Web/Fixtures/FixtureGameQueries.cs | 7 +- .../Queries/GameQueriesPostgresTests.cs | 19 ++++- .../WebSocket/WebSocketProbeTests.cs | 53 ++++++++++-- .../Crawl/WebSocketEndpointPostgresTests.cs | 25 +++++- tests/MUI.Web.Tests/Api/GameApiTests.cs | 2 + 15 files changed, 208 insertions(+), 37 deletions(-) diff --git a/migrations/0045_websocket_endpoint.sql b/migrations/0045_websocket_endpoint.sql index 2b3c3ed6..998543b2 100644 --- a/migrations/0045_websocket_endpoint.sql +++ b/migrations/0045_websocket_endpoint.sql @@ -12,6 +12,12 @@ -- observed, and the writer refuses an address another game holds rather than taking it. ALTER TABLE game_endpoint ADD COLUMN path text; +-- The subprotocol the server chose when the handshake offered the mudstandards.org names, or null +-- when it chose none. It is the measurement that says what a client must speak once connected: +-- Evennia answers telnet bytes on a socket with no subprotocol as malformed JSON, and only the chosen +-- name tells a client that the socket is not telnet. +ALTER TABLE game_endpoint ADD COLUMN subprotocol text; + -- Nothing has written 'websocket' yet, but a row that did would otherwise fail the CHECK below. UPDATE game_endpoint SET path = '/' WHERE kind = 'websocket' AND path IS NULL; @@ -26,3 +32,8 @@ ALTER TABLE game_endpoint ADD CONSTRAINT game_endpoint_path_only_on_websockets -- and a bound. The value comes from a game's MSSP, so it is somebody else's text. ALTER TABLE game_endpoint ADD CONSTRAINT game_endpoint_path_is_a_path CHECK (path IS NULL OR (path ~ '^/[!-~]*$' AND length(path) <= 256)); + +-- Only a WebSocket has a subprotocol, and it is an RFC 6455 token: one the probe offered, so short. +ALTER TABLE game_endpoint ADD CONSTRAINT game_endpoint_subprotocol_only_on_websockets + CHECK (subprotocol IS NULL OR (kind IN ('websocket', 'wss') + AND subprotocol ~ '^[!#-''*+.0-9A-Z^-z|~-]+$' AND length(subprotocol) <= 64)); diff --git a/src/MUI.Catalog/Games/Views.cs b/src/MUI.Catalog/Games/Views.cs index e29ff914..9b3b1eaf 100644 --- a/src/MUI.Catalog/Games/Views.cs +++ b/src/MUI.Catalog/Games/Views.cs @@ -269,6 +269,10 @@ public sealed record ReferralNeighbour( /// set, the way a telnet one is tls. /// /// A WebSocket's request path (/ws-play/); null for every other kind. +/// +/// The subprotocol a WebSocket's server chose when offered the mudstandards.org names; null when it +/// chose none, and for every other kind. +/// public sealed record GameEndpointView( string Host, int Port, @@ -277,7 +281,8 @@ public sealed record GameEndpointView( DateTimeOffset FirstSeenAt, DateTimeOffset LastSeenAt, string State, - string? Path = null) + string? Path = null, + string? SubProtocol = null) { /// Whether we still reach the game here. public bool IsCurrent => string.Equals(State, "active", StringComparison.Ordinal); diff --git a/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs b/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs index 90adde52..8eb547ae 100644 --- a/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs +++ b/src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs @@ -9,7 +9,7 @@ public sealed class NpgsqlEndpointStore(NpgsqlDataSource source) : IEndpointStor { private const string Columns = """ game_id AS GameId, host AS Host, port AS Port, kind AS Kind, - first_seen_at AS FirstSeenAt, last_seen_at AS LastSeenAt, state AS State, path AS Path + first_seen_at AS FirstSeenAt, last_seen_at AS LastSeenAt, state AS State, path AS Path, subprotocol AS SubProtocol """; public async Task> ForGameAsync( @@ -99,11 +99,12 @@ public async Task UpsertAsync(GameEndpoint endpoint, CancellationToken cancellat // how long we have known the address, not how long the current answer has been true. await connection.ExecuteAsync(new CommandDefinition( """ - INSERT INTO game_endpoint (game_id, host, port, kind, first_seen_at, last_seen_at, state, path) - VALUES (@gameId, @host, @port, @kind, @firstSeenAt, @lastSeenAt, @state, @path) + INSERT INTO game_endpoint (game_id, host, port, kind, first_seen_at, last_seen_at, state, path, subprotocol) + VALUES (@gameId, @host, @port, @kind, @firstSeenAt, @lastSeenAt, @state, @path, @subprotocol) ON CONFLICT (game_id, host, port) DO UPDATE SET kind = EXCLUDED.kind, path = EXCLUDED.path, + subprotocol = EXCLUDED.subprotocol, last_seen_at = GREATEST(game_endpoint.last_seen_at, EXCLUDED.last_seen_at), state = EXCLUDED.state """, @@ -117,6 +118,7 @@ ON CONFLICT (game_id, host, port) DO UPDATE lastSeenAt = endpoint.LastSeenAt.ToUniversalTime(), state = SqlEnums.ToDb(endpoint.State), path = endpoint.Path, + subprotocol = endpoint.SubProtocol, }, cancellationToken: cancellationToken)); } @@ -139,8 +141,10 @@ private sealed class Row public string? Path { get; init; } + public string? SubProtocol { get; init; } + public GameEndpoint ToRecord() => new( GameId, Host, Port, SqlEnums.ToEndpointKind(Kind), FirstSeenAt, LastSeenAt, - SqlEnums.ToEndpointState(State), Path); + SqlEnums.ToEndpointState(State), Path, SubProtocol); } } diff --git a/src/MUI.Catalog/Persistence/Games/Records.cs b/src/MUI.Catalog/Persistence/Games/Records.cs index 279336a2..2e7363cb 100644 --- a/src/MUI.Catalog/Persistence/Games/Records.cs +++ b/src/MUI.Catalog/Persistence/Games/Records.cs @@ -82,6 +82,10 @@ public enum EndpointState /// The request path of a WebSocket endpoint (/ws-play/), and null for every other kind: migration 0045's /// CHECK holds the two together. /// +/// +/// The WebSocket subprotocol the server chose (terminal.mudstandards.org), or null when it chose +/// none; always null for a non-WebSocket kind. +/// public sealed record GameEndpoint( Guid GameId, string Host, @@ -90,7 +94,8 @@ public sealed record GameEndpoint( DateTimeOffset FirstSeenAt, DateTimeOffset LastSeenAt, EndpointState State, - string? Path = null) + string? Path = null, + string? SubProtocol = null) { /// Whether this is a WebSocket, behind TLS or not. public bool IsWebSocket => Kind is EndpointKind.WebSocket or EndpointKind.SecureWebSocket; diff --git a/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs b/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs index 2efeb72f..28b17840 100644 --- a/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs +++ b/src/MUI.Catalog/Persistence/Queries/NpgsqlGameQueries.GamePage.cs @@ -157,7 +157,8 @@ private async Task PageAsync( e.FirstSeenAt, e.LastSeenAt, SqlEnums.ToDb(e.State), - e.Path)) + e.Path, + e.SubProtocol)) .ToList(), ConnectScreen: Winner(fields, InternalFields.ConnectScreen)?.Value, ConnectScreenSuppressed: string.Equals( diff --git a/src/MUI.Crawl/WebSocket/WebSocketProbe.cs b/src/MUI.Crawl/WebSocket/WebSocketProbe.cs index 9580a9e7..c2b3abd1 100644 --- a/src/MUI.Crawl/WebSocket/WebSocketProbe.cs +++ b/src/MUI.Crawl/WebSocket/WebSocketProbe.cs @@ -7,9 +7,13 @@ namespace MUI.Crawl; /// What came of one WebSocket handshake. /// True only when the server completed the upgrade. /// Why not, for a log line. Never written to a game's record. -public sealed record WebSocketHandshake(bool Answered, string? Detail = null) +/// The subprotocol the server chose, or null when it chose none. +public sealed record WebSocketHandshake(bool Answered, string? Detail = null, string? SubProtocol = null) { public static readonly WebSocketHandshake Upgraded = new(true); + + public static WebSocketHandshake UpgradedWith(string? subProtocol) => + string.IsNullOrEmpty(subProtocol) ? Upgraded : new(true, SubProtocol: subProtocol); } /// @@ -36,11 +40,15 @@ Task HandshakeAsync( /// /// /// -/// No subprotocol is offered. The real bridges are strict about it: websockify answers 400 to a -/// name it does not know, and MUME's Apache answers 502 to telnet.mudstandards.org, while both -/// accept a handshake that names none. The question here is whether a client can reach the game at -/// this address, and offering a name the bridge refuses would record our choice of offer as the -/// game's failure (rule 5). +/// The mudstandards.org names are offered first, then none. Which one the server chooses is +/// the fact a client needs: Evennia 6.1 chooses terminal., gmcp. or +/// json.mudstandards.org and never telnet., and with none chosen it talks its own JSON, +/// so a socket that upgraded says nothing about what a client must speak until the choice is known. +/// But the plain bridges are strict: websockify answers 400 to a name it does not know, and MUME's +/// Apache answers 502 to telnet.mudstandards.org, while both accept a handshake that names +/// none. So an HTTP refusal of the offer is retried once with no offer, and an upgrade there is an +/// upgrade with no subprotocol — offering a name the bridge refuses must not become the game's +/// failure (rule 5). /// /// /// The socket goes to the addresses the scope gate ruled on, never to a second lookup of the @@ -55,6 +63,18 @@ Task HandshakeAsync( /// public sealed class WebSocketProbe(TimeSpan? timeout = null) : IWebSocketProbe { + /// + /// The subprotocols offered, in the order a client of this site's would prefer them: telnet first, + /// since that is what a MU* client already speaks, then the three the spec adds beside it. + /// + public static readonly IReadOnlyList Offered = + [ + "telnet.mudstandards.org", + "gmcp.mudstandards.org", + "terminal.mudstandards.org", + "json.mudstandards.org", + ]; + /// The whole handshake's budget, connect and TLS included. public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(15); @@ -76,6 +96,30 @@ public async Task HandshakeAsync( using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); budget.CancelAfter(_timeout); + var offered = await AttemptAsync(address, addresses, Offered, budget.Token, cancellationToken); + + // A status means the server read the request and turned down the offer; anything else (no + // answer, a reset, the budget) would fail the same way without it, and is not retried. + if (offered.Answered || offered.Status is null) + { + return offered.Result; + } + + return (await AttemptAsync(address, addresses, [], budget.Token, cancellationToken)).Result; + } + + private sealed record Attempt(WebSocketHandshake Result, int? Status) + { + public bool Answered => Result.Answered; + } + + private async Task AttemptAsync( + WebSocketAddress address, + IReadOnlyList addresses, + IReadOnlyList subProtocols, + CancellationToken budget, + CancellationToken cancellationToken) + { using var handler = new SocketsHttpHandler { UseProxy = false, @@ -103,24 +147,34 @@ public async Task HandshakeAsync( using var socket = new ClientWebSocket(); socket.Options.CollectHttpResponseDetails = true; + foreach (var subProtocol in subProtocols) + { + socket.Options.AddSubProtocol(subProtocol); + } + try { - await socket.ConnectAsync(address.Uri, invoker, budget.Token).ConfigureAwait(false); + await socket.ConnectAsync(address.Uri, invoker, budget).ConfigureAwait(false); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { - return new WebSocketHandshake(false, $"no upgrade within {_timeout.TotalSeconds:0} s"); + return new Attempt(new WebSocketHandshake(false, $"no upgrade within {_timeout.TotalSeconds:0} s"), null); } catch (Exception error) when (error is WebSocketException or HttpRequestException or IOException or SocketException) { - return new WebSocketHandshake( - false, - socket.HttpStatusCode != 0 ? $"HTTP {(int)socket.HttpStatusCode}" : error.Message); + var status = socket.HttpStatusCode != 0 ? (int?)socket.HttpStatusCode : null; + + return new Attempt( + new WebSocketHandshake(false, status is { } code ? $"HTTP {code}" : error.Message), + status); } + // ClientWebSocket refuses a choice that was not offered, so what is here is one of ours. + var chosen = socket.SubProtocol; + try { - await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, budget.Token).ConfigureAwait(false); + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, budget).ConfigureAwait(false); } catch (Exception error) when (error is WebSocketException or OperationCanceledException or IOException) { @@ -128,6 +182,6 @@ public async Task HandshakeAsync( socket.Abort(); } - return WebSocketHandshake.Upgraded; + return new Attempt(WebSocketHandshake.UpgradedWith(chosen), null); } } diff --git a/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs b/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs index 6e920786..335cbf52 100644 --- a/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs +++ b/src/MUI.Crawler/Crawl/WebSocketEndpointWriter.cs @@ -115,7 +115,8 @@ await endpoints.UpsertAsync( existing?.FirstSeenAt ?? now, now, EndpointState.Active, - address.Path), + address.Path, + handshake.SubProtocol), cancellationToken); return true; diff --git a/src/MUI.Web/Api/ApiMapper.cs b/src/MUI.Web/Api/ApiMapper.cs index 15f7d111..58b84ce2 100644 --- a/src/MUI.Web/Api/ApiMapper.cs +++ b/src/MUI.Web/Api/ApiMapper.cs @@ -193,7 +193,8 @@ public static CapabilityView Capability(CapabilityRow row, DateTimeOffset now) endpoint.FirstSeenAt, endpoint.LastSeenAt, endpoint.State, - endpoint.Path); + endpoint.Path, + endpoint.SubProtocol); public static FeedEntryView Feed(FeedEntry entry) => new( entry.Id, diff --git a/src/MUI.Web/Api/ApiModels.cs b/src/MUI.Web/Api/ApiModels.cs index 1f24169b..5383fb99 100644 --- a/src/MUI.Web/Api/ApiModels.cs +++ b/src/MUI.Web/Api/ApiModels.cs @@ -100,6 +100,11 @@ public enum PlayerCountState /// state is the catalogue's own word (active/stale/gone), not a threshold applied here, so this can't disagree with the page. /// telnet, tls or websocket; a wss:// endpoint is websocket with tlsMeasured. /// A WebSocket's request path, such as /ws-play/; absent for telnet. +/// +/// The WebSocket subprotocol the server chose when offered the mudstandards.org names +/// (telnet.mudstandards.org, terminal.mudstandards.org, …); absent when it chose none, which +/// is what a bare telnet bridge such as websockify does, and for telnet. +/// public sealed record EndpointView( string Host, int Port, @@ -108,7 +113,8 @@ public sealed record EndpointView( DateTimeOffset FirstSeenAt, DateTimeOffset LastSeenAt, string State, - string? Path = null); + string? Path = null, + string? SubProtocol = null); public sealed record ChangeView(DateTimeOffset At, string Summary); diff --git a/src/MUI.Web/Components/Pages/Game.razor b/src/MUI.Web/Components/Pages/Game.razor index 33666cc6..4e53f5f8 100644 --- a/src/MUI.Web/Components/Pages/Game.razor +++ b/src/MUI.Web/Components/Pages/Game.razor @@ -101,6 +101,11 @@ else { ● tls } + @* What a client must speak once connected: the server's own choice, a name, not prose. *@ + @if (e.SubProtocol is { } subProtocol) + { + @subProtocol + } @if (e.IsCurrent) { @L("game.answeringSince", ("date", Dates.Absolute(Http.LocaleOf().Tag, e.FirstSeenAt))) diff --git a/src/MUI.Web/Fixtures/FixtureGameQueries.cs b/src/MUI.Web/Fixtures/FixtureGameQueries.cs index 132f5aa4..07c3f0b6 100644 --- a/src/MUI.Web/Fixtures/FixtureGameQueries.cs +++ b/src/MUI.Web/Fixtures/FixtureGameQueries.cs @@ -422,7 +422,7 @@ public Task> ForGameAsync( Endpoint("ashen.example", 4000, "tls", tls: true, sinceDays: 600), // A WebSocket the game declared in MSSP and that upgraded (migration 0045). - Endpoint("ashen.example", 443, "websocket", tls: true, sinceDays: 30, path: "/play/"), + Endpoint("ashen.example", 443, "websocket", tls: true, sinceDays: 30, path: "/play/", subProtocol: "telnet.mudstandards.org"), ], "hollow-bell" => [Endpoint("hollowbell.example", 4201, "telnet", tls: false, sinceDays: 2400)], "gaslight-row" => [Endpoint("gaslight.example", 4201, "telnet", tls: false, sinceDays: 3000)], @@ -432,7 +432,7 @@ public Task> ForGameAsync( /// How long ago we last reached it, for an address the game has left. private static GameEndpointView Endpoint( - string host, int port, string kind, bool tls, int sinceDays, int? goneDays = null, string? path = null) => new( + string host, int port, string kind, bool tls, int sinceDays, int? goneDays = null, string? path = null, string? subProtocol = null) => new( host, port, kind, @@ -440,7 +440,8 @@ private static GameEndpointView Endpoint( Now.AddDays(-sinceDays), goneDays is { } left ? Now.AddDays(-left) : Now, goneDays is null ? "active" : "gone", - path); + path, + subProtocol); private static string? Screen(GameSummary g) => g.Slug switch { diff --git a/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs b/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs index c20d5b0f..215158e4 100644 --- a/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs +++ b/tests/MUI.Catalog.Tests/Persistence/Queries/GameQueriesPostgresTests.cs @@ -957,7 +957,7 @@ public async Task AWebSocketEndpointIsShownWithItsPathAndWhetherItIsSecure() var endpoints = new NpgsqlEndpointStore(db.DataSource); await endpoints.UpsertAsync(new GameEndpoint( - game, "mume.org", 443, EndpointKind.SecureWebSocket, Now, Now, EndpointState.Active, "/ws-play/")); + game, "mume.org", 443, EndpointKind.SecureWebSocket, Now, Now, EndpointState.Active, "/ws-play/", "telnet.mudstandards.org")); await endpoints.UpsertAsync(new GameEndpoint( game, "mume.org", 8080, EndpointKind.WebSocket, Now, Now, EndpointState.Active, "/")); @@ -970,6 +970,8 @@ await endpoints.UpsertAsync(new GameEndpoint( await Assert.That(secure.TlsMeasured).IsTrue(); await Assert.That(secure.Path).IsEqualTo("/ws-play/"); await Assert.That(secure.Url).IsEqualTo("wss://mume.org:443/ws-play/"); + await Assert.That(secure.SubProtocol).IsEqualTo("telnet.mudstandards.org"); + await Assert.That(plain.SubProtocol).IsNull(); await Assert.That(plain.TlsMeasured).IsFalse(); await Assert.That(plain.Url).IsEqualTo("ws://mume.org:8080/"); } @@ -992,6 +994,21 @@ await Assert.That(async () => await endpoints.UpsertAsync(new GameEndpoint( .Throws(); } + [Test] + public async Task OnlyAWebSocketEndpointCarriesASubprotocolAndItIsAToken() + { + await using var db = await PostgresFixture.MigratedAsync(); + var game = await Seed.GameAsync(db); + var endpoints = new NpgsqlEndpointStore(db.DataSource); + + await Assert.That(async () => await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 4242, EndpointKind.Telnet, Now, Now, EndpointState.Active, null, "telnet.mudstandards.org"))) + .Throws(); + await Assert.That(async () => await endpoints.UpsertAsync(new GameEndpoint( + game, "mume.org", 443, EndpointKind.SecureWebSocket, Now, Now, EndpointState.Active, "/", "two words"))) + .Throws(); + } + private static ActivityCell Cell(IReadOnlyList cells, DateTimeOffset at) => cells.Single(c => c.DayOfWeek == (int)at.UtcDateTime.DayOfWeek && c.Hour == at.UtcDateTime.Hour); diff --git a/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs b/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs index def8553d..23705361 100644 --- a/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs +++ b/tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs @@ -11,7 +11,7 @@ public class WebSocketProbeTests [Test] public async Task ABridgeThatRefusesUnknownSubprotocolsUpgradesTheProbe() { - // websockify answers 400 to a subprotocol it does not know; the probe offers none. + // websockify answers 400 to a subprotocol it does not know; the probe asks again offering none. await using var bridge = Bridge.Start(refuseAnyOffer: true); var handshake = await new WebSocketProbe().HandshakeAsync( @@ -19,8 +19,40 @@ public async Task ABridgeThatRefusesUnknownSubprotocolsUpgradesTheProbe() [IPAddress.Loopback]); await Assert.That(handshake.Answered).IsTrue(); + await Assert.That(handshake.SubProtocol).IsNull(); await Assert.That(bridge.Paths).Contains("/ws/telnet/"); - await Assert.That(bridge.Offers).Contains((string?)null); + await Assert.That(bridge.Offers.Count).IsEqualTo(2); + await Assert.That(bridge.Offers[0]).IsEqualTo(string.Join(", ", WebSocketProbe.Offered)); + await Assert.That(bridge.Offers[1]).IsNull(); + } + + [Test] + public async Task TheSubprotocolTheServerChoseIsReported() + { + // Evennia 6.1 chooses terminal.mudstandards.org from the offer and never telnet. + await using var bridge = Bridge.Start(choose: "terminal.mudstandards.org"); + + var handshake = await new WebSocketProbe().HandshakeAsync( + new WebSocketAddress("localhost", bridge.Port, false, "/"), + [IPAddress.Loopback]); + + await Assert.That(handshake.Answered).IsTrue(); + await Assert.That(handshake.SubProtocol).IsEqualTo("terminal.mudstandards.org"); + await Assert.That(bridge.Offers.Count).IsEqualTo(1); + } + + [Test] + public async Task AServerThatIgnoresTheOfferUpgradesWithNoSubprotocolAtOnce() + { + await using var bridge = Bridge.Start(); + + var handshake = await new WebSocketProbe().HandshakeAsync( + new WebSocketAddress("localhost", bridge.Port, false, "/"), + [IPAddress.Loopback]); + + await Assert.That(handshake.Answered).IsTrue(); + await Assert.That(handshake.SubProtocol).IsNull(); + await Assert.That(bridge.Offers.Count).IsEqualTo(1); } [Test] @@ -34,6 +66,7 @@ public async Task ARefusedUpgradeSaysItsStatus() await Assert.That(handshake.Answered).IsFalse(); await Assert.That(handshake.Detail).IsEqualTo("HTTP 400"); + await Assert.That(bridge.Offers.Count).IsEqualTo(2); } [Test] @@ -78,10 +111,10 @@ private sealed class Bridge : IAsyncDisposable private readonly CancellationTokenSource _stop = new(); private readonly Task _loop; - private Bridge(TcpListener listener, bool refuseAnyOffer, bool refuseEverything) + private Bridge(TcpListener listener, bool refuseAnyOffer, bool refuseEverything, string? choose) { _listener = listener; - _loop = Task.Run(() => AcceptAsync(refuseAnyOffer, refuseEverything)); + _loop = Task.Run(() => AcceptAsync(refuseAnyOffer, refuseEverything, choose)); } public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port; @@ -90,14 +123,14 @@ private Bridge(TcpListener listener, bool refuseAnyOffer, bool refuseEverything) public List Offers { get; } = []; - public static Bridge Start(bool refuseAnyOffer = false, bool refuseEverything = false) + public static Bridge Start(bool refuseAnyOffer = false, bool refuseEverything = false, string? choose = null) { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); - return new Bridge(listener, refuseAnyOffer, refuseEverything); + return new Bridge(listener, refuseAnyOffer, refuseEverything, choose); } - private async Task AcceptAsync(bool refuseAnyOffer, bool refuseEverything) + private async Task AcceptAsync(bool refuseAnyOffer, bool refuseEverything, string? choose) { while (!_stop.IsCancellationRequested) { @@ -140,8 +173,12 @@ private async Task AcceptAsync(bool refuseAnyOffer, bool refuseEverything) { var accept = Convert.ToBase64String(SHA1.HashData(Encoding.ASCII.GetBytes( Header("Sec-WebSocket-Key") + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))); + var chosen = choose is not null && offer is not null + && offer.Split(',').Select(o => o.Trim()).Contains(choose, StringComparer.Ordinal) + ? $"Sec-WebSocket-Protocol: {choose}\r\n" + : string.Empty; response = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" - + $"Sec-WebSocket-Accept: {accept}\r\n\r\n"; + + $"Sec-WebSocket-Accept: {accept}\r\n{chosen}\r\n"; } await stream.WriteAsync(Encoding.ASCII.GetBytes(response)); diff --git a/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs b/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs index 97f4b9ff..a9dd0b07 100644 --- a/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs +++ b/tests/MUI.Crawler.Tests/Crawl/WebSocketEndpointPostgresTests.cs @@ -26,7 +26,7 @@ public class WebSocketEndpointPostgresTests mssp: Probes.Mssp(("NAME", "Multi-Users in Middle-earth"), ("WEBSOCKET", value)), banner: "Welcome to MUME")); - private sealed class Handshakes(bool answer) : IWebSocketProbe + private sealed class Handshakes(bool answer, string? subProtocol = null) : IWebSocketProbe { public ConcurrentQueue<(WebSocketAddress Address, IReadOnlyList Addresses)> Asked { get; } = []; @@ -36,7 +36,7 @@ public Task HandshakeAsync( CancellationToken cancellationToken = default) { Asked.Enqueue((address, addresses)); - return Task.FromResult(answer ? WebSocketHandshake.Upgraded : new WebSocketHandshake(false, "HTTP 502")); + return Task.FromResult(answer ? WebSocketHandshake.UpgradedWith(subProtocol) : new WebSocketHandshake(false, "HTTP 502")); } } @@ -71,6 +71,27 @@ await Assert.That(await connection.ExecuteScalarAsync( await Assert.That(handshakes.Asked.Single().Addresses.Single()).IsEqualTo(IPAddress.Parse("198.51.100.7")); } + [Test] + public async Task TheSubprotocolTheServerChoseIsKeptWithTheEndpoint() + { + await using var database = await PostgresFixture.MigratedAsync(); + var source = database.DataSource; + + await CrawlCycles.SeedAsync(source, new CrawlSeed("mume.org", 4242)); + + await CrawlCycles.Build( + source, Declaring("wss://mume.org/ws-play/"), TimeProvider.System, + options: CrawlCycles.Confirming(), + webSockets: new Handshakes(answer: true, subProtocol: "terminal.mudstandards.org")) + .RunAsync(); + + await using var connection = await source.OpenConnectionAsync(); + + await Assert.That(await connection.ExecuteScalarAsync( + "SELECT subprotocol FROM game_endpoint WHERE host = 'mume.org' AND port = 443")) + .IsEqualTo("terminal.mudstandards.org"); + } + [Test] public async Task AnAddressThatDidNotUpgradeLeavesNothing() { diff --git a/tests/MUI.Web.Tests/Api/GameApiTests.cs b/tests/MUI.Web.Tests/Api/GameApiTests.cs index 275ff31e..0663124e 100644 --- a/tests/MUI.Web.Tests/Api/GameApiTests.cs +++ b/tests/MUI.Web.Tests/Api/GameApiTests.cs @@ -143,7 +143,9 @@ public async Task AWebSocketEndpointCarriesItsPathAndATelnetOneCarriesNone() await Assert.That(socket.GetProperty("path").GetString()).IsEqualTo("/play/"); await Assert.That(socket.GetProperty("tlsMeasured").GetBoolean()).IsTrue(); + await Assert.That(socket.GetProperty("subProtocol").GetString()).IsEqualTo("telnet.mudstandards.org"); await Assert.That(telnet.GetProperty("path").ValueKind).IsEqualTo(System.Text.Json.JsonValueKind.Null); + await Assert.That(telnet.GetProperty("subProtocol").ValueKind).IsEqualTo(System.Text.Json.JsonValueKind.Null); } /// A suppressed screen is withheld here as well as on the page (spec §11).