diff --git a/Directory.Packages.props b/Directory.Packages.props index fb24880..5fc4955 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -19,7 +19,7 @@ - + diff --git a/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs b/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs index c7d10e9..b9334e1 100644 --- a/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs +++ b/src/SharpMUTerm.Core/Transport/WebSocketTransport.cs @@ -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; @@ -10,6 +13,9 @@ namespace SharpMUTerm.Core.Transport; /// 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. +/// 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 uses, and the endpoint reached is the one +/// names (through a proxy, that is the proxy). /// public sealed class WebSocketTransport(ConnectionOptions options) : ITransport { @@ -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; @@ -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})"; } /// @@ -114,5 +147,7 @@ public async ValueTask DisposeAsync() await CloseAsync().ConfigureAwait(false); _socket?.Dispose(); _socket = null; + _invoker?.Dispose(); + _invoker = null; } } diff --git a/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs b/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs index 39c9305..2120922 100644 --- a/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs +++ b/tests/SharpMUTerm.Core.Tests/Transport/WebSocketWorldTests.cs @@ -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() {