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 @@ -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.5" />
<PackageVersion Include="TelnetNegotiationCore" Version="4.13.6" />

<!-- The version, from the git tag (see Directory.Build.props). Build-time only. -->
<PackageVersion Include="MinVer" Version="8.0.0" />
Expand Down
45 changes: 40 additions & 5 deletions src/SharpMUTerm.Core/Transport/WebSocketTransport.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Net.WebSockets;
using TelnetNegotiationCore.Connections;
using TelnetNegotiationCore.WebSockets;
Expand All @@ -10,6 +13,9 @@ namespace SharpMUTerm.Core.Transport;
/// <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.
/// The handshake runs through a handler of this transport's own, so the socket is dialled with no delay, the
/// certificate is checked by the same rule <see cref="TcpTransport"/> uses, and the endpoint reached is the one
/// <see cref="RemoteDescription"/> names (through a proxy, that is the proxy).
/// </summary>
public sealed class WebSocketTransport(ConnectionOptions options) : ITransport
{
Expand All @@ -18,6 +24,7 @@ public sealed class WebSocketTransport(ConnectionOptions options) : ITransport

private readonly ConnectionOptions _options = options ?? throw new ArgumentNullException(nameof(options));
private ClientWebSocket? _socket;
private HttpMessageInvoker? _invoker;

public bool IsConnected => _socket?.State == WebSocketState.Open;

Expand All @@ -38,20 +45,46 @@ public async Task ConnectAsync(CancellationToken cancellationToken = default)
var address = new Uri(WebSocketAddress.Format(_options.Host, _options.Port, _options.UseTls, _options.WebSocketPath!));
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(_options.ConnectTimeout);
EndPoint? reached = null;
var handler = new SocketsHttpHandler
{
// A redirect is a second address nobody configured.
AllowAutoRedirect = false,
UseCookies = false,
ConnectCallback = async (context, token) =>
{
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
{
await socket.ConnectAsync(context.DnsEndPoint, token).ConfigureAwait(false);
// A dual-mode socket reports an IPv4 peer as ::ffff:a.b.c.d; say it as the address it is.
reached = socket.RemoteEndPoint is IPEndPoint { Address.IsIPv4MappedToIPv6: true } mapped
? new IPEndPoint(mapped.Address.MapToIPv4(), mapped.Port)
: socket.RemoteEndPoint;
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
},
};
handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, errors) =>
errors == System.Net.Security.SslPolicyErrors.None || _options.AllowInvalidCertificates;
_invoker = new HttpMessageInvoker(handler);
_socket = await TelnetWebSocketClient.ConnectAsync(
address,
_invoker,
socket =>
{
// A quiet connection behind a proxy is kept open, and one that stops answering is noticed.
socket.KeepAliveInterval = PingInterval(_options.KeepaliveInterval);
socket.KeepAliveTimeout = TimeSpan.FromSeconds(30);
if (_options.AllowInvalidCertificates)
{
socket.RemoteCertificateValidationCallback = static (_, _, _, _) => true;
}
},
bridges: null,
timeout.Token).ConfigureAwait(false);
RemoteDescription = address.ToString();
RemoteDescription = reached is null ? address.ToString() : $"{address} ({reached})";
}

/// <summary>
Expand Down Expand Up @@ -114,5 +147,7 @@ public async ValueTask DisposeAsync()
await CloseAsync().ConfigureAwait(false);
_socket?.Dispose();
_socket = null;
_invoker?.Dispose();
_invoker = null;
}
}
12 changes: 12 additions & 0 deletions tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ public async Task AnEvenniaGameIsReachedOverGmcpWithNoTelnetByteSent()
await Assert.That(Encoding.UTF8.GetString(server.Received)).IsEqualTo("look\r\n");
}

[Test]
public async Task TheTransportSaysWhichEndpointTheHandshakeReached()
{
await using var server = await WebSocketServer.StartAsync();
await using var transport = new WebSocketTransport(new ConnectionOptions { Host = "127.0.0.1", Port = server.Port, WebSocketPath = "/ws" });

await transport.ConnectAsync();

await Assert.That(transport.IsConnected).IsTrue();
await Assert.That(transport.RemoteDescription).IsEqualTo($"ws://127.0.0.1:{server.Port}/ws (127.0.0.1:{server.Port})");
}

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