diff --git a/CHANGELOG.md b/CHANGELOG.md index e8a6a3f1..e29d603b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,10 +14,14 @@ and a release's notes are its section. The procedure is in [`docs/RELEASING.md`] and F5 has a *websocket path* field: blank keeps the world on plain telnet. Everything else (triggers, GMCP, MXP, logging) works the same over either. +- Evennia games can be reached over their WebSocket. Evennia speaks no telnet there, so the connection used to close + at once with no reason given; it now uses Evennia's GMCP channel, so the game's text, colours and GMCP data (the + status meters, game data, Lua's `gmcp.get`) all arrive. Window size, terminal type and MXP are not available over it. + ### Changed -- Updated TelnetNegotiationCore to 4.13.3, MarkupString to 2.31.3 and Microsoft.Extensions.Logging.Abstractions to - 11.0.0 (which 4.13.3 needs). The connection is now read by the telnet library itself, which is what lets a world be +- Updated TelnetNegotiationCore to 4.13.5, MarkupString to 2.31.3 and Microsoft.Extensions.Logging.Abstractions to + 11.0.0 (which it needs). The connection is now read by the telnet library itself, which is what lets a world be reached over a WebSocket; a telnet world behaves as before. ## [0.3.5] - 2026-11-15 diff --git a/CLAUDE.md b/CLAUDE.md index 202c8223..c1d327e0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3578,7 +3578,10 @@ markup (`[bold #rrggbb on #rrggbb]…[/]`, `[[`/`]]` escaping, `[link=url]…[/] - **WebSocket worlds** (`WorldDefinition.WebSocketPath`, null = telnet; `WebSocketTransport`, `WebSocketAddress`, Core; F5 ▸ `websocket path`; `/connect ws://…|wss://…`; Browse lists mu*index's `websocket` endpoints, `wss` where TLS was measured, at the endpoint's optional `path`, else `/`). Dialled through `TelnetWebSocketClient` - (subprotocols `telnet.mudstandards.org`, then `telnet`), binary frames, telnet inside unchanged. A path is + (offers `telnet.mudstandards.org`, `telnet`, then `gmcp.mudstandards.org`, `terminal.mudstandards.org`) and run by + `TelnetTransport.WebSocketClient`: telnet inside unchanged, or on gmcp/terminal TNC's bridge (text in BINARY, GMCP + in TEXT, opened as if the server sent `WILL GMCP`, every telnet byte we write dropped). Evennia offers no telnet and + lands on gmcp, so no NAWS, TTYPE, CHARSET, echo, MSSP or MXP there. A path is refused, not tidied (`IsPath`: starts with `/`, ASCII address characters, 256 at most); an address with user information or a fragment is refused. A `telnet://` link never matches a WebSocket world. - **Never pin a version that is not on nuget.org, and never work around it with a local feed.** A diff --git a/Directory.Packages.props b/Directory.Packages.props index 7271e221..fb248806 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -19,7 +19,7 @@ - + diff --git a/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs b/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs index d8c912f4..bfa2014a 100644 --- a/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs +++ b/src/SharpMUTerm.Core/Configuration/WorldDefinition.cs @@ -353,5 +353,6 @@ public sealed class WorldDefinition UseTls = UseTls, AllowInvalidCertificates = AllowInvalidCertificates, WebSocketPath = WebSocketPath, + KeepaliveInterval = Telnet.TelnetSessionOptions.ResolveKeepalive(KeepaliveSeconds), }; } diff --git a/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs b/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs index 741f98a3..f76549cb 100644 --- a/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs +++ b/src/SharpMUTerm.Core/Transport/ConnectionOptions.cs @@ -24,6 +24,12 @@ public sealed class ConnectionOptions /// public string? WebSocketPath { get; init; } + /// + /// The world's keepalive, or null for none. A WebSocket pings at least this often: on gmcp and terminal the + /// telnet NOP that would otherwise keep a quiet connection open never reaches the server. + /// + public TimeSpan? KeepaliveInterval { get; init; } + /// SNI / certificate target host. Defaults to when null. public string? TlsTargetHost { get; init; } diff --git a/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs b/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs index f200a3c4..c7d10e95 100644 --- a/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs +++ b/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs @@ -6,13 +6,15 @@ namespace SharpMUTerm.Core.Transport; /// /// A world reached over a WebSocket (). TelnetNegotiationCore connects the -/// socket, offering telnet.mudstandards.org and then telnet, and its own transport runs the session over -/// it (), so the framing — one BINARY message per write, frames fed as they arrive, and the -/// Base64 variant — is the library's. +/// socket, offering telnet.mudstandards.org and telnet, then gmcp.mudstandards.org and +/// terminal.mudstandards.org, and its own transport runs the session over whichever the server picked +/// (). Evennia offers no telnet and picks gmcp: text and GMCP only, with no NAWS, TTYPE, +/// CHARSET, echo or MXP, and the library drops every telnet byte this client writes before it reaches the server. /// public sealed class WebSocketTransport(ConnectionOptions options) : ITransport { private static readonly TimeSpan CloseWait = TimeSpan.FromSeconds(2); + private static readonly TimeSpan DefaultPing = TimeSpan.FromSeconds(30); private readonly ConnectionOptions _options = options ?? throw new ArgumentNullException(nameof(options)); private ClientWebSocket? _socket; @@ -41,7 +43,7 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) socket => { // A quiet connection behind a proxy is kept open, and one that stops answering is noticed. - socket.KeepAliveInterval = TimeSpan.FromSeconds(30); + socket.KeepAliveInterval = PingInterval(_options.KeepaliveInterval); socket.KeepAliveTimeout = TimeSpan.FromSeconds(30); if (_options.AllowInvalidCertificates) { @@ -52,8 +54,15 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default) RemoteDescription = address.ToString(); } + /// + /// 30 seconds, or the world's keepalive when that is shorter: a ping is the only keepalive a gmcp or terminal + /// socket carries. + /// + public static TimeSpan PingInterval(TimeSpan? keepalive) => + keepalive is { } wanted && wanted < DefaultPing ? wanted : DefaultPing; + public ITelnetTransport ForTelnet(int receiveBufferSize) => - TelnetTransport.WebSocket(_socket ?? throw new InvalidOperationException("Transport is not connected.")); + TelnetTransport.WebSocketClient(_socket ?? throw new InvalidOperationException("Transport is not connected.")); public async ValueTask SendAsync(ReadOnlyMemory data, CancellationToken cancellationToken = default) { diff --git a/tests/SharpMUTerm.Avalonia.Tests/ListEditorTests.cs b/tests/SharpMUTerm.Avalonia.Tests/ListEditorTests.cs index 26725457..89fd1c8c 100644 --- a/tests/SharpMUTerm.Avalonia.Tests/ListEditorTests.cs +++ b/tests/SharpMUTerm.Avalonia.Tests/ListEditorTests.cs @@ -188,7 +188,7 @@ public async Task TheLiveTestListsTheMatchingLinesWithTheMatchMarked() await Assert.That(lines[0]).Contains("matches 2 of the last 3"); await Assert.That(lines.Skip(1).Count()).IsEqualTo(2); - await Assert.That(marked).All().Satisfy(m => m.StartsWith("You gain", StringComparison.Ordinal), m => m.IsTrue()); + await Assert.That(marked).All().Satisfy(m => m!.StartsWith("You gain", StringComparison.Ordinal), m => m.IsTrue()); } [Test] diff --git a/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs b/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs index e4d893f1..39c93054 100644 --- a/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs +++ b/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs @@ -41,6 +41,51 @@ public async Task AWorldWithAPathReadsAndWritesTelnetInsideAWebSocket() await Assert.That(server.SubProtocol).IsEqualTo("telnet.mudstandards.org"); } + [Test] + public async Task AnEvenniaGameIsReachedOverGmcpWithNoTelnetByteSent() + { + // Evennia offers no telnet subprotocol: it picks gmcp, sends text in BINARY frames and GMCP in TEXT frames. + await using var server = await WebSocketServer.StartAsync(pick: "gmcp.mudstandards.org"); + var world = new WorldDefinition { Name = "Synapse", Host = "127.0.0.1", Port = server.Port, WebSocketPath = "/ws" }; + await using var session = new WorldSession(world, null); + var lines = new List(); + session.LinePrinted += (_, line) => + { + lock (lines) + { + lines.Add(line.Text); + } + }; + + await session.ConnectAsync(); + // Evennia sends each message with no line ending; each is still a line of its own. + await server.SendAsync("Welcome, runner.\u001b[0m"); + await server.SendTextAsync("Char.Vitals {\"hp\":10,\"maxhp\":12}"); + await server.SendAsync("Type your name.\u001b[0m"); + await server.SendAsync("Name: "); + await Until(() => { lock (lines) { return lines.Contains("Welcome, runner.") && lines.Contains("Type your name."); } }); + await Until(() => session.GameData.GetText("Char.Vitals.hp") == "10"); + + // The client says hello once the server's choice reads as WILL GMCP, and never as a telnet byte. + await Until(() => server.Text.Any(t => t.StartsWith("Core.Hello ", StringComparison.Ordinal))); + await session.SendCommandAsync("look"); + await Until(() => Encoding.UTF8.GetString(server.Received).Contains("look\r\n", StringComparison.Ordinal)); + + await Assert.That(server.SubProtocol).IsEqualTo("gmcp.mudstandards.org"); + await Assert.That(server.Received).DoesNotContain((byte)0xFF); + await Assert.That(Encoding.UTF8.GetString(server.Received)).IsEqualTo("look\r\n"); + } + + [Test] + public async Task AWorldKeepaliveShorterThanTheDefaultPingSetsThePing() + { + var world = new WorldDefinition { Name = "W", Host = "example.org", Port = 443, WebSocketPath = "/ws", KeepaliveSeconds = 10 }; + + await Assert.That(WebSocketTransport.PingInterval(world.ToConnectionOptions().KeepaliveInterval)).IsEqualTo(TimeSpan.FromSeconds(10)); + await Assert.That(WebSocketTransport.PingInterval(TimeSpan.FromMinutes(5))).IsEqualTo(TimeSpan.FromSeconds(30)); + await Assert.That(WebSocketTransport.PingInterval(null)).IsEqualTo(TimeSpan.FromSeconds(30)); + } + [Test] public async Task AServerThatClosesTheSocketEndsTheConnection() { @@ -130,11 +175,14 @@ private sealed class WebSocketServer : IAsyncDisposable private readonly TaskCompletionSource _socket = new(TaskCreationOptions.RunContinuationsAsynchronously); private readonly Lock _gate = new(); private readonly List _received = []; + private readonly List _text = []; + private readonly string? _pick; private readonly CancellationTokenSource _cts = new(); - private WebSocketServer(int port) + private WebSocketServer(int port, string? pick) { Port = port; + _pick = pick; _listener.Prefixes.Add($"http://127.0.0.1:{port}/"); } @@ -155,14 +203,27 @@ public byte[] Received } } - public static Task StartAsync() + /// Text frames the client sent. + public string[] Text + { + get + { + lock (_gate) + { + return [.. _text]; + } + } + } + + /// The subprotocol to pick when the client offers it; the first offered otherwise. + public static Task StartAsync(string? pick = null) { var probe = new TcpListener(IPAddress.Loopback, 0); probe.Start(); var port = ((IPEndPoint)probe.LocalEndpoint).Port; probe.Stop(); - var server = new WebSocketServer(port); + var server = new WebSocketServer(port, pick); server._listener.Start(); _ = Task.Run(server.AcceptAsync); return Task.FromResult(server); @@ -174,6 +235,12 @@ public async Task SendAsync(string text) await socket.SendAsync(Encoding.ASCII.GetBytes(text), WebSocketMessageType.Binary, true, CancellationToken.None); } + public async Task SendTextAsync(string text) + { + var socket = await _socket.Task.WaitAsync(TimeSpan.FromSeconds(10)); + await socket.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, CancellationToken.None); + } + public async Task CloseAsync() { var socket = await _socket.Task.WaitAsync(TimeSpan.FromSeconds(10)); @@ -187,10 +254,12 @@ private async Task AcceptAsync() var context = await _listener.GetContextAsync(); Path = context.Request.Url?.PathAndQuery; var offered = context.Request.Headers["Sec-WebSocket-Protocol"] ?? string.Empty; - SubProtocol = offered.Split(',', StringSplitOptions.TrimEntries).FirstOrDefault(); + var names = offered.Split(',', StringSplitOptions.TrimEntries); + SubProtocol = _pick is not null && names.Contains(_pick) ? _pick : names.FirstOrDefault(); var accepted = await context.AcceptWebSocketAsync(SubProtocol); _socket.SetResult(accepted.WebSocket); var buffer = new byte[4096]; + var message = new List(); while (!_cts.IsCancellationRequested) { var result = await accepted.WebSocket.ReceiveAsync(buffer, _cts.Token); @@ -201,7 +270,19 @@ private async Task AcceptAsync() lock (_gate) { - _received.AddRange(buffer.AsSpan(0, result.Count)); + if (result.MessageType == WebSocketMessageType.Text) + { + message.AddRange(buffer.AsSpan(0, result.Count)); + if (result.EndOfMessage) + { + _text.Add(Encoding.UTF8.GetString([.. message])); + message.Clear(); + } + } + else + { + _received.AddRange(buffer.AsSpan(0, result.Count)); + } } } }