From b57233c618dc9f4ed0edce30757152dcafb2441d Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:10:32 +0100 Subject: [PATCH 1/6] Port ReplyServerChallenge and CheckIPConnectionReuse --- Source.Engine/Server/BaseServer.cs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/Source.Engine/Server/BaseServer.cs b/Source.Engine/Server/BaseServer.cs index a3e9ceff..0313b177 100644 --- a/Source.Engine/Server/BaseServer.cs +++ b/Source.Engine/Server/BaseServer.cs @@ -1374,8 +1374,24 @@ protected virtual bool CheckPassword(NetAddress adr, ReadOnlySpan password return false; } + const int MAX_REUSE_PER_IP = 5; + protected virtual bool CheckIPConnectionReuse(NetAddress adr) { - throw new NotImplementedException(); + int simultaneouslyConnections = 0; + + for (int i = 0; i < Clients.Count; i++) { + BaseClient client = Clients[i]; + + if (client.IsConnected() && !client.IsActive() && !client.IsFakeClient() && adr.CompareAdr(client.NetChannel.GetRemoteAddress(), true)) + simultaneouslyConnections++; + } + + if (simultaneouslyConnections > MAX_REUSE_PER_IP) { + Msg($"Too many connect packets from {adr}\n"); + return false; + } + + return true; } protected virtual void ReplyChallenge(NetAddress adr, int clientChallenge) { @@ -1403,7 +1419,15 @@ protected virtual void ReplyChallenge(NetAddress adr, int clientChallenge) { Net.SendPacket(null!, Socket, adr, msg.GetData(), msg.BytesWritten); } protected virtual void ReplyServerChallenge(NetAddress adr) { - throw new NotImplementedException(); + byte[] buffer = new byte[16]; + bf_write msg = new(buffer, buffer.Length); + + int challengeNr = GetChallengeNr(adr); + + msg.WriteLong(Protocol.CONNECTIONLESS_HEADER); + msg.WriteByte(S2C.Challenge); + msg.WriteLong(challengeNr); + Net.SendPacket(null!, Socket, adr, msg.GetData(), msg.BytesWritten); } protected virtual void CalculateCPUUsage() { From a460505940dd84a60254daa83441b59defb05750 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:10:32 +0100 Subject: [PATCH 2/6] Split long connectionless packets --- Source.Engine/Net.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Source.Engine/Net.cs b/Source.Engine/Net.cs index 01891162..4596af6d 100644 --- a/Source.Engine/Net.cs +++ b/Source.Engine/Net.cs @@ -1038,12 +1038,10 @@ public int SendPacket(NetChannel chan, NetSocketType sock, NetAddress? to, byte[ // simple case, small packet, just send it ret = SendTo(true, netSocket, data, length, addr, gameDataLength); } - else if (chan != null) { + else { // split packet into smaller pieces - ret = SendLong(chan, sock, netSocket, data, length, addr, maxRoutable); + ret = SendLong(chan!, sock, netSocket, data, length, addr, maxRoutable); } - else - ret = -1; end: if (ret == -1) { @@ -1065,6 +1063,14 @@ private int SendToImpl(Socket s, Span buf, int len, NetAddress to, int gam private readonly int net_splitrate = 1; + static readonly int[] SplitPacketSequenceNumber = CreateSplitPacketSequenceNumbers(); + + static int[] CreateSplitPacketSequenceNumbers() { + int[] numbers = new int[(int)NetSocketType.Max]; + numbers[0] = 1; + return numbers; + } + public unsafe int SendLong(NetChannel netchan, NetSocketType sock, Socket s, byte[] buf, int len, NetAddress to, int maxRoutable) { short splitSizeMinusHeader = (short)(maxRoutable - sizeof(SPLITPACKET)); @@ -1073,7 +1079,7 @@ public unsafe int SendLong(NetChannel netchan, NetSocketType sock, Socket s, byt sequenceNumber = netchan.IncrementSplitPacketSequence(); } else { - Debug.Assert(false, "FINISH THIS"); + sequenceNumber = Interlocked.Increment(ref SplitPacketSequenceNumber[(int)sock]); } int packetNumber = 0; From 30c2c2315479d5eb1ac68443748d959203f02cd1 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:10:32 +0100 Subject: [PATCH 3/6] Publish server rules and drop tag functions absent from GMod --- Source.Engine/Server/BaseServer.cs | 41 +++++++++++++++++------------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/Source.Engine/Server/BaseServer.cs b/Source.Engine/Server/BaseServer.cs index 0313b177..25229a7e 100644 --- a/Source.Engine/Server/BaseServer.cs +++ b/Source.Engine/Server/BaseServer.cs @@ -660,16 +660,13 @@ private void ServerNotifyVarChangeCallback(IConVar var, in ConVarChangeContext c private void SetMasterServerKeyValue(ISteamGameServer server, IConVar var) { if (var.IsFlagSet(FCvar.Protected)) { - if (var.GetString()[0] != '\0' && 0 != stricmp(var.GetString(), "none")) + if (var.GetString().Length != 0 && 0 != stricmp(var.GetString(), "none")) SteamGameServer.SetKeyValue(var.GetName(), "1"); else SteamGameServer.SetKeyValue(var.GetName(), "0"); } else SteamGameServer.SetKeyValue(var.GetName(), var.GetString()); - - if (Steam3Server().BIsActive()) - sv.RecalculateTags(); } public virtual void Clear() { @@ -1045,19 +1042,6 @@ public virtual bool CheckIPRestrictions(NetAddress adr, int nAuthProtocol) { public void SetMasterServerRulesDirty() { MasterServerRulesDirty = true; } - public void SendQueryPortToClient(NetAddress adr) { - throw new NotImplementedException(); - } - - public void RecalculateTags() { - throw new NotImplementedException(); - } - public void AddTag(ReadOnlySpan pszTag) { - throw new NotImplementedException(); - } - public void RemoveTag(ReadOnlySpan pszTag) { - throw new NotImplementedException(); - } public int GetNumConnections() => NumConnections; @@ -1488,7 +1472,28 @@ protected void UpdateMasterServer() { UpdateMasterServerPlayers(); Steam3Server().SendUpdatedServerDetails(); } - protected void UpdateMasterServerRules() { } + protected void UpdateMasterServerRules() { + if (!MasterServerRulesDirty) + return; + + ISteamGameServer? updater = Steam3Server().SteamGameServer(); + if (updater == null) + return; + + updater.ClearAllKeyValues(); + + foreach (ConCommandBase var in cvar.GetCommands()) { + if (!var.IsFlagSet(FCvar.Notify)) + continue; + + if (var is not ConVar conVar) + continue; + + SetMasterServerKeyValue(updater, conVar); + } + + MasterServerRulesDirty = false; + } protected virtual void UpdateMasterServerPlayers() { } readonly byte[] packetData = new byte[16 * 1024]; readonly NetAddress adr = new(); From a10be9cd6bcec6a488791cde3d18d1a70a79220b Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:43:16 +0100 Subject: [PATCH 4/6] Return ip:port from NetChannel GetAddress --- Source.Engine/NetChannel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Engine/NetChannel.cs b/Source.Engine/NetChannel.cs index 3f1b71bd..514749e0 100644 --- a/Source.Engine/NetChannel.cs +++ b/Source.Engine/NetChannel.cs @@ -1838,7 +1838,7 @@ public void SetTimeout(TimeUnit_t time) { public TimeUnit_t GetAverageData(int flow) => DataFlow[flow].AverageBytesPerSec; public TimeUnit_t GetAveragePackets(int flow) => DataFlow[flow].AveragePacketsPerSec; - public ReadOnlySpan GetAddress() => RemoteAddress?.ToString(); + public ReadOnlySpan GetAddress() => RemoteAddress == null ? default : RemoteAddress.ToString(false); public double GetTime() => Net.Time; From c38bf76a3aa0a252d34dc3fbf9171089a79c4bcb Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:15:01 +0100 Subject: [PATCH 5/6] Port IP rate limit check --- Source.Engine/IPRateLimit.cs | 96 +++++++++++++++++++++++++++++++++--- 1 file changed, 90 insertions(+), 6 deletions(-) diff --git a/Source.Engine/IPRateLimit.cs b/Source.Engine/IPRateLimit.cs index 4a4b54bb..be5a54d1 100644 --- a/Source.Engine/IPRateLimit.cs +++ b/Source.Engine/IPRateLimit.cs @@ -1,14 +1,33 @@ -using Source.Common.Commands; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Mathematics; using Source.Common.Networking; +using System.Buffers.Binary; +using System.Net.Sockets; + namespace Source.Engine; -public class IPRateLimit(ConVar maxSec, ConVar maxWindow, ConVar maxSecGlobal) +public class IPRateLimit { + [CvarIgnore] readonly ConVar maxSec; + [CvarIgnore] readonly ConVar maxWindow; + [CvarIgnore] readonly ConVar maxSecGlobal; + + public IPRateLimit(ConVar maxSec, ConVar maxWindow, ConVar maxSecGlobal) { + this.maxSec = maxSec; + this.maxWindow = maxWindow; + this.maxSecGlobal = maxSecGlobal; + } + + const int MAX_TREE_SIZE = 32768; const int FLUSH_TIMEOUT = 120; - readonly Dictionary IP = []; + + static readonly ConVar sv_logblocks = new("sv_logblocks", "0", 0, "If true when log when a query is blocked (can cause very large log files)"); + + readonly SortedDictionary IPTree = []; int globalCount; - long lastTime; + long lastTime = -1; double flushTime; struct IPRate @@ -17,8 +36,73 @@ struct IPRate public int Count; } - public bool CheckIP(NetAddress ip) { + public bool CheckIP(NetAddress adr) { + bool ret = CheckIPInternal(adr); + if (!ret && sv_logblocks.GetBool()) + g_Log.Print($"Traffic from {adr.ToString(false)} was blocked for exceeding rate limits\n"); + + return ret; + } + + bool CheckIPInternal(NetAddress adr) { + globalCount++; + + long curTime = (long)Platform.Time; + + if ((float)(curTime - lastTime) > maxWindow.GetFloat()) { + lastTime = curTime; + globalCount = 1; + } + + float queryRate = globalCount / maxWindow.GetFloat(); + if (maxSecGlobal.GetFloat() > MathLibConsts.FLT_EPSILON && queryRate > maxSecGlobal.GetFloat()) + return false; + + int clientIP = 0; + if (adr.Endpoint != null && adr.Endpoint.AddressFamily == AddressFamily.InterNetwork) { + Span ip = stackalloc byte[4]; + adr.Endpoint.Address.TryWriteBytes(ip, out _); + clientIP = BinaryPrimitives.ReadInt32LittleEndian(ip); + } + + if (IPTree.Count > MAX_TREE_SIZE && curTime > flushTime + FLUSH_TIMEOUT / 4) { + flushTime = curTime; + + int count = IPTree.Count; + List expired = []; + foreach (KeyValuePair entry in IPTree.Reverse()) { + if (count <= 2 * MAX_TREE_SIZE / 3) + break; + + if (curTime - entry.Value.LastTime > FLUSH_TIMEOUT && entry.Key != clientIP) { + expired.Add(entry.Key); + count--; + } + } + + foreach (int key in expired) + IPTree.Remove(key); + } + + if (IPTree.TryGetValue(clientIP, out IPRate rate)) { + rate.Count++; + + if ((float)(curTime - rate.LastTime) > maxWindow.GetFloat()) { + rate.LastTime = curTime; + rate.Count = 1; + IPTree[clientIP] = rate; + } + else { + IPTree[clientIP] = rate; + + float flQueryRate = rate.Count / maxWindow.GetFloat(); + if (flQueryRate > maxSec.GetFloat()) + return false; + } + } + else + IPTree.Add(clientIP, new() { Count = 1, LastTime = curTime }); + return true; - // ^^^^^^^^^^^ TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO TODO } } From 7283394f347c1077eb6045a72257e268846bb657 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:36:15 +0100 Subject: [PATCH 6/6] Publish query port in server startup table --- Source.Engine/Server/GameServer.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Source.Engine/Server/GameServer.cs b/Source.Engine/Server/GameServer.cs index f0cf7c97..0229f668 100644 --- a/Source.Engine/Server/GameServer.cs +++ b/Source.Engine/Server/GameServer.cs @@ -78,7 +78,11 @@ protected override BaseClient CreateNewClient(int slot) { } public void SetQueryPortFromSteamServer() { - // todo + if (ServerStartupDataTable == null) + return; + + int queryPort = Steam3Server().GetQueryPort(); + ServerStartupDataTable.AddString(true, "QueryPort", sizeof(int), MemoryMarshal.AsBytes(new ReadOnlySpan(in queryPort))); } internal bool IsLevelMainMenuBackground() { return LevelMainMenuBackground;