diff --git a/Source.CodeAnalysis.ConVars/ConVarRegistrationGenerator.cs b/Source.CodeAnalysis.ConVars/ConVarRegistrationGenerator.cs index e3b205d2..6551834c 100644 --- a/Source.CodeAnalysis.ConVars/ConVarRegistrationGenerator.cs +++ b/Source.CodeAnalysis.ConVars/ConVarRegistrationGenerator.cs @@ -258,8 +258,8 @@ static void Analyze(Symbols s, INamedTypeSymbol type, List models, Li break; } case IMethodSymbol method: { - AttributeData? attribute = FindAttribute(method, s.ConCommandAttribute); - if (attribute == null) { + AttributeData[] attributes = method.GetAttributes().Where(a => DerivesFrom(a.AttributeClass, s.ConCommandAttribute)).ToArray(); + if (attributes.Length == 0) { for (IMethodSymbol? overridden = method.OverriddenMethod; overridden != null; overridden = overridden.OverriddenMethod) { if (FindAttribute(overridden, s.ConCommandAttribute) != null) { candidates = true; @@ -271,12 +271,14 @@ static void Analyze(Symbols s, INamedTypeSymbol type, List models, Li } candidates = true; - Member? member = AnalyzeCommand(s, type, method, attribute, nameable, isStruct); - if (member == null) - reflect = true; - else { - member.Id = nextId++; - model.Members.Add(member); + foreach (AttributeData attribute in attributes) { + Member? member = AnalyzeCommand(s, type, method, attribute, nameable, isStruct); + if (member == null) + reflect = true; + else { + member.Id = nextId++; + model.Members.Add(member); + } } break; } diff --git a/Source.Common/Commands/ConCommandAttribute.cs b/Source.Common/Commands/ConCommandAttribute.cs index 44432de7..32fe7896 100644 --- a/Source.Common/Commands/ConCommandAttribute.cs +++ b/Source.Common/Commands/ConCommandAttribute.cs @@ -3,7 +3,7 @@ /// /// Indicates the method will be constructed as a concommand. /// -[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] +[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class ConCommandAttribute : Attribute { public readonly string? Name; public readonly string? HelpText; diff --git a/Source.Engine/EngineBuilder.cs b/Source.Engine/EngineBuilder.cs index 2b0b452d..ab9e746e 100644 --- a/Source.Engine/EngineBuilder.cs +++ b/Source.Engine/EngineBuilder.cs @@ -555,35 +555,36 @@ static void ConVar_RegisterByReflection(IEngineAPI engineAPI, ICvar cvar, Type t for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; - ConCommandAttribute? cmdAttr = method.GetCustomAttribute(); - if (cmdAttr == null) + ConCommandAttribute[] cmdAttrs = [.. method.GetCustomAttributes()]; + if (cmdAttrs.Length == 0) continue; - ConCommandAttribute attribute = method.GetCustomAttribute()!; // < never null! object? instance = method.IsStatic ? null : DetermineInstance(engineAPI, type, true, method.Name); - // Lets see if we can find a FnCommandCompletionCallback... - FnCommandCompletionCallback? completionCallback = null; - if (attribute.AutoCompleteMethod != null) - type.TryExtractMethodDelegate(instance, x => x.Name == attribute.AutoCompleteMethod, out completionCallback); - - // Construct a new ConCommand - string cmdName = attribute.Name ?? method.Name; - string? helpText = attribute.HelpText; - FCvar flags = attribute.Flags; - - ConCommand cmd; - - if (method.TryToDelegate(instance, out var callbackVoid)) - cmd = new ConCommand(cmdName, callbackVoid, helpText, flags, completionCallback); - else if (method.TryToDelegate(instance, out var callback)) - cmd = new ConCommand(cmdName, callback, helpText, flags, completionCallback); - else if (method.TryToDelegate(instance, out var callbackSourced)) - cmd = new ConCommand(cmdName, callbackSourced, helpText, flags, completionCallback); - else - throw new ArgumentException("Cannot dynamically produce ConCommand with the arguments we were given"); - - cvar.RegisterConCommand(cmd); + foreach (ConCommandAttribute attribute in cmdAttrs) { + // Lets see if we can find a FnCommandCompletionCallback... + FnCommandCompletionCallback? completionCallback = null; + if (attribute.AutoCompleteMethod != null) + type.TryExtractMethodDelegate(instance, x => x.Name == attribute.AutoCompleteMethod, out completionCallback); + + // Construct a new ConCommand + string cmdName = attribute.Name ?? method.Name; + string? helpText = attribute.HelpText; + FCvar flags = attribute.Flags; + + ConCommand cmd; + + if (method.TryToDelegate(instance, out var callbackVoid)) + cmd = new ConCommand(cmdName, callbackVoid, helpText, flags, completionCallback); + else if (method.TryToDelegate(instance, out var callback)) + cmd = new ConCommand(cmdName, callback, helpText, flags, completionCallback); + else if (method.TryToDelegate(instance, out var callbackSourced)) + cmd = new ConCommand(cmdName, callbackSourced, helpText, flags, completionCallback); + else + throw new ArgumentException("Cannot dynamically produce ConCommand with the arguments we were given"); + + cvar.RegisterConCommand(cmd); + } } } } diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index 2e4b02c3..f2fadd74 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -1461,6 +1461,7 @@ public void GMOD_BuildConVarUpdateMessageBF(bf_write buf, FCvar flags, bool nonD #endif [ConCommand(helpText: "Exits the engine")] + [ConCommand("exit", "Exit the engine.")] void quit(in TokenizedCommand args) { #if !SWDS if (!args.FindArg("prompt").IsEmpty) { @@ -1481,8 +1482,247 @@ void quit(in TokenizedCommand args) { HostState.Shutdown(); } - [ConCommand("exit", "Exit the engine.")] - void exit(in TokenizedCommand args) => quit(in args); + static ulong atoui64(ReadOnlySpan str) { + ulong val = 0; + int pos = 0; + + if (str.Length > 1 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { + pos = 2; + while (pos < str.Length) { + char c = str[pos++]; + if (c >= '0' && c <= '9') + val = (val << 4) + c - '0'; + else if (c >= 'a' && c <= 'f') + val = (val << 4) + c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + val = (val << 4) + c - 'A' + 10; + else + return val; + } + return val; + } + + if (str.Length > 0 && str[0] == '\'') + return str.Length > 1 ? str[1] : 0ul; + + while (pos < str.Length) { + char c = str[pos++]; + if (c < '0' || c > '9') + return val; + val = val * 10 + c - '0'; + } + + return val; + } + + static string KickMessage(in TokenizedCommand args, int first) { + StringBuilder message = new(); + for (int i = first; i < args.ArgC(); i++) { + if (i > first) + message.Append(' '); + message.Append(args[i]); + } + + if (message.Length > 511) + message.Length = 511; + + return message.ToString(); + } + + [ConCommand("kickid", "Kick a player by userid or uniqueid, with a message.")] + void kickid(in TokenizedCommand args, CommandSource source, int clientSlot) { + if (!sv.IsActive()) { + ConMsg("No server running, noone to kick.\n"); + return; + } + + if (args.ArgC() <= 1) { + ConMsg("Usage: kickid < userid | steamid | steamid64 > { message }\n"); + return; + } + + string searchString = ""; + string message; + ulong id = atoui64(args[1]); + if (id != 0) + message = KickMessage(in args, 2); + else if (args.ArgC() >= 6 && args[1].StartsWith("STEAM_", StringComparison.OrdinalIgnoreCase) && args[2].Contains(':') && args[4].Contains(':')) { + searchString = $"{args[1]}:{args[3]}:{args[5]}"; + message = KickMessage(in args, 6); + } + else { + searchString = new(args[1]); + message = KickMessage(in args, 2); + } + + if (searchString.Length > 127) + searchString = searchString[..127]; + + bool steamID64 = (id >> 32) != 0; + EUniverse universe = EUniverse.k_EUniversePublic; + if (steamID64) { + Source.Common.Steam.ISteamUtils? steamUtils = Steam3Client().SteamUtils(); + if (steamUtils != null) + universe = steamUtils.GetConnectedUniverse(); + } + + IClient? client = null; + int i; + for (i = 0; i < sv.GetClientCount(); i++) { + client = sv.GetClient(i)!; + + if (!client.IsConnected()) + continue; + + if (client.IsHLTV()) + continue; + + if (id != 0) { + if (steamID64) { + if (sv.GetPlayerInfo(i, out PlayerInfo info)) { + if (info.FriendsID == 0 && !info.FakePlayer) + break; + + CSteamID steamID = new(new AccountID_t(info.FriendsID), universe, info.FakePlayer ? EAccountType.k_EAccountTypeAnonGameServer : EAccountType.k_EAccountTypeIndividual); + if (steamID.m_SteamID == id) + break; + } + } + else if (client.GetUserID() == (long)id) + break; + } + else if (stricmp(client.GetNetworkIDString(), searchString) == 0) + break; + } + + if (i < sv.GetClientCount()) { + if (!sv.IsDedicated() && client!.GetPlayerSlot() == 0) { + Msg("Preventing kick of local server host!\n"); + return; + } + + if (source != CommandSource.Command && !sv.IsDedicated() && sv.GetClient(clientSlot) == client) { + Msg("Preventing kick of yourself!\n"); + return; + } + + if (message.Length != 0) + client!.Disconnect(message); + else if (source == CommandSource.Command) + client!.Disconnect("Kicked from server"); + else + client!.Disconnect($"Kicked by {sv.GetClient(clientSlot)!.GetClientName()}"); + + return; + } + + if (steamID64) + ConMsg($"steamid64 \"{id}\" not found\n"); + else if (id != 0) + ConMsg($"userid \"{id}\" not found\n"); + else + ConMsg($"steamid \"{searchString}\" not found\n"); + } + + [ConCommand("kick", "Kick a player by name.")] + void kick(in TokenizedCommand args, CommandSource source, int clientSlot) { + if (!sv.IsActive()) { + ConMsg("No server running, noone to kick.\n"); + return; + } + + if (args.ArgC() <= 1) { + ConMsg("Usage: kick < name >\n"); + return; + } + + ReadOnlySpan name = args.ArgS(); + if (name.Length > 63) + name = name[..63]; + + if (name.IsEmpty) + return; + + if (name[0] == '"' && name[^1] == '"') + name = name.Length > 1 ? name[1..^1] : name[1..]; + + IClient? client = null; + int i; + for (i = 0; i < sv.GetClientCount(); i++) { + client = sv.GetClient(i)!; + + if (!client.IsConnected()) + continue; + + if (client.IsHLTV()) + continue; + + if (stricmp(client.GetClientName(), name) == 0) + break; + } + + if (i < sv.GetClientCount()) { + if (!sv.IsDedicated() && client!.GetPlayerSlot() == 0) { + Msg("Preventing kick of local server host!\n"); + return; + } + + if (source == CommandSource.Command) + client!.Disconnect("Kicked from server"); + else { + if (!sv.IsDedicated() && sv.GetClient(clientSlot) == client) + return; + + client!.Disconnect($"Kicked by {sv.GetClient(clientSlot)!.GetClientName()}"); + } + } + else + ConMsg($"name \"{name}\" not found\n"); + } + + [ConCommand("kickall", "Kicks everybody connected with a message.")] + void kickall(in TokenizedCommand args, CommandSource source, int clientSlot) { + if (!sv.IsActive()) { + ConMsg("No server running, noone to kick.\n"); + return; + } + + ReadOnlySpan message = args.ArgS(); + if (message.Length > 127) + message = message[..127]; + + for (int i = 0; i < sv.GetClientCount(); i++) { + IClient client = sv.GetClient(i)!; + + if (!client.IsConnected()) + continue; + + if (!sv.IsDedicated() && client.GetPlayerSlot() == 0) { + Msg("Preventing kick of local server host!\n"); + continue; + } + + if (source != CommandSource.Command && !sv.IsDedicated() && sv.GetClient(clientSlot) == client) + continue; + + if (client.IsHLTV()) + continue; + + if (source == CommandSource.Command) { + if (!message.IsEmpty) + client.Disconnect(message); + else + client.Disconnect("Kicked from server"); + } + else { + ReadOnlySpan who = sv.GetClient(clientSlot)!.GetClientName(); + if (!message.IsEmpty) + client.Disconnect($"Kicked by {who} : {message}"); + else + client.Disconnect($"Kicked by {who}"); + } + } + } readonly ConVar voice_recordtofile = new("voice_recordtofile", "0", 0, "Record mic data and decompressed voice data into 'voice_micdata.wav' and 'voice_decompressed.wav'"); readonly ConVar voice_inputfromfile; diff --git a/Source.Engine/Net.cs b/Source.Engine/Net.cs index 01891162..c36b8f7c 100644 --- a/Source.Engine/Net.cs +++ b/Source.Engine/Net.cs @@ -145,6 +145,8 @@ public static void OutOfBandPrint(NetSocketType sock, NetAddress? adr, ReadOnlyS Singleton().SendPacket(null!, sock, adr, msg.GetData(), msg.BytesWritten); } + Source.Engine.Server.Filter? _filter = null; Source.Engine.Server.Filter Filter => _filter ??= Singleton(); + public bool StringToAdr(ReadOnlySpan host, [NotNullWhen(true)] out IPEndPoint? ep) { host = host.SliceNullTerminatedString(); ep = null; @@ -282,6 +284,11 @@ public void ProcessSocket(NetSocketType sock, IConnectionlessPacketHandler handl break; } + if (Filter.ShouldDiscard(packet.From)) { + Filter.SendBan(packet.From); + continue; + } + unsafe { int header = packet.Message.ReadLong(); diff --git a/Source.Engine/SV.cs b/Source.Engine/SV.cs index fac83e38..cfc54991 100644 --- a/Source.Engine/SV.cs +++ b/Source.Engine/SV.cs @@ -145,6 +145,27 @@ private void InitSendTables(ServerClass? classes) { readonly ConVar tv_enable = new("tv_enable", "0", FCvar.Notify, "Activates SourceTV on server."); + [ConCommand(helpText: "Show user info for players on server.")] + void users() { + if (!sv.IsActive()) { + ConMsg("Can't 'users', not running a server\n"); + return; + } + + int c = 0; + ConMsg("\n"); + for (int i = 0; i < sv.GetClientCount(); i++) { + IClient client = sv.GetClient(i)!; + + if (client.IsConnected()) { + ConMsg($"{client.GetPlayerSlot()}:{client.GetUserID()}:\"{client.GetClientName()}\"\n"); + c++; + } + } + + ConMsg($"{c} users\n"); + } + [ConCommand(helpText: "Change the maximum number of players allowed on this server.")] void maxplayers(in TokenizedCommand args) { if (args.ArgC() != 2) { diff --git a/Source.Engine/Server/BaseClient.cs b/Source.Engine/Server/BaseClient.cs index 5699466a..56c2bb86 100644 --- a/Source.Engine/Server/BaseClient.cs +++ b/Source.Engine/Server/BaseClient.cs @@ -699,24 +699,25 @@ public virtual void SendSnapshot(ClientFrame frame) { public int GetClientChallenge() => ClientChallenge; static readonly char[] idstr = new char[Constants.MAX_NETWORKID_LENGTH]; - public ReadOnlySpan GetUserIDString(USERID id) { + public static ReadOnlySpan GetUserIDString(USERID id) { idstr[0] = '\0'; switch (id.IDType) { case IDType.Steam: - if (Steam3Server().BLanOnly() && id.SteamID == CSteamID.Nil) + uint accountID = (uint)id.SteamID.GetAccountID(); + if (Steam3Server().BLanOnly() && accountID == 0) strcpy(idstr, "STEAM_ID_LAN"); - else if (id.SteamID == CSteamID.Nil) + else if (accountID == 0) strcpy(idstr, "STEAM_ID_PENDING"); else - strcpy(idstr, id.SteamID.Render()); + strcpy(idstr, $"STEAM_0:{accountID & 1}:{accountID >> 1}"); break; case IDType.HLTV: strcpy(idstr, "HLTV"); break; case IDType.Replay: strcpy(idstr, "REPLAY"); break; default: strcpy(idstr, "UNKNOWN"); break; } - return idstr; + return ((ReadOnlySpan)idstr).SliceNullTerminatedString(); } public USERID GetNetworkID() { diff --git a/Source.Engine/Server/Filter.cs b/Source.Engine/Server/Filter.cs index b75286ef..25dd96de 100644 --- a/Source.Engine/Server/Filter.cs +++ b/Source.Engine/Server/Filter.cs @@ -1,8 +1,17 @@ -using Source.Common.Commands; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Filesystem; +using Source.Common.Networking; using Source.Common.Server; +using Steamworks; + using System; using System.Collections.Generic; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; using System.Text; namespace Source.Engine.Server; @@ -10,14 +19,14 @@ namespace Source.Engine.Server; public struct IPFilter { public uint Mask; public uint Compare; - public TimeUnit_t BanEndTime; - public TimeUnit_t BanTime; + public float BanEndTime; + public float BanTime; } public struct UserFilter { public USERID UserID; - public TimeUnit_t BanEndTime; - public TimeUnit_t BanTime; + public float BanEndTime; + public float BanTime; } [EngineComponent] @@ -30,11 +39,293 @@ public class Filter(Host Host) public const string BANNED_USER_FILENAME = "banned_user.cfg"; public const string CONFIG_DIR = "cfg/"; public const string STEAM_PREFIX = "STEAM_"; - + static ConVar sv_filterban = new("sv_filterban", "1", 0, "Set packet filtering by IP mode"); readonly List IPFilters = []; readonly List UserFilters = []; + Net? _net = null; Net Net => _net ??= Singleton(); + + public void SendBan(NetAddress adr) { + Net.OutOfBandPrint(NetSocketType.Server, adr, $"{(char)A2A.Print}Banned by server\n"); + } + + static uint GetIP(NetAddress adr) { + Span ip = stackalloc byte[4]; + ip.Clear(); + IPAddress? address = adr.Endpoint?.Address; + if (address != null && address.AddressFamily == AddressFamily.InterNetwork) + address.TryWriteBytes(ip, out _); + return MemoryMarshal.Read(ip); + } + + public bool ShouldDiscard(NetAddress adr) { + if (sv_filterban.GetInt() == 0) + return false; + + bool negativeFilter = sv_filterban.GetInt() == 1; + + if (IPFilters.Count == 0) + return !negativeFilter; + + uint ip = GetIP(adr); + + for (int i = IPFilters.Count - 1; i >= 0; i--) { + if ((IPFilters[i].Compare != 0xffffffff) && + (IPFilters[i].BanEndTime != 0.0f) && + (IPFilters[i].BanEndTime <= Host.RealTime)) { + IPFilters.RemoveAt(i); + continue; + } + + if ((ip & IPFilters[i].Mask) == IPFilters[i].Compare) + return negativeFilter; + } + + return !negativeFilter; + } + + static bool ConvertString(ReadOnlySpan s, out IPFilter f) { + Span num = stackalloc char[128]; + Span b = stackalloc byte[4]; + Span m = stackalloc byte[4]; + b.Clear(); + m.Clear(); + f = default; + + int pos = 0; + for (int i = 0; i < 4; i++) { + if (pos >= s.Length || s[pos] < '0' || s[pos] > '9') { + ConMsg($"Bad filter address: {s[Math.Min(pos, s.Length)..]}\n"); + return false; + } + + int j = 0; + while (pos < s.Length && s[pos] >= '0' && s[pos] <= '9') + num[j++] = s[pos++]; + + b[i] = (byte)atoi(num[..j]); + if (b[i] != 0) + m[i] = 255; + + if (pos >= s.Length) + break; + + pos++; + } + + f.Mask = MemoryMarshal.Read(m); + f.Compare = MemoryMarshal.Read(b); + + return true; + } + + static ReadOnlySpan CommandIssuer(CommandSource source, int clientSlot) + => source == CommandSource.Command ? "Console" : sv.GetClient(clientSlot)!.GetClientName(); + + static string BanDuration(float banTime) + => banTime == 0.0f ? "permanently" : $"for {banTime.ToString("F2", CultureInfo.InvariantCulture)} minutes"; + + [ConCommand("addip", "Add an IP address to the ban list.")] + void addip(in TokenizedCommand args, CommandSource source, int clientSlot) { + bool kick = true; + bool found = false; + BaseClient? client = null; + + if (stricmp(args[0], "banip") == 0) + ConMsg("Note: should use \"addip\" instead of \"banip\".\n"); + + if (args.ArgC() != 3) { + ConMsg("Usage: addip < minutes > < ipaddress >\nUse 0 minutes for permanent\n"); + return; + } + + if (!ConvertString(args[2], out IPFilter f)) + return; + + int i; + for (i = 0; i < IPFilters.Count; i++) { + if (IPFilters[i].Compare == 0xffffffff || (IPFilters[i].Compare == f.Compare && IPFilters[i].Mask == f.Mask)) + break; + } + + if (i == IPFilters.Count) { + if (IPFilters.Count == MAX_IPFILTERS) { + ConMsg("addip: IP filter list is full\n"); + return; + } + + IPFilters.Add(default); + } + else + kick = false; + + float banTime = (float)atof(args[1]); + if (banTime < 0.01f) + banTime = 0.0f; + + if (!ConvertString(args[2], out IPFilter filter)) + filter.Compare = 0xffffffff; + + filter.BanTime = banTime; + filter.BanEndTime = (banTime != 0.0f) ? (float)(Host.RealTime + 60.0 * banTime) : 0.0f; + IPFilters[i] = filter; + + if (kick) { + for (i = 0; i < sv.GetClientCount(); i++) { + client = (BaseClient?)sv.GetClient(i); + + if (client == null || !client.IsActive() || !client.IsConnected() || !client.IsSpawned()) + continue; + + if (client.IsFakeClient()) + continue; + + if (!ShouldDiscard(client.GetNetChannel()!.GetRemoteAddress()!)) + continue; + + found = true; + break; + } + } + + string duration = BanDuration(banTime); + + IGameEvent? ev = g_GameEventManager.CreateEvent("server_addban"); + if (ev != null) { + if (found && client != null) { + ev.SetString("name", client.GetClientName()); + ev.SetInt("userid", client.GetUserID()); + ev.SetString("networkid", client.GetNetworkIDString()); + } + else { + ev.SetString("name", ""); + ev.SetInt("userid", 0); + ev.SetString("networkid", ""); + } + + ev.SetString("ip", args[2]); + ev.SetString("duration", duration); + ev.SetString("by", CommandIssuer(source, clientSlot)); + ev.SetBool("kicked", kick && found && client != null); + + g_GameEventManager.FireEvent(ev); + } + + if (kick && found && client != null) { + client.ClientPrintf("The server operator has added you to the banned list.\n"); + client.Disconnect("Added to banned list"); + } + } + + [ConCommand("banip", "Add an IP address to the ban list.")] + void banip(in TokenizedCommand args, CommandSource source, int clientSlot) => addip(in args, source, clientSlot); + + [ConCommand("removeip", "Remove an IP address from the ban list.")] + void removeip(in TokenizedCommand args, CommandSource source, int clientSlot) { + if (args.ArgC() < 1) { + ConMsg("Usage: removeip < slot | ipaddress >\n"); + return; + } + + if (!args[1].Contains('.')) { + int slot = atoi(args[1]); + if (slot > 0 && slot <= IPFilters.Count) { + slot--; + + Span b = stackalloc byte[4]; + MemoryMarshal.Write(b, IPFilters[slot].Compare); + string ip = $"{b[0],3}.{b[1],3}.{b[2],3}.{b[3],3}"; + + IPFilters.RemoveAt(slot); + + ConMsg($"removeip: filter removed for {args[1]}, IP {ip}\n"); + + IGameEvent? slotEvent = g_GameEventManager.CreateEvent("server_removeban"); + if (slotEvent != null) { + slotEvent.SetString("networkid", ""); + slotEvent.SetString("ip", ip); + slotEvent.SetString("by", CommandIssuer(source, clientSlot)); + g_GameEventManager.FireEvent(slotEvent); + } + + return; + } + + ConMsg($"removeip: invalid slot {slot}\n"); + return; + } + + if (!ConvertString(args[1], out IPFilter f)) + return; + + for (int i = 0; i < IPFilters.Count; i++) { + if ((IPFilters[i].Mask == f.Mask) && (IPFilters[i].Compare == f.Compare)) { + IPFilters.RemoveAt(i); + ConMsg($"removeip: filter removed for {args[1]}\n"); + + IGameEvent? ev = g_GameEventManager.CreateEvent("server_removeban"); + if (ev != null) { + ev.SetString("networkid", ""); + ev.SetString("ip", args[1]); + ev.SetString("by", CommandIssuer(source, clientSlot)); + g_GameEventManager.FireEvent(ev); + } + + return; + } + } + + ConMsg($"removeip: couldn't find {args[1]}\n"); + } + + [ConCommand("listip", "List IP addresses on the ban list.")] + void listip() { + int count = IPFilters.Count; + if (count == 0) { + ConMsg("IP filter list: empty\n"); + return; + } + + if (count == 1) + ConMsg($"IP filter list: {count} entry\n"); + else + ConMsg($"IP filter list: {count} entries\n"); + + Span b = stackalloc byte[4]; + for (int i = 0; i < count; i++) { + MemoryMarshal.Write(b, IPFilters[i].Compare); + + if (IPFilters[i].BanTime != 0.0f) + ConMsg($"{i + 1} {b[0],3}.{b[1],3}.{b[2],3}.{b[3],3} : {IPFilters[i].BanTime.ToString("F3", CultureInfo.InvariantCulture)} min\n"); + else + ConMsg($"{i + 1} {b[0],3}.{b[1],3}.{b[2],3}.{b[3],3} : permanent\n"); + } + } + + [ConCommand("writeip", "Save the ban list to " + BANNED_IP_FILENAME + ".")] + void writeip() { + const string name = CONFIG_DIR + BANNED_IP_FILENAME; + + ConMsg($"Writing {name}.\n"); + + using IFileHandle? f = g_pFileSystem.Open(name, FileOpenOptions.Write | FileOpenOptions.Binary, null); + if (f == null) { + ConMsg($"Couldn't open {name}\n"); + return; + } + + Span b = stackalloc byte[4]; + for (int i = 0; i < IPFilters.Count; i++) { + MemoryMarshal.Write(b, IPFilters[i].Compare); + + if (IPFilters[i].BanTime != 0.0f) + continue; + + f.Stream.Write(Encoding.ASCII.GetBytes($"addip 0 {b[0]}.{b[1]}.{b[2]}.{b[3]}\r\n")); + } + } + public bool IsUserBanned(USERID userid) { if (sv_filterban.GetInt() == 0) return false; @@ -42,16 +333,291 @@ public bool IsUserBanned(USERID userid) { bool negativeFilter = sv_filterban.GetInt() == 1; for (int i = UserFilters.Count - 1; i >= 0; i--) { - if ((UserFilters[i].BanEndTime != 0.0) && + if ((UserFilters[i].BanEndTime != 0.0f) && (UserFilters[i].BanEndTime <= Host.RealTime)) { UserFilters.RemoveAt(i); continue; } - if (Steam3Server().CompareUserID(userid, UserFilters[i].UserID)) + if (Steam3Server().CompareUserID(userid, UserFilters[i].UserID)) return negativeFilter; } return !negativeFilter; } + + static USERID StringToUserID(ReadOnlySpan str) { + USERID id = default; + + if (!str.IsEmpty) { + ReadOnlySpan temp = default; + if (str.StartsWith(STEAM_PREFIX, StringComparison.OrdinalIgnoreCase)) { + temp = str[STEAM_PREFIX.Length..]; + if (temp.Length > 126) + temp = temp[..126]; + id.IDType = IDType.Steam; + } + + TokenizedCommand args = new(); + args.Tokenize(temp); + if (args.ArgC() >= 5) { + uint high = (uint)atoi(args[2]); + uint low = (uint)atoi(args[4]); + id.SteamID = new CSteamID(new AccountID_t(low * 2 + high), EUniverse.k_EUniversePublic, EAccountType.k_EAccountTypeIndividual); + } + } + + return id; + } + + [ConCommand("writeid", "Writes a list of permanently-banned user IDs to " + BANNED_USER_FILENAME + ".")] + void writeid() { + const string name = CONFIG_DIR + BANNED_USER_FILENAME; + + ConMsg($"Writing {name}.\n"); + + using IFileHandle? f = g_pFileSystem.Open(name, FileOpenOptions.Write | FileOpenOptions.Binary, null); + if (f == null) { + ConMsg($"Couldn't open {name}\n"); + return; + } + + for (int i = 0; i < UserFilters.Count; i++) { + if (UserFilters[i].BanTime != 0.0f) + continue; + + f.Stream.Write(Encoding.ASCII.GetBytes($"banid 0 {BaseClient.GetUserIDString(UserFilters[i].UserID)}\r\n")); + } + } + + [ConCommand("removeid", "Remove a user ID from the ban list.")] + void removeid(in TokenizedCommand args, CommandSource source, int clientSlot) { + if (args.ArgC() != 2 && args.ArgC() != 6) { + ConMsg("Usage: removeid < slot | uniqueid >\n"); + return; + } + + ReadOnlySpan arg1 = args[1]; + + if (arg1.StartsWith('#')) { + ConMsg("Usage: removeid < userid | uniqueid >\n"); + ConMsg("No # necessary\n"); + return; + } + + if (arg1.IsEmpty || arg1[0] < '0' || arg1[0] > '9') { + string searchString; + if (arg1.StartsWith(STEAM_PREFIX, StringComparison.OrdinalIgnoreCase) && args[2].Contains(':')) + searchString = $"{arg1}:{args[3]}:{args[5]}"; + else if (arg1.StartsWith(STEAM_PREFIX, StringComparison.OrdinalIgnoreCase) && arg1.Contains(':')) + searchString = new(arg1); + else { + ConMsg($"removeid: invalid ban ID \"{arg1}\"\n"); + return; + } + + if (searchString.Length > 63) + searchString = searchString[..63]; + + for (int i = 0; i < UserFilters.Count; i++) { + if (stricmp(BaseClient.GetUserIDString(UserFilters[i].UserID), searchString) != 0) + continue; + + UserFilters.RemoveAt(i); + ConMsg($"removeid: filter removed for {searchString}\n"); + + IGameEvent? ev = g_GameEventManager.CreateEvent("server_removeban"); + if (ev != null) { + ev.SetString("networkid", searchString); + ev.SetString("ip", ""); + ev.SetString("by", CommandIssuer(source, clientSlot)); + g_GameEventManager.FireEvent(ev); + } + + return; + } + + ConMsg($"removeid: couldn't find {searchString}\n"); + return; + } + + int slot = atoi(arg1); + if (slot <= 0 || slot > UserFilters.Count) { + ConMsg($"removeid: invalid slot {slot}\n"); + return; + } + + USERID id = UserFilters[--slot].UserID; + UserFilters.RemoveAt(slot); + + string idString = new(BaseClient.GetUserIDString(id)); + ConMsg($"removeid: filter removed for {arg1}, ID {idString}\n"); + + IGameEvent? slotEvent = g_GameEventManager.CreateEvent("server_removeban"); + if (slotEvent != null) { + slotEvent.SetString("networkid", idString); + slotEvent.SetString("ip", ""); + slotEvent.SetString("by", CommandIssuer(source, clientSlot)); + g_GameEventManager.FireEvent(slotEvent); + } + } + + [ConCommand("listid", "Lists banned users.")] + void listid() { + int count = UserFilters.Count; + if (count == 0) { + ConMsg("ID filter list: empty\n"); + return; + } + + if (count == 1) + ConMsg($"ID filter list: {count} entry\n"); + else + ConMsg($"ID filter list: {count} entries\n"); + + for (int i = 0; i < count; i++) { + string uid = new(BaseClient.GetUserIDString(UserFilters[i].UserID)); + + if (UserFilters[i].BanTime != 0.0f) + ConMsg($"{i + 1} {uid} : {UserFilters[i].BanTime.ToString("F3", CultureInfo.InvariantCulture)} min\n"); + else + ConMsg($"{i + 1} {uid} : permanent\n"); + } + } + + [ConCommand("banid", "Add a user ID to the ban list.")] + void banid(in TokenizedCommand args, CommandSource source, int clientSlot) { + if (Steam3Server().BLanOnly()) { + ConMsg("Can't ban users on a LAN\n"); + return; + } + + if (args.ArgC() < 3 || args.ArgC() > 8) { + ConMsg("Usage: banid < minutes > < userid | uniqueid > { kick }\n"); + ConMsg("Use 0 minutes for permanent\n"); + return; + } + + float banTime = (float)atof(args[1]); + if (banTime < 0.01f) + banTime = 0.0f; + + ReadOnlySpan arg2 = args[2]; + if (arg2.StartsWith('#')) { + ConMsg("Usage: banid < minutes > < userid | uniqueid > { kick }\n"); + ConMsg("No # necessary\n"); + return; + } + + bool kick = args.ArgC() >= 4 && stricmp(args[args.ArgC() - 1], "kick") == 0; + + string searchString = ""; + int searchIndex; + if (arg2.IsEmpty || arg2[0] < '0' || arg2[0] > '9') { + searchIndex = -1; + + if (arg2.StartsWith(STEAM_PREFIX, StringComparison.OrdinalIgnoreCase) && args[3].Contains(':')) { + searchString = $"{arg2}:{args[4]}:{args[6]}"; + if (searchString.Length > 63) + searchString = searchString[..63]; + } + else { + ConMsg($"Can't ban users with ID \"{arg2}\"\n"); + return; + } + } + else + searchIndex = atoi(arg2); + + bool playing = false; + USERID id = default; + BaseClient? client = null; + for (int c = 0; c < sv.GetClientCount(); c++) { + client = (BaseClient?)sv.GetClient(c); + if (client == null || !client.IsActive() || !client.IsConnected() || !client.IsSpawned()) + continue; + + if (client.IsFakeClient()) + continue; + + if (searchIndex != -1) { + if (client.GetUserID() == searchIndex) { + id = client.GetNetworkID(); + playing = true; + break; + } + } + else { + if (stricmp(client.GetNetworkIDString(), searchString) == 0) { + id = client.GetNetworkID(); + playing = true; + break; + } + } + } + + if (!playing) { + if (searchIndex != -1) { + ConMsg($"banid: couldn't find userid {searchIndex}\n"); + return; + } + + id = StringToUserID(searchString); + } + + int i; + for (i = 0; i < UserFilters.Count; i++) { + if (Steam3Server().CompareUserID(UserFilters[i].UserID, id)) + break; + } + + if (!sv.IsDedicated() && playing && client!.GetPlayerSlot() == 0) { + Msg("Preventing ban of local server host!\n"); + return; + } + + if (i >= UserFilters.Count) { + if (UserFilters.Count >= MAX_USERFILTERS) { + ConMsg("banid: user filter list is full\n"); + return; + } + + i = UserFilters.Count; + UserFilters.Add(default); + } + + UserFilters[i] = new() { + BanTime = banTime, + BanEndTime = (banTime != 0.0f) ? (float)(Host.RealTime + 60.0 * banTime) : 0.0f, + UserID = id + }; + + string duration = BanDuration(banTime); + + IGameEvent? ev = g_GameEventManager.CreateEvent("server_addban"); + if (ev != null) { + if (playing) { + ev.SetString("name", client!.GetClientName()); + ev.SetInt("userid", client.GetUserID()); + ev.SetString("networkid", client.GetNetworkIDString()); + } + else { + ev.SetString("name", ""); + ev.SetInt("userid", 0); + ev.SetString("networkid", BaseClient.GetUserIDString(id)); + } + + ev.SetString("ip", ""); + ev.SetString("duration", duration); + ev.SetString("by", CommandIssuer(source, clientSlot)); + ev.SetInt("kicked", (kick && playing && client != null) ? 1 : 0); + + g_GameEventManager.FireEvent(ev); + } + + if (kick && playing && client != null) { + client.ClientPrintf($"You have been kicked and banned {duration} by the server.\n"); + client.Disconnect("Kicked and banned"); + } + } }