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
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
argue around. 4.13.4 reads a WebSocket server that picked gmcp or terminal rather than
telnet (Evennia) through a bridge, which ProbeLine offers.
-->
<PackageVersion Include="TelnetNegotiationCore" Version="4.13.5" />
<PackageVersion Include="TelnetNegotiationCore" Version="4.13.6" />
<PackageVersion Include="MarkupString.Ansi" Version="2.31.3" />

<!--
Expand Down
19 changes: 5 additions & 14 deletions src/MUI.Crawl/Telnet/ProbeLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ public async Task OpenAsync(ProbeTarget target, ProbeTransport transport, Cancel
/// server had offered it, so the session above reads the same either way.
/// </para>
/// <para>
/// That helper is not used directly because it resolves the name itself, and the scope guard's
/// ruling is on addresses (spec §7.2): the
/// <see cref="SocketsHttpHandler.ConnectCallback"/> here dials exactly the addresses the guard
/// vetted, the same as the TCP path.
/// The helper is handed an invoker of ours, because the scope guard's ruling is on addresses
/// (spec §7.2): the <see cref="SocketsHttpHandler.ConnectCallback"/> here dials exactly the
/// addresses the guard vetted, the same as the TCP path, and the helper's second dial (with no
/// subprotocol, after a server answers the first with an HTTP error) goes through it too.
/// </para>
/// <para>
/// The handler lives for one dial and is disposed with the line, so none of the DNS-pinning
Expand Down Expand Up @@ -138,16 +138,7 @@ private async Task OpenWebSocketAsync(ProbeTarget target, CancellationToken canc
},
disposeHandler: true);

_socket = new ClientWebSocket();
_socket.Options.AddSubProtocol(MudWebSocketSubprotocols.Telnet);
_socket.Options.AddSubProtocol(MudWebSocketSubprotocols.TelnetAlias);

foreach (var name in Bridges.Names)
{
_socket.Options.AddSubProtocol(name);
}

await _socket.ConnectAsync(uri, _invoker, cancellationToken);
_socket = await TelnetWebSocketClient.ConnectAsync(uri, _invoker, null, Bridges, cancellationToken);

// Throws ArgumentException for a server that picked a subprotocol that is neither telnet nor
// bridged. It cannot, having been offered only those, but if it does that is not a game this
Expand Down
135 changes: 67 additions & 68 deletions src/MUI.Crawl/WebSocket/WebSocketProbe.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using TelnetNegotiationCore.WebSockets;

namespace MUI.Crawl;

Expand Down Expand Up @@ -40,20 +41,24 @@ Task<WebSocketHandshake> HandshakeAsync(
/// </summary>
/// <remarks>
/// <para>
/// <b>The mudstandards.org names are offered first, then none.</b> Which one the server chooses is
/// the fact a client needs: Evennia 6.1 chooses <c>terminal.</c>, <c>gmcp.</c> or
/// <c>json.mudstandards.org</c> and never <c>telnet.</c>, 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 <c>telnet.mudstandards.org</c>, 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).
/// <b>TelnetNegotiationCore makes the handshake</b> (<see cref="TelnetWebSocketClient"/>), so the probe offers
/// exactly what a client built on it offers, in its order, and is refused exactly where such a client is. Which
/// one the server chooses is the fact a client needs: Evennia 6.1 chooses <c>terminal.</c>, <c>gmcp.</c> or
/// <c>json.mudstandards.org</c> and never <c>telnet.</c>, 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.
/// </para>
/// <para>
/// <b>An HTTP refusal of the offer is retried once with no offer</b>, by the library. The plain bridges are
/// strict: websockify answers 400 to a name it does not know, and MUME's Apache answers 502 to
/// <c>telnet.mudstandards.org</c>, while both accept a handshake that names none. An upgrade there is an
/// upgrade with no subprotocol — offering a name the bridge refuses must not become the game's failure
/// (rule 5). A failure with no HTTP answer (no route, a reset, the budget) is not retried.
/// </para>
/// <para>
/// <b>The socket goes to the addresses the scope gate ruled on</b>, never to a second lookup of the
/// name — <see cref="TelnetProbe"/>'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
/// name — <see cref="TelnetProbe"/>'s rule, and §7.2's. Both dials, the offer and the retry, go through
/// one invoker whose <c>ConnectCallback</c> dials those addresses. 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.
/// </para>
/// <para>
Expand All @@ -64,15 +69,22 @@ Task<WebSocketHandshake> HandshakeAsync(
public sealed class WebSocketProbe(TimeSpan? timeout = null) : IWebSocketProbe
{
/// <summary>
/// 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.
/// What the library offers after the telnet names: its bridged <c>gmcp.</c> and <c>terminal.</c>, then
/// <c>json.mudstandards.org</c>, which no client here speaks but which Evennia may choose.
/// </summary>
/// <remarks>The probe closes the socket at the upgrade, so no bridge is ever made.</remarks>
private static readonly WebSocketClientBridges Bridges = WebSocketClientBridges.Default
.Add("json.mudstandards.org", static () => throw new NotSupportedException("The probe runs no session."));

/// <summary>
/// The subprotocols offered, in the order a TelnetNegotiationCore client offers them: the telnet names
/// first, since that is what a MU* client already speaks, then the names the spec adds beside them.
/// </summary>
public static readonly IReadOnlyList<string> Offered =
[
"telnet.mudstandards.org",
"gmcp.mudstandards.org",
"terminal.mudstandards.org",
"json.mudstandards.org",
MudWebSocketSubprotocols.Telnet,
MudWebSocketSubprotocols.TelnetAlias,
.. Bridges.Names,
];

/// <summary>The whole handshake's budget, connect and TLS included.</summary>
Expand All @@ -96,31 +108,7 @@ public async Task<WebSocketHandshake> 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<Attempt> AttemptAsync(
WebSocketAddress address,
IReadOnlyList<IPAddress> addresses,
IReadOnlyList<string> subProtocols,
CancellationToken budget,
CancellationToken cancellationToken)
{
using var handler = new SocketsHttpHandler
var status = new LastStatus(new SocketsHttpHandler
{
UseProxy = false,
AllowAutoRedirect = false,
Expand All @@ -141,47 +129,58 @@ private async Task<Attempt> AttemptAsync(
throw;
}
},
};
});

using var invoker = new HttpMessageInvoker(handler);
using var socket = new ClientWebSocket();
socket.Options.CollectHttpResponseDetails = true;

foreach (var subProtocol in subProtocols)
{
socket.Options.AddSubProtocol(subProtocol);
}
using var invoker = new HttpMessageInvoker(status);
ClientWebSocket socket;

try
{
await socket.ConnectAsync(address.Uri, invoker, budget).ConfigureAwait(false);
socket = await TelnetWebSocketClient.ConnectAsync(address.Uri, invoker, null, Bridges, budget.Token)
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
return new Attempt(new WebSocketHandshake(false, $"no upgrade within {_timeout.TotalSeconds:0} s"), null);
return new WebSocketHandshake(false, $"no upgrade within {_timeout.TotalSeconds:0} s");
}
catch (Exception error) when (error is WebSocketException or HttpRequestException or IOException or SocketException)
{
var status = socket.HttpStatusCode != 0 ? (int?)socket.HttpStatusCode : null;

return new Attempt(
new WebSocketHandshake(false, status is { } code ? $"HTTP {code}" : error.Message),
status);
return new WebSocketHandshake(false, status.Code is { } code and not 101 ? $"HTTP {code}" : error.Message);
}

// ClientWebSocket refuses a choice that was not offered, so what is here is one of ours.
var chosen = socket.SubProtocol;

try
using (socket)
{
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, budget).ConfigureAwait(false);
// 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);
}
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.UpgradedWith(chosen);
}
catch (Exception error) when (error is WebSocketException or OperationCanceledException or IOException)
}

/// <summary>
/// Remembers the status of the last answer to an upgrade request, for the log line. The library disposes
/// a socket whose handshake failed, and its status with it.
/// </summary>
private sealed class LastStatus(HttpMessageHandler inner) : DelegatingHandler(inner)
{
public int? Code { get; private set; }

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// The upgrade is the measurement; how the close went is not.
socket.Abort();
Code = null;
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
Code = (int)response.StatusCode;
return response;
}

return new Attempt(WebSocketHandshake.UpgradedWith(chosen), null);
}
}
30 changes: 28 additions & 2 deletions tests/MUI.Crawl.Tests/Telnet/WebSocketTransportTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ public async Task AnUpgradeTheServerRefusesIsAFailedDial()
await Assert.That(result.Outcome).IsEqualTo(ProbeOutcome.Failed);
await Assert.That(result.Banner).IsNull();
await Assert.That(result.Transport).IsEqualTo(ProbeTransport.WebSocket);
// The retry with no subprotocol is TelnetNegotiationCore's, and it goes through the same
// vetted dial.
await Assert.That(game.Requests.Count).IsEqualTo(2);
await Assert.That(game.Requests[1].Count).IsEqualTo(0);
}

[Test]
Expand Down Expand Up @@ -236,6 +240,26 @@ public WebSocketGame()

public Exception? Fault { get; private set; }

/// <summary>The subprotocols each refused upgrade offered, in order (empty for no offer).</summary>
public List<IReadOnlyList<string>> Requests { get; } = [];

private const string NotFound = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";

/// <summary>
/// TelnetNegotiationCore dials once more, offering nothing, after an HTTP error; that one is
/// refused too.
/// </summary>
private async Task RefuseTheRetryAsync()
{
using var client = await _listener.AcceptTcpClientAsync(_stopping.Token);
var stream = client.GetStream();
var request = await ReadRequestAsync(stream);
var offer = request.Split("\r\n")
.FirstOrDefault(line => line.StartsWith("Sec-WebSocket-Protocol:", StringComparison.OrdinalIgnoreCase));
Requests.Add(offer is null ? [] : [.. offer.Split(':', 2)[1].Split(',', StringSplitOptions.TrimEntries)]);
await stream.WriteAsync(Encoding.ASCII.GetBytes(NotFound));
}

/// <summary>Every message a server with no telnet layer was sent.</summary>
public IReadOnlyList<byte[]> RawReceived
{
Expand Down Expand Up @@ -290,8 +314,10 @@ private async Task ServeAsync()

if (RefuseUpgrade)
{
await stream.WriteAsync(Encoding.ASCII.GetBytes(
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"));
Requests.Add(Offered);
await stream.WriteAsync(Encoding.ASCII.GetBytes(NotFound));
client.Dispose();
await RefuseTheRetryAsync();
return;
}

Expand Down
16 changes: 16 additions & 0 deletions tests/MUI.Crawl.Tests/WebSocket/WebSocketProbeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,22 @@ public async Task TheSocketGoesToTheRuledAddressNotToTheName()
await Assert.That(handshake.Answered).IsTrue();
}

[Test]
public async Task TheRetryWithNoOfferGoesToTheRuledAddressToo()
{
// The name does not resolve, and the bridge refuses the offer: the second dial upgrades only if it
// goes through the same ruled addresses as the first.
await using var bridge = Bridge.Start(refuseAnyOffer: true);

var handshake = await new WebSocketProbe().HandshakeAsync(
new WebSocketAddress("unresolvable.invalid", bridge.Port, false, "/"),
[IPAddress.Loopback]);

await Assert.That(handshake.Answered).IsTrue();
await Assert.That(bridge.Offers.Count).IsEqualTo(2);
await Assert.That(bridge.Offers[1]).IsNull();
}

[Test]
public async Task ASilentServerRunsOutOfBudget()
{
Expand Down
Loading