fix: Fixes TCPServer accept async, makes Firewall/IP Limiter multithreaded (#2134)

This commit is contained in:
Kamron Batman 2025-02-27 22:19:38 -08:00 • committed by GitHub
parent bcab91255a
commit 2a8c62e8be
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 578 additions and 215 deletions

View file

@ -13,15 +13,17 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Server.Logging;
using Server.Misc;
namespace Server.Network;
@ -35,8 +37,11 @@ public static class TcpServer
public static IPEndPoint[] ListeningAddresses { get; private set; }
public static Socket[] Listeners { get; private set; }
private static IPRateLimiter _ipRateLimiter;
public static void Start()
{
_ipRateLimiter = new IPRateLimiter(10, 10000, 1000, 2.0, 3_600_000, Core.ClosingTokenSource.Token);
HashSet<IPEndPoint> listeningAddresses = [];
List<Socket> listeners = [];
foreach (var ipep in ServerConfiguration.Listeners)
@ -123,49 +128,92 @@ public static class TcpServer
return null;
}
private static async void BeginAcceptingSockets(Socket listener)
private static async ValueTask BeginAcceptingSockets(Socket listener)
{
while (!Core.Closing)
{
Socket socket = null;
try
{
socket = await listener.AcceptAsync();
var socket = await listener.AcceptAsync(Core.ClosingTokenSource.Token);
var remoteIP = ((IPEndPoint)socket.RemoteEndPoint)!.Address;
if (!IPLimiter.Verify(remoteIP))
if (!_ipRateLimiter.Verify(remoteIP, out var totalAttempts))
{
TraceDisconnect("Past IP limit threshold", remoteIP);
logger.Debug("{Address} Past IP limit threshold", remoteIP);
logger.Debug("{Address} Past IP limit threshold ({TotalAttempts})", remoteIP, totalAttempts);
}
else if (Firewall.IsBlocked(remoteIP))
{
TraceDisconnect("Firewalled", remoteIP);
logger.Debug("{Address} Firewalled", remoteIP);
}
else
{
var args = new SocketConnectEventArgs(socket);
EventSink.InvokeSocketConnect(args);
if (args.AllowConnection)
{
_ = new NetState(socket);
continue;
}
TraceDisconnect("Rejected by socket event handler", remoteIP);
// Reject the connection
socket.Send(_socketRejected, SocketFlags.None);
_ = Task.Run(() => ProcessSocketConnection(socket), Core.ClosingTokenSource.Token);
}
CloseSocket(socket);
}
catch
{
// ignored
}
}
}
private static async ValueTask ProcessSocketConnection(Socket socket)
{
byte[] firstBytes = ArrayPool<byte>.Shared.Rent(83);
var cts = CancellationTokenSource.CreateLinkedTokenSource(Core.ClosingTokenSource.Token);
cts.CancelAfter(TimeSpan.FromMilliseconds(500));
try
{
var bytesRead = await socket.ReceiveAsync(firstBytes, SocketFlags.Peek, cts.Token);
var isValid =
// Older clients only send the 4 byte seed first
(UOClient.MinRequired == null || UOClient.MinRequired < ClientVersion.Version6050) && bytesRead == 4 ||
(UOClient.MaxRequired == null || UOClient.MaxRequired >= ClientVersion.Version6050) && (
// Account Login - 0xEF + 0x80 (83 bytes)
bytesRead >= 83 && firstBytes[0] == 0xEF && firstBytes[21] == 0x80 ||
// Game Login - 4 bytes + 0x91 (69 bytes)
firstBytes[4] == 0x91 && bytesRead >= 69
);
// TODO: Validate client version is v4 -> v7 for 0xEF packet
// TODO: Validate Account Login seed matches Game Login seed
// TODO: Validate AuthId for 0x91 packet
// TODO: Validate username is ascii and not empty
// TODO: Validate password is ascii and not empty
if (isValid)
{
var args = new SocketConnectEventArgs(socket);
EventSink.InvokeSocketConnect(args);
if (args.AllowConnection)
{
Core.LoopContext.Post(() => _ = new NetState(socket), EventLoopContext.Priority.High);
return;
}
logger.Debug("{Address} Rejected by socket handler", ((IPEndPoint)socket.RemoteEndPoint)!.Address);
cts.TryReset();
cts.CancelAfter(TimeSpan.FromMilliseconds(500));
await socket.SendAsync(_socketRejected, SocketFlags.None, cts.Token);
CloseSocket(socket);
}
else
{
ForceCloseSocket(socket);
}
}
catch
{
ForceCloseSocket(socket);
}
finally
{
ArrayPool<byte>.Shared.Return(firstBytes);
cts.Dispose();
}
}
@ -182,22 +230,16 @@ public static class TcpServer
}
}
private static void TraceDisconnect(string reason, IPAddress ip)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ForceCloseSocket(Socket socket)
{
try
{
using StreamWriter op = new StreamWriter("network-socket-disconnects.log", true);
op.WriteLine($"# {Core.Now}");
op.WriteLine($"Address: {ip}");
op.WriteLine(reason);
op.WriteLine();
op.WriteLine();
socket.Disconnect(false);
}
catch
finally
{
// ignored
socket.Close(0);
}
}
}