Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions migrations/0045_websocket_endpoint.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
-- 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;

-- 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;

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));

-- 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));
24 changes: 23 additions & 1 deletion src/MUI.Catalog/Games/Views.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,17 +264,39 @@ 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.
/// </remarks>
/// <param name="Kind">
/// <c>telnet</c>, <c>tls</c> or <c>websocket</c>. A WebSocket behind TLS is <c>websocket</c> with
/// <paramref name="TlsMeasured"/> set, the way a telnet one is <c>tls</c>.
/// </param>
/// <param name="Path">A WebSocket's request path (<c>/ws-play/</c>); null for every other kind.</param>
/// <param name="SubProtocol">
/// The subprotocol a WebSocket's server chose when offered the mudstandards.org names; null when it
/// chose none, and for every other kind.
/// </param>
public sealed record GameEndpointView(
string Host,
int Port,
string Kind,
bool TlsMeasured,
DateTimeOffset FirstSeenAt,
DateTimeOffset LastSeenAt,
string State)
string State,
string? Path = null,
string? SubProtocol = null)
{
/// <summary>Whether we still reach the game here.</summary>
public bool IsCurrent => string.Equals(State, "active", StringComparison.Ordinal);

/// <summary>Whether this is a WebSocket, which a telnet client cannot open.</summary>
public bool IsWebSocket => string.Equals(Kind, "websocket", StringComparison.Ordinal);

/// <summary>
/// The URL a WebSocket client dials (<c>wss://mume.org:443/ws-play/</c>), or null for a telnet endpoint.
/// The port is always written: the catalogue measured it, and leaving the default implied is a guess.
/// </summary>
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);
Expand Down
16 changes: 12 additions & 4 deletions src/MUI.Catalog/Persistence/Games/NpgsqlEndpointStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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, subprotocol AS SubProtocol
""";

public async Task<IReadOnlyList<GameEndpoint>> ForGameAsync(
Expand Down Expand Up @@ -99,10 +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)
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, 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
""",
Expand All @@ -115,6 +117,8 @@ ON CONFLICT (game_id, host, port) DO UPDATE
firstSeenAt = endpoint.FirstSeenAt.ToUniversalTime(),
lastSeenAt = endpoint.LastSeenAt.ToUniversalTime(),
state = SqlEnums.ToDb(endpoint.State),
path = endpoint.Path,
subprotocol = endpoint.SubProtocol,
},
cancellationToken: cancellationToken));
}
Expand All @@ -135,8 +139,12 @@ private sealed class Row

public string State { get; init; } = string.Empty;

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));
SqlEnums.ToEndpointState(State), Path, SubProtocol);
}
}
25 changes: 24 additions & 1 deletion src/MUI.Catalog/Persistence/Games/Records.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,16 @@ public enum EndpointKind
{
Telnet,
Tls,

/// <summary>A WebSocket (<c>ws://</c>) carrying telnet. Always has a <see cref="GameEndpoint.Path"/>.</summary>
WebSocket,

/// <summary>
/// A WebSocket behind TLS (<c>wss://</c>): the handshake completed, as <see cref="Tls"/> means for telnet.
/// Always has a <see cref="GameEndpoint.Path"/>.
/// </summary>
SecureWebSocket,

Http,
}

Expand All @@ -69,14 +78,28 @@ public enum EndpointState
}

/// <summary>An address a game answers on (spec §5.5).</summary>
/// <param name="Path">
/// The request path of a WebSocket endpoint (<c>/ws-play/</c>), and null for every other kind: migration 0045's
/// CHECK holds the two together.
/// </param>
/// <param name="SubProtocol">
/// The WebSocket subprotocol the server chose (<c>terminal.mudstandards.org</c>), or null when it chose
/// none; always null for a non-WebSocket kind.
/// </param>
public sealed record GameEndpoint(
Guid GameId,
string Host,
int Port,
EndpointKind Kind,
DateTimeOffset FirstSeenAt,
DateTimeOffset LastSeenAt,
EndpointState State);
EndpointState State,
string? Path = null,
string? SubProtocol = null)
{
/// <summary>Whether this is a WebSocket, behind TLS or not.</summary>
public bool IsWebSocket => Kind is EndpointKind.WebSocket or EndpointKind.SecureWebSocket;
}

/// <summary>
/// Who measured an availability interval.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,15 @@ private async Task<GamePage> 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,
e.SubProtocol))
.ToList(),
ConnectScreen: Winner(fields, InternalFields.ConnectScreen)?.Value,
ConnectScreenSuppressed: string.Equals(
Expand Down
2 changes: 2 additions & 0 deletions src/MUI.Catalog/Persistence/SqlEnums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};
Expand All @@ -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)),
};
Expand Down
129 changes: 129 additions & 0 deletions src/MUI.Crawl/WebSocket/WebSocketAddress.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
namespace MUI.Crawl;

/// <summary>
/// One WebSocket address a game declared in its MSSP <c>WEBSOCKET</c> variable.
/// </summary>
/// <remarks>
/// A declaration, not a measurement: nothing here says the address answers. It becomes a fact about
/// the game only once <see cref="IWebSocketProbe"/> has completed a handshake there (rule 1).
/// </remarks>
/// <param name="Host">The host, lower-cased, IPv6 without brackets.</param>
/// <param name="Port">The port, the scheme's default where the URL named none.</param>
/// <param name="Tls">True for <c>wss</c>.</param>
/// <param name="Path">The path and query, always starting with <c>/</c>.</param>
public sealed record WebSocketAddress(string Host, int Port, bool Tls, string Path)
{
/// <summary>The address as a URL, the port always written.</summary>
public Uri Uri => new(
$"{(Tls ? "wss" : "ws")}://{(Host.Contains(':', StringComparison.Ordinal) ? $"[{Host}]" : Host)}:{Port}{Path}");
}

/// <summary>
/// Reads the MSSP <c>WEBSOCKET</c> variable: one or more <c>ws://</c> or <c>wss://</c> URLs.
/// </summary>
/// <remarks>
/// <para>
/// 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 <see cref="MaxPathLength"/>. The same path
/// rule is the database's (migration 0045).
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
public static class WebSocketAddresses
{
/// <summary>The variable's name.</summary>
public const string Variable = "WEBSOCKET";

/// <summary>The longest path kept, the database's own limit.</summary>
public const int MaxPathLength = 256;

/// <summary>How many addresses one report may name. More than this is noise, not a game.</summary>
public const int MaxAddresses = 4;

/// <summary>Every address the report declares that this site would show, in order, once each.</summary>
public static IReadOnlyList<WebSocketAddress> From(IReadOnlyDictionary<string, IReadOnlyList<string>>? report)
{
if (report is null || !report.TryGetValue(Variable, out var values))
{
return [];
}

var found = new List<WebSocketAddress>();

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;
}

/// <summary>One URL, or null when it is not one this site would show.</summary>
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);
}
}
Loading
Loading