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
8 changes: 6 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<PackageVersion Include="MarkupString.Pueblo" Version="2.31.3" />

<!-- Telnet negotiation: TELOPT/NAWS/MTTS/EOR/CHARSET/MSSP/GMCP/MSDP/MCCP/MXP negotiation. -->
<PackageVersion Include="TelnetNegotiationCore" Version="4.13.3" />
<PackageVersion Include="TelnetNegotiationCore" Version="4.13.5" />

<!-- The version, from the git tag (see Directory.Build.props). Build-time only. -->
<PackageVersion Include="MinVer" Version="8.0.0" />
Expand Down
1 change: 1 addition & 0 deletions src/SharpMUTerm.Core/Configuration/WorldDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,5 +353,6 @@ public sealed class WorldDefinition
UseTls = UseTls,
AllowInvalidCertificates = AllowInvalidCertificates,
WebSocketPath = WebSocketPath,
KeepaliveInterval = Telnet.TelnetSessionOptions.ResolveKeepalive(KeepaliveSeconds),
};
}
6 changes: 6 additions & 0 deletions src/SharpMUTerm.Core/Transport/ConnectionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ public sealed class ConnectionOptions
/// </summary>
public string? WebSocketPath { get; init; }

/// <summary>
/// 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.
/// </summary>
public TimeSpan? KeepaliveInterval { get; init; }

/// <summary>SNI / certificate target host. Defaults to <see cref="Host"/> when null.</summary>
public string? TlsTargetHost { get; init; }

Expand Down
19 changes: 14 additions & 5 deletions src/SharpMUTerm.Core/Transport/WebSocketTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ namespace SharpMUTerm.Core.Transport;

/// <summary>
/// A world reached over a WebSocket (<see cref="ConnectionOptions.WebSocketPath"/>). TelnetNegotiationCore connects the
/// socket, offering <c>telnet.mudstandards.org</c> and then <c>telnet</c>, and its own transport runs the session over
/// it (<see cref="ForTelnet"/>), so the framing — one BINARY message per write, frames fed as they arrive, and the
/// Base64 variant — is the library's.
/// socket, offering <c>telnet.mudstandards.org</c> and <c>telnet</c>, then <c>gmcp.mudstandards.org</c> and
/// <c>terminal.mudstandards.org</c>, and its own transport runs the session over whichever the server picked
/// (<see cref="ForTelnet"/>). Evennia offers no telnet and picks <c>gmcp</c>: 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.
/// </summary>
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;
Expand Down Expand Up @@ -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)
{
Expand All @@ -52,8 +54,15 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
RemoteDescription = address.ToString();
}

/// <summary>
/// 30 seconds, or the world's keepalive when that is shorter: a ping is the only keepalive a gmcp or terminal
/// socket carries.
/// </summary>
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."));
Comment thread
HarryCordewener marked this conversation as resolved.
Resolved

public async ValueTask SendAsync(ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default)
{
Expand Down
2 changes: 1 addition & 1 deletion tests/SharpMUTerm.Avalonia.Tests/ListEditorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
91 changes: 86 additions & 5 deletions tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();
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()
{
Expand Down Expand Up @@ -130,11 +175,14 @@ private sealed class WebSocketServer : IAsyncDisposable
private readonly TaskCompletionSource<WebSocket> _socket = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Lock _gate = new();
private readonly List<byte> _received = [];
private readonly List<string> _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}/");
}

Expand All @@ -155,14 +203,27 @@ public byte[] Received
}
}

public static Task<WebSocketServer> StartAsync()
/// <summary>Text frames the client sent.</summary>
public string[] Text
{
get
{
lock (_gate)
{
return [.. _text];
}
}
}

/// <param name="pick">The subprotocol to pick when the client offers it; the first offered otherwise.</param>
public static Task<WebSocketServer> 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);
Expand All @@ -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));
Expand All @@ -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<byte>();
while (!_cts.IsCancellationRequested)
{
var result = await accepted.WebSocket.ReceiveAsync(buffer, _cts.Token);
Expand All @@ -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));
}
}
}
}
Expand Down
Loading