From 4fad609794d10c1dd0ddc2b89c19f0dcd10fafa9 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:49:39 +0100 Subject: [PATCH 1/2] Skip file CRC check like GMod and mark pure file tracker as dead code --- Source.Engine/Server/GameClient.cs | 4 ++++ Source.Engine/Server/PureServerWhitelist.cs | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Source.Engine/Server/GameClient.cs b/Source.Engine/Server/GameClient.cs index db191e6b4..db928e25d 100644 --- a/Source.Engine/Server/GameClient.cs +++ b/Source.Engine/Server/GameClient.cs @@ -151,6 +151,9 @@ protected override bool ProcessRespondCvarValue(CLC_RespondCvarValue msg) { protected override bool ProcessFileCRCCheck(CLC_FileCRCCheck msg) { +#if GMOD_DLL + return true; +#else if (!sv.IsInPureServerMode()) return true; @@ -198,6 +201,7 @@ protected override bool ProcessFileCRCCheck(CLC_FileCRCCheck msg) { } return true; +#endif } protected override bool ProcessFileMD5Check(CLC_FileMD5Check msg) { diff --git a/Source.Engine/Server/PureServerWhitelist.cs b/Source.Engine/Server/PureServerWhitelist.cs index ae8733dfd..b51552dea 100644 --- a/Source.Engine/Server/PureServerWhitelist.cs +++ b/Source.Engine/Server/PureServerWhitelist.cs @@ -119,13 +119,13 @@ public void AddUserReportedFileHash(int idxFile, ref FileHash fileHash, USERID u } public bool DoesFileMatch(ReadOnlySpan pathID, ReadOnlySpan relativeFilename, int fileFraction, ref FileHash fileHash, USERID userID) { - return true; // todo + return true; // note: dead code in GMod } public int ListUserFiles(bool listAll, ReadOnlySpan filenameFind) { - return 0; // todo + return 0; // note: dead code in GMod } public int ListAllTrackedFiles(bool listAll, ReadOnlySpan filenameFind, int fileFractionMin, int fileFractionMax) { - return 0; // todo + return 0; // note: dead code in GMod } public readonly RedBlackTree TreeAllReportedFiles; From 612a4e96d9bf5143e20c814594936be2b5d882b4 Mon Sep 17 00:00:00 2001 From: Space V <40030799+spacevx@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:30:15 +0100 Subject: [PATCH 2/2] Port pure server whitelist and sv_pure --- Source.Engine/CL.cs | 27 ++ Source.Engine/Client/ClientState.cs | 6 + Source.Engine/SV.cs | 78 +++- Source.Engine/Server/GameServer.cs | 33 +- Source.Engine/Server/PureServerWhitelist.cs | 465 +++++++++++++++++++- 5 files changed, 598 insertions(+), 11 deletions(-) diff --git a/Source.Engine/CL.cs b/Source.Engine/CL.cs index 053e3c3d6..3a6c685e4 100644 --- a/Source.Engine/CL.cs +++ b/Source.Engine/CL.cs @@ -11,6 +11,7 @@ using Source.Common.Launcher; using Source.Common.MaterialSystem; using Source.Common.Networking; +using Source.Common.Utilities; using Source.Engine.Client; using Source.Engine.Server; @@ -520,6 +521,32 @@ internal bool CheckCRCs(ReadOnlySpan levelFileName) { return true; } + public static PureServerWhitelist? LoadWhitelist(INetworkStringTable table, ReadOnlySpan name) { + int stringIdx = table.FindStringIndex(name); + if (stringIdx == INetworkStringTable.INVALID_STRING_INDEX) + return null; + + byte[]? data = table.GetStringUserData(stringIdx); + if (data == null) + return null; + + UtlBuffer buf = new(data, UtlBuffer.BufferFlags.ReadOnly); + + PureServerWhitelist whitelist = PureServerWhitelist.Create(g_pFileSystem); + whitelist.Decode(buf); + return whitelist; + } + + public static void CheckForPureServerWhitelist() { + if (cl.MaxClients <= 1 || cl.IsHLTV) + return; + + if (cl.ServerStartupTable != null) + LoadWhitelist(cl.ServerStartupTable, "PureServerWhitelist"); + } + + public static void PrintWhitelistInfo() => cl.PureServerWhitelist?.PrintWhitelistContents(); + readonly byte[] voiceData = new byte[2048]; public void SendVoicePacket(bool final) { diff --git a/Source.Engine/Client/ClientState.cs b/Source.Engine/Client/ClientState.cs index 06fb4fb30..43b069ad7 100644 --- a/Source.Engine/Client/ClientState.cs +++ b/Source.Engine/Client/ClientState.cs @@ -102,6 +102,7 @@ public class ClientState : BaseClientState public INetworkStringTable? LightStyleTable; public INetworkStringTable? UserInfoTable; public INetworkStringTable? ServerStartupTable; + public PureServerWhitelist? PureServerWhitelist; // note: GMod never sets it public INetworkStringTable? DynamicModelsTable; public INetworkStringTable? DownloadableFileTable; @@ -259,6 +260,9 @@ public override bool HookClientStringTable(ReadOnlySpan tableName) { case Protocol.USER_INFO_TABLENAME: UserInfoTable = table; return true; + case Protocol.SERVER_STARTUP_DATA_TABLENAME: + ServerStartupTable = table; + return true; case Protocol.DOWNLOADABLE_FILE_TABLENAME: DownloadableFileTable = table; return true; @@ -919,6 +923,8 @@ public void FinishSignonState_New() { modelloader.ResetModelServerCounts(); SetModel(1); + CL.CheckForPureServerWhitelist(); + CL.RegisterResources(); if (host_state.WorldModel == null) { diff --git a/Source.Engine/SV.cs b/Source.Engine/SV.cs index fac83e388..7040612ad 100644 --- a/Source.Engine/SV.cs +++ b/Source.Engine/SV.cs @@ -39,7 +39,83 @@ public partial class SV(IServiceProvider services, Cbuf Cbuf, ED ED, Host Host, EngineVGui EngineVGui => field ??= Singleton(); #endif - public static readonly ConVar sv_pure_kick_clients = new("sv_pure_kick_clients", "1", 0, "If set to 1, the server will kick clients with mismatching files. Otherwise, it will issue a warning to the client."); +#if GMOD_DLL + static int g_sv_pure_mode = -2; + + static int GetSvPureModeFromCommandLine() { + if (commandLine.CheckParm("+sv_pure")) + return commandLine.ParmValue("+sv_pure", 1); + + if (commandLine.CheckParm("-sv_pure")) + return commandLine.ParmValue("-sv_pure", 1); + + return -1; + } + + public static int GetSvPureMode() { + if (g_sv_pure_mode == -2) + g_sv_pure_mode = GetSvPureModeFromCommandLine(); + + return g_sv_pure_mode; + } +#else + static int g_sv_pure_mode; + + public static int GetSvPureMode() => g_sv_pure_mode; +#endif + + [ConCommand(helpText: "Show user data.")] + void sv_pure(in TokenizedCommand args) { + int pureMode = -2; + if (args.ArgC() == 2) + pureMode = atoi(args[1]); + + Msg("--------------------------------------------------------\n"); + if (pureMode >= -1 && pureMode <= 2) { +#if GMOD_DLL + if (pureMode > 0 && GetSvPureModeFromCommandLine() <= 0) { + Msg("sv_pure must be specified on the command line to function properly. sv_pure mode not changed\n"); + return; + } +#endif + + if (pureMode == GetSvPureMode()) + Msg("sv_pure value unchanged (current value is %d).\n", GetSvPureMode()); + else { + g_sv_pure_mode = pureMode; + Msg("sv_pure set to %d.\n", g_sv_pure_mode); + +#if GMOD_DLL + if (sv.IsActive()) + Msg("Note: Changes to sv_pure take effect when the next map is loaded.\n"); +#endif + } + } + else + Msg("sv_pure: Only allow client to use certain files.\n" + + "\n" + + " -1 - Do not apply any rules or restrict which files the client may load.\n" + + " 0 - Apply rules in cfg/pure_server_minimal.txt only.\n" + + " 1 - Apply rules in cfg/pure_server_full.txt and then cfg/pure_server_whitelist.txt.\n" + + " 2 - Apply rules in cfg/pure_server_full.txt.\n" + + "\n" + + " See cfg/pure_server_whitelist_example.txt for more details.\n"); + + if (pureMode == -2) { +#if !SWDS + if (cl.IsConnected()) { + Msg("\n\n"); + CL.PrintWhitelistInfo(); + } + else +#endif + Msg("\nCurrent sv_pure value is %d.\n", GetSvPureMode()); + } + + Msg("--------------------------------------------------------\n"); + } + + public static readonly ConVar sv_pure_kick_clients = new("sv_pure_kick_clients", "1", 0,"If set to 1, the server will kick clients with mismatching files. Otherwise, it will issue a warning to the client."); public static readonly ConVar sv_pure_trace = new("sv_pure_trace", "0", 0, "If set to 1, the server will print a message whenever a client is verifying a CRC for a file."); public static readonly ConVar sv_pure_consensus = new("sv_pure_consensus", "5", 0, "Minimum number of file hashes to agree to form a consensus."); public static readonly ConVar sv_pure_retiretime = new("sv_pure_retiretime", "900", 0, "Seconds of server idle time to flush the sv_pure file hash cache."); diff --git a/Source.Engine/Server/GameServer.cs b/Source.Engine/Server/GameServer.cs index f0cf7c97e..2e786112e 100644 --- a/Source.Engine/Server/GameServer.cs +++ b/Source.Engine/Server/GameServer.cs @@ -4,6 +4,7 @@ using Source.Common.Engine; using Source.Common.Filesystem; using Source.Common.Formats.BSP; +using Source.Common.Formats.Keyvalues; using Source.Common.Networking; using Source.Common.Server; using Source.Common.Utilities; @@ -80,6 +81,34 @@ protected override BaseClient CreateNewClient(int slot) { public void SetQueryPortFromSteamServer() { // todo } + + public void CopyPureServerWhitelistToStringTable() { + if (PureServerWhitelist == null) + return; + + UtlBuffer buf = new(); + PureServerWhitelist.Encode(buf); + ServerStartupDataTable!.AddString(true, "PureServerWhitelist", buf.TellPut(), buf.Base().AsSpan(0, buf.TellPut())); + } + + public void ReloadWhitelist(ReadOnlySpan mapName) { + PureServerWhitelist = null; + + if (GetMaxClients() <= 1) + return; + + if (SV.GetSvPureMode() < 0) + return; + + PureServerWhitelist = PureServerWhitelist.Create(g_pFileSystem); + PureServerWhitelist.Load(SV.GetSvPureMode()); + + if (SV.GetSvPureMode() == 1) { + KeyValues kv = new(""); + if (kv.LoadFromFile(g_pFileSystem, $"maps/{mapName}_whitelist.txt")) + PureServerWhitelist.LoadCommandsFromKeyValues(kv); + } + } internal bool IsLevelMainMenuBackground() { return LevelMainMenuBackground; } @@ -147,7 +176,7 @@ public void CreateEngineStringTables() { ServerStartupDataTable = StringTables.CreateStringTable(Protocol.SERVER_STARTUP_DATA_TABLENAME, 4); SetQueryPortFromSteamServer(); - // CopyPureServerWhitelistToStringTable(); + CopyPureServerWhitelistToStringTable(); Assert( DownloadableFileTable != null && @@ -589,7 +618,7 @@ internal bool SpawnServer(ReadOnlySpan mapName, ReadOnlySpan mapFile } #endif - // ReloadWhitelist(mapName); + ReloadWhitelist(mapName); Common.TimestampedLog($"SV_SpawnServer({mapName})"); #if !SWDS EngineVGui().UpdateProgressBar(LevelLoadingProgress.SpawnServer); diff --git a/Source.Engine/Server/PureServerWhitelist.cs b/Source.Engine/Server/PureServerWhitelist.cs index b51552dea..a4a2a61fa 100644 --- a/Source.Engine/Server/PureServerWhitelist.cs +++ b/Source.Engine/Server/PureServerWhitelist.cs @@ -4,31 +4,480 @@ using DStruct.BinaryTrees; +using Source.Common; using Source.Common.Filesystem; +using Source.Common.Formats.Keyvalues; using Source.Common.Server; +using Source.Common.Utilities; + +using System.Runtime.InteropServices; +using System.Text; namespace Source.Engine.Server; public static class PureGlobals { public static readonly PureFileTracker g_PureFileTracker = new(); - public static PureServerWhitelist CreatePureServerWhitelist(IFileSystem fileSystem) { - throw new NotImplementedException(); - } + public static PureServerWhitelist CreatePureServerWhitelist(IFileSystem fileSystem) => PureServerWhitelist.Create(fileSystem); } public class PureServerWhitelist : IPureServerWhitelist { - public PureServerFileClass GetFileClass(ReadOnlySpan filename) { - throw new NotImplementedException(); + const ushort kLoadOrder_HardcodedOverride = 0xffff; + +#if WIN32 + const char PATH_SEPARATOR = '\\'; +#else + const char PATH_SEPARATOR = '/'; +#endif + + sealed class Command + { + public PureServerFileClass FileClass; + public ushort LoadOrder; + } + + sealed class CaselessStringLessThan : IComparer + { + public int Compare(string? lhs, string? rhs) => stricmp(lhs, rhs); + } + + ushort LoadCounter; + + readonly SortedDictionary FileCommands = new(new CaselessStringLessThan()); + readonly SortedDictionary RecursiveDirCommands = new(new CaselessStringLessThan()); + readonly SortedDictionary NonRecursiveDirCommands = new(new CaselessStringLessThan()); + + IFileSystem? FileSystem; + + readonly List TrustedKeys = []; + + public static PureServerWhitelist Create(IFileSystem fileSystem) { + PureServerWhitelist ret = new(); + ret.Init(fileSystem); + return ret; + } + + void Init(IFileSystem fileSystem) { + Term(); + FileSystem = fileSystem; + } + + public void Load(int pureMode) { + Term(); + + if (pureMode < 0) + return; + + { + KeyValues kv = new(""); + if (kv.LoadFromFile(g_pFileSystem, "cfg/trusted_keys_base.txt", "game")) + LoadTrustedKeysFromKeyValues(kv); + else + Warning("Error loading cfg/trusted_keys_base.txt\n"); + } + + if (pureMode == 0) { + KeyValues kv = new(""); + if (kv.LoadFromFile(g_pFileSystem, "cfg/pure_server_minimal.txt", "game")) + LoadCommandsFromKeyValues(kv); + else + Warning("Error loading cfg/pure_server_minimal.txt\n"); + + return; + } + + { + KeyValues kv = new(""); + if (kv.LoadFromFile(g_pFileSystem, "cfg/pure_server_full.txt", "game")) + LoadCommandsFromKeyValues(kv); + else + Warning("Error loading cfg/pure_server_full.txt\n"); + } + + if (pureMode == 1) { + { + KeyValues kv = new(""); + bool loaded = kv.LoadFromFile(g_pFileSystem, "cfg/pure_server_whitelist.txt", "game"); + if (!loaded) + loaded = kv.LoadFromFile(g_pFileSystem, "pure_server_whitelist.txt", "game"); + + if (loaded) + LoadCommandsFromKeyValues(kv); + else + Msg("pure_server_whitelist.txt not present; pure server using only base file rules\n"); + } + + KeyValues keys = new(""); + if (keys.LoadFromFile(g_pFileSystem, "cfg/trusted_keys.txt", "game")) + LoadTrustedKeysFromKeyValues(keys); + else + Msg("trusted_keys.txt not present; pure server using only base trusted key list\n"); + } + + AddHardcodedFileCommands(); + } + + void Term() { + FileCommands.Clear(); + RecursiveDirCommands.Clear(); + NonRecursiveDirCommands.Clear(); + TrustedKeys.Clear(); + LoadCounter = 0; } + public bool LoadCommandsFromKeyValues(KeyValues kv) { + Span pathName = stackalloc char[MAX_PATH]; + + for (KeyValues? curItem = kv.GetFirstValue(); curItem != null; curItem = curItem.GetNextValue()) { + string keyValue = curItem.Name; + ReadOnlySpan modifiers = curItem.GetString(); + + strcpy(pathName, keyValue); + StrTools.FixSlashes(pathName, PATH_SEPARATOR); + ReadOnlySpan value = pathName.SliceNullTerminatedString(); + + bool fromTrustedSource = false, allowFromDisk = false, checkCRC = false, any = false; + + foreach (string mod in modifiers.ToString().Split('+', StringSplitOptions.RemoveEmptyEntries)) { + if (stricmp(mod, "from_steam") == 0 || stricmp(mod, "trusted_source") == 0) + fromTrustedSource = true; + else if (stricmp(mod, "allow_from_disk") == 0) + allowFromDisk = true; + else if (stricmp(mod, "check_crc") == 0 || stricmp(mod, "check_hash") == 0) + checkCRC = true; + else if (stricmp(mod, "any") == 0) + any = true; + else + Warning("Unknown modifier in whitelist file: %s.\n", mod); + } + + if ((fromTrustedSource && (allowFromDisk || checkCRC || any)) || (any && checkCRC)) { + Warning("Whitelist: incompatible flags used on %s.\n", value.ToString()); + continue; + } + + PureServerFileClass fileClass; + if (checkCRC) + fileClass = PureServerFileClass.CheckHash; + else if (fromTrustedSource) + fileClass = PureServerFileClass.AnyTrusted; + else + fileClass = PureServerFileClass.Any; + + AddFileCommand(value, fileClass, LoadCounter++); + } + + return true; + } + + void AddHardcodedFileCommands() { + AddFileCommand("materials/vgui/replay/thumbnails/...", PureServerFileClass.Any, kLoadOrder_HardcodedOverride); + AddFileCommand("sound/ui/hitsound.wav", PureServerFileClass.Any, kLoadOrder_HardcodedOverride); + AddFileCommand("materials/vgui/logos/...", PureServerFileClass.Any, kLoadOrder_HardcodedOverride); + } + + static bool ExtractFilePath(ReadOnlySpan path, Span dest) { + int src = path.Length != 0 ? path.Length - 1 : 0; + while (src != 0 && !path[src - 1].IsPathSeparator()) + src--; + + int copysize = Math.Min(src, dest.Length - 1); + path[..copysize].CopyTo(dest); + dest[copysize] = '\0'; + + return copysize != 0; + } + + void AddFileCommand(ReadOnlySpan commandPath, PureServerFileClass fileClass, ushort loadOrder) { + Command command = new() { + LoadOrder = loadOrder, + FileClass = fileClass + }; + + SortedDictionary list; + ReadOnlySpan endPart = commandPath.UnqualifiedFileName(); + if (stricmp(endPart, "...") == 0) + list = RecursiveDirCommands; + else if (stricmp(endPart, "*.*") == 0) + list = NonRecursiveDirCommands; + else + list = FileCommands; + + Span filePath = stackalloc char[MAX_PATH]; + if (list == RecursiveDirCommands || list == NonRecursiveDirCommands) + ExtractFilePath(commandPath, filePath); + else + strcpy(filePath, commandPath); + + StrTools.FixSlashes(filePath, PATH_SEPARATOR); + + string key = new(filePath.SliceNullTerminatedString()); + list.Remove(key); + list.Add(key, command); + } + + static int Nibble(char c) { + if (c >= '0' && c <= '9') + return c - '0'; + + if (c >= 'A' && c <= 'F') + return 0x0a + (c - 'A'); + + if (c >= 'a' && c <= 'f') + return 0x0a + (c - 'a'); + + return '0'; + } + + public bool LoadTrustedKeysFromKeyValues(KeyValues kv) { + for (KeyValues? curItem = kv.GetFirstTrueSubKey(); curItem != null; curItem = curItem.GetNextTrueSubKey()) { + if (stricmp(curItem.Name, "public_key") != 0) { + Warning("Trusted key list has unexpected block '%s'; expected only 'public_key' blocks\n", curItem.Name); + continue; + } + + ReadOnlySpan type = curItem.GetString("type", "(none)"); + if (stricmp(type, "rsa") != 0) { + Warning("Trusted key type '%s' not supported.\n", type.ToString()); + continue; + } + + ReadOnlySpan keyData = curItem.GetString("rsa_public_key", ""); + if (keyData.IsEmpty) { + Warning("trusted key is missing 'rsa_public_key' data; ignored\n"); + continue; + } + + int numchars = keyData.Length & ~0x1; + byte[] bits = new byte[keyData.Length / 2]; + for (int i = 0, o = 0; i < numchars && o < bits.Length; i += 2, o++) + bits[o] = (byte)((Nibble(keyData[i]) << 4) | Nibble(keyData[i + 1])); + + TrustedKeys.Add([.. bits]); + } + + return true; + } + + static void UpdateCommandStats(SortedDictionary commands, ref int highest, ref int longestPathName) { + foreach (KeyValuePair command in commands) { + highest = Math.Max(highest, command.Value.LoadOrder); + longestPathName = Math.Max(longestPathName, command.Key.Length); + } + } + + static void PrintCommand(string fileSpec, string? ext, int maxPathnameLen, Command command) { + ReadOnlySpan tempFileSpec = fileSpec; + if (tempFileSpec.Length > 0 && (tempFileSpec[^1] == '/' || tempFileSpec[^1] == '\\')) + tempFileSpec = tempFileSpec[..^1]; + + StringBuilder buf = new(); + if (ext != null) + buf.Append(tempFileSpec).Append(PATH_SEPARATOR).Append(ext); + else + buf.Append(tempFileSpec); + + for (int i = fileSpec.Length; i < maxPathnameLen + 6; i++) + buf.Append(' '); + + buf.Append('\t'); + switch (command.FileClass) { + default: + buf.Append($"(bogus value {(int)command.FileClass})"); + Assert(false); + break; + case PureServerFileClass.Any: + buf.Append("any"); + break; + case PureServerFileClass.AnyTrusted: + buf.Append("trusted_source"); + break; + case PureServerFileClass.CheckHash: + buf.Append("check_crc"); + break; + } + + Msg("%s\n", buf.ToString()); + } + + static string? FindCommandByLoadOrder(SortedDictionary commands, int loadOrder) { + foreach (KeyValuePair command in commands) { + if (command.Value.LoadOrder == loadOrder) + return command.Key; + } + + return null; + } + + public void PrintWhitelistContents() { + int highestLoadOrder = 0, longestPathName = 0; + UpdateCommandStats(FileCommands, ref highestLoadOrder, ref longestPathName); + UpdateCommandStats(RecursiveDirCommands, ref highestLoadOrder, ref longestPathName); + UpdateCommandStats(NonRecursiveDirCommands, ref highestLoadOrder, ref longestPathName); + + for (int loadOrder = 0; loadOrder <= highestLoadOrder; loadOrder++) { + string? command = FindCommandByLoadOrder(FileCommands, loadOrder); + if (command != null) + PrintCommand(command, null, longestPathName, FileCommands[command]); + else { + command = FindCommandByLoadOrder(RecursiveDirCommands, loadOrder); + if (command != null) + PrintCommand(command, "...", longestPathName, RecursiveDirCommands[command]); + else { + command = FindCommandByLoadOrder(NonRecursiveDirCommands, loadOrder); + if (command != null) + PrintCommand(command, "*.*", longestPathName, NonRecursiveDirCommands[command]); + } + } + } + } + + public void Encode(UtlBuffer buf) { + buf.PutUnsignedInt(0xffff); + + EncodeCommandList(FileCommands, buf); + EncodeCommandList(RecursiveDirCommands, buf); + EncodeCommandList(NonRecursiveDirCommands, buf); + + buf.PutUnsignedInt((uint)TrustedKeys.Count); + for (int i = 0; i < TrustedKeys.Count; i++) { + buf.PutUnsignedInt((uint)TrustedKeys[i].Count); + buf.Put(CollectionsMarshal.AsSpan(TrustedKeys[i])); + } + } + + static void EncodeCommandList(SortedDictionary theList, UtlBuffer buf) { + int count = 0; + foreach (KeyValuePair command in theList) { + if (command.Value.LoadOrder != kLoadOrder_HardcodedOverride) + ++count; + } + + buf.PutInt(count); + + foreach (KeyValuePair command in theList) { + if (command.Value.LoadOrder == kLoadOrder_HardcodedOverride) + continue; + + buf.PutUnsignedChar((byte)command.Value.FileClass); + buf.PutUnsignedShort(command.Value.LoadOrder); + buf.PutString(command.Key); + } + } + + public void Decode(UtlBuffer buf) { + Term(); + + uint versionTag = buf.TellMaxPut() - buf.TellGet() >= sizeof(uint) ? BitConverter.ToUInt32(buf.Base(), buf.TellGet()) : 0; + uint formatVersion = 0; + if (versionTag == 0xffff) { + buf.GetUnsignedInt(); + formatVersion = 1; + } + else + Load(2); + + DecodeCommandList(FileCommands, buf, formatVersion); + DecodeCommandList(RecursiveDirCommands, buf, formatVersion); + DecodeCommandList(NonRecursiveDirCommands, buf, formatVersion); + + AddHardcodedFileCommands(); + + if (formatVersion >= 1) { + uint keyCount = buf.GetUnsignedInt(); + for (uint i = 0; i < keyCount && buf.IsValid(); i++) { // note: GMod trusts the count + uint keySize = buf.GetUnsignedInt(); + if (!buf.IsValid() || keySize > buf.TellMaxPut() - buf.TellGet()) + break; + + byte[] key = new byte[keySize]; + buf.Get(key); + TrustedKeys.Add([.. key]); + } + } + } + + void DecodeCommandList(SortedDictionary theList, UtlBuffer buf, uint formatVersion) { + Span str = stackalloc char[MAX_PATH]; + + int commands = buf.GetInt(); + for (int i = 0; i < commands && buf.IsValid(); i++) { // note: GMod trusts the count + Command command = new(); + + byte val = buf.GetUnsignedChar(); + ushort loadOrder = buf.GetUnsignedShort(); + + if (formatVersion == 0) { + command.FileClass = (val & 1) != 0 ? PureServerFileClass.Any : PureServerFileClass.AnyTrusted; + command.LoadOrder = (ushort)(loadOrder + LoadCounter); + } + else { + command.FileClass = (PureServerFileClass)val; + command.LoadOrder = loadOrder; + } + + buf.GetString(str); + StrTools.FixSlashes(str, PATH_SEPARATOR); + + theList[new(str.SliceNullTerminatedString())] = command; + } + } + + Command? GetBestEntry(ReadOnlySpan filename) { + Span relativeFilename = stackalloc char[MAX_PATH]; + strcpy(relativeFilename, filename); + + if (!StrTools.IsAbsolutePath(relativeFilename.SliceNullTerminatedString()) || FileSystem!.FullPathToRelativePath(filename, relativeFilename)) { + StrTools.FixSlashes(relativeFilename, PATH_SEPARATOR); + + Span relativeDir = stackalloc char[MAX_PATH]; + if (!ExtractFilePath(relativeFilename.SliceNullTerminatedString(), relativeDir)) + relativeDir[0] = '\0'; + + Command? bestEntry = null; + + bestEntry = CheckEntry(FileCommands, relativeFilename.SliceNullTerminatedString(), bestEntry); + if (relativeDir[0] != '\0') { + bestEntry = CheckEntry(NonRecursiveDirCommands, relativeDir.SliceNullTerminatedString(), bestEntry); + + while (relativeDir[0] != '\0') { + bestEntry = CheckEntry(RecursiveDirCommands, relativeDir.SliceNullTerminatedString(), bestEntry); + if (!StrTools.StripLastDir(relativeDir)) + break; + + StrTools.FixSlashes(relativeDir, PATH_SEPARATOR); + } + } + + return bestEntry; + } + + return null; + } + + static Command? CheckEntry(SortedDictionary dict, ReadOnlySpan entryName, Command? bestEntry) { + if (dict.TryGetValue(new(entryName), out Command? command) && (bestEntry == null || command.LoadOrder > bestEntry.LoadOrder)) + bestEntry = command; + + return bestEntry; + } + + public int GetTrustedKeyCount() => TrustedKeys.Count; + public ReadOnlySpan GetTrustedKey(int keyIndex) { - throw new NotImplementedException(); + if (keyIndex < 0 || keyIndex >= TrustedKeys.Count) + return default; + + return CollectionsMarshal.AsSpan(TrustedKeys[keyIndex]); } - public int GetTrustedKeyCount() { - throw new NotImplementedException(); + public PureServerFileClass GetFileClass(ReadOnlySpan filename) { + Command? command = GetBestEntry(filename); + if (command != null) + return command.FileClass; + + return PureServerFileClass.Any; } }