Skip to content
Open
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
96 changes: 90 additions & 6 deletions Source.Engine/IPRateLimit.cs
Original file line number Diff line number Diff line change
@@ -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<uint, IPRateLimit> 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<int, IPRate> IPTree = [];
int globalCount;
long lastTime;
long lastTime = -1;
double flushTime;

struct IPRate
Expand All @@ -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<byte> 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<int> expired = [];
foreach (KeyValuePair<int, IPRate> 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
}
}
16 changes: 11 additions & 5 deletions Source.Engine/Net.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -1065,6 +1063,14 @@ private int SendToImpl(Socket s, Span<byte> 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));

Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion Source.Engine/NetChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<char> GetAddress() => RemoteAddress?.ToString();
public ReadOnlySpan<char> GetAddress() => RemoteAddress == null ? default : RemoteAddress.ToString(false);

public double GetTime() => Net.Time;

Expand Down
69 changes: 49 additions & 20 deletions Source.Engine/Server/BaseServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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<char> pszTag) {
throw new NotImplementedException();
}
public void RemoveTag(ReadOnlySpan<char> pszTag) {
throw new NotImplementedException();
}

public int GetNumConnections() => NumConnections;

Expand Down Expand Up @@ -1374,8 +1358,24 @@ protected virtual bool CheckPassword(NetAddress adr, ReadOnlySpan<char> 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) {
Expand Down Expand Up @@ -1403,7 +1403,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() {
Expand Down Expand Up @@ -1464,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();
Expand Down
6 changes: 5 additions & 1 deletion Source.Engine/Server/GameServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>(in queryPort)));
}
internal bool IsLevelMainMenuBackground() {
return LevelMainMenuBackground;
Expand Down
Loading