From 1ba85dac9c06025d071ef673d7130d5d107ebdb3 Mon Sep 17 00:00:00 2001 From: Asher Baker Date: Thu, 29 Oct 2015 16:29:51 +0000 Subject: [PATCH] Clean up logic source. --- core/logic/AMBuilder | 50 +- core/logic/{AdminCache.cpp => admincache.cpp} | 4158 ++++++++--------- core/logic/{AdminCache.h => admincache.h} | 0 core/logic/{ADTFactory.cpp => adtfactory.cpp} | 6 +- core/logic/{ADTFactory.h => adtfactory.h} | 0 core/logic/{CDataPack.cpp => cdatapack.cpp} | 6 +- core/logic/{CDataPack.h => cdatapack.h} | 0 core/logic/{CellArray.h => cellarray.h} | 0 core/logic/common_logic.cpp | 44 +- core/logic/{Database.cpp => database.cpp} | 34 +- core/logic/{Database.h => database.h} | 0 .../{DebugReporter.cpp => debugreporter.cpp} | 6 +- .../{DebugReporter.h => debugreporter.h} | 0 .../{ExtensionSys.cpp => extensionsys.cpp} | 48 +- core/logic/{ExtensionSys.h => extensionsys.h} | 12 +- core/logic/{ForwardSys.cpp => forwardsys.cpp} | 20 +- core/logic/{ForwardSys.h => forwardsys.h} | 32 +- .../{GameConfigs.cpp => gameconfigs.cpp} | 24 +- core/logic/{GameConfigs.h => gameconfigs.h} | 0 core/logic/{HandleSys.cpp => handlesys.cpp} | 46 +- core/logic/{HandleSys.h => handlesys.h} | 0 core/logic/{LibrarySys.cpp => librarysys.cpp} | 6 +- core/logic/{LibrarySys.h => librarysys.h} | 0 core/logic/{Logger.cpp => logger.cpp} | 16 +- core/logic/{Logger.h => logger.h} | 0 .../{MemoryUtils.cpp => memoryutils.cpp} | 50 +- core/logic/{MemoryUtils.h => memoryutils.h} | 0 .../{MersenneTwister.h => mersennetwister.h} | 0 core/logic/{Native.h => native.h} | 0 .../{NativeOwner.cpp => nativeowner.cpp} | 8 +- core/logic/{NativeOwner.h => nativeowner.h} | 6 +- ...aseCollection.cpp => phrasecollection.cpp} | 8 +- ...{PhraseCollection.h => phrasecollection.h} | 0 core/logic/{PluginSys.cpp => pluginsys.cpp} | 40 +- core/logic/{PluginSys.h => pluginsys.h} | 44 +- .../{ProfileTools.cpp => profiletools.cpp} | 382 +- core/logic/{ProfileTools.h => profiletools.h} | 0 ...ootConsoleMenu.cpp => rootconsolemenu.cpp} | 578 +-- .../{RootConsoleMenu.h => rootconsolemenu.h} | 0 core/logic/{ShareSys.cpp => sharesys.cpp} | 20 +- core/logic/{ShareSys.h => sharesys.h} | 6 +- core/logic/smn_adt_array.cpp | 2 +- core/logic/smn_adt_stack.cpp | 26 +- core/logic/smn_console.cpp | 710 +-- core/logic/smn_core.cpp | 150 +- core/logic/smn_database.cpp | 44 +- core/logic/smn_datapacks.cpp | 6 +- core/logic/smn_fakenatives.cpp | 6 +- core/logic/smn_filesystem.cpp | 60 +- core/logic/smn_float.cpp | 8 +- core/logic/smn_gameconfigs.cpp | 8 +- core/logic/smn_lang.cpp | 8 +- core/logic/smn_maplists.cpp | 24 +- core/logic/smn_menus.cpp | 16 +- core/logic/smn_players.cpp | 30 +- core/logic/smn_profiler.cpp | 6 +- core/logic/smn_sorting.cpp | 40 +- core/logic/smn_timers.cpp | 18 +- core/logic/sprintf.cpp | 2528 +++++----- core/logic/stringutil.cpp | 14 +- .../{TextParsers.cpp => textparsers.cpp} | 108 +- core/logic/{TextParsers.h => textparsers.h} | 0 .../thread/{BaseWorker.cpp => baseworker.cpp} | 8 +- .../thread/{BaseWorker.h => baseworker.h} | 4 +- .../{PosixThreads.cpp => posixthreads.cpp} | 8 +- .../thread/{PosixThreads.h => posixthreads.h} | 0 .../{ThreadWorker.cpp => threadworker.cpp} | 10 +- .../thread/{ThreadWorker.h => threadworker.h} | 4 +- .../thread/{WinThreads.cpp => winthreads.cpp} | 10 +- .../thread/{WinThreads.h => winthreads.h} | 0 .../{ThreadSupport.cpp => threadsupport.cpp} | 8 +- .../{ThreadSupport.h => threadsupport.h} | 0 core/logic/{Translator.cpp => translator.cpp} | 86 +- core/logic/{Translator.h => translator.h} | 24 +- 74 files changed, 4812 insertions(+), 4812 deletions(-) rename core/logic/{AdminCache.cpp => admincache.cpp} (95%) rename core/logic/{AdminCache.h => admincache.h} (100%) rename core/logic/{ADTFactory.cpp => adtfactory.cpp} (94%) rename core/logic/{ADTFactory.h => adtfactory.h} (100%) rename core/logic/{CDataPack.cpp => cdatapack.cpp} (94%) rename core/logic/{CDataPack.h => cdatapack.h} (100%) rename core/logic/{CellArray.h => cellarray.h} (100%) rename core/logic/{Database.cpp => database.cpp} (94%) rename core/logic/{Database.h => database.h} (100%) rename core/logic/{DebugReporter.cpp => debugreporter.cpp} (95%) rename core/logic/{DebugReporter.h => debugreporter.h} (100%) rename core/logic/{ExtensionSys.cpp => extensionsys.cpp} (95%) rename core/logic/{ExtensionSys.h => extensionsys.h} (94%) rename core/logic/{ForwardSys.cpp => forwardsys.cpp} (94%) rename core/logic/{ForwardSys.h => forwardsys.h} (87%) rename core/logic/{GameConfigs.cpp => gameconfigs.cpp} (95%) rename core/logic/{GameConfigs.h => gameconfigs.h} (100%) rename core/logic/{HandleSys.cpp => handlesys.cpp} (93%) rename core/logic/{HandleSys.h => handlesys.h} (100%) rename core/logic/{LibrarySys.cpp => librarysys.cpp} (94%) rename core/logic/{LibrarySys.h => librarysys.h} (100%) rename core/logic/{Logger.cpp => logger.cpp} (94%) rename core/logic/{Logger.h => logger.h} (100%) rename core/logic/{MemoryUtils.cpp => memoryutils.cpp} (95%) rename core/logic/{MemoryUtils.h => memoryutils.h} (100%) rename core/logic/{MersenneTwister.h => mersennetwister.h} (100%) rename core/logic/{Native.h => native.h} (100%) rename core/logic/{NativeOwner.cpp => nativeowner.cpp} (94%) rename core/logic/{NativeOwner.h => nativeowner.h} (94%) rename core/logic/{PhraseCollection.cpp => phrasecollection.cpp} (94%) rename core/logic/{PhraseCollection.h => phrasecollection.h} (100%) rename core/logic/{PluginSys.cpp => pluginsys.cpp} (95%) rename core/logic/{PluginSys.h => pluginsys.h} (93%) rename core/logic/{ProfileTools.cpp => profiletools.cpp} (96%) rename core/logic/{ProfileTools.h => profiletools.h} (100%) rename core/logic/{RootConsoleMenu.cpp => rootconsolemenu.cpp} (96%) rename core/logic/{RootConsoleMenu.h => rootconsolemenu.h} (100%) rename core/logic/{ShareSys.cpp => sharesys.cpp} (93%) rename core/logic/{ShareSys.h => sharesys.h} (95%) rename core/logic/{TextParsers.cpp => textparsers.cpp} (91%) rename core/logic/{TextParsers.h => textparsers.h} (100%) rename core/logic/thread/{BaseWorker.cpp => baseworker.cpp} (93%) rename core/logic/thread/{BaseWorker.h => baseworker.h} (96%) rename core/logic/thread/{PosixThreads.cpp => posixthreads.cpp} (93%) rename core/logic/thread/{PosixThreads.h => posixthreads.h} (100%) rename core/logic/thread/{ThreadWorker.cpp => threadworker.cpp} (94%) rename core/logic/thread/{ThreadWorker.h => threadworker.h} (96%) rename core/logic/thread/{WinThreads.cpp => winthreads.cpp} (94%) rename core/logic/thread/{WinThreads.h => winthreads.h} (100%) rename core/logic/{ThreadSupport.cpp => threadsupport.cpp} (92%) rename core/logic/{ThreadSupport.h => threadsupport.h} (100%) rename core/logic/{Translator.cpp => translator.cpp} (92%) rename core/logic/{Translator.h => translator.h} (91%) diff --git a/core/logic/AMBuilder b/core/logic/AMBuilder index 3098675d0..e26bd2f31 100644 --- a/core/logic/AMBuilder +++ b/core/logic/AMBuilder @@ -32,59 +32,59 @@ binary.sources += [ 'smn_adt_array.cpp', 'smn_sorting.cpp', 'smn_maplists.cpp', - 'ADTFactory.cpp', + 'adtfactory.cpp', 'smn_adt_stack.cpp', - 'thread/ThreadWorker.cpp', - 'thread/BaseWorker.cpp', - 'ThreadSupport.cpp', + 'thread/threadworker.cpp', + 'thread/baseworker.cpp', + 'threadsupport.cpp', 'smn_float.cpp', - 'TextParsers.cpp', + 'textparsers.cpp', 'smn_textparse.cpp', 'smn_adt_trie.cpp', 'smn_functions.cpp', 'smn_timers.cpp', 'smn_players.cpp', - 'MemoryUtils.cpp', + 'memoryutils.cpp', 'smn_admin.cpp', 'smn_banning.cpp', 'smn_filesystem.cpp', 'stringutil.cpp', - 'Translator.cpp', - 'PhraseCollection.cpp', + 'translator.cpp', + 'phrasecollection.cpp', 'smn_lang.cpp', 'smn_string.cpp', 'smn_handles.cpp', 'smn_datapacks.cpp', 'smn_gameconfigs.cpp', 'smn_fakenatives.cpp', - 'GameConfigs.cpp', + 'gameconfigs.cpp', 'sm_crc32.cpp', 'smn_profiler.cpp', - 'ShareSys.cpp', - 'PluginSys.cpp', - 'HandleSys.cpp', - 'NativeOwner.cpp', - 'ExtensionSys.cpp', - 'DebugReporter.cpp', - 'Database.cpp', + 'sharesys.cpp', + 'pluginsys.cpp', + 'handlesys.cpp', + 'nativeowner.cpp', + 'extensionsys.cpp', + 'debugreporter.cpp', + 'database.cpp', 'smn_database.cpp', - 'ForwardSys.cpp', - 'AdminCache.cpp', + 'forwardsys.cpp', + 'admincache.cpp', 'sm_trie.cpp', 'smn_console.cpp', - 'ProfileTools.cpp', - 'Logger.cpp', + 'profiletools.cpp', + 'logger.cpp', 'smn_core.cpp', 'smn_menus.cpp', 'sprintf.cpp', - 'LibrarySys.cpp', - 'RootConsoleMenu.cpp', - 'CDataPack.cpp', + 'librarysys.cpp', + 'rootconsolemenu.cpp', + 'cdatapack.cpp', 'frame_tasks.cpp', ] if builder.target_platform == 'windows': - binary.sources += ['thread/WinThreads.cpp'] + binary.sources += ['thread/winthreads.cpp'] else: - binary.sources += ['thread/PosixThreads.cpp'] + binary.sources += ['thread/posixthreads.cpp'] SM.binaries += [builder.Add(binary)] diff --git a/core/logic/AdminCache.cpp b/core/logic/admincache.cpp similarity index 95% rename from core/logic/AdminCache.cpp rename to core/logic/admincache.cpp index 5ae0b02dc..9ab8cf233 100644 --- a/core/logic/AdminCache.cpp +++ b/core/logic/admincache.cpp @@ -1,2079 +1,2079 @@ -/** - * vim: set ts=4 sw=4 tw=99 noet : - * ============================================================================= - * SourceMod - * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#include -#include -#include -#include -#include -#include -#include -#include "AdminCache.h" -#include "Translator.h" -#include "common_logic.h" -#include "stringutil.h" -#include -#include -#include - -#define LEVEL_STATE_NONE 0 -#define LEVEL_STATE_LEVELS 1 -#define LEVEL_STATE_FLAGS 2 - -AdminCache g_Admins; -char g_ReverseFlags[AdminFlags_TOTAL]; -AdminFlag g_FlagLetters[26]; -bool g_FlagCharSet[26]; - -/* Default flags */ -AdminFlag g_DefaultFlags[26] = -{ - Admin_Reservation, Admin_Generic, Admin_Kick, Admin_Ban, Admin_Unban, - Admin_Slay, Admin_Changemap, Admin_Convars, Admin_Config, Admin_Chat, - Admin_Vote, Admin_Password, Admin_RCON, Admin_Cheats, Admin_Custom1, - Admin_Custom2, Admin_Custom3, Admin_Custom4, Admin_Custom5, Admin_Custom6, - Admin_Generic, Admin_Generic, Admin_Generic, Admin_Generic, Admin_Generic, - Admin_Root -}; - - -class FlagReader : public ITextListener_SMC -{ -public: - void LoadLevels() - { - if (!Parse()) - { - memcpy(g_FlagLetters, g_DefaultFlags, sizeof(AdminFlag) * 26); - for (unsigned int i=0; i<20; i++) - { - g_FlagCharSet[i] = true; - } - g_FlagCharSet[25] = true; - } - } -private: - bool Parse() - { - SMCStates states; - SMCError error; - - m_bFileNameLogged = false; - g_pSM->BuildPath(Path_SM, m_File, sizeof(m_File), "configs/admin_levels.cfg"); - - if ((error = textparsers->ParseFile_SMC(m_File, this, &states)) - != SMCError_Okay) - { - const char *err_string = textparsers->GetSMCErrorString(error); - if (!err_string) - { - err_string = "Unknown error"; - } - ParseError(NULL, "Error %d (%s)", error, err_string); - return false; - } - - return true; - } - void ReadSMC_ParseStart() - { - m_LevelState = LEVEL_STATE_NONE; - m_IgnoreLevel = 0; - memset(g_FlagCharSet, 0, sizeof(g_FlagCharSet)); - } - SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name) - { - if (m_IgnoreLevel) - { - m_IgnoreLevel++; - return SMCResult_Continue; - } - - if (m_LevelState == LEVEL_STATE_NONE) - { - if (strcmp(name, "Levels") == 0) - { - m_LevelState = LEVEL_STATE_LEVELS; - } - else - { - m_IgnoreLevel++; - } - } else if (m_LevelState == LEVEL_STATE_LEVELS) { - if (strcmp(name, "Flags") == 0) - { - m_LevelState = LEVEL_STATE_FLAGS; - } - else - { - m_IgnoreLevel++; - } - } - else - { - m_IgnoreLevel++; - } - - return SMCResult_Continue; - } - SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value) - { - if (m_LevelState != LEVEL_STATE_FLAGS || m_IgnoreLevel) - { - return SMCResult_Continue; - } - - unsigned char c = (unsigned)value[0]; - - if (c < (unsigned)'a' || c > (unsigned)'z') - { - ParseError(states, "Flag \"%c\" is not a lower-case ASCII letter", c); - return SMCResult_Continue; - } - - c -= (unsigned)'a'; - - if (!g_Admins.FindFlag(key, &g_FlagLetters[c])) - { - ParseError(states, "Unrecognized admin level \"%s\"", key); - return SMCResult_Continue; - } - - g_FlagCharSet[c] = true; - - return SMCResult_Continue; - } - SMCResult ReadSMC_LeavingSection(const SMCStates *states) - { - if (m_IgnoreLevel) - { - m_IgnoreLevel--; - return SMCResult_Continue; - } - - if (m_LevelState == LEVEL_STATE_FLAGS) - { - m_LevelState = LEVEL_STATE_LEVELS; - return SMCResult_Halt; - } - else if (m_LevelState == LEVEL_STATE_LEVELS) - { - m_LevelState = LEVEL_STATE_NONE; - } - - return SMCResult_Continue; - } - void ParseError(const SMCStates *states, const char *message, ...) - { - va_list ap; - char buffer[256]; - - va_start(ap, message); - g_pSM->FormatArgs(buffer, sizeof(buffer), message, ap); - va_end(ap); - - if (!m_bFileNameLogged) - { - logger->LogError("[SM] Parse error(s) detected in file \"%s\":", m_File); - m_bFileNameLogged = true; - } - - logger->LogError("[SM] (Line %d): %s", states ? states->line : 0, buffer); - } -private: - bool m_bFileNameLogged; - char m_File[PLATFORM_MAX_PATH]; - int m_LevelState; - int m_IgnoreLevel; -} s_FlagReader; - -AdminCache::AdminCache() -{ - m_pStrings = new BaseStringTable(1024); - m_pMemory = m_pStrings->GetMemTable(); - m_FreeGroupList = m_FirstGroup = m_LastGroup = INVALID_GROUP_ID; - m_FreeUserList = m_FirstUser = m_LastUser = INVALID_ADMIN_ID; - m_pCacheFwd = NULL; - m_FirstGroup = -1; - m_InvalidatingAdmins = false; - m_destroying = false; -} - -AdminCache::~AdminCache() -{ - m_destroying = true; - DumpAdminCache(AdminCache_Overrides, false); - DumpAdminCache(AdminCache_Groups, false); - - List::iterator iter; - for (iter=m_AuthMethods.begin(); - iter!=m_AuthMethods.end(); - iter++) - { - delete *iter; - } - - delete m_pStrings; -} - -void AdminCache::OnSourceModStartup(bool late) -{ - RegisterAuthIdentType("steam"); - RegisterAuthIdentType("name"); - RegisterAuthIdentType("ip"); - - NameFlag("reservation", Admin_Reservation); - NameFlag("kick", Admin_Kick); - NameFlag("generic", Admin_Generic); - NameFlag("ban", Admin_Ban); - NameFlag("unban", Admin_Unban); - NameFlag("slay", Admin_Slay); - NameFlag("changemap", Admin_Changemap); - NameFlag("cvars", Admin_Convars); - NameFlag("config", Admin_Config); - NameFlag("chat", Admin_Chat); - NameFlag("vote", Admin_Vote); - NameFlag("password", Admin_Password); - NameFlag("rcon", Admin_RCON); - NameFlag("cheats", Admin_Cheats); - NameFlag("root", Admin_Root); - NameFlag("custom1", Admin_Custom1); - NameFlag("custom2", Admin_Custom2); - NameFlag("custom3", Admin_Custom3); - NameFlag("custom4", Admin_Custom4); - NameFlag("custom5", Admin_Custom5); - NameFlag("custom6", Admin_Custom6); - - auto sm_dump_admcache = [this] (int client, const ICommandArgs *args) -> bool { - char buffer[PLATFORM_MAX_PATH]; - g_pSM->BuildPath(Path_SM, buffer, sizeof(buffer), "data/admin_cache_dump.txt"); - - if (!DumpCache(buffer)) { - bridge->ConsolePrint("Could not open file for writing: %s", buffer); - return true; - } - - bridge->ConsolePrint("Admin cache dumped to: %s", buffer); - return true; - }; - - bridge->DefineCommand("sm_dump_admcache", "Dumps the admin cache for debugging", sm_dump_admcache); -} - -void AdminCache::OnSourceModAllInitialized() -{ - m_pCacheFwd = forwardsys->CreateForward("OnRebuildAdminCache", ET_Ignore, 1, NULL, Param_Cell); - sharesys->AddInterface(NULL, this); -} - -void AdminCache::OnSourceModLevelChange(const char *mapName) -{ - int i; - AdminFlag flag; - - /* For now, we only read these once per level. */ - s_FlagReader.LoadLevels(); - - memset(g_ReverseFlags, '?', sizeof(g_ReverseFlags)); - - for (i = 0; i < 26; i++) - { - if (FindFlag('a' + i, &flag)) - { - g_ReverseFlags[flag] = 'a' + i; - } - } -} - -void AdminCache::OnSourceModShutdown() -{ - forwardsys->ReleaseForward(m_pCacheFwd); - m_pCacheFwd = NULL; -} - -void AdminCache::OnSourceModPluginsLoaded() -{ - DumpAdminCache(AdminCache_Overrides, true); - DumpAdminCache(AdminCache_Groups, true); -} - -void AdminCache::NameFlag(const char *str, AdminFlag flag) -{ - m_LevelNames.insert(str, flag); -} - -bool AdminCache::FindFlag(const char *str, AdminFlag *pFlag) -{ - return m_LevelNames.retrieve(str, pFlag); -} - -void AdminCache::AddCommandOverride(const char *cmd, OverrideType type, FlagBits flags) -{ - FlagMap *map; - if (type == Override_Command) - map = &m_CmdOverrides; - else if (type == Override_CommandGroup) - map = &m_CmdGrpOverrides; - else - return; - - map->insert(cmd, flags); - bridge->UpdateAdminCmdFlags(cmd, type, flags, false); -} - -bool AdminCache::GetCommandOverride(const char *cmd, OverrideType type, FlagBits *pFlags) -{ - FlagMap *map; - if (type == Override_Command) - map = &m_CmdOverrides; - else if (type == Override_CommandGroup) - map = &m_CmdGrpOverrides; - else - return false; - - return map->retrieve(cmd, pFlags); -} - -void AdminCache::UnsetCommandOverride(const char *cmd, OverrideType type) -{ - if (type == Override_Command) - { - return _UnsetCommandOverride(cmd); - } else if (type == Override_CommandGroup) { - return _UnsetCommandGroupOverride(cmd); - } -} - -void AdminCache::_UnsetCommandGroupOverride(const char *group) -{ - m_CmdGrpOverrides.remove(group); - bridge->UpdateAdminCmdFlags(group, Override_CommandGroup, 0, true); -} - -void AdminCache::_UnsetCommandOverride(const char *cmd) -{ - m_CmdOverrides.remove(cmd); - bridge->UpdateAdminCmdFlags(cmd, Override_Command, 0, true); -} - -void AdminCache::DumpCommandOverrideCache(OverrideType type) -{ - if (type == Override_Command) - m_CmdOverrides.clear(); - else if (type == Override_CommandGroup) - m_CmdGrpOverrides.clear(); -} - -AdminId AdminCache::CreateAdmin(const char *name) -{ - AdminId id; - AdminUser *pUser; - - if (m_FreeUserList != INVALID_ADMIN_ID) - { - pUser = (AdminUser *)m_pMemory->GetAddress(m_FreeUserList); - assert(pUser->magic == USR_MAGIC_UNSET); - id = m_FreeUserList; - m_FreeUserList = pUser->next_user; - } - else - { - id = m_pMemory->CreateMem(sizeof(AdminUser), (void **)&pUser); - pUser->grp_size = 0; - pUser->grp_table = -1; - } - - pUser->flags = 0; - pUser->eflags = 0; - pUser->grp_count = 0; - pUser->password = -1; - pUser->magic = USR_MAGIC_SET; - pUser->auth.identidx = -1; - pUser->auth.index = 0; - pUser->immunity_level = 0; - pUser->serialchange = 1; - - if (m_FirstUser == INVALID_ADMIN_ID) - { - m_FirstUser = id; - m_LastUser = id; - } - else - { - AdminUser *pPrev = (AdminUser *)m_pMemory->GetAddress(m_LastUser); - pPrev->next_user = id; - pUser->prev_user = m_LastUser; - m_LastUser = id; - } - - /* Since we always append to the tail, we should invalidate their next */ - pUser->next_user = -1; - - if (name && name[0] != '\0') - { - int nameidx = m_pStrings->AddString(name); - pUser = (AdminUser *)m_pMemory->GetAddress(id); - pUser->nameidx = nameidx; - } - else - { - pUser->nameidx = -1; - } - - return id; -} - -GroupId AdminCache::AddGroup(const char *group_name) -{ - if (m_Groups.contains(group_name)) - return INVALID_GROUP_ID; - - GroupId id; - AdminGroup *pGroup; - if (m_FreeGroupList != INVALID_GROUP_ID) - { - pGroup = (AdminGroup *)m_pMemory->GetAddress(m_FreeGroupList); - assert(pGroup->magic == GRP_MAGIC_UNSET); - id = m_FreeGroupList; - m_FreeGroupList = pGroup->next_grp; - } else { - id = m_pMemory->CreateMem(sizeof(AdminGroup), (void **)&pGroup); - } - - pGroup->immunity_level = 0; - pGroup->immune_table = -1; - pGroup->magic = GRP_MAGIC_SET; - pGroup->next_grp = INVALID_GROUP_ID; - pGroup->pCmdGrpTable = NULL; - pGroup->pCmdTable = NULL; - pGroup->addflags = 0; - - if (m_FirstGroup == INVALID_GROUP_ID) - { - m_FirstGroup = id; - m_LastGroup = id; - pGroup->prev_grp = INVALID_GROUP_ID; - } else { - AdminGroup *pPrev = (AdminGroup *)m_pMemory->GetAddress(m_LastGroup); - assert(pPrev->magic == GRP_MAGIC_SET); - pPrev->next_grp = id; - pGroup->prev_grp = m_LastGroup; - m_LastGroup = id; - } - - int nameidx = m_pStrings->AddString(group_name); - pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - pGroup->nameidx = nameidx; - - m_Groups.insert(group_name, id); - return id; -} - -GroupId AdminCache::FindGroupByName(const char *group_name) -{ - GroupId id; - if (!m_Groups.retrieve(group_name, &id)) - return INVALID_GROUP_ID; - - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - return INVALID_GROUP_ID; - - return id; -} - -void AdminCache::SetGroupAddFlag(GroupId id, AdminFlag flag, bool enabled) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return; - } - - if (flag < Admin_Reservation || flag >= AdminFlags_TOTAL) - { - return; - } - - FlagBits bits = (1<<(FlagBits)flag); - - if (enabled) - { - pGroup->addflags |= bits; - } else { - pGroup->addflags &= ~bits; - } -} - -bool AdminCache::GetGroupAddFlag(GroupId id, AdminFlag flag) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return false; - } - - if (flag < Admin_Reservation || flag >= AdminFlags_TOTAL) - { - return false; - } - - FlagBits bit = 1<<(FlagBits)flag; - return ((pGroup->addflags & bit) == bit); -} - -FlagBits AdminCache::GetGroupAddFlags(GroupId id) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return 0; - } - - return pGroup->addflags; -} - -const char *AdminCache::GetGroupName(GroupId gid) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return NULL; - } - - return m_pStrings->GetString(pGroup->nameidx); -} - -void AdminCache::SetGroupGenericImmunity(GroupId id, ImmunityType type, bool enabled) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return; - } - - unsigned int level = 0; - - if (enabled) - { - if (type == Immunity_Default) - { - level = 1; - } else if (type == Immunity_Global) { - level = 2; - } - if (level > pGroup->immunity_level) - { - pGroup->immunity_level = level; - } - } else { - pGroup->immunity_level = 0; - } -} - -bool AdminCache::GetGroupGenericImmunity(GroupId id, ImmunityType type) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return false; - } - - if (type == Immunity_Default && pGroup->immunity_level >= 1) - { - return true; - } else if (type == Immunity_Global && pGroup->immunity_level >= 2) { - return true; - } - - return false; -} - -void AdminCache::AddGroupImmunity(GroupId id, GroupId other_id) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(other_id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return; - } - - pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return; - } - - /* We always need to resize the immunity table */ - int *table, tblidx; - if (pGroup->immune_table == -1) - { - tblidx = m_pMemory->CreateMem(sizeof(int) * 2, (void **)&table); - pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - table[0] = 0; - } else { - int *old_table = (int *)m_pMemory->GetAddress(pGroup->immune_table); - /* Break out if this group is already in the list */ - for (int i=0; iCreateMem(sizeof(int) * (old_table[0] + 2), (void **)&table); - /* Get the old address again in case of resize */ - pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - old_table = (int *)m_pMemory->GetAddress(pGroup->immune_table); - table[0] = old_table[0]; - for (unsigned int i=1; i<=(unsigned int)old_table[0]; i++) - { - table[i] = old_table[i]; - } - } - - /* Assign */ - pGroup->immune_table = tblidx; - - /* Add to the array */ - table[0]++; - table[table[0]] = other_id; -} - -unsigned int AdminCache::GetGroupImmunityCount(GroupId id) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return 0; - } - - if (pGroup->immune_table == -1) - { - return 0; - } - - int *table = (int *)m_pMemory->GetAddress(pGroup->immune_table); - - return table[0]; -} - -GroupId AdminCache::GetGroupImmunity(GroupId id, unsigned int number) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return INVALID_GROUP_ID; - } - - if (pGroup->immune_table == -1) - { - return INVALID_GROUP_ID; - } - - int *table = (int *)m_pMemory->GetAddress(pGroup->immune_table); - if (number >= (unsigned int)table[0]) - { - return INVALID_GROUP_ID; - } - - return table[1 + number]; -} - -void AdminCache::AddGroupCommandOverride(GroupId id, const char *name, OverrideType type, OverrideRule rule) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return; - } - - OverrideMap *map; - if (type == Override_Command) - { - if (pGroup->pCmdTable == NULL) - pGroup->pCmdTable = new OverrideMap(); - map = pGroup->pCmdTable; - } else if (type == Override_CommandGroup) { - if (pGroup->pCmdGrpTable == NULL) - pGroup->pCmdGrpTable = new OverrideMap(); - map = pGroup->pCmdGrpTable; - } else { - return; - } - - map->insert(name, rule); -} - -bool AdminCache::GetGroupCommandOverride(GroupId id, const char *name, OverrideType type, OverrideRule *pRule) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return false; - } - - OverrideMap *map; - if (type == Override_Command) - { - if (pGroup->pCmdTable == NULL) - return false; - map = pGroup->pCmdTable; - } else if (type == Override_CommandGroup) { - if (pGroup->pCmdGrpTable == NULL) - return false; - map = pGroup->pCmdGrpTable; - } else { - return false; - } - - return map->retrieve(name, pRule); -} - -AuthMethod *AdminCache::GetMethodByIndex(unsigned int index) -{ - List::iterator iter; - for (iter=m_AuthMethods.begin(); - iter!=m_AuthMethods.end(); - iter++) - { - if (index-- == 0) - { - return *iter; - } - } - - return NULL; -} - -bool AdminCache::InvalidateAdmin(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - AdminUser *pOther; - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return false; - } - - if (!m_InvalidatingAdmins && !m_destroying) - { - playerhelpers->ClearAdminId(id); - } - - /* Unlink from the dbl link list */ - if (id == m_FirstUser && id == m_LastUser) - { - m_FirstUser = INVALID_ADMIN_ID; - m_LastUser = INVALID_ADMIN_ID; - } else if (id == m_FirstUser) { - m_FirstUser = pUser->next_user; - pOther = (AdminUser *)m_pMemory->GetAddress(m_FirstUser); - pOther->prev_user = INVALID_ADMIN_ID; - } else if (id == m_LastUser) { - m_LastUser = pUser->prev_user; - pOther = (AdminUser *)m_pMemory->GetAddress(m_LastUser); - pOther->next_user = INVALID_ADMIN_ID; - } else { - pOther = (AdminUser *)m_pMemory->GetAddress(pUser->prev_user); - pOther->next_user = pUser->next_user; - pOther = (AdminUser *)m_pMemory->GetAddress(pUser->next_user); - pOther->prev_user = pUser->prev_user; - } - - /* Unlink from auth tables */ - if (pUser->auth.identidx != -1) - { - AuthMethod *method = GetMethodByIndex(pUser->auth.index); - if (method) - method->identities.remove(m_pStrings->GetString(pUser->auth.identidx)); - } - - /* Clear table counts */ - pUser->grp_count = 0; - - /* Link into free list */ - pUser->magic = USR_MAGIC_UNSET; - pUser->next_user = m_FreeUserList; - m_FreeUserList = id; - - /* Unset serial change */ - pUser->serialchange = 0; - - return true; -} - - -void AdminCache::InvalidateGroup(GroupId id) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); - AdminGroup *pOther; - - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return; - } - - const char *str = m_pStrings->GetString(pGroup->nameidx); - m_Groups.remove(str); - - /* Unlink from the live dbllink list */ - if (id == m_FirstGroup && id == m_LastGroup) - { - m_LastGroup = INVALID_GROUP_ID; - m_FirstGroup = INVALID_GROUP_ID; - } else if (id == m_FirstGroup) { - m_FirstGroup = pGroup->next_grp; - pOther = (AdminGroup *)m_pMemory->GetAddress(m_FirstGroup); - pOther->prev_grp = INVALID_GROUP_ID; - } else if (id == m_LastGroup) { - m_LastGroup = pGroup->prev_grp; - pOther = (AdminGroup *)m_pMemory->GetAddress(m_LastGroup); - pOther->next_grp = INVALID_GROUP_ID; - } else { - pOther = (AdminGroup *)m_pMemory->GetAddress(pGroup->prev_grp); - pOther->next_grp = pGroup->next_grp; - pOther = (AdminGroup *)m_pMemory->GetAddress(pGroup->next_grp); - pOther->prev_grp = pGroup->prev_grp; - } - - /* Free any used memory */ - delete pGroup->pCmdGrpTable; - pGroup->pCmdGrpTable = NULL; - delete pGroup->pCmdTable; - pGroup->pCmdTable = NULL; - - /* Link into the free list */ - pGroup->magic = GRP_MAGIC_UNSET; - pGroup->next_grp = m_FreeGroupList; - m_FreeGroupList = id; - - int idx = m_FirstUser; - AdminUser *pUser; - int *table; - while (idx != INVALID_ADMIN_ID) - { - pUser = (AdminUser *)m_pMemory->GetAddress(idx); - if (pUser->grp_count > 0) - { - table = (int *)m_pMemory->GetAddress(pUser->grp_table); - for (unsigned int i=0; igrp_count; i++) - { - if (table[i] == id) - { - /* We have to remove this entry */ - for (unsigned int j=i+1; jgrp_count; j++) - { - /* Move everything down by one */ - table[j-1] = table[j]; - } - /* Decrease count */ - pUser->grp_count--; - /* Recalculate effective flags */ - pUser->eflags = pUser->flags; - for (unsigned int j=0; jgrp_count; j++) - { - pOther = (AdminGroup *)m_pMemory->GetAddress(table[j]); - pUser->eflags |= pOther->addflags; - } - /* Mark as changed */ - pUser->serialchange++; - /* Break now, duplicates aren't allowed */ - break; - } - } - } - idx = pUser->next_user; - } -} - -void AdminCache::InvalidateGroupCache() -{ - /* Nuke the free list */ - m_FreeGroupList = -1; - - /* Nuke reverse lookups */ - m_Groups.clear(); - - /* Free memory on groups */ - GroupId cur = m_FirstGroup; - AdminGroup *pGroup; - while (cur != INVALID_GROUP_ID) - { - pGroup = (AdminGroup *)m_pMemory->GetAddress(cur); - assert(pGroup->magic == GRP_MAGIC_SET); - delete pGroup->pCmdGrpTable; - delete pGroup->pCmdTable; - cur = pGroup->next_grp; - } - - m_FirstGroup = INVALID_GROUP_ID; - m_LastGroup = INVALID_GROUP_ID; - - InvalidateAdminCache(false); - - /* Reset the memory table */ - m_pMemory->Reset(); -} - -void AdminCache::AddAdminListener(IAdminListener *pListener) -{ - m_hooks.push_back(pListener); -} - -void AdminCache::RemoveAdminListener(IAdminListener *pListener) -{ - m_hooks.remove(pListener); -} - -void AdminCache::RegisterAuthIdentType(const char *name) -{ - if (m_AuthTables.contains(name)) - return; - - AuthMethod *method = new AuthMethod(name); - m_AuthMethods.push_back(method); - m_AuthTables.insert(name, method); -} - -void AdminCache::InvalidateAdminCache(bool unlink_admins) -{ - m_InvalidatingAdmins = true; - if (!m_destroying) - { - int maxClients = playerhelpers->GetMaxClients(); - for (int i = 1; i <= maxClients; ++i) - { - playerhelpers->GetGamePlayer(i)->ClearAdmin(); - } - } - /* Wipe the identity cache first */ - List::iterator iter; - for (iter=m_AuthMethods.begin(); - iter!=m_AuthMethods.end(); - iter++) - { - (*iter)->identities.clear(); - } - - if (unlink_admins) - { - while (m_FirstUser != INVALID_ADMIN_ID) - { - InvalidateAdmin(m_FirstUser); - } - } else { - m_FirstUser = -1; - m_LastUser = -1; - m_FreeUserList = -1; - } - m_InvalidatingAdmins = false; -} - -void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild) -{ - List::iterator iter; - IAdminListener *pListener; - - if (part == AdminCache_Overrides) - { - DumpCommandOverrideCache(Override_Command); - DumpCommandOverrideCache(Override_CommandGroup); - if (rebuild && !m_destroying) - { - for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) - { - pListener = (*iter); - pListener->OnRebuildOverrideCache(); - } - m_pCacheFwd->PushCell(part); - m_pCacheFwd->Execute(); - } - } else if (part == AdminCache_Groups || part == AdminCache_Admins) { - if (part == AdminCache_Groups) - { - InvalidateGroupCache(); - if (rebuild && !m_destroying) - { - for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) - { - pListener = (*iter); - pListener->OnRebuildGroupCache(); - } - m_pCacheFwd->PushCell(part); - m_pCacheFwd->Execute(); - } - } - InvalidateAdminCache(true); - if (rebuild && !m_destroying) - { - for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) - { - pListener = (*iter); - pListener->OnRebuildAdminCache((part == AdminCache_Groups)); - } - m_pCacheFwd->PushCell(AdminCache_Admins); - m_pCacheFwd->Execute(); - playerhelpers->RecheckAnyAdmins(); - } - } -} - -const char *AdminCache::GetAdminName(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return NULL; - } - - return m_pStrings->GetString(pUser->nameidx); -} - -bool AdminCache::GetMethodIndex(const char *name, unsigned int *_index) -{ - List::iterator iter; - unsigned int index = 0; - for (iter=m_AuthMethods.begin(); - iter!=m_AuthMethods.end(); - iter++,index++) - { - if ((*iter)->name.compare(name) == 0) - { - *_index = index; - return true; - } - } - - return false; -} - -/* - * Converts Steam2 id, Steam3 id, or SteamId64 to unified, legacy - * admin identity format. (account id part of Steam2 format) - */ -bool AdminCache::GetUnifiedSteamIdentity(const char *ident, char *out, size_t maxlen) -{ - int len = strlen(ident); - if (!strcmp(ident, "BOT")) - { - // Bots - strncopy(out, ident, maxlen); - return true; - } - else if (len >= 11 && !strncmp(ident, "STEAM_", 6) && ident[8] != '_') - { - // non-bot/lan Steam2 Id, strip off the STEAM_* part - snprintf(out, maxlen, "%s", &ident[8]); - return true; - } - else if (len >= 7 && !strncmp(ident, "[U:", 3) && ident[len-1] == ']') - { - // Steam3 Id, replicate the Steam2 Post-"STEAM_" part - uint32_t accountId = strtoul(&ident[5], nullptr, 10); - snprintf(out, maxlen, "%u:%u", accountId & 1, accountId >> 1); - return true; - } - else - { - // 64-bit CSteamID, replicate the Steam2 Post-"STEAM_" part - - // some constants from steamclientpublic.h - static const uint32_t k_EAccountTypeIndividual = 1; - static const int k_EUniverseInvalid = 0; - static const int k_EUniverseMax = 5; - static const unsigned int k_unSteamUserWebInstance = 4; - - uint64_t steamId = strtoull(ident, nullptr, 10); - if (steamId > 0) - { - // Make some attempt at being sure it's a valid id rather than other number, - // even though we're only going to use the lower 32 bits. - uint32_t accountId = steamId & 0xFFFFFFFF; - uint32_t accountType = (steamId >> 52) & 0xF; - int universe = steamId >> 56; - uint32_t accountInstance = (steamId >> 32) & 0xFFFFF; - if (accountId > 0 - && universe > k_EUniverseInvalid && universe < k_EUniverseMax - && accountType == k_EAccountTypeIndividual && accountInstance <= k_unSteamUserWebInstance - ) - { - snprintf(out, maxlen, "%u:%u", accountId & 1, accountId >> 1); - return true; - } - } - } - - return false; -} - -bool AdminCache::BindAdminIdentity(AdminId id, const char *auth, const char *ident) -{ - if (ident[0] == '\0') - { - return false; - } - - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return false; - } - - AuthMethod *method; - if (!m_AuthTables.retrieve(auth, &method)) - return false; - - /* If the auth type is steam, the id could be in a number of formats. Unify it. */ - char steamIdent[16]; - if (strcmp(auth, "steam") == 0) - { - if (!GetUnifiedSteamIdentity(ident, steamIdent, sizeof(steamIdent))) - return false; - - ident = steamIdent; - } - - if (method->identities.contains(ident)) - return false; - - int i_ident = m_pStrings->AddString(ident); - - pUser = (AdminUser *)m_pMemory->GetAddress(id); - pUser->auth.identidx = i_ident; - GetMethodIndex(auth, &pUser->auth.index); - - return method->identities.insert(ident, id); -} - -AdminId AdminCache::FindAdminByIdentity(const char *auth, const char *identity) -{ - AuthMethod *method; - if (!m_AuthTables.retrieve(auth, &method)) - return INVALID_ADMIN_ID; - - /* If the auth type is steam, the id could be in a number of formats. Unify it. */ - char steamIdent[16]; - if (strcmp(auth, "steam") == 0) - { - if (!GetUnifiedSteamIdentity(identity, steamIdent, sizeof(steamIdent))) - return INVALID_ADMIN_ID; - - identity = steamIdent; - } - - AdminId id; - if (!method->identities.retrieve(identity, &id)) - return INVALID_ADMIN_ID; - return id; -} - -void AdminCache::SetAdminFlag(AdminId id, AdminFlag flag, bool enabled) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return; - } - - if (flag < Admin_Reservation - || flag >= AdminFlags_TOTAL) - { - return; - } - - FlagBits bits = (1<<(FlagBits)flag); - - if (enabled) - { - pUser->flags |= bits; - pUser->eflags |= bits; - } else { - pUser->flags &= ~bits; - pUser->eflags &= ~bits; - } - - pUser->serialchange++; -} - -bool AdminCache::GetAdminFlag(AdminId id, AdminFlag flag, AccessMode mode) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return false; - } - - if (flag < Admin_Reservation - || flag >= AdminFlags_TOTAL) - { - return false; - } - - FlagBits bit = (1<<(FlagBits)flag); - - if (mode == Access_Real) - { - return ((pUser->flags & bit) == bit); - } else if (mode == Access_Effective) { - bool has_bit = ((pUser->eflags & bit) == bit); - if (!has_bit && flag != Admin_Root && ((pUser->eflags & ADMFLAG_ROOT) == ADMFLAG_ROOT)) - { - has_bit = true; - } - return has_bit; - } - - return false; -} - -FlagBits AdminCache::GetAdminFlags(AdminId id, AccessMode mode) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return 0; - } - - if (mode == Access_Real) - { - return pUser->flags; - } else if (mode == Access_Effective) { - return pUser->eflags; - } - - return 0; -} - -void AdminCache::SetAdminFlags(AdminId id, AccessMode mode, FlagBits bits) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return; - } - - if (mode == Access_Real) - { - pUser->flags = bits; - pUser->eflags = bits; - } else if (mode == Access_Effective) { - pUser->eflags = bits; - } - - pUser->serialchange++; -} - -bool AdminCache::AdminInheritGroup(AdminId id, GroupId gid) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return false; - } - - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return false; - } - - /* First check for duplicates */ - if (pUser->grp_count != 0) - { - int *temp_table = (int *)m_pMemory->GetAddress(pUser->grp_table); - for (unsigned int i=0; igrp_count; i++) - { - if (temp_table[i] == gid) - { - return false; - } - } - } - - int *table; - if (pUser->grp_count + 1 > pUser->grp_size) - { - int new_size = 0; - int tblidx; - - if (pUser->grp_size == 0) - { - new_size = 2; - } else { - new_size = pUser->grp_size * 2; - } - - /* Create and refresh pointers */ - tblidx = m_pMemory->CreateMem(new_size * sizeof(int), (void **)&table); - pUser = (AdminUser *)m_pMemory->GetAddress(id); - pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); - - /* Copy old data if necessary */ - if (pUser->grp_table != -1) - { - int *old_table = (int *)m_pMemory->GetAddress(pUser->grp_table); - memcpy(table, old_table, sizeof(int) * pUser->grp_count); - } - pUser->grp_table = tblidx; - pUser->grp_size = new_size; - } else { - table = (int *)m_pMemory->GetAddress(pUser->grp_table); - } - - table[pUser->grp_count] = gid; - pUser->grp_count++; - - /* Compute new effective permissions */ - pUser->eflags |= pGroup->addflags; - - if (pGroup->immunity_level > pUser->immunity_level) - { - pUser->immunity_level = pGroup->immunity_level; - } - - pUser->serialchange++; - - return true; -} - -bool AdminCache::IsValidAdmin(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - return (pUser != NULL && pUser->magic == USR_MAGIC_SET); -} - -unsigned int AdminCache::GetAdminGroupCount(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return 0; - } - - return pUser->grp_count; -} - -GroupId AdminCache::GetAdminGroup(AdminId id, unsigned int index, const char **name) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET || index >= pUser->grp_count) - { - return INVALID_GROUP_ID; - } - - int *table = (int *)m_pMemory->GetAddress(pUser->grp_table); - - GroupId gid = table[index]; - - if (name) - { - *name = GetGroupName(gid); - } - - return gid; -} - -const char *AdminCache::GetAdminPassword(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return NULL; - } - - return m_pStrings->GetString(pUser->password); -} - -void AdminCache::SetAdminPassword(AdminId id, const char *password) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return; - } - - if (password[0] == '\0') - { - pUser->password = -1; - return; - } - - int i_password = m_pStrings->AddString(password); - pUser = (AdminUser *)m_pMemory->GetAddress(id); - pUser->password = i_password; -} - -unsigned int AdminCache::FlagBitsToBitArray(FlagBits bits, bool array[], unsigned int maxSize) -{ - unsigned int i; - for (i=0; iGetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return false; - } - - return ((pUser->eflags & bits) == bits); -} - -bool AdminCache::CanAdminTarget(AdminId id, AdminId target) -{ - /** - * Zeroth, if the targeting AdminId is INVALID_ADMIN_ID, targeting fails. - * First, if the targeted AdminId is INVALID_ADMIN_ID, targeting succeeds. - */ - - if (id == INVALID_ADMIN_ID) - { - return false; - } - - if (target == INVALID_ADMIN_ID) - { - return true; - } - - if (id == target) - { - return true; - } - - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return false; - } - - AdminUser *pTarget = (AdminUser *)m_pMemory->GetAddress(target); - if (!pTarget || pTarget->magic != USR_MAGIC_SET) - { - return false; - } - - /** - * Second, if the targeting admin is root, targeting succeeds. - */ - if (pUser->eflags & ADMFLAG_ROOT) - { - return true; - } - - /** Fourth, if the targeted admin is immune from targeting admin. */ - int mode = bridge->GetImmunityMode(); - switch (mode) - { - case 1: - { - if (pTarget->immunity_level > pUser->immunity_level) - { - return false; - } - break; - } - case 3: - { - /* If neither has any immunity, let this pass. */ - if (!pUser->immunity_level && !pTarget->immunity_level) - { - return true; - } - /* Don't break, go to the next case. */ - } - case 2: - { - if (pTarget->immunity_level >= pUser->immunity_level) - { - return false; - } - break; - } - } - - /** - * Fifth, if the targeted admin has specific immunity from the - * targeting admin via group immunities, targeting fails. - */ - //:TODO: speed this up... maybe with trie hacks. - //idea is to insert %d.%d in the trie after computing this and use it as a cache lookup. - //problem is the trie cannot delete prefixes, so we'd have a problem with invalidations. - if (pTarget->grp_count > 0 && pUser->grp_count > 0) - { - int *grp_table = (int *)m_pMemory->GetAddress(pTarget->grp_table); - int *src_table = (int *)m_pMemory->GetAddress(pUser->grp_table); - GroupId id, other; - unsigned int num; - for (unsigned int i=0; igrp_count; i++) - { - id = grp_table[i]; - num = GetGroupImmunityCount(id); - for (unsigned int j=0; jgrp_count; k++) - { - if (other == src_table[k]) - { - return false; - } - } - } - } - } - - return true; -} - -bool AdminCache::FindFlag(char c, AdminFlag *pAdmFlag) -{ - if (c < 'a' - || c > 'z' - || !g_FlagCharSet[(unsigned)c - (unsigned)'a']) - { - return false; - } - - if (pAdmFlag) - { - *pAdmFlag = g_FlagLetters[(unsigned)c - (unsigned)'a']; - } - - return true; -} - -bool AdminCache::FindFlagChar(AdminFlag flag, char *c) -{ - char flagchar = g_ReverseFlags[flag]; - if (c) - { - *c = flagchar; - } - - return flagchar != '?'; -} - -FlagBits AdminCache::ReadFlagString(const char *flags, const char **end) -{ - FlagBits bits = 0; - - while (flags && (*flags != '\0')) - { - AdminFlag flag; - if (!FindFlag(*flags, &flag)) - { - break; - } - bits |= FlagArrayToBits(&flag, 1); - flags++; - } - - if (end) - { - *end = flags; - } - - return bits; -} - -unsigned int AdminCache::GetAdminSerialChange(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return 0; - } - - return pUser->serialchange; -} - -bool AdminCache::CanAdminUseCommand(int client, const char *cmd) -{ - FlagBits bits; - OverrideType otype = Override_Command; - - if (cmd[0] == '@') - { - otype = Override_CommandGroup; - cmd++; - } - - if (!bridge->LookForCommandAdminFlags(cmd, &bits)) - { - if (!GetCommandOverride(cmd, otype, &bits)) - { - bits = 0; - } - } - - return CheckClientCommandAccess(client, cmd, bits); -} - -unsigned int AdminCache::SetGroupImmunityLevel(GroupId gid, unsigned int level) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return 0; - } - - unsigned int old_level = pGroup->immunity_level; - - pGroup->immunity_level = level; - - return old_level; -} - -unsigned int AdminCache::GetGroupImmunityLevel(GroupId gid) -{ - AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return 0; - } - - return pGroup->immunity_level; -} - -unsigned int AdminCache::SetAdminImmunityLevel(AdminId id, unsigned int level) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return 0; - } - - unsigned int old_level = pUser->immunity_level; - - pUser->immunity_level = level; - - return old_level; -} - -unsigned int AdminCache::GetAdminImmunityLevel(AdminId id) -{ - AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); - if (!pUser || pUser->magic != USR_MAGIC_SET) - { - return 0; - } - - return pUser->immunity_level; -} - -bool AdminCache::CheckAccess(int client, const char *cmd, FlagBits flags, bool override_only) -{ - if (client == 0) - { - return true; - } - - /* Auto-detect a command if we can */ - FlagBits bits = flags; - bool found_command = false; - if (!override_only) - { - found_command = bridge->LookForCommandAdminFlags(cmd, &bits); - } - - if (!found_command) - { - GetCommandOverride(cmd, Override_Command, &bits); - } - - return CheckClientCommandAccess(client, cmd, bits) ? 1 : 0; -} - -void iterator_glob_basic_override(FILE *fp, const char *key, FlagBits flags) -{ - char flagstr[64]; - g_Admins.FillFlagString(flags, flagstr, sizeof(flagstr)); - fprintf(fp, "\t\"%s\"\t\t\"%s\"\n", key, flagstr); -} - -void iterator_glob_grp_override(FILE *fp, const char *key, FlagBits flags) -{ - char flagstr[64]; - g_Admins.FillFlagString(flags, flagstr, sizeof(flagstr)); - fprintf(fp, "\t\"@%s\"\t\t\"%s\"\n", key, flagstr); -} - -void iterator_group_basic_override(FILE *fp, const char *key, OverrideRule rule) -{ - const char *str = (rule == Command_Allow) ? "allow" : "deny"; - fprintf(fp, "\t\t\t\"%s\"\t\t\"%s\"\n", key, str); -} - -void iterator_group_grp_override(FILE *fp, const char *key, OverrideRule rule) -{ - const char *str = (rule == Command_Allow) ? "allow" : "deny"; - fprintf(fp, "\t\t\t\"@%s\"\t\t\"%s\"\n", key, str); -} - -bool AdminCache::DumpCache(const char *filename) -{ - int *itable; - AdminId aid; - GroupId gid; - char flagstr[64]; - unsigned int num; - AdminUser *pAdmin; - AdminGroup *pGroup; - - FILE *fp; - if ((fp = fopen(filename, "wt")) == NULL) - { - return false; - } - - fprintf(fp, "\"Groups\"\n{\n"); - - num = 0; - gid = m_FirstGroup; - while (gid != INVALID_GROUP_ID - && (pGroup = GetGroup(gid)) != NULL) - { - num++; - FillFlagString(pGroup->addflags, flagstr, sizeof(flagstr)); - - fprintf(fp, "\t/* num = %d, gid = 0x%X */\n", num, gid); - fprintf(fp, "\t\"%s\"\n\t{\n", GetString(pGroup->nameidx)); - fprintf(fp, "\t\t\"flags\"\t\t\t\"%s\"\n", flagstr); - fprintf(fp, "\t\t\"immunity\"\t\t\"%d\"\n", pGroup->immunity_level); - - if (pGroup->immune_table != -1 - && (itable = (int *)m_pMemory->GetAddress(pGroup->immune_table)) != NULL) - { - AdminGroup *pAltGroup; - const char *gname, *mod; - - for (int i = 1; i <= itable[0]; i++) - { - if ((pAltGroup = GetGroup(itable[i])) == NULL) - { - /* Assume the rest of the table is corrupt */ - break; - } - gname = GetString(pAltGroup->nameidx); - if (atoi(gname) != 0) - { - mod = "@"; - } - else - { - mod = ""; - } - fprintf(fp, "\t\t\"immunity\"\t\t\"%s%s\"\n", mod, gname); - } - } - - fprintf(fp, "\n\t\t\"Overrides\"\n\t\t{\n"); - if (pGroup->pCmdGrpTable != NULL) - { - for (OverrideMap::iterator iter = pGroup->pCmdTable->iter(); !iter.empty(); iter.next()) - iterator_group_grp_override(fp, iter->key.chars(), iter->value); - } - if (pGroup->pCmdTable != NULL) - { - for (OverrideMap::iterator iter = pGroup->pCmdTable->iter(); !iter.empty(); iter.next()) - iterator_group_basic_override(fp, iter->key.chars(), iter->value); - } - fprintf(fp, "\t\t}\n"); - - fprintf(fp, "\t}\n"); - - if ((gid = pGroup->next_grp) != INVALID_GROUP_ID) - { - fprintf(fp, "\n"); - } - } - - fprintf(fp, "}\n\n"); - fprintf(fp, "\"Admins\"\n{\n"); - - num = 0; - aid = m_FirstUser; - while (aid != INVALID_ADMIN_ID - && (pAdmin = GetUser(aid)) != NULL) - { - num++; - FillFlagString(pAdmin->flags, flagstr, sizeof(flagstr)); - - fprintf(fp, "\t/* num = %d, aid = 0x%X, serialno = 0x%X*/\n", num, aid, pAdmin->serialchange); - - if (pAdmin->nameidx != -1) - { - fprintf(fp, "\t\"%s\"\n\t{\n", GetString(pAdmin->nameidx)); - } - else - { - fprintf(fp, "\t\"\"\n\t{\n"); - } - - if (pAdmin->auth.identidx != -1) - { - fprintf(fp, "\t\t\"auth\"\t\t\t\"%s\"\n", GetMethodName(pAdmin->auth.index)); - fprintf(fp, "\t\t\"identity\"\t\t\"%s\"\n", GetString(pAdmin->auth.identidx)); - } - if (pAdmin->password != -1) - { - fprintf(fp, "\t\t\"password\"\t\t\"%s\"\n", GetString(pAdmin->password)); - } - fprintf(fp, "\t\t\"flags\"\t\t\t\"%s\"\n", flagstr); - fprintf(fp, "\t\t\"immunity\"\t\t\"%d\"\n", pAdmin->immunity_level); - - if (pAdmin->grp_count != 0 - && pAdmin->grp_table != -1 - && (itable = (int *)m_pMemory->GetAddress(pAdmin->grp_table)) != NULL) - { - unsigned int i; - - for (i = 0; i < pAdmin->grp_count; i++) - { - if ((pGroup = GetGroup(itable[i])) == NULL) - { - /* Assume the rest of the table is corrupt */ - break; - } - fprintf(fp, "\t\t\"group\"\t\t\t\"%s\"\n", GetString(pGroup->nameidx)); - } - } - - fprintf(fp, "\t}\n"); - - if ((aid = pAdmin->next_user) != INVALID_ADMIN_ID) - { - fprintf(fp, "\n"); - } - } - - fprintf(fp, "}\n\n"); - - fprintf(fp, "\"Overrides\"\n{\n"); - for (FlagMap::iterator iter = m_CmdGrpOverrides.iter(); !iter.empty(); iter.next()) - iterator_glob_grp_override(fp, iter->key.chars(), iter->value); - for (FlagMap::iterator iter = m_CmdOverrides.iter(); !iter.empty(); iter.next()) - iterator_glob_basic_override(fp, iter->key.chars(), iter->value); - fprintf(fp, "}\n"); - - fclose(fp); - - return true; -} - -AdminGroup *AdminCache::GetGroup(GroupId gid) -{ - AdminGroup *pGroup; - - pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); - if (!pGroup || pGroup->magic != GRP_MAGIC_SET) - { - return NULL; - } - - return pGroup; -} - -AdminUser *AdminCache::GetUser(AdminId aid) -{ - AdminUser *pAdmin; - - pAdmin = (AdminUser *)m_pMemory->GetAddress(aid); - if (!pAdmin || pAdmin->magic != USR_MAGIC_SET) - { - return NULL; - } - - return pAdmin; -} - -const char *AdminCache::GetMethodName(unsigned int index) -{ - List::iterator iter; - for (iter=m_AuthMethods.begin(); - iter!=m_AuthMethods.end(); - iter++) - { - if (index-- == 0) - { - return (*iter)->name.c_str(); - } - } - - return NULL; -} - -const char *AdminCache::GetString(int idx) -{ - return m_pStrings->GetString(idx); -} - -size_t AdminCache::FillFlagString(FlagBits bits, char *buffer, size_t maxlen) -{ - size_t pos; - unsigned int i, num_flags; - AdminFlag flags[AdminFlags_TOTAL]; - - num_flags = FlagBitsToArray(bits, flags, AdminFlags_TOTAL); - - pos = 0; - for (i = 0; pos < maxlen && i < num_flags; i++) - { - if (FindFlagChar(flags[i], &buffer[pos])) - { - pos++; - } - } - buffer[pos] = '\0'; - - return pos; -} - -bool AdminCache::CheckClientCommandAccess(int client, const char *cmd, FlagBits cmdflags) -{ - if (cmdflags == 0 || client == 0) - { - return true; - } - - /* If running listen server, then client 1 is the server host and should have 'root' access */ - if (client == 1 && !engine->IsDedicatedServer()) - { - return true; - } - - IGamePlayer *player = playerhelpers->GetGamePlayer(client); - if (!player - || player->GetEdict() == NULL - || player->IsFakeClient()) - { - return false; - } - - return CheckAdminCommandAccess(player->GetAdminId(), cmd, cmdflags); -} - -bool AdminCache::CheckAdminCommandAccess(AdminId adm, const char *cmd, FlagBits cmdflags) -{ - if (adm != INVALID_ADMIN_ID) - { - FlagBits bits = GetAdminFlags(adm, Access_Effective); - - /* root knows all, WHOA */ - if ((bits & ADMFLAG_ROOT) == ADMFLAG_ROOT) - { - return true; - } - - /* Check for overrides - * :TODO: is it worth optimizing this? - */ - unsigned int groups = GetAdminGroupCount(adm); - GroupId gid; - OverrideRule rule; - bool override = false; - for (unsigned int i = 0; i. + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + * + * Version: $Id$ + */ + +#include +#include +#include +#include +#include +#include +#include +#include "admincache.h" +#include "translator.h" +#include "common_logic.h" +#include "stringutil.h" +#include +#include +#include + +#define LEVEL_STATE_NONE 0 +#define LEVEL_STATE_LEVELS 1 +#define LEVEL_STATE_FLAGS 2 + +AdminCache g_Admins; +char g_ReverseFlags[AdminFlags_TOTAL]; +AdminFlag g_FlagLetters[26]; +bool g_FlagCharSet[26]; + +/* Default flags */ +AdminFlag g_DefaultFlags[26] = +{ + Admin_Reservation, Admin_Generic, Admin_Kick, Admin_Ban, Admin_Unban, + Admin_Slay, Admin_Changemap, Admin_Convars, Admin_Config, Admin_Chat, + Admin_Vote, Admin_Password, Admin_RCON, Admin_Cheats, Admin_Custom1, + Admin_Custom2, Admin_Custom3, Admin_Custom4, Admin_Custom5, Admin_Custom6, + Admin_Generic, Admin_Generic, Admin_Generic, Admin_Generic, Admin_Generic, + Admin_Root +}; + + +class FlagReader : public ITextListener_SMC +{ +public: + void LoadLevels() + { + if (!Parse()) + { + memcpy(g_FlagLetters, g_DefaultFlags, sizeof(AdminFlag) * 26); + for (unsigned int i=0; i<20; i++) + { + g_FlagCharSet[i] = true; + } + g_FlagCharSet[25] = true; + } + } +private: + bool Parse() + { + SMCStates states; + SMCError error; + + m_bFileNameLogged = false; + g_pSM->BuildPath(Path_SM, m_File, sizeof(m_File), "configs/admin_levels.cfg"); + + if ((error = textparsers->ParseFile_SMC(m_File, this, &states)) + != SMCError_Okay) + { + const char *err_string = textparsers->GetSMCErrorString(error); + if (!err_string) + { + err_string = "Unknown error"; + } + ParseError(NULL, "Error %d (%s)", error, err_string); + return false; + } + + return true; + } + void ReadSMC_ParseStart() + { + m_LevelState = LEVEL_STATE_NONE; + m_IgnoreLevel = 0; + memset(g_FlagCharSet, 0, sizeof(g_FlagCharSet)); + } + SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name) + { + if (m_IgnoreLevel) + { + m_IgnoreLevel++; + return SMCResult_Continue; + } + + if (m_LevelState == LEVEL_STATE_NONE) + { + if (strcmp(name, "Levels") == 0) + { + m_LevelState = LEVEL_STATE_LEVELS; + } + else + { + m_IgnoreLevel++; + } + } else if (m_LevelState == LEVEL_STATE_LEVELS) { + if (strcmp(name, "Flags") == 0) + { + m_LevelState = LEVEL_STATE_FLAGS; + } + else + { + m_IgnoreLevel++; + } + } + else + { + m_IgnoreLevel++; + } + + return SMCResult_Continue; + } + SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value) + { + if (m_LevelState != LEVEL_STATE_FLAGS || m_IgnoreLevel) + { + return SMCResult_Continue; + } + + unsigned char c = (unsigned)value[0]; + + if (c < (unsigned)'a' || c > (unsigned)'z') + { + ParseError(states, "Flag \"%c\" is not a lower-case ASCII letter", c); + return SMCResult_Continue; + } + + c -= (unsigned)'a'; + + if (!g_Admins.FindFlag(key, &g_FlagLetters[c])) + { + ParseError(states, "Unrecognized admin level \"%s\"", key); + return SMCResult_Continue; + } + + g_FlagCharSet[c] = true; + + return SMCResult_Continue; + } + SMCResult ReadSMC_LeavingSection(const SMCStates *states) + { + if (m_IgnoreLevel) + { + m_IgnoreLevel--; + return SMCResult_Continue; + } + + if (m_LevelState == LEVEL_STATE_FLAGS) + { + m_LevelState = LEVEL_STATE_LEVELS; + return SMCResult_Halt; + } + else if (m_LevelState == LEVEL_STATE_LEVELS) + { + m_LevelState = LEVEL_STATE_NONE; + } + + return SMCResult_Continue; + } + void ParseError(const SMCStates *states, const char *message, ...) + { + va_list ap; + char buffer[256]; + + va_start(ap, message); + g_pSM->FormatArgs(buffer, sizeof(buffer), message, ap); + va_end(ap); + + if (!m_bFileNameLogged) + { + logger->LogError("[SM] Parse error(s) detected in file \"%s\":", m_File); + m_bFileNameLogged = true; + } + + logger->LogError("[SM] (Line %d): %s", states ? states->line : 0, buffer); + } +private: + bool m_bFileNameLogged; + char m_File[PLATFORM_MAX_PATH]; + int m_LevelState; + int m_IgnoreLevel; +} s_FlagReader; + +AdminCache::AdminCache() +{ + m_pStrings = new BaseStringTable(1024); + m_pMemory = m_pStrings->GetMemTable(); + m_FreeGroupList = m_FirstGroup = m_LastGroup = INVALID_GROUP_ID; + m_FreeUserList = m_FirstUser = m_LastUser = INVALID_ADMIN_ID; + m_pCacheFwd = NULL; + m_FirstGroup = -1; + m_InvalidatingAdmins = false; + m_destroying = false; +} + +AdminCache::~AdminCache() +{ + m_destroying = true; + DumpAdminCache(AdminCache_Overrides, false); + DumpAdminCache(AdminCache_Groups, false); + + List::iterator iter; + for (iter=m_AuthMethods.begin(); + iter!=m_AuthMethods.end(); + iter++) + { + delete *iter; + } + + delete m_pStrings; +} + +void AdminCache::OnSourceModStartup(bool late) +{ + RegisterAuthIdentType("steam"); + RegisterAuthIdentType("name"); + RegisterAuthIdentType("ip"); + + NameFlag("reservation", Admin_Reservation); + NameFlag("kick", Admin_Kick); + NameFlag("generic", Admin_Generic); + NameFlag("ban", Admin_Ban); + NameFlag("unban", Admin_Unban); + NameFlag("slay", Admin_Slay); + NameFlag("changemap", Admin_Changemap); + NameFlag("cvars", Admin_Convars); + NameFlag("config", Admin_Config); + NameFlag("chat", Admin_Chat); + NameFlag("vote", Admin_Vote); + NameFlag("password", Admin_Password); + NameFlag("rcon", Admin_RCON); + NameFlag("cheats", Admin_Cheats); + NameFlag("root", Admin_Root); + NameFlag("custom1", Admin_Custom1); + NameFlag("custom2", Admin_Custom2); + NameFlag("custom3", Admin_Custom3); + NameFlag("custom4", Admin_Custom4); + NameFlag("custom5", Admin_Custom5); + NameFlag("custom6", Admin_Custom6); + + auto sm_dump_admcache = [this] (int client, const ICommandArgs *args) -> bool { + char buffer[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_SM, buffer, sizeof(buffer), "data/admin_cache_dump.txt"); + + if (!DumpCache(buffer)) { + bridge->ConsolePrint("Could not open file for writing: %s", buffer); + return true; + } + + bridge->ConsolePrint("Admin cache dumped to: %s", buffer); + return true; + }; + + bridge->DefineCommand("sm_dump_admcache", "Dumps the admin cache for debugging", sm_dump_admcache); +} + +void AdminCache::OnSourceModAllInitialized() +{ + m_pCacheFwd = forwardsys->CreateForward("OnRebuildAdminCache", ET_Ignore, 1, NULL, Param_Cell); + sharesys->AddInterface(NULL, this); +} + +void AdminCache::OnSourceModLevelChange(const char *mapName) +{ + int i; + AdminFlag flag; + + /* For now, we only read these once per level. */ + s_FlagReader.LoadLevels(); + + memset(g_ReverseFlags, '?', sizeof(g_ReverseFlags)); + + for (i = 0; i < 26; i++) + { + if (FindFlag('a' + i, &flag)) + { + g_ReverseFlags[flag] = 'a' + i; + } + } +} + +void AdminCache::OnSourceModShutdown() +{ + forwardsys->ReleaseForward(m_pCacheFwd); + m_pCacheFwd = NULL; +} + +void AdminCache::OnSourceModPluginsLoaded() +{ + DumpAdminCache(AdminCache_Overrides, true); + DumpAdminCache(AdminCache_Groups, true); +} + +void AdminCache::NameFlag(const char *str, AdminFlag flag) +{ + m_LevelNames.insert(str, flag); +} + +bool AdminCache::FindFlag(const char *str, AdminFlag *pFlag) +{ + return m_LevelNames.retrieve(str, pFlag); +} + +void AdminCache::AddCommandOverride(const char *cmd, OverrideType type, FlagBits flags) +{ + FlagMap *map; + if (type == Override_Command) + map = &m_CmdOverrides; + else if (type == Override_CommandGroup) + map = &m_CmdGrpOverrides; + else + return; + + map->insert(cmd, flags); + bridge->UpdateAdminCmdFlags(cmd, type, flags, false); +} + +bool AdminCache::GetCommandOverride(const char *cmd, OverrideType type, FlagBits *pFlags) +{ + FlagMap *map; + if (type == Override_Command) + map = &m_CmdOverrides; + else if (type == Override_CommandGroup) + map = &m_CmdGrpOverrides; + else + return false; + + return map->retrieve(cmd, pFlags); +} + +void AdminCache::UnsetCommandOverride(const char *cmd, OverrideType type) +{ + if (type == Override_Command) + { + return _UnsetCommandOverride(cmd); + } else if (type == Override_CommandGroup) { + return _UnsetCommandGroupOverride(cmd); + } +} + +void AdminCache::_UnsetCommandGroupOverride(const char *group) +{ + m_CmdGrpOverrides.remove(group); + bridge->UpdateAdminCmdFlags(group, Override_CommandGroup, 0, true); +} + +void AdminCache::_UnsetCommandOverride(const char *cmd) +{ + m_CmdOverrides.remove(cmd); + bridge->UpdateAdminCmdFlags(cmd, Override_Command, 0, true); +} + +void AdminCache::DumpCommandOverrideCache(OverrideType type) +{ + if (type == Override_Command) + m_CmdOverrides.clear(); + else if (type == Override_CommandGroup) + m_CmdGrpOverrides.clear(); +} + +AdminId AdminCache::CreateAdmin(const char *name) +{ + AdminId id; + AdminUser *pUser; + + if (m_FreeUserList != INVALID_ADMIN_ID) + { + pUser = (AdminUser *)m_pMemory->GetAddress(m_FreeUserList); + assert(pUser->magic == USR_MAGIC_UNSET); + id = m_FreeUserList; + m_FreeUserList = pUser->next_user; + } + else + { + id = m_pMemory->CreateMem(sizeof(AdminUser), (void **)&pUser); + pUser->grp_size = 0; + pUser->grp_table = -1; + } + + pUser->flags = 0; + pUser->eflags = 0; + pUser->grp_count = 0; + pUser->password = -1; + pUser->magic = USR_MAGIC_SET; + pUser->auth.identidx = -1; + pUser->auth.index = 0; + pUser->immunity_level = 0; + pUser->serialchange = 1; + + if (m_FirstUser == INVALID_ADMIN_ID) + { + m_FirstUser = id; + m_LastUser = id; + } + else + { + AdminUser *pPrev = (AdminUser *)m_pMemory->GetAddress(m_LastUser); + pPrev->next_user = id; + pUser->prev_user = m_LastUser; + m_LastUser = id; + } + + /* Since we always append to the tail, we should invalidate their next */ + pUser->next_user = -1; + + if (name && name[0] != '\0') + { + int nameidx = m_pStrings->AddString(name); + pUser = (AdminUser *)m_pMemory->GetAddress(id); + pUser->nameidx = nameidx; + } + else + { + pUser->nameidx = -1; + } + + return id; +} + +GroupId AdminCache::AddGroup(const char *group_name) +{ + if (m_Groups.contains(group_name)) + return INVALID_GROUP_ID; + + GroupId id; + AdminGroup *pGroup; + if (m_FreeGroupList != INVALID_GROUP_ID) + { + pGroup = (AdminGroup *)m_pMemory->GetAddress(m_FreeGroupList); + assert(pGroup->magic == GRP_MAGIC_UNSET); + id = m_FreeGroupList; + m_FreeGroupList = pGroup->next_grp; + } else { + id = m_pMemory->CreateMem(sizeof(AdminGroup), (void **)&pGroup); + } + + pGroup->immunity_level = 0; + pGroup->immune_table = -1; + pGroup->magic = GRP_MAGIC_SET; + pGroup->next_grp = INVALID_GROUP_ID; + pGroup->pCmdGrpTable = NULL; + pGroup->pCmdTable = NULL; + pGroup->addflags = 0; + + if (m_FirstGroup == INVALID_GROUP_ID) + { + m_FirstGroup = id; + m_LastGroup = id; + pGroup->prev_grp = INVALID_GROUP_ID; + } else { + AdminGroup *pPrev = (AdminGroup *)m_pMemory->GetAddress(m_LastGroup); + assert(pPrev->magic == GRP_MAGIC_SET); + pPrev->next_grp = id; + pGroup->prev_grp = m_LastGroup; + m_LastGroup = id; + } + + int nameidx = m_pStrings->AddString(group_name); + pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + pGroup->nameidx = nameidx; + + m_Groups.insert(group_name, id); + return id; +} + +GroupId AdminCache::FindGroupByName(const char *group_name) +{ + GroupId id; + if (!m_Groups.retrieve(group_name, &id)) + return INVALID_GROUP_ID; + + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + return INVALID_GROUP_ID; + + return id; +} + +void AdminCache::SetGroupAddFlag(GroupId id, AdminFlag flag, bool enabled) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return; + } + + if (flag < Admin_Reservation || flag >= AdminFlags_TOTAL) + { + return; + } + + FlagBits bits = (1<<(FlagBits)flag); + + if (enabled) + { + pGroup->addflags |= bits; + } else { + pGroup->addflags &= ~bits; + } +} + +bool AdminCache::GetGroupAddFlag(GroupId id, AdminFlag flag) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return false; + } + + if (flag < Admin_Reservation || flag >= AdminFlags_TOTAL) + { + return false; + } + + FlagBits bit = 1<<(FlagBits)flag; + return ((pGroup->addflags & bit) == bit); +} + +FlagBits AdminCache::GetGroupAddFlags(GroupId id) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return 0; + } + + return pGroup->addflags; +} + +const char *AdminCache::GetGroupName(GroupId gid) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return NULL; + } + + return m_pStrings->GetString(pGroup->nameidx); +} + +void AdminCache::SetGroupGenericImmunity(GroupId id, ImmunityType type, bool enabled) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return; + } + + unsigned int level = 0; + + if (enabled) + { + if (type == Immunity_Default) + { + level = 1; + } else if (type == Immunity_Global) { + level = 2; + } + if (level > pGroup->immunity_level) + { + pGroup->immunity_level = level; + } + } else { + pGroup->immunity_level = 0; + } +} + +bool AdminCache::GetGroupGenericImmunity(GroupId id, ImmunityType type) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return false; + } + + if (type == Immunity_Default && pGroup->immunity_level >= 1) + { + return true; + } else if (type == Immunity_Global && pGroup->immunity_level >= 2) { + return true; + } + + return false; +} + +void AdminCache::AddGroupImmunity(GroupId id, GroupId other_id) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(other_id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return; + } + + pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return; + } + + /* We always need to resize the immunity table */ + int *table, tblidx; + if (pGroup->immune_table == -1) + { + tblidx = m_pMemory->CreateMem(sizeof(int) * 2, (void **)&table); + pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + table[0] = 0; + } else { + int *old_table = (int *)m_pMemory->GetAddress(pGroup->immune_table); + /* Break out if this group is already in the list */ + for (int i=0; iCreateMem(sizeof(int) * (old_table[0] + 2), (void **)&table); + /* Get the old address again in case of resize */ + pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + old_table = (int *)m_pMemory->GetAddress(pGroup->immune_table); + table[0] = old_table[0]; + for (unsigned int i=1; i<=(unsigned int)old_table[0]; i++) + { + table[i] = old_table[i]; + } + } + + /* Assign */ + pGroup->immune_table = tblidx; + + /* Add to the array */ + table[0]++; + table[table[0]] = other_id; +} + +unsigned int AdminCache::GetGroupImmunityCount(GroupId id) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return 0; + } + + if (pGroup->immune_table == -1) + { + return 0; + } + + int *table = (int *)m_pMemory->GetAddress(pGroup->immune_table); + + return table[0]; +} + +GroupId AdminCache::GetGroupImmunity(GroupId id, unsigned int number) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return INVALID_GROUP_ID; + } + + if (pGroup->immune_table == -1) + { + return INVALID_GROUP_ID; + } + + int *table = (int *)m_pMemory->GetAddress(pGroup->immune_table); + if (number >= (unsigned int)table[0]) + { + return INVALID_GROUP_ID; + } + + return table[1 + number]; +} + +void AdminCache::AddGroupCommandOverride(GroupId id, const char *name, OverrideType type, OverrideRule rule) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return; + } + + OverrideMap *map; + if (type == Override_Command) + { + if (pGroup->pCmdTable == NULL) + pGroup->pCmdTable = new OverrideMap(); + map = pGroup->pCmdTable; + } else if (type == Override_CommandGroup) { + if (pGroup->pCmdGrpTable == NULL) + pGroup->pCmdGrpTable = new OverrideMap(); + map = pGroup->pCmdGrpTable; + } else { + return; + } + + map->insert(name, rule); +} + +bool AdminCache::GetGroupCommandOverride(GroupId id, const char *name, OverrideType type, OverrideRule *pRule) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return false; + } + + OverrideMap *map; + if (type == Override_Command) + { + if (pGroup->pCmdTable == NULL) + return false; + map = pGroup->pCmdTable; + } else if (type == Override_CommandGroup) { + if (pGroup->pCmdGrpTable == NULL) + return false; + map = pGroup->pCmdGrpTable; + } else { + return false; + } + + return map->retrieve(name, pRule); +} + +AuthMethod *AdminCache::GetMethodByIndex(unsigned int index) +{ + List::iterator iter; + for (iter=m_AuthMethods.begin(); + iter!=m_AuthMethods.end(); + iter++) + { + if (index-- == 0) + { + return *iter; + } + } + + return NULL; +} + +bool AdminCache::InvalidateAdmin(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + AdminUser *pOther; + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return false; + } + + if (!m_InvalidatingAdmins && !m_destroying) + { + playerhelpers->ClearAdminId(id); + } + + /* Unlink from the dbl link list */ + if (id == m_FirstUser && id == m_LastUser) + { + m_FirstUser = INVALID_ADMIN_ID; + m_LastUser = INVALID_ADMIN_ID; + } else if (id == m_FirstUser) { + m_FirstUser = pUser->next_user; + pOther = (AdminUser *)m_pMemory->GetAddress(m_FirstUser); + pOther->prev_user = INVALID_ADMIN_ID; + } else if (id == m_LastUser) { + m_LastUser = pUser->prev_user; + pOther = (AdminUser *)m_pMemory->GetAddress(m_LastUser); + pOther->next_user = INVALID_ADMIN_ID; + } else { + pOther = (AdminUser *)m_pMemory->GetAddress(pUser->prev_user); + pOther->next_user = pUser->next_user; + pOther = (AdminUser *)m_pMemory->GetAddress(pUser->next_user); + pOther->prev_user = pUser->prev_user; + } + + /* Unlink from auth tables */ + if (pUser->auth.identidx != -1) + { + AuthMethod *method = GetMethodByIndex(pUser->auth.index); + if (method) + method->identities.remove(m_pStrings->GetString(pUser->auth.identidx)); + } + + /* Clear table counts */ + pUser->grp_count = 0; + + /* Link into free list */ + pUser->magic = USR_MAGIC_UNSET; + pUser->next_user = m_FreeUserList; + m_FreeUserList = id; + + /* Unset serial change */ + pUser->serialchange = 0; + + return true; +} + + +void AdminCache::InvalidateGroup(GroupId id) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(id); + AdminGroup *pOther; + + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return; + } + + const char *str = m_pStrings->GetString(pGroup->nameidx); + m_Groups.remove(str); + + /* Unlink from the live dbllink list */ + if (id == m_FirstGroup && id == m_LastGroup) + { + m_LastGroup = INVALID_GROUP_ID; + m_FirstGroup = INVALID_GROUP_ID; + } else if (id == m_FirstGroup) { + m_FirstGroup = pGroup->next_grp; + pOther = (AdminGroup *)m_pMemory->GetAddress(m_FirstGroup); + pOther->prev_grp = INVALID_GROUP_ID; + } else if (id == m_LastGroup) { + m_LastGroup = pGroup->prev_grp; + pOther = (AdminGroup *)m_pMemory->GetAddress(m_LastGroup); + pOther->next_grp = INVALID_GROUP_ID; + } else { + pOther = (AdminGroup *)m_pMemory->GetAddress(pGroup->prev_grp); + pOther->next_grp = pGroup->next_grp; + pOther = (AdminGroup *)m_pMemory->GetAddress(pGroup->next_grp); + pOther->prev_grp = pGroup->prev_grp; + } + + /* Free any used memory */ + delete pGroup->pCmdGrpTable; + pGroup->pCmdGrpTable = NULL; + delete pGroup->pCmdTable; + pGroup->pCmdTable = NULL; + + /* Link into the free list */ + pGroup->magic = GRP_MAGIC_UNSET; + pGroup->next_grp = m_FreeGroupList; + m_FreeGroupList = id; + + int idx = m_FirstUser; + AdminUser *pUser; + int *table; + while (idx != INVALID_ADMIN_ID) + { + pUser = (AdminUser *)m_pMemory->GetAddress(idx); + if (pUser->grp_count > 0) + { + table = (int *)m_pMemory->GetAddress(pUser->grp_table); + for (unsigned int i=0; igrp_count; i++) + { + if (table[i] == id) + { + /* We have to remove this entry */ + for (unsigned int j=i+1; jgrp_count; j++) + { + /* Move everything down by one */ + table[j-1] = table[j]; + } + /* Decrease count */ + pUser->grp_count--; + /* Recalculate effective flags */ + pUser->eflags = pUser->flags; + for (unsigned int j=0; jgrp_count; j++) + { + pOther = (AdminGroup *)m_pMemory->GetAddress(table[j]); + pUser->eflags |= pOther->addflags; + } + /* Mark as changed */ + pUser->serialchange++; + /* Break now, duplicates aren't allowed */ + break; + } + } + } + idx = pUser->next_user; + } +} + +void AdminCache::InvalidateGroupCache() +{ + /* Nuke the free list */ + m_FreeGroupList = -1; + + /* Nuke reverse lookups */ + m_Groups.clear(); + + /* Free memory on groups */ + GroupId cur = m_FirstGroup; + AdminGroup *pGroup; + while (cur != INVALID_GROUP_ID) + { + pGroup = (AdminGroup *)m_pMemory->GetAddress(cur); + assert(pGroup->magic == GRP_MAGIC_SET); + delete pGroup->pCmdGrpTable; + delete pGroup->pCmdTable; + cur = pGroup->next_grp; + } + + m_FirstGroup = INVALID_GROUP_ID; + m_LastGroup = INVALID_GROUP_ID; + + InvalidateAdminCache(false); + + /* Reset the memory table */ + m_pMemory->Reset(); +} + +void AdminCache::AddAdminListener(IAdminListener *pListener) +{ + m_hooks.push_back(pListener); +} + +void AdminCache::RemoveAdminListener(IAdminListener *pListener) +{ + m_hooks.remove(pListener); +} + +void AdminCache::RegisterAuthIdentType(const char *name) +{ + if (m_AuthTables.contains(name)) + return; + + AuthMethod *method = new AuthMethod(name); + m_AuthMethods.push_back(method); + m_AuthTables.insert(name, method); +} + +void AdminCache::InvalidateAdminCache(bool unlink_admins) +{ + m_InvalidatingAdmins = true; + if (!m_destroying) + { + int maxClients = playerhelpers->GetMaxClients(); + for (int i = 1; i <= maxClients; ++i) + { + playerhelpers->GetGamePlayer(i)->ClearAdmin(); + } + } + /* Wipe the identity cache first */ + List::iterator iter; + for (iter=m_AuthMethods.begin(); + iter!=m_AuthMethods.end(); + iter++) + { + (*iter)->identities.clear(); + } + + if (unlink_admins) + { + while (m_FirstUser != INVALID_ADMIN_ID) + { + InvalidateAdmin(m_FirstUser); + } + } else { + m_FirstUser = -1; + m_LastUser = -1; + m_FreeUserList = -1; + } + m_InvalidatingAdmins = false; +} + +void AdminCache::DumpAdminCache(AdminCachePart part, bool rebuild) +{ + List::iterator iter; + IAdminListener *pListener; + + if (part == AdminCache_Overrides) + { + DumpCommandOverrideCache(Override_Command); + DumpCommandOverrideCache(Override_CommandGroup); + if (rebuild && !m_destroying) + { + for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) + { + pListener = (*iter); + pListener->OnRebuildOverrideCache(); + } + m_pCacheFwd->PushCell(part); + m_pCacheFwd->Execute(); + } + } else if (part == AdminCache_Groups || part == AdminCache_Admins) { + if (part == AdminCache_Groups) + { + InvalidateGroupCache(); + if (rebuild && !m_destroying) + { + for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) + { + pListener = (*iter); + pListener->OnRebuildGroupCache(); + } + m_pCacheFwd->PushCell(part); + m_pCacheFwd->Execute(); + } + } + InvalidateAdminCache(true); + if (rebuild && !m_destroying) + { + for (iter=m_hooks.begin(); iter!=m_hooks.end(); iter++) + { + pListener = (*iter); + pListener->OnRebuildAdminCache((part == AdminCache_Groups)); + } + m_pCacheFwd->PushCell(AdminCache_Admins); + m_pCacheFwd->Execute(); + playerhelpers->RecheckAnyAdmins(); + } + } +} + +const char *AdminCache::GetAdminName(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return NULL; + } + + return m_pStrings->GetString(pUser->nameidx); +} + +bool AdminCache::GetMethodIndex(const char *name, unsigned int *_index) +{ + List::iterator iter; + unsigned int index = 0; + for (iter=m_AuthMethods.begin(); + iter!=m_AuthMethods.end(); + iter++,index++) + { + if ((*iter)->name.compare(name) == 0) + { + *_index = index; + return true; + } + } + + return false; +} + +/* + * Converts Steam2 id, Steam3 id, or SteamId64 to unified, legacy + * admin identity format. (account id part of Steam2 format) + */ +bool AdminCache::GetUnifiedSteamIdentity(const char *ident, char *out, size_t maxlen) +{ + int len = strlen(ident); + if (!strcmp(ident, "BOT")) + { + // Bots + strncopy(out, ident, maxlen); + return true; + } + else if (len >= 11 && !strncmp(ident, "STEAM_", 6) && ident[8] != '_') + { + // non-bot/lan Steam2 Id, strip off the STEAM_* part + snprintf(out, maxlen, "%s", &ident[8]); + return true; + } + else if (len >= 7 && !strncmp(ident, "[U:", 3) && ident[len-1] == ']') + { + // Steam3 Id, replicate the Steam2 Post-"STEAM_" part + uint32_t accountId = strtoul(&ident[5], nullptr, 10); + snprintf(out, maxlen, "%u:%u", accountId & 1, accountId >> 1); + return true; + } + else + { + // 64-bit CSteamID, replicate the Steam2 Post-"STEAM_" part + + // some constants from steamclientpublic.h + static const uint32_t k_EAccountTypeIndividual = 1; + static const int k_EUniverseInvalid = 0; + static const int k_EUniverseMax = 5; + static const unsigned int k_unSteamUserWebInstance = 4; + + uint64_t steamId = strtoull(ident, nullptr, 10); + if (steamId > 0) + { + // Make some attempt at being sure it's a valid id rather than other number, + // even though we're only going to use the lower 32 bits. + uint32_t accountId = steamId & 0xFFFFFFFF; + uint32_t accountType = (steamId >> 52) & 0xF; + int universe = steamId >> 56; + uint32_t accountInstance = (steamId >> 32) & 0xFFFFF; + if (accountId > 0 + && universe > k_EUniverseInvalid && universe < k_EUniverseMax + && accountType == k_EAccountTypeIndividual && accountInstance <= k_unSteamUserWebInstance + ) + { + snprintf(out, maxlen, "%u:%u", accountId & 1, accountId >> 1); + return true; + } + } + } + + return false; +} + +bool AdminCache::BindAdminIdentity(AdminId id, const char *auth, const char *ident) +{ + if (ident[0] == '\0') + { + return false; + } + + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return false; + } + + AuthMethod *method; + if (!m_AuthTables.retrieve(auth, &method)) + return false; + + /* If the auth type is steam, the id could be in a number of formats. Unify it. */ + char steamIdent[16]; + if (strcmp(auth, "steam") == 0) + { + if (!GetUnifiedSteamIdentity(ident, steamIdent, sizeof(steamIdent))) + return false; + + ident = steamIdent; + } + + if (method->identities.contains(ident)) + return false; + + int i_ident = m_pStrings->AddString(ident); + + pUser = (AdminUser *)m_pMemory->GetAddress(id); + pUser->auth.identidx = i_ident; + GetMethodIndex(auth, &pUser->auth.index); + + return method->identities.insert(ident, id); +} + +AdminId AdminCache::FindAdminByIdentity(const char *auth, const char *identity) +{ + AuthMethod *method; + if (!m_AuthTables.retrieve(auth, &method)) + return INVALID_ADMIN_ID; + + /* If the auth type is steam, the id could be in a number of formats. Unify it. */ + char steamIdent[16]; + if (strcmp(auth, "steam") == 0) + { + if (!GetUnifiedSteamIdentity(identity, steamIdent, sizeof(steamIdent))) + return INVALID_ADMIN_ID; + + identity = steamIdent; + } + + AdminId id; + if (!method->identities.retrieve(identity, &id)) + return INVALID_ADMIN_ID; + return id; +} + +void AdminCache::SetAdminFlag(AdminId id, AdminFlag flag, bool enabled) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return; + } + + if (flag < Admin_Reservation + || flag >= AdminFlags_TOTAL) + { + return; + } + + FlagBits bits = (1<<(FlagBits)flag); + + if (enabled) + { + pUser->flags |= bits; + pUser->eflags |= bits; + } else { + pUser->flags &= ~bits; + pUser->eflags &= ~bits; + } + + pUser->serialchange++; +} + +bool AdminCache::GetAdminFlag(AdminId id, AdminFlag flag, AccessMode mode) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return false; + } + + if (flag < Admin_Reservation + || flag >= AdminFlags_TOTAL) + { + return false; + } + + FlagBits bit = (1<<(FlagBits)flag); + + if (mode == Access_Real) + { + return ((pUser->flags & bit) == bit); + } else if (mode == Access_Effective) { + bool has_bit = ((pUser->eflags & bit) == bit); + if (!has_bit && flag != Admin_Root && ((pUser->eflags & ADMFLAG_ROOT) == ADMFLAG_ROOT)) + { + has_bit = true; + } + return has_bit; + } + + return false; +} + +FlagBits AdminCache::GetAdminFlags(AdminId id, AccessMode mode) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return 0; + } + + if (mode == Access_Real) + { + return pUser->flags; + } else if (mode == Access_Effective) { + return pUser->eflags; + } + + return 0; +} + +void AdminCache::SetAdminFlags(AdminId id, AccessMode mode, FlagBits bits) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return; + } + + if (mode == Access_Real) + { + pUser->flags = bits; + pUser->eflags = bits; + } else if (mode == Access_Effective) { + pUser->eflags = bits; + } + + pUser->serialchange++; +} + +bool AdminCache::AdminInheritGroup(AdminId id, GroupId gid) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return false; + } + + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return false; + } + + /* First check for duplicates */ + if (pUser->grp_count != 0) + { + int *temp_table = (int *)m_pMemory->GetAddress(pUser->grp_table); + for (unsigned int i=0; igrp_count; i++) + { + if (temp_table[i] == gid) + { + return false; + } + } + } + + int *table; + if (pUser->grp_count + 1 > pUser->grp_size) + { + int new_size = 0; + int tblidx; + + if (pUser->grp_size == 0) + { + new_size = 2; + } else { + new_size = pUser->grp_size * 2; + } + + /* Create and refresh pointers */ + tblidx = m_pMemory->CreateMem(new_size * sizeof(int), (void **)&table); + pUser = (AdminUser *)m_pMemory->GetAddress(id); + pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); + + /* Copy old data if necessary */ + if (pUser->grp_table != -1) + { + int *old_table = (int *)m_pMemory->GetAddress(pUser->grp_table); + memcpy(table, old_table, sizeof(int) * pUser->grp_count); + } + pUser->grp_table = tblidx; + pUser->grp_size = new_size; + } else { + table = (int *)m_pMemory->GetAddress(pUser->grp_table); + } + + table[pUser->grp_count] = gid; + pUser->grp_count++; + + /* Compute new effective permissions */ + pUser->eflags |= pGroup->addflags; + + if (pGroup->immunity_level > pUser->immunity_level) + { + pUser->immunity_level = pGroup->immunity_level; + } + + pUser->serialchange++; + + return true; +} + +bool AdminCache::IsValidAdmin(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + return (pUser != NULL && pUser->magic == USR_MAGIC_SET); +} + +unsigned int AdminCache::GetAdminGroupCount(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return 0; + } + + return pUser->grp_count; +} + +GroupId AdminCache::GetAdminGroup(AdminId id, unsigned int index, const char **name) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET || index >= pUser->grp_count) + { + return INVALID_GROUP_ID; + } + + int *table = (int *)m_pMemory->GetAddress(pUser->grp_table); + + GroupId gid = table[index]; + + if (name) + { + *name = GetGroupName(gid); + } + + return gid; +} + +const char *AdminCache::GetAdminPassword(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return NULL; + } + + return m_pStrings->GetString(pUser->password); +} + +void AdminCache::SetAdminPassword(AdminId id, const char *password) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return; + } + + if (password[0] == '\0') + { + pUser->password = -1; + return; + } + + int i_password = m_pStrings->AddString(password); + pUser = (AdminUser *)m_pMemory->GetAddress(id); + pUser->password = i_password; +} + +unsigned int AdminCache::FlagBitsToBitArray(FlagBits bits, bool array[], unsigned int maxSize) +{ + unsigned int i; + for (i=0; iGetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return false; + } + + return ((pUser->eflags & bits) == bits); +} + +bool AdminCache::CanAdminTarget(AdminId id, AdminId target) +{ + /** + * Zeroth, if the targeting AdminId is INVALID_ADMIN_ID, targeting fails. + * First, if the targeted AdminId is INVALID_ADMIN_ID, targeting succeeds. + */ + + if (id == INVALID_ADMIN_ID) + { + return false; + } + + if (target == INVALID_ADMIN_ID) + { + return true; + } + + if (id == target) + { + return true; + } + + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return false; + } + + AdminUser *pTarget = (AdminUser *)m_pMemory->GetAddress(target); + if (!pTarget || pTarget->magic != USR_MAGIC_SET) + { + return false; + } + + /** + * Second, if the targeting admin is root, targeting succeeds. + */ + if (pUser->eflags & ADMFLAG_ROOT) + { + return true; + } + + /** Fourth, if the targeted admin is immune from targeting admin. */ + int mode = bridge->GetImmunityMode(); + switch (mode) + { + case 1: + { + if (pTarget->immunity_level > pUser->immunity_level) + { + return false; + } + break; + } + case 3: + { + /* If neither has any immunity, let this pass. */ + if (!pUser->immunity_level && !pTarget->immunity_level) + { + return true; + } + /* Don't break, go to the next case. */ + } + case 2: + { + if (pTarget->immunity_level >= pUser->immunity_level) + { + return false; + } + break; + } + } + + /** + * Fifth, if the targeted admin has specific immunity from the + * targeting admin via group immunities, targeting fails. + */ + //:TODO: speed this up... maybe with trie hacks. + //idea is to insert %d.%d in the trie after computing this and use it as a cache lookup. + //problem is the trie cannot delete prefixes, so we'd have a problem with invalidations. + if (pTarget->grp_count > 0 && pUser->grp_count > 0) + { + int *grp_table = (int *)m_pMemory->GetAddress(pTarget->grp_table); + int *src_table = (int *)m_pMemory->GetAddress(pUser->grp_table); + GroupId id, other; + unsigned int num; + for (unsigned int i=0; igrp_count; i++) + { + id = grp_table[i]; + num = GetGroupImmunityCount(id); + for (unsigned int j=0; jgrp_count; k++) + { + if (other == src_table[k]) + { + return false; + } + } + } + } + } + + return true; +} + +bool AdminCache::FindFlag(char c, AdminFlag *pAdmFlag) +{ + if (c < 'a' + || c > 'z' + || !g_FlagCharSet[(unsigned)c - (unsigned)'a']) + { + return false; + } + + if (pAdmFlag) + { + *pAdmFlag = g_FlagLetters[(unsigned)c - (unsigned)'a']; + } + + return true; +} + +bool AdminCache::FindFlagChar(AdminFlag flag, char *c) +{ + char flagchar = g_ReverseFlags[flag]; + if (c) + { + *c = flagchar; + } + + return flagchar != '?'; +} + +FlagBits AdminCache::ReadFlagString(const char *flags, const char **end) +{ + FlagBits bits = 0; + + while (flags && (*flags != '\0')) + { + AdminFlag flag; + if (!FindFlag(*flags, &flag)) + { + break; + } + bits |= FlagArrayToBits(&flag, 1); + flags++; + } + + if (end) + { + *end = flags; + } + + return bits; +} + +unsigned int AdminCache::GetAdminSerialChange(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return 0; + } + + return pUser->serialchange; +} + +bool AdminCache::CanAdminUseCommand(int client, const char *cmd) +{ + FlagBits bits; + OverrideType otype = Override_Command; + + if (cmd[0] == '@') + { + otype = Override_CommandGroup; + cmd++; + } + + if (!bridge->LookForCommandAdminFlags(cmd, &bits)) + { + if (!GetCommandOverride(cmd, otype, &bits)) + { + bits = 0; + } + } + + return CheckClientCommandAccess(client, cmd, bits); +} + +unsigned int AdminCache::SetGroupImmunityLevel(GroupId gid, unsigned int level) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return 0; + } + + unsigned int old_level = pGroup->immunity_level; + + pGroup->immunity_level = level; + + return old_level; +} + +unsigned int AdminCache::GetGroupImmunityLevel(GroupId gid) +{ + AdminGroup *pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return 0; + } + + return pGroup->immunity_level; +} + +unsigned int AdminCache::SetAdminImmunityLevel(AdminId id, unsigned int level) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return 0; + } + + unsigned int old_level = pUser->immunity_level; + + pUser->immunity_level = level; + + return old_level; +} + +unsigned int AdminCache::GetAdminImmunityLevel(AdminId id) +{ + AdminUser *pUser = (AdminUser *)m_pMemory->GetAddress(id); + if (!pUser || pUser->magic != USR_MAGIC_SET) + { + return 0; + } + + return pUser->immunity_level; +} + +bool AdminCache::CheckAccess(int client, const char *cmd, FlagBits flags, bool override_only) +{ + if (client == 0) + { + return true; + } + + /* Auto-detect a command if we can */ + FlagBits bits = flags; + bool found_command = false; + if (!override_only) + { + found_command = bridge->LookForCommandAdminFlags(cmd, &bits); + } + + if (!found_command) + { + GetCommandOverride(cmd, Override_Command, &bits); + } + + return CheckClientCommandAccess(client, cmd, bits) ? 1 : 0; +} + +void iterator_glob_basic_override(FILE *fp, const char *key, FlagBits flags) +{ + char flagstr[64]; + g_Admins.FillFlagString(flags, flagstr, sizeof(flagstr)); + fprintf(fp, "\t\"%s\"\t\t\"%s\"\n", key, flagstr); +} + +void iterator_glob_grp_override(FILE *fp, const char *key, FlagBits flags) +{ + char flagstr[64]; + g_Admins.FillFlagString(flags, flagstr, sizeof(flagstr)); + fprintf(fp, "\t\"@%s\"\t\t\"%s\"\n", key, flagstr); +} + +void iterator_group_basic_override(FILE *fp, const char *key, OverrideRule rule) +{ + const char *str = (rule == Command_Allow) ? "allow" : "deny"; + fprintf(fp, "\t\t\t\"%s\"\t\t\"%s\"\n", key, str); +} + +void iterator_group_grp_override(FILE *fp, const char *key, OverrideRule rule) +{ + const char *str = (rule == Command_Allow) ? "allow" : "deny"; + fprintf(fp, "\t\t\t\"@%s\"\t\t\"%s\"\n", key, str); +} + +bool AdminCache::DumpCache(const char *filename) +{ + int *itable; + AdminId aid; + GroupId gid; + char flagstr[64]; + unsigned int num; + AdminUser *pAdmin; + AdminGroup *pGroup; + + FILE *fp; + if ((fp = fopen(filename, "wt")) == NULL) + { + return false; + } + + fprintf(fp, "\"Groups\"\n{\n"); + + num = 0; + gid = m_FirstGroup; + while (gid != INVALID_GROUP_ID + && (pGroup = GetGroup(gid)) != NULL) + { + num++; + FillFlagString(pGroup->addflags, flagstr, sizeof(flagstr)); + + fprintf(fp, "\t/* num = %d, gid = 0x%X */\n", num, gid); + fprintf(fp, "\t\"%s\"\n\t{\n", GetString(pGroup->nameidx)); + fprintf(fp, "\t\t\"flags\"\t\t\t\"%s\"\n", flagstr); + fprintf(fp, "\t\t\"immunity\"\t\t\"%d\"\n", pGroup->immunity_level); + + if (pGroup->immune_table != -1 + && (itable = (int *)m_pMemory->GetAddress(pGroup->immune_table)) != NULL) + { + AdminGroup *pAltGroup; + const char *gname, *mod; + + for (int i = 1; i <= itable[0]; i++) + { + if ((pAltGroup = GetGroup(itable[i])) == NULL) + { + /* Assume the rest of the table is corrupt */ + break; + } + gname = GetString(pAltGroup->nameidx); + if (atoi(gname) != 0) + { + mod = "@"; + } + else + { + mod = ""; + } + fprintf(fp, "\t\t\"immunity\"\t\t\"%s%s\"\n", mod, gname); + } + } + + fprintf(fp, "\n\t\t\"Overrides\"\n\t\t{\n"); + if (pGroup->pCmdGrpTable != NULL) + { + for (OverrideMap::iterator iter = pGroup->pCmdTable->iter(); !iter.empty(); iter.next()) + iterator_group_grp_override(fp, iter->key.chars(), iter->value); + } + if (pGroup->pCmdTable != NULL) + { + for (OverrideMap::iterator iter = pGroup->pCmdTable->iter(); !iter.empty(); iter.next()) + iterator_group_basic_override(fp, iter->key.chars(), iter->value); + } + fprintf(fp, "\t\t}\n"); + + fprintf(fp, "\t}\n"); + + if ((gid = pGroup->next_grp) != INVALID_GROUP_ID) + { + fprintf(fp, "\n"); + } + } + + fprintf(fp, "}\n\n"); + fprintf(fp, "\"Admins\"\n{\n"); + + num = 0; + aid = m_FirstUser; + while (aid != INVALID_ADMIN_ID + && (pAdmin = GetUser(aid)) != NULL) + { + num++; + FillFlagString(pAdmin->flags, flagstr, sizeof(flagstr)); + + fprintf(fp, "\t/* num = %d, aid = 0x%X, serialno = 0x%X*/\n", num, aid, pAdmin->serialchange); + + if (pAdmin->nameidx != -1) + { + fprintf(fp, "\t\"%s\"\n\t{\n", GetString(pAdmin->nameidx)); + } + else + { + fprintf(fp, "\t\"\"\n\t{\n"); + } + + if (pAdmin->auth.identidx != -1) + { + fprintf(fp, "\t\t\"auth\"\t\t\t\"%s\"\n", GetMethodName(pAdmin->auth.index)); + fprintf(fp, "\t\t\"identity\"\t\t\"%s\"\n", GetString(pAdmin->auth.identidx)); + } + if (pAdmin->password != -1) + { + fprintf(fp, "\t\t\"password\"\t\t\"%s\"\n", GetString(pAdmin->password)); + } + fprintf(fp, "\t\t\"flags\"\t\t\t\"%s\"\n", flagstr); + fprintf(fp, "\t\t\"immunity\"\t\t\"%d\"\n", pAdmin->immunity_level); + + if (pAdmin->grp_count != 0 + && pAdmin->grp_table != -1 + && (itable = (int *)m_pMemory->GetAddress(pAdmin->grp_table)) != NULL) + { + unsigned int i; + + for (i = 0; i < pAdmin->grp_count; i++) + { + if ((pGroup = GetGroup(itable[i])) == NULL) + { + /* Assume the rest of the table is corrupt */ + break; + } + fprintf(fp, "\t\t\"group\"\t\t\t\"%s\"\n", GetString(pGroup->nameidx)); + } + } + + fprintf(fp, "\t}\n"); + + if ((aid = pAdmin->next_user) != INVALID_ADMIN_ID) + { + fprintf(fp, "\n"); + } + } + + fprintf(fp, "}\n\n"); + + fprintf(fp, "\"Overrides\"\n{\n"); + for (FlagMap::iterator iter = m_CmdGrpOverrides.iter(); !iter.empty(); iter.next()) + iterator_glob_grp_override(fp, iter->key.chars(), iter->value); + for (FlagMap::iterator iter = m_CmdOverrides.iter(); !iter.empty(); iter.next()) + iterator_glob_basic_override(fp, iter->key.chars(), iter->value); + fprintf(fp, "}\n"); + + fclose(fp); + + return true; +} + +AdminGroup *AdminCache::GetGroup(GroupId gid) +{ + AdminGroup *pGroup; + + pGroup = (AdminGroup *)m_pMemory->GetAddress(gid); + if (!pGroup || pGroup->magic != GRP_MAGIC_SET) + { + return NULL; + } + + return pGroup; +} + +AdminUser *AdminCache::GetUser(AdminId aid) +{ + AdminUser *pAdmin; + + pAdmin = (AdminUser *)m_pMemory->GetAddress(aid); + if (!pAdmin || pAdmin->magic != USR_MAGIC_SET) + { + return NULL; + } + + return pAdmin; +} + +const char *AdminCache::GetMethodName(unsigned int index) +{ + List::iterator iter; + for (iter=m_AuthMethods.begin(); + iter!=m_AuthMethods.end(); + iter++) + { + if (index-- == 0) + { + return (*iter)->name.c_str(); + } + } + + return NULL; +} + +const char *AdminCache::GetString(int idx) +{ + return m_pStrings->GetString(idx); +} + +size_t AdminCache::FillFlagString(FlagBits bits, char *buffer, size_t maxlen) +{ + size_t pos; + unsigned int i, num_flags; + AdminFlag flags[AdminFlags_TOTAL]; + + num_flags = FlagBitsToArray(bits, flags, AdminFlags_TOTAL); + + pos = 0; + for (i = 0; pos < maxlen && i < num_flags; i++) + { + if (FindFlagChar(flags[i], &buffer[pos])) + { + pos++; + } + } + buffer[pos] = '\0'; + + return pos; +} + +bool AdminCache::CheckClientCommandAccess(int client, const char *cmd, FlagBits cmdflags) +{ + if (cmdflags == 0 || client == 0) + { + return true; + } + + /* If running listen server, then client 1 is the server host and should have 'root' access */ + if (client == 1 && !engine->IsDedicatedServer()) + { + return true; + } + + IGamePlayer *player = playerhelpers->GetGamePlayer(client); + if (!player + || player->GetEdict() == NULL + || player->IsFakeClient()) + { + return false; + } + + return CheckAdminCommandAccess(player->GetAdminId(), cmd, cmdflags); +} + +bool AdminCache::CheckAdminCommandAccess(AdminId adm, const char *cmd, FlagBits cmdflags) +{ + if (adm != INVALID_ADMIN_ID) + { + FlagBits bits = GetAdminFlags(adm, Access_Effective); + + /* root knows all, WHOA */ + if ((bits & ADMFLAG_ROOT) == ADMFLAG_ROOT) + { + return true; + } + + /* Check for overrides + * :TODO: is it worth optimizing this? + */ + unsigned int groups = GetAdminGroupCount(adm); + GroupId gid; + OverrideRule rule; + bool override = false; + for (unsigned int i = 0; i #include -#include "CDataPack.h" +#include "cdatapack.h" #include #include @@ -88,7 +88,7 @@ void CDataPack::CheckSize(size_t typesize) { m_capacity *= 2; } while (pos + typesize > m_capacity); - + m_pBase = (char *)realloc(m_pBase, m_capacity); m_curptr = m_pBase + pos; } diff --git a/core/logic/CDataPack.h b/core/logic/cdatapack.h similarity index 100% rename from core/logic/CDataPack.h rename to core/logic/cdatapack.h diff --git a/core/logic/CellArray.h b/core/logic/cellarray.h similarity index 100% rename from core/logic/CellArray.h rename to core/logic/cellarray.h diff --git a/core/logic/common_logic.cpp b/core/logic/common_logic.cpp index a39ed8bd1..e544fe8be 100644 --- a/core/logic/common_logic.cpp +++ b/core/logic/common_logic.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -34,28 +34,28 @@ #include #include #include "common_logic.h" -#include "TextParsers.h" +#include "textparsers.h" #include "sm_crc32.h" -#include "MemoryUtils.h" +#include "memoryutils.h" #include "stringutil.h" -#include "ThreadSupport.h" -#include "Translator.h" -#include "GameConfigs.h" -#include "DebugReporter.h" -#include "PluginSys.h" -#include "ShareSys.h" -#include "NativeOwner.h" -#include "HandleSys.h" -#include "ExtensionSys.h" -#include "ForwardSys.h" -#include "AdminCache.h" -#include "ProfileTools.h" -#include "Logger.h" +#include "threadsupport.h" +#include "translator.h" +#include "gameconfigs.h" +#include "debugreporter.h" +#include "pluginsys.h" +#include "sharesys.h" +#include "nativeowner.h" +#include "handlesys.h" +#include "extensionsys.h" +#include "forwardsys.h" +#include "admincache.h" +#include "profiletools.h" +#include "logger.h" #include "frame_tasks.h" #include "sprintf.h" -#include "LibrarySys.h" -#include "RootConsoleMenu.h" -#include "CDataPack.h" +#include "librarysys.h" +#include "rootconsolemenu.h" +#include "cdatapack.h" #include #include @@ -180,7 +180,7 @@ static void logic_init(CoreProvider* core, sm_logic_t* _logic) g_ShareSys.Initialize(); g_pCoreIdent = g_ShareSys.CreateCoreIdentity(); - + _logic->core_ident = g_pCoreIdent; } @@ -215,12 +215,12 @@ void *operator new(size_t size) return malloc(size); } -void *operator new[](size_t size) +void *operator new[](size_t size) { return malloc(size); } -void operator delete(void *ptr) +void operator delete(void *ptr) { free(ptr); } diff --git a/core/logic/Database.cpp b/core/logic/database.cpp similarity index 94% rename from core/logic/Database.cpp rename to core/logic/database.cpp index c7dd38d46..50c03758f 100644 --- a/core/logic/Database.cpp +++ b/core/logic/database.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,11 +29,11 @@ * Version: $Id$ */ -#include "Database.h" -#include "ISourceMod.h" -#include "HandleSys.h" -#include "ExtensionSys.h" -#include "PluginSys.h" +#include "database.h" +#include +#include "handlesys.h" +#include "extensionsys.h" +#include "pluginsys.h" #include #include #include @@ -45,7 +45,7 @@ DBManager g_DBMan; static bool s_OneTimeThreaderErrorMsg = false; -DBManager::DBManager() +DBManager::DBManager() : m_Terminate(false), m_ParseLevel(0), m_ParseState(0), @@ -65,7 +65,7 @@ void DBManager::OnSourceModAllInitialized() g_HandleSys.InitAccessDefaults(NULL, &sec); sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY; sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY; - + m_DriverType = g_HandleSys.CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL); m_DatabaseType = g_HandleSys.CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL); @@ -74,7 +74,7 @@ void DBManager::OnSourceModAllInitialized() g_pSM->BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg"); g_PluginSys.AddPluginsListener(this); - + g_pSM->AddGameFrameHook(&FrameHook); } @@ -243,7 +243,7 @@ SMCResult DBManager::ReadSMC_LeavingSection(const SMCStates *states) cdb->info.host = cdb->host.c_str(); cdb->info.user = cdb->user.c_str(); cdb->info.pass = cdb->pass.c_str(); - + /* Save it.. */ m_confs.push_back(cdb); @@ -318,7 +318,7 @@ void DBManager::AddDriver(IDBDriver *pDriver) { /* Let's kill the worker. Join the thread and let the queries flush. * This is kind of stupid but we just want to unload safely. - * Rather than recreate the worker, we'll wait until someone throws + * Rather than recreate the worker, we'll wait until someone throws * another query through. */ KillWorkerThread(); @@ -329,8 +329,8 @@ void DBManager::AddDriver(IDBDriver *pDriver) void DBManager::RemoveDriver(IDBDriver *pDriver) { /* Again, we're forced to kill the worker. How rude! - * Doing this flushes the queue, and thus we don't need to - * clean anything else. + * Doing this flushes the queue, and thus we don't need to + * clean anything else. */ KillWorkerThread(); @@ -616,8 +616,8 @@ void DBManager::ThreadMain() ke::AutoLock lock(&m_ThinkLock); m_ThinkQueue.push(op); } - - + + if (!m_Terminate) { ke::AutoUnlock unlock(&m_QueueEvent); @@ -664,7 +664,7 @@ void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken) KillWorkerThread(); /* Run all of the think operations. - * Unlike the driver unloading example, we'll let these calls go through, + * Unlike the driver unloading example, we'll let these calls go through, * since a plugin unloading is far more normal. */ Queue::iterator iter = m_ThinkQueue.begin(); @@ -702,7 +702,7 @@ void DBManager::OnPluginUnloaded(IPlugin *plugin) plugin->SetProperty("DisallowDBThreads", NULL); /* Run all of the think operations. - * Unlike the driver unloading example, we'll let these calls go through, + * Unlike the driver unloading example, we'll let these calls go through, * since a plugin unloading is far more normal. */ Queue::iterator iter = m_ThinkQueue.begin(); diff --git a/core/logic/Database.h b/core/logic/database.h similarity index 100% rename from core/logic/Database.h rename to core/logic/database.h diff --git a/core/logic/DebugReporter.cpp b/core/logic/debugreporter.cpp similarity index 95% rename from core/logic/DebugReporter.cpp rename to core/logic/debugreporter.cpp index 012934986..481054b37 100644 --- a/core/logic/DebugReporter.cpp +++ b/core/logic/debugreporter.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,8 +31,8 @@ #include #include -#include "DebugReporter.h" -#include "Logger.h" +#include "debugreporter.h" +#include "logger.h" #include DebugReport g_DbgReporter; diff --git a/core/logic/DebugReporter.h b/core/logic/debugreporter.h similarity index 100% rename from core/logic/DebugReporter.h rename to core/logic/debugreporter.h diff --git a/core/logic/ExtensionSys.cpp b/core/logic/extensionsys.cpp similarity index 95% rename from core/logic/ExtensionSys.cpp rename to core/logic/extensionsys.cpp index 673eda3b5..0ec3d766b 100644 --- a/core/logic/ExtensionSys.cpp +++ b/core/logic/extensionsys.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,11 +30,11 @@ */ #include -#include "ExtensionSys.h" +#include "extensionsys.h" #include #include #include "common_logic.h" -#include "PluginSys.h" +#include "pluginsys.h" #include #include #include @@ -120,8 +120,8 @@ CLocalExtension::CLocalExtension(const char *filename) } /* First see if there is an engine specific build! */ - g_pSM->BuildPath(Path_SM, - path, + g_pSM->BuildPath(Path_SM, + path, PLATFORM_MAX_PATH, "extensions/auto.%s/%s." PLATFORM_LIB_EXT, filename, @@ -253,10 +253,10 @@ bool CLocalExtension::Reload(char *error, size_t maxlength) { if (m_pLib == NULL) // FIXME: just load it instead? return false; - + m_pAPI->OnExtensionUnload(); Unload(); - + return Load(error, maxlength); } @@ -282,7 +282,7 @@ bool CExtension::PerformAPICheck(char *error, size_t maxlength) snprintf(error, maxlength, "No IExtensionInterface instance provided"); return false; } - + if (m_pAPI->GetExtensionVersion() > SMINTERFACE_EXTENSIONAPI_VERSION) { snprintf(error, maxlength, "Extension version is too new to load (%d, max is %d)", m_pAPI->GetExtensionVersion(), SMINTERFACE_EXTENSIONAPI_VERSION); @@ -574,7 +574,7 @@ void CExtensionManager::TryAutoload() strcpy(&file[len - 9], ".ext"); LoadAutoExtension(file); - + pDir->NextEntry(); } } @@ -611,7 +611,7 @@ IExtension *CExtensionManager::LoadAutoExtension(const char *path, bool bErrorOn { logger->LogError("[SM] Unable to load extension \"%s\": %s", path, error); } - + p->SetError(error); } @@ -921,8 +921,8 @@ void CExtensionManager::MarkAllLoaded() void CExtensionManager::AddDependency(IExtension *pSource, const char *file, bool required, bool autoload) { - /* This function doesn't really need to do anything now. We make sure the - * other extension is loaded, but handling of dependencies is really done + /* This function doesn't really need to do anything now. We make sure the + * other extension is loaded, but handling of dependencies is really done * by the interface fetcher. */ if (required || autoload) @@ -998,13 +998,13 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand ke::SafeSprintf(path, sizeof(path), "%s%s%s", filename, !strstr(filename, ".ext") ? ".ext" : "", !strstr(filename, "." PLATFORM_LIB_EXT) ? "." PLATFORM_LIB_EXT : ""); - + if (FindExtensionByFile(path) != NULL) { rootmenu->ConsolePrint("[SM] Extension %s is already loaded.", path); return; } - + if (LoadExtension(path, error, sizeof(error))) { rootmenu->ConsolePrint("[SM] Loaded extension %s successfully.", path); @@ -1012,7 +1012,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand { rootmenu->ConsolePrint("[SM] Extension %s failed to load: %s", path, error); } - + return; } else if (strcmp(cmd, "info") == 0) @@ -1135,7 +1135,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand return; } - if (!pExt->IsLoaded() + if (!pExt->IsLoaded() || (!pExt->m_ChildDeps.size() && !pExt->m_Dependents.size())) { char filename[PLATFORM_MAX_PATH]; @@ -1224,7 +1224,7 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand rootmenu->ConsolePrint("[SM] Usage: sm exts reload <#>"); return; } - + const char *arg = command->Arg(3); unsigned int num = atoi(arg); CExtension *pExt = FindByOrder(num); @@ -1234,14 +1234,14 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand rootmenu->ConsolePrint("[SM] Extension number %d was not found.", num); return; } - + if (pExt->IsLoaded()) { char filename[PLATFORM_MAX_PATH]; char error[255]; - + snprintf(filename, PLATFORM_MAX_PATH, "%s", pExt->GetFilename()); - + if (pExt->Reload(error, sizeof(error))) { rootmenu->ConsolePrint("[SM] Extension %s is now reloaded.", filename); @@ -1250,16 +1250,16 @@ void CExtensionManager::OnRootConsoleCommand(const char *cmdname, const ICommand { rootmenu->ConsolePrint("[SM] Extension %s failed to reload: %s", filename, error); } - + return; - } + } else { rootmenu->ConsolePrint("[SM] Extension %s is not loaded.", pExt->GetFilename()); - + return; } - + } } diff --git a/core/logic/ExtensionSys.h b/core/logic/extensionsys.h similarity index 94% rename from core/logic/ExtensionSys.h rename to core/logic/extensionsys.h index be310494c..09e9ab06a 100644 --- a/core/logic/ExtensionSys.h +++ b/core/logic/extensionsys.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -39,8 +39,8 @@ #include "common_logic.h" #include #include -#include "NativeOwner.h" -#include "ShareSys.h" +#include "nativeowner.h" +#include "sharesys.h" #include class CPlayer; @@ -56,7 +56,7 @@ struct sm_extnative_t const sp_nativeinfo_t *info; }; -class CExtension : +class CExtension : public IExtension, public CNativeOwner { @@ -135,7 +135,7 @@ public: bool IsSameFile(const char *file); }; -class CExtensionManager : +class CExtensionManager : public IExtensionSys, public SMGlobalClass, public IPluginsListener, @@ -148,7 +148,7 @@ public: //SMGlobalClass void OnSourceModAllInitialized(); void OnSourceModShutdown(); public: //IExtensionManager - IExtension *LoadExtension(const char *path, + IExtension *LoadExtension(const char *path, char *error, size_t maxlength); bool UnloadExtension(IExtension *pExt); diff --git a/core/logic/ForwardSys.cpp b/core/logic/forwardsys.cpp similarity index 94% rename from core/logic/ForwardSys.cpp rename to core/logic/forwardsys.cpp index 3ec59b041..bedcedf8e 100644 --- a/core/logic/ForwardSys.cpp +++ b/core/logic/forwardsys.cpp @@ -7,7 +7,7 @@ // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License, version 3.0, as published by the // Free Software Foundation. -// +// // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -28,8 +28,8 @@ #include #include #include -#include "ForwardSys.h" -#include "DebugReporter.h" +#include "forwardsys.h" +#include "debugreporter.h" #include "common_logic.h" #include #include @@ -52,7 +52,7 @@ IForward *CForwardManager::CreateForward(const char *name, ExecType et, unsigned { va_list ap; va_start(ap, types); - + CForward *fwd = CForward::CreateForward(name, et, num_params, types, ap); va_end(ap); @@ -192,7 +192,7 @@ CForward *CForward::CreateForward(const char *name, ExecType et, unsigned int nu { return NULL; } - + if (types == NULL && num_params) { for (unsigned int i=0; iPushCellByRef(¶m->val); + err = func->PushCellByRef(¶m->val); } else { @@ -291,14 +291,14 @@ int CForward::Execute(cell_t *result, IForwardFilter *filter) if (err != SP_ERROR_NONE) { - g_DbgReporter.GenerateError(func->GetParentContext(), - func->GetFunctionID(), - err, + g_DbgReporter.GenerateError(func->GetParentContext(), + func->GetFunctionID(), + err, "Failed to push parameter while executing forward"); continue; } } - + /* Call the function and deal with the return value. */ if ((err=func->Execute(&cur_result)) == SP_ERROR_NONE) { diff --git a/core/logic/ForwardSys.h b/core/logic/forwardsys.h similarity index 87% rename from core/logic/ForwardSys.h rename to core/logic/forwardsys.h index 420335c5f..682171b17 100644 --- a/core/logic/ForwardSys.h +++ b/core/logic/forwardsys.h @@ -7,7 +7,7 @@ // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License, version 3.0, as published by the // Free Software Foundation. -// +// // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,8 +31,8 @@ #include #include #include "common_logic.h" -#include "ISourceMod.h" -#include "ReentrantList.h" +#include +#include typedef ReentrantList::iterator FuncIter; @@ -62,10 +62,10 @@ public: //IChangeableForward virtual bool AddFunction(IPluginContext *ctx, funcid_t index); virtual bool RemoveFunction(IPluginContext *ctx, funcid_t index); public: - static CForward *CreateForward(const char *name, - ExecType et, - unsigned int num_params, - const ParamType *types, + static CForward *CreateForward(const char *name, + ExecType et, + unsigned int num_params, + const ParamType *types, va_list ap); bool IsFunctionRegistered(IPluginFunction *func); private: @@ -96,22 +96,22 @@ protected: int m_errstate; }; -class CForwardManager : +class CForwardManager : public IForwardManager, public IPluginsListener, public SMGlobalClass { friend class CForward; public: //IForwardManager - IForward *CreateForward(const char *name, - ExecType et, - unsigned int num_params, - const ParamType *types, + IForward *CreateForward(const char *name, + ExecType et, + unsigned int num_params, + const ParamType *types, ...); - IChangeableForward *CreateForwardEx(const char *name, - ExecType et, - int num_params, - const ParamType *types, + IChangeableForward *CreateForwardEx(const char *name, + ExecType et, + int num_params, + const ParamType *types, ...); IForward *FindForward(const char *name, IChangeableForward **ifchng); void ReleaseForward(IForward *forward); diff --git a/core/logic/GameConfigs.cpp b/core/logic/gameconfigs.cpp similarity index 95% rename from core/logic/GameConfigs.cpp rename to core/logic/gameconfigs.cpp index 792db8a2b..f644975b1 100644 --- a/core/logic/GameConfigs.cpp +++ b/core/logic/gameconfigs.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -32,7 +32,7 @@ #include #include #include -#include "GameConfigs.h" +#include "gameconfigs.h" #include "stringutil.h" #include #include @@ -41,7 +41,7 @@ #include #include "common_logic.h" #include "sm_crc32.h" -#include "MemoryUtils.h" +#include "memoryutils.h" #include #include #include @@ -275,7 +275,7 @@ SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *n if (strcmp(name, "server") != 0) { ke::SafeSprintf(error, sizeof(error), "Unrecognized library \"%s\"", name); - } + } else if (!s_ServerBinCRC_Ok) { FILE *fp; @@ -506,7 +506,7 @@ SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states) if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0) && (!m_Offsets.retrieve(m_offset))) { - logger->LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", + logger->LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", m_Class, m_Prop, m_CurFile, @@ -559,8 +559,8 @@ SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states) void *final_addr = NULL; if (addrInBase == NULL) { - logger->LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", - s_TempSig.library, + logger->LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", + s_TempSig.library, m_CurFile); } else if (s_TempSig.sig[0]) @@ -831,7 +831,7 @@ bool CGameConfig::Reparse(char *error, size_t maxlength) const char *msg = textparsers->GetSMCErrorString(err); logger->LogError("[SM] Error parsing master gameconf file \"%s\":", path); - logger->LogError("[SM] Error %d on line %d, col %d: %s", + logger->LogError("[SM] Error %d on line %d, col %d: %s", err, state.line, state.col, @@ -867,7 +867,7 @@ bool CGameConfig::Reparse(char *error, size_t maxlength) customDir->NextEntry(); continue; } - + const char *curFile = customDir->GetEntryName(); /* Only allow .txt files */ @@ -875,7 +875,7 @@ bool CGameConfig::Reparse(char *error, size_t maxlength) if (len > 4 && strcmp(&curFile[len-4], ".txt") != 0) { customDir->NextEntry(); - continue; + continue; } ke::SafeSprintf(path, sizeof(path), "%s/custom/%s", m_File, curFile); @@ -919,7 +919,7 @@ bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength) const char *msg = textparsers->GetSMCErrorString(err); logger->LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile); - logger->LogError("[SM] Error %d on line %d, col %d: %s", + logger->LogError("[SM] Error %d on line %d, col %d: %s", err, state.line, state.col, @@ -1049,7 +1049,7 @@ void GameConfigManager::OnSourceModAllInitialized() { /* NOW initialize the game file */ CGameConfig *pGameConf = (CGameConfig *)g_pGameConf; - + char error[255]; if (!pGameConf->Reparse(error, sizeof(error))) { diff --git a/core/logic/GameConfigs.h b/core/logic/gameconfigs.h similarity index 100% rename from core/logic/GameConfigs.h rename to core/logic/gameconfigs.h diff --git a/core/logic/HandleSys.cpp b/core/logic/handlesys.cpp similarity index 93% rename from core/logic/HandleSys.cpp rename to core/logic/handlesys.cpp index 10c9791c7..8e8de32a3 100644 --- a/core/logic/HandleSys.cpp +++ b/core/logic/handlesys.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,13 +29,13 @@ * Version: $Id$ */ -#include "HandleSys.h" +#include "handlesys.h" #include #include #include "common_logic.h" -#include "ShareSys.h" -#include "ExtensionSys.h" -#include "PluginSys.h" +#include "sharesys.h" +#include "extensionsys.h" +#include "pluginsys.h" #include #include @@ -71,11 +71,11 @@ HandleSystem::~HandleSystem() } -HandleType_t HandleSystem::CreateType(const char *name, - IHandleTypeDispatch *dispatch, - HandleType_t parent, - const TypeAccess *typeAccess, - const HandleAccess *hndlAccess, +HandleType_t HandleSystem::CreateType(const char *name, + IHandleTypeDispatch *dispatch, + HandleType_t parent, + const TypeAccess *typeAccess, + const HandleAccess *hndlAccess, IdentityToken_t *ident, HandleError *err) { @@ -202,7 +202,7 @@ HandleType_t HandleSystem::CreateType(const char *name, } QHandleType *pType = &m_Types[index]; - + pType->dispatch = dispatch; if (name && name[0] != '\0') { @@ -265,9 +265,9 @@ HandleError HandleSystem::TryAllocHandle(unsigned int *handle) return HandleError_None; } -HandleError HandleSystem::MakePrimHandle(HandleType_t type, - QHandle **in_pHandle, - unsigned int *in_index, +HandleError HandleSystem::MakePrimHandle(HandleType_t type, + QHandle **in_pHandle, + unsigned int *in_index, Handle_t *in_handle, IdentityToken_t *owner, bool identity) @@ -291,7 +291,7 @@ HandleError HandleSystem::MakePrimHandle(HandleType_t type, } QHandle *pHandle = &m_Handles[handle]; - + assert(pHandle->set == false); if (++m_HSerial >= HANDLESYS_MAX_SERIALS) @@ -322,7 +322,7 @@ HandleError HandleSystem::MakePrimHandle(HandleType_t type, *in_index = handle; *in_handle = hash; - /* Decode the identity token + /* Decode the identity token * For now, we don't allow nested ownership */ if (owner && !identity) @@ -365,10 +365,10 @@ void HandleSystem::SetTypeSecurityOwner(HandleType_t type, IdentityToken_t *pTok m_Types[type].typeSec.ident = pToken; } -Handle_t HandleSystem::CreateHandleInt(HandleType_t type, - void *object, +Handle_t HandleSystem::CreateHandleInt(HandleType_t type, + void *object, const HandleSecurity *pSec, - HandleError *err, + HandleError *err, const HandleAccess *pAccess, bool identity) { @@ -384,7 +384,7 @@ Handle_t HandleSystem::CreateHandleInt(HandleType_t type, owner = NULL; } - if (!type + if (!type || type >= HANDLESYS_TYPEARRAY_SIZE || m_Types[type].dispatch == NULL) { @@ -470,8 +470,8 @@ bool HandleSystem::TypeCheck(HandleType_t intype, HandleType_t outtype) } HandleError HandleSystem::GetHandle(Handle_t handle, - IdentityToken_t *ident, - QHandle **in_pHandle, + IdentityToken_t *ident, + QHandle **in_pHandle, unsigned int *in_index, bool ignoreFree) { @@ -647,7 +647,7 @@ HandleError HandleSystem::FreeHandle(QHandle *pHandle, unsigned int index) { if (pHandle->is_destroying) { - /* Someone tried to free this recursively. + /* Someone tried to free this recursively. * We'll just ignore this safely. */ return HandleError_None; diff --git a/core/logic/HandleSys.h b/core/logic/handlesys.h similarity index 100% rename from core/logic/HandleSys.h rename to core/logic/handlesys.h diff --git a/core/logic/LibrarySys.cpp b/core/logic/librarysys.cpp similarity index 94% rename from core/logic/LibrarySys.cpp rename to core/logic/librarysys.cpp index 69f2077cc..cefe138b5 100644 --- a/core/logic/LibrarySys.cpp +++ b/core/logic/librarysys.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -34,7 +34,7 @@ #include #include #include -#include "LibrarySys.h" +#include "librarysys.h" #include #include #include @@ -299,7 +299,7 @@ size_t LibrarySystem::GetFileFromPath(char *buffer, size_t maxlength, const char i <= length - 1; i--) { - if (path[i] == '/' + if (path[i] == '/' #if defined PLATFORM_WINDOWS || path[i] == '\\' #endif diff --git a/core/logic/LibrarySys.h b/core/logic/librarysys.h similarity index 100% rename from core/logic/LibrarySys.h rename to core/logic/librarysys.h diff --git a/core/logic/Logger.cpp b/core/logic/logger.cpp similarity index 94% rename from core/logic/Logger.cpp rename to core/logic/logger.cpp index 2671016d1..dc01c1d26 100644 --- a/core/logic/Logger.cpp +++ b/core/logic/logger.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,7 +31,7 @@ #include #include -#include "Logger.h" +#include "logger.h" #include #include #include @@ -44,10 +44,10 @@ Logger g_Logger; * :TODO: This should be creating the log folder if it doesn't exist */ -ConfigResult Logger::OnSourceModConfigChanged(const char *key, - const char *value, +ConfigResult Logger::OnSourceModConfigChanged(const char *key, + const char *value, ConfigSource source, - char *error, + char *error, size_t maxlength) { if (strcasecmp(key, "Logging") == 0) @@ -73,7 +73,7 @@ ConfigResult Logger::OnSourceModConfigChanged(const char *key, return ConfigResult_Accept; } else if (strcasecmp(key, "LogMode") == 0) { - if (strcasecmp(value, "daily") == 0) + if (strcasecmp(value, "daily") == 0) { m_Mode = LoggingMode_Daily; } else if (strcasecmp(value, "map") == 0) { @@ -115,7 +115,7 @@ void Logger::_NewMapFile() /* Append "Log file closed" to previous log file */ _CloseFile(); - + char _filename[256]; int i = 0; @@ -535,7 +535,7 @@ void Logger::LogFatal(const char *msg, ...) void Logger::LogFatalEx(const char *msg, va_list ap) { /* :TODO: make this print all pretty-like - * In fact, the pretty log printing function should be abstracted. + * In fact, the pretty log printing function should be abstracted. * It's already implemented twice which is bad. */ diff --git a/core/logic/Logger.h b/core/logic/logger.h similarity index 100% rename from core/logic/Logger.h rename to core/logic/logger.h diff --git a/core/logic/MemoryUtils.cpp b/core/logic/memoryutils.cpp similarity index 95% rename from core/logic/MemoryUtils.cpp rename to core/logic/memoryutils.cpp index 151ede1b9..6f6b23771 100644 --- a/core/logic/MemoryUtils.cpp +++ b/core/logic/memoryutils.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -27,7 +27,7 @@ * or . */ -#include "MemoryUtils.h" +#include "memoryutils.h" #ifdef PLATFORM_LINUX #include #include @@ -144,7 +144,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) #ifdef PLATFORM_WINDOWS return GetProcAddress((HMODULE)handle, symbol); - + #elif defined PLATFORM_LINUX struct link_map *dlmap; @@ -165,7 +165,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) symtab_hdr = NULL; strtab_hdr = NULL; table = NULL; - + /* See if we already have a symbol table for this library */ for (size_t i = 0; i < m_SymTables.size(); i++) { @@ -280,7 +280,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) return symbol_entry ? symbol_entry->address : NULL; #elif defined PLATFORM_APPLE - + uintptr_t dlbase, linkedit_addr; uint32_t image_count; struct mach_header *file_hdr; @@ -294,20 +294,20 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) LibSymbolTable *libtable; SymbolTable *table; Symbol *symbol_entry; - + dlbase = 0; image_count = m_ImageList->infoArrayCount; linkedit_hdr = NULL; symtab_hdr = NULL; table = NULL; - + /* Loop through mach-o images in process. * We can skip index 0 since that is just the executable. */ for (uint32_t i = 1; i < image_count; i++) { const struct dyld_image_info &info = m_ImageList->infoArray[i]; - + /* "Load" each one until we get a matching handle */ void *h = dlopen(info.imageFilePath, RTLD_NOLOAD); if (h == handle) @@ -316,16 +316,16 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) dlclose(h); break; } - + dlclose(h); } - + if (!dlbase) { /* Uh oh, we couldn't find a matching handle */ return NULL; } - + /* See if we already have a symbol table for this library */ for (size_t i = 0; i < m_SymTables.size(); i++) { @@ -336,7 +336,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) break; } } - + /* If we don't have a symbol table for this library, then create one */ if (table == NULL) { @@ -347,20 +347,20 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) table = &libtable->table; m_SymTables.push_back(libtable); } - + /* See if the symbol is already cached in our table */ symbol_entry = table->FindSymbol(symbol, strlen(symbol)); if (symbol_entry != NULL) { return symbol_entry->address; } - + /* If symbol isn't in our table, then we have to locate it in memory */ - + file_hdr = (struct mach_header *)dlbase; loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header)); loadcmd_count = file_hdr->ncmds; - + /* Loop through load commands until we find the ones for the symbol table */ for (uint32_t i = 0; i < loadcmd_count; i++) { @@ -388,7 +388,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) /* Load commands are not of a fixed size which is why we add the size */ loadcmds = (struct load_command *)((uintptr_t)loadcmds + loadcmds->cmdsize); } - + if (!linkedit_hdr || !symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff) { /* Uh oh, no symbol table */ @@ -399,7 +399,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) symtab = (struct nlist *)(linkedit_addr + symtab_hdr->symoff - linkedit_hdr->fileoff); strtab = (const char *)(linkedit_addr + symtab_hdr->stroff - linkedit_hdr->fileoff); symbol_count = symtab_hdr->nsyms; - + /* Iterate symbol table starting from the position we were at last time */ for (uint32_t i = libtable->last_pos; i < symbol_count; i++) { @@ -407,13 +407,13 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) /* Ignore the prepended underscore on all symbols, so +1 here */ const char *sym_name = strtab + sym.n_un.n_strx + 1; Symbol *cur_sym; - + /* Skip symbols that are undefined */ if (sym.n_sect == NO_SECT) { continue; } - + /* Caching symbols as we go along */ cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlbase + sym.n_value)); if (strcmp(symbol, sym_name) == 0) @@ -423,7 +423,7 @@ void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) break; } } - + return symbol_entry ? symbol_entry->address : NULL; #endif @@ -540,7 +540,7 @@ bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib) if (hdr.p_type == PT_LOAD && hdr.p_flags == (PF_X|PF_R)) { /* From glibc, elf/dl-load.c: - * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1) + * c->mapend = ((ph->p_vaddr + ph->p_filesz + GLRO(dl_pagesize) - 1) * & ~(GLRO(dl_pagesize) - 1)); * * In glibc, the segment file size is aligned up to the nearest page size and @@ -592,15 +592,15 @@ bool MemoryUtils::GetLibraryInfo(const void *libPtr, DynLibInfo &lib) cmd_count = file->ncmds; seg = (struct segment_command *)(baseAddr + sizeof(struct mach_header)); - + /* Add up memory sizes of mapped segments */ for (uint32_t i = 0; i < cmd_count; i++) - { + { if (seg->cmd == LC_SEGMENT) { lib.memorySize += seg->vmsize; } - + seg = (struct segment_command *)((uintptr_t)seg + seg->cmdsize); } diff --git a/core/logic/MemoryUtils.h b/core/logic/memoryutils.h similarity index 100% rename from core/logic/MemoryUtils.h rename to core/logic/memoryutils.h diff --git a/core/logic/MersenneTwister.h b/core/logic/mersennetwister.h similarity index 100% rename from core/logic/MersenneTwister.h rename to core/logic/mersennetwister.h diff --git a/core/logic/Native.h b/core/logic/native.h similarity index 100% rename from core/logic/Native.h rename to core/logic/native.h diff --git a/core/logic/NativeOwner.cpp b/core/logic/nativeowner.cpp similarity index 94% rename from core/logic/NativeOwner.cpp rename to core/logic/nativeowner.cpp index a4b092e62..db534f88c 100644 --- a/core/logic/NativeOwner.cpp +++ b/core/logic/nativeowner.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -28,9 +28,9 @@ * * Version: $Id$ */ -#include "NativeOwner.h" -#include "ShareSys.h" -#include "PluginSys.h" +#include "nativeowner.h" +#include "sharesys.h" +#include "pluginsys.h" CNativeOwner::CNativeOwner() : m_nMarkSerial(0) { diff --git a/core/logic/NativeOwner.h b/core/logic/nativeowner.h similarity index 94% rename from core/logic/NativeOwner.h rename to core/logic/nativeowner.h index f55d954b9..228c0de7e 100644 --- a/core/logic/NativeOwner.h +++ b/core/logic/nativeowner.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -36,7 +36,7 @@ #include #include #include "common_logic.h" -#include "Native.h" +#include "native.h" #include struct Native; @@ -46,7 +46,7 @@ using namespace SourceMod; struct WeakNative { - WeakNative(IPlugin *plugin, uint32_t index) : + WeakNative(IPlugin *plugin, uint32_t index) : pl(plugin), idx(index) { pl = plugin; diff --git a/core/logic/PhraseCollection.cpp b/core/logic/phrasecollection.cpp similarity index 94% rename from core/logic/PhraseCollection.cpp rename to core/logic/phrasecollection.cpp index 124f0094e..9619b8436 100644 --- a/core/logic/PhraseCollection.cpp +++ b/core/logic/phrasecollection.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,8 +30,8 @@ */ #include "common_logic.h" -#include "PhraseCollection.h" -#include "Translator.h" +#include "phrasecollection.h" +#include "translator.h" #include "sprintf.h" #include @@ -57,7 +57,7 @@ IPhraseFile *CPhraseCollection::AddPhraseFile(const char *filename) /* No compat shim here. The user should have read the doc. */ ke::SafeSprintf(full_name, sizeof(full_name), "%s.txt", filename); - + fid = g_Translator.FindOrAddPhraseFile(full_name); pFile = g_Translator.GetFileByIndex(fid); diff --git a/core/logic/PhraseCollection.h b/core/logic/phrasecollection.h similarity index 100% rename from core/logic/PhraseCollection.h rename to core/logic/phrasecollection.h diff --git a/core/logic/PluginSys.cpp b/core/logic/pluginsys.cpp similarity index 95% rename from core/logic/PluginSys.cpp rename to core/logic/pluginsys.cpp index 273e05d37..d70873d8b 100644 --- a/core/logic/PluginSys.cpp +++ b/core/logic/pluginsys.cpp @@ -31,18 +31,18 @@ #include #include -#include "PluginSys.h" -#include "ShareSys.h" +#include "pluginsys.h" +#include "sharesys.h" #include #include #include #include #include -#include "ExtensionSys.h" -#include "GameConfigs.h" +#include "extensionsys.h" +#include "gameconfigs.h" #include "common_logic.h" -#include "Translator.h" -#include "Logger.h" +#include "translator.h" +#include "logger.h" #include "frame_tasks.h" #include #include @@ -694,7 +694,7 @@ void CPlugin::DropEverything() * to centralize that here, i'm omitting it for now. Thus, * the code below to walk the plugins list will suffice. */ - + /* Other plugins could be holding weak references that were * added by us. We need to clean all of those up now. */ @@ -767,7 +767,7 @@ CPluginManager::CPluginManager() m_AllPluginsLoaded = false; m_MyIdent = NULL; m_LoadingLocked = false; - + m_bBlockBadPlugins = true; } @@ -1186,12 +1186,12 @@ CPlugin *CPluginManager::CompileAndPrep(const char *path) bool CPluginManager::MalwareCheckPass(CPlugin *pPlugin) { unsigned char *pCodeHash = pPlugin->GetRuntime()->GetCodeHash(); - + char codeHashBuf[40]; ke::SafeSprintf(codeHashBuf, 40, "plugin_"); for (int i = 0; i < 16; i++) ke::SafeSprintf(codeHashBuf + 7 + (i * 2), 3, "%02x", pCodeHash[i]); - + const char *bulletinUrl = g_pGameConf->GetKeyValue(codeHashBuf); if (!bulletinUrl) return true; @@ -1253,7 +1253,7 @@ bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxleng pListener = (*iter); pListener->OnPluginLoaded(pPlugin); } - + /* Tell this plugin to finish initializing itself */ pPlugin->Call_OnPluginStart(); @@ -1294,7 +1294,7 @@ bool CPluginManager::RunSecondPass(CPlugin *pPlugin, char *error, size_t maxleng /* :TODO: optimize? does this even matter? */ pPlugin->GetPhrases()->AddPhraseFile("core.phrases"); - + /* Go through all other already loaded plugins and tell this plugin, that their libraries are loaded */ for (List::iterator pl_iter = m_plugins.begin(); pl_iter != m_plugins.end(); pl_iter++) { @@ -1434,7 +1434,7 @@ void CPluginManager::UnloadPluginImpl(CPlugin *pPlugin) pListener = (*iter); pListener->OnPluginDestroyed(pPlugin); } - + /* Tell the plugin to delete itself */ delete pPlugin; } @@ -1722,7 +1722,7 @@ void CPluginManager::OnSourceModAllInitialized() rootmenu->AddRootConsoleCommand3("plugins", "Manage Plugins", this); g_ShareSys.AddInterface(NULL, GetOldAPI()); - + m_pOnLibraryAdded = forwardsys->CreateForward("OnLibraryAdded", ET_Ignore, 1, NULL, Param_String); m_pOnLibraryRemoved = forwardsys->CreateForward("OnLibraryRemoved", ET_Ignore, 1, NULL, Param_String); } @@ -1736,7 +1736,7 @@ void CPluginManager::OnSourceModShutdown() handlesys->RemoveType(g_PluginType, m_MyIdent); g_ShareSys.DestroyIdentType(g_PluginIdent); g_ShareSys.DestroyIdentity(m_MyIdent); - + forwardsys->ReleaseForward(m_pOnLibraryAdded); forwardsys->ReleaseForward(m_pOnLibraryRemoved); } @@ -2130,14 +2130,14 @@ void CPluginManager::OnRootConsoleCommand(const char *cmdname, const ICommandArg { rootmenu->ConsolePrint(" Timestamp: %s", pl->m_DateTime); } - + unsigned char *pCodeHash = pl->m_pRuntime->GetCodeHash(); unsigned char *pDataHash = pl->m_pRuntime->GetDataHash(); - + char combinedHash[33]; for (int i = 0; i < 16; i++) ke::SafeSprintf(combinedHash + (i * 2), 3, "%02x", pCodeHash[i] ^ pDataHash[i]); - + rootmenu->ConsolePrint(" Hash: %s", combinedHash); } else @@ -2314,7 +2314,7 @@ void CPluginManager::_SetPauseState(CPlugin *pl, bool paused) { pListener = (*iter); pListener->OnPluginPauseChange(pl, paused); - } + } } void CPluginManager::AddFunctionsToForward(const char *name, IChangeableForward *pForward) @@ -2434,7 +2434,7 @@ SMPlugin *CPluginManager::FindPluginByConsoleArg(const char *arg) int id; char *end; CPlugin *pl; - + id = strtol(arg, &end, 10); if (*end == '\0') diff --git a/core/logic/PluginSys.h b/core/logic/pluginsys.h similarity index 93% rename from core/logic/PluginSys.h rename to core/logic/pluginsys.h index 835ac0f77..0534041d2 100644 --- a/core/logic/PluginSys.h +++ b/core/logic/pluginsys.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -46,11 +46,11 @@ #include #include #include -#include "ITranslator.h" -#include "IGameConfigs.h" -#include "NativeOwner.h" -#include "ShareSys.h" -#include "PhraseCollection.h" +#include +#include +#include "nativeowner.h" +#include "sharesys.h" +#include "phrasecollection.h" #include #include #include @@ -62,12 +62,12 @@ using namespace SourceHook; /** * NOTES: * - * UPDATE 2008-03-11: These comments are horribly out of date. They paint a good overall - * picture of how PluginSys works, but things like dependencies and fake natives have + * UPDATE 2008-03-11: These comments are horribly out of date. They paint a good overall + * picture of how PluginSys works, but things like dependencies and fake natives have * complicated things quite a bit. * - * Currently this system needs a lot of work but it's good skeletally. Plugin creation - * is done without actually compiling anything. This is done by Load functions in the + * Currently this system needs a lot of work but it's good skeletally. Plugin creation + * is done without actually compiling anything. This is done by Load functions in the * manager. This will need a rewrite when we add context switching. * * The plugin object itself has a few things to note. The most important is that it stores @@ -78,8 +78,8 @@ using namespace SourceHook; * However, the state itself being set prevents any runtime action. * Plugin_BadLoad --> The plugin failed to load entirely and nothing can be done to save it. * - * If a plugin fails to load externally, it is never added to the internal tracker. However, - * plugins that failed to load from the internal loading mechanism are always tracked. This + * If a plugin fails to load externally, it is never added to the internal tracker. However, + * plugins that failed to load from the internal loading mechanism are always tracked. This * allows users to see which automatically loaded plugins failed, and makes the interface a bit * more flexible. * @@ -124,7 +124,7 @@ enum APLRes APLRes_SilentFailure }; -class CPlugin : +class CPlugin : public SMPlugin, public CNativeOwner { @@ -169,7 +169,7 @@ public: * Creates a plugin object with default values. * If an error buffer is specified, and an error occurs, the error will be copied to the buffer * and NULL will be returned. - * If an error buffer is not specified, the error will be copied to an internal buffer and + * If an error buffer is not specified, the error will be copied to an internal buffer and * a valid (but error-stated) CPlugin will be returned. */ static CPlugin *Create(const char *file); @@ -305,7 +305,7 @@ private: ke::AString info_url_; }; -class CPluginManager : +class CPluginManager : public IScriptManager, public SMGlobalClass, public IHandleTypeDispatch, @@ -334,7 +334,7 @@ public: }; friend class CPluginManager::CPluginIterator; public: //IScriptManager - IPlugin *LoadPlugin(const char *path, + IPlugin *LoadPlugin(const char *path, bool debug, PluginType type, char error[], @@ -393,12 +393,12 @@ public: * csdm/ban csdm/ban * ban csdm/ban * csdm/ban optional/csdm/ban - * All of these will return true for an alias match. + * All of these will return true for an alias match. * Wildcards are allowed in the filename. */ bool TestAliasMatch(const char *alias, const char *localdir); - /** + /** * Returns whether anything loaded will be a late load. */ bool IsLateLoadTime() const; @@ -415,13 +415,13 @@ public: int GetOrderOfPlugin(IPlugin *pl); - /** + /** * Internal version of FindPluginByContext() */ CPlugin *GetPluginByCtx(const sp_context_t *ctx); /** - * Gets status text for a status code + * Gets status text for a status code */ const char *GetStatusText(PluginStatus status); @@ -517,10 +517,10 @@ private: List m_Natives; bool m_LoadingLocked; - + // Config bool m_bBlockBadPlugins; - + // Forwards IForward *m_pOnLibraryAdded; IForward *m_pOnLibraryRemoved; diff --git a/core/logic/ProfileTools.cpp b/core/logic/profiletools.cpp similarity index 96% rename from core/logic/ProfileTools.cpp rename to core/logic/profiletools.cpp index 0305ec9dd..92065ec5f 100644 --- a/core/logic/ProfileTools.cpp +++ b/core/logic/profiletools.cpp @@ -1,191 +1,191 @@ -// vim: set ts=4 sw=4 tw=99 noet : -// ============================================================================= -// SourceMod -// Copyright (C) 2004-2014 AlliedModders LLC. All rights reserved. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . - -#include "ProfileTools.h" -#include -#include - -ProfileToolManager g_ProfileToolManager; - -ProfileToolManager::ProfileToolManager() - : active_(nullptr), - default_(nullptr) -{ -} - -void -ProfileToolManager::OnSourceModAllInitialized() -{ - rootmenu->AddRootConsoleCommand3("prof", "Profiling", this); -} - -void -ProfileToolManager::OnSourceModShutdown() -{ - rootmenu->RemoveRootConsoleCommand("prof", this); -} - -IProfilingTool * -ProfileToolManager::FindToolByName(const char *name) -{ - for (size_t i = 0; i < tools_.length(); i++) { - if (strcmp(tools_[i]->Name(), name) == 0) - return tools_[i]; - } - return nullptr; -} - -static void -render_help(const char *fmt, ...) -{ - char buffer[2048]; - - va_list ap; - va_start(ap, fmt); - ke::SafeVsprintf(buffer, sizeof(buffer), fmt, ap); - va_end(ap); - - rootmenu->ConsolePrint("%s", buffer); -} - -void -ProfileToolManager::StartFromConsole(IProfilingTool *tool) -{ - if (active_) { - rootmenu->ConsolePrint("A profile is already active using %s.", active_->Name()); - return; - } - - active_ = tool; - if (!active_->Start()) { - rootmenu->ConsolePrint("Failed to attach to or start %s.", active_->Name()); - active_ = nullptr; - return; - } - - g_pSourcePawn2->SetProfilingTool(active_); - g_pSourcePawn2->EnableProfiling(); - rootmenu->ConsolePrint("Started profiling with %s.", active_->Name()); - - default_ = active_; -} - -void -ProfileToolManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs *args) -{ - if (tools_.length() == 0) { - rootmenu->ConsolePrint("No profiling tools are enabled."); - return; - } - - if (args->ArgC() >= 3) { - cmdname = args->Arg(2); - - if (strcmp(cmdname, "list") == 0) { - rootmenu->ConsolePrint("Profiling tools:"); - for (size_t i = 0; i < tools_.length(); i++) { - rootmenu->DrawGenericOption(tools_[i]->Name(), tools_[i]->Description()); - } - return; - } - if (strcmp(cmdname, "stop") == 0) { - if (!active_) { - rootmenu->ConsolePrint("No profiler is active."); - return; - } - g_pSourcePawn2->DisableProfiling(); - g_pSourcePawn2->SetProfilingTool(nullptr); - active_->Stop(render_help); - active_ = nullptr; - return; - } - if (strcmp(cmdname, "dump") == 0) { - if (active_) { - // if we have an active profiler, dump it - active_->Dump(); - return; - } - } - - if (args->ArgC() < 4) { - if (strcmp(cmdname, "start") == 0) { - if (!default_) { - default_ = FindToolByName("vprof"); - if (!default_ && tools_.length() > 0) - default_ = tools_[0]; - if (!default_) { - rootmenu->ConsolePrint("Could not find any profiler to use."); - return; - } - } - StartFromConsole(default_); - return; - } - } - - if (args->ArgC() < 4) { - rootmenu->ConsolePrint("You must specify a profiling tool name."); - return; - } - - const char *toolname = args->Arg(3); - if (strcmp(cmdname, "start") == 0) { - IProfilingTool *tool = FindToolByName(toolname); - if (!tool) { - rootmenu->ConsolePrint("No tool with the name \"%s\" was found.", toolname); - return; - } - StartFromConsole(tool); - return; - } - if (strcmp(cmdname, "dump") == 0) { - IProfilingTool *tool = FindToolByName(toolname); - if (!tool) { - rootmenu->ConsolePrint("No tool with the name \"%s\" was found.", toolname); - return; - } - tool->Dump(); - return; - } - if (strcmp(cmdname, "help") == 0) { - IProfilingTool *tool = FindToolByName(toolname); - if (!tool) { - rootmenu->ConsolePrint("No tool with the name \"%s\" was found.", toolname); - return; - } - tool->RenderHelp(render_help); - return; - } - } - - rootmenu->ConsolePrint("Profiling commands:"); - rootmenu->DrawGenericOption("list", "List all available profiling tools."); - rootmenu->DrawGenericOption("start", "Start a profile with a given tool."); - rootmenu->DrawGenericOption("stop", "Stop the current profile session."); - rootmenu->DrawGenericOption("dump", "Dumps output from the current profile session."); - rootmenu->DrawGenericOption("help", "Display help text for a profiler."); -} +// vim: set ts=4 sw=4 tw=99 noet : +// ============================================================================= +// SourceMod +// Copyright (C) 2004-2014 AlliedModders LLC. All rights reserved. +// ============================================================================= +// +// This program is free software; you can redistribute it and/or modify it under +// the terms of the GNU General Public License, version 3.0, as published by the +// Free Software Foundation. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +// details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . +// +// As a special exception, AlliedModders LLC gives you permission to link the +// code of this program (as well as its derivative works) to "Half-Life 2," the +// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software +// by the Valve Corporation. You must obey the GNU General Public License in +// all respects for all other code used. Additionally, AlliedModders LLC grants +// this exception to all derivative works. AlliedModders LLC defines further +// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), +// or . + +#include "profiletools.h" +#include +#include + +ProfileToolManager g_ProfileToolManager; + +ProfileToolManager::ProfileToolManager() + : active_(nullptr), + default_(nullptr) +{ +} + +void +ProfileToolManager::OnSourceModAllInitialized() +{ + rootmenu->AddRootConsoleCommand3("prof", "Profiling", this); +} + +void +ProfileToolManager::OnSourceModShutdown() +{ + rootmenu->RemoveRootConsoleCommand("prof", this); +} + +IProfilingTool * +ProfileToolManager::FindToolByName(const char *name) +{ + for (size_t i = 0; i < tools_.length(); i++) { + if (strcmp(tools_[i]->Name(), name) == 0) + return tools_[i]; + } + return nullptr; +} + +static void +render_help(const char *fmt, ...) +{ + char buffer[2048]; + + va_list ap; + va_start(ap, fmt); + ke::SafeVsprintf(buffer, sizeof(buffer), fmt, ap); + va_end(ap); + + rootmenu->ConsolePrint("%s", buffer); +} + +void +ProfileToolManager::StartFromConsole(IProfilingTool *tool) +{ + if (active_) { + rootmenu->ConsolePrint("A profile is already active using %s.", active_->Name()); + return; + } + + active_ = tool; + if (!active_->Start()) { + rootmenu->ConsolePrint("Failed to attach to or start %s.", active_->Name()); + active_ = nullptr; + return; + } + + g_pSourcePawn2->SetProfilingTool(active_); + g_pSourcePawn2->EnableProfiling(); + rootmenu->ConsolePrint("Started profiling with %s.", active_->Name()); + + default_ = active_; +} + +void +ProfileToolManager::OnRootConsoleCommand(const char *cmdname, const ICommandArgs *args) +{ + if (tools_.length() == 0) { + rootmenu->ConsolePrint("No profiling tools are enabled."); + return; + } + + if (args->ArgC() >= 3) { + cmdname = args->Arg(2); + + if (strcmp(cmdname, "list") == 0) { + rootmenu->ConsolePrint("Profiling tools:"); + for (size_t i = 0; i < tools_.length(); i++) { + rootmenu->DrawGenericOption(tools_[i]->Name(), tools_[i]->Description()); + } + return; + } + if (strcmp(cmdname, "stop") == 0) { + if (!active_) { + rootmenu->ConsolePrint("No profiler is active."); + return; + } + g_pSourcePawn2->DisableProfiling(); + g_pSourcePawn2->SetProfilingTool(nullptr); + active_->Stop(render_help); + active_ = nullptr; + return; + } + if (strcmp(cmdname, "dump") == 0) { + if (active_) { + // if we have an active profiler, dump it + active_->Dump(); + return; + } + } + + if (args->ArgC() < 4) { + if (strcmp(cmdname, "start") == 0) { + if (!default_) { + default_ = FindToolByName("vprof"); + if (!default_ && tools_.length() > 0) + default_ = tools_[0]; + if (!default_) { + rootmenu->ConsolePrint("Could not find any profiler to use."); + return; + } + } + StartFromConsole(default_); + return; + } + } + + if (args->ArgC() < 4) { + rootmenu->ConsolePrint("You must specify a profiling tool name."); + return; + } + + const char *toolname = args->Arg(3); + if (strcmp(cmdname, "start") == 0) { + IProfilingTool *tool = FindToolByName(toolname); + if (!tool) { + rootmenu->ConsolePrint("No tool with the name \"%s\" was found.", toolname); + return; + } + StartFromConsole(tool); + return; + } + if (strcmp(cmdname, "dump") == 0) { + IProfilingTool *tool = FindToolByName(toolname); + if (!tool) { + rootmenu->ConsolePrint("No tool with the name \"%s\" was found.", toolname); + return; + } + tool->Dump(); + return; + } + if (strcmp(cmdname, "help") == 0) { + IProfilingTool *tool = FindToolByName(toolname); + if (!tool) { + rootmenu->ConsolePrint("No tool with the name \"%s\" was found.", toolname); + return; + } + tool->RenderHelp(render_help); + return; + } + } + + rootmenu->ConsolePrint("Profiling commands:"); + rootmenu->DrawGenericOption("list", "List all available profiling tools."); + rootmenu->DrawGenericOption("start", "Start a profile with a given tool."); + rootmenu->DrawGenericOption("stop", "Stop the current profile session."); + rootmenu->DrawGenericOption("dump", "Dumps output from the current profile session."); + rootmenu->DrawGenericOption("help", "Display help text for a profiler."); +} diff --git a/core/logic/ProfileTools.h b/core/logic/profiletools.h similarity index 100% rename from core/logic/ProfileTools.h rename to core/logic/profiletools.h diff --git a/core/logic/RootConsoleMenu.cpp b/core/logic/rootconsolemenu.cpp similarity index 96% rename from core/logic/RootConsoleMenu.cpp rename to core/logic/rootconsolemenu.cpp index 063ff4c7d..160e609ef 100644 --- a/core/logic/RootConsoleMenu.cpp +++ b/core/logic/rootconsolemenu.cpp @@ -1,289 +1,289 @@ -// vim: set ts=4 sw=4 tw=99 noet : -// ============================================================================= -// SourceMod -// Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . -#include "RootConsoleMenu.h" -#include -#include -#include -#include -#include "HandleSys.h" - -RootConsoleMenu g_RootMenu; - -// Some top-level commands that are just thrown in here. -static bool sm_dump_handles(int client, const ICommandArgs *args); - -RootConsoleMenu::RootConsoleMenu() -{ -} - -RootConsoleMenu::~RootConsoleMenu() -{ - List::iterator iter; - for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) - { - delete (*iter); - } - m_Menu.clear(); -} - -void RootConsoleMenu::OnSourceModStartup(bool late) -{ - AddRootConsoleCommand3("version", "Display version information", this); - AddRootConsoleCommand3("credits", "Display credits listing", this); - - bridge->DefineCommand("sm_dump_handles", "Dumps Handle usage to a file for finding Handle leaks", - sm_dump_handles); - bridge->DefineCommand("sm", "SourceMod Menu", [this] (int client, const ICommandArgs *args) -> bool { - GotRootCmd(args); - return true; - }); -} - -void RootConsoleMenu::OnSourceModAllInitialized() -{ - sharesys->AddInterface(NULL, this); -} - -void RootConsoleMenu::OnSourceModShutdown() -{ - RemoveRootConsoleCommand("credits", this); - RemoveRootConsoleCommand("version", this); -} - -void RootConsoleMenu::ConsolePrint(const char *fmt, ...) -{ - va_list ap; - va_start(ap, fmt); - bridge->ConsolePrintVa(fmt, ap); - va_end(ap); -} - -bool RootConsoleMenu::AddRootConsoleCommand(const char *cmd, const char *text, IRootConsoleCommand *pHandler) -{ - return false; -} - -bool RootConsoleMenu::AddRootConsoleCommand2(const char *cmd, const char *text, IRootConsoleCommand *pHandler) -{ - return false; -} - -bool RootConsoleMenu::AddRootConsoleCommand3(const char *cmd, - const char *text, - IRootConsoleCommand *pHandler) -{ - if (m_Commands.contains(cmd)) - return false; - - /* Sort this into the menu */ - List::iterator iter = m_Menu.begin(); - ConsoleEntry *pEntry; - bool inserted = false; - while (iter != m_Menu.end()) - { - pEntry = (*iter); - if (strcmp(cmd, pEntry->command.c_str()) < 0) - { - ConsoleEntry *pNew = new ConsoleEntry; - pNew->command.assign(cmd); - pNew->description.assign(text); - pNew->cmd = pHandler; - m_Commands.insert(cmd, pNew); - m_Menu.insert(iter, pNew); - inserted = true; - break; - } - iter++; - } - - if (!inserted) - { - ConsoleEntry *pNew = new ConsoleEntry; - pNew->command.assign(cmd); - pNew->description.assign(text); - pNew->cmd = pHandler; - m_Commands.insert(cmd, pNew); - m_Menu.push_back(pNew); - } - - return true; -} - -bool RootConsoleMenu::RemoveRootConsoleCommand(const char *cmd, IRootConsoleCommand *pHandler) -{ - m_Commands.remove(cmd); - - List::iterator iter; - ConsoleEntry *pEntry; - for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) - { - pEntry = (*iter); - if (pEntry->command.compare(cmd) == 0) - { - delete pEntry; - m_Menu.erase(iter); - break; - } - } - - return true; -} - -void RootConsoleMenu::DrawGenericOption(const char *cmd, const char *text) -{ - char buffer[255]; - size_t len, cmdlen = strlen(cmd); - - len = ke::SafeSprintf(buffer, sizeof(buffer), " %s", cmd); - if (cmdlen < 16) - { - size_t num = 16 - cmdlen; - for (size_t i = 0; i < num; i++) - { - buffer[len++] = ' '; - } - len += snprintf(&buffer[len], sizeof(buffer) - len, " - %s", text); - ConsolePrint("%s", buffer); - } -} - -const char *RootConsoleMenu::GetInterfaceName() -{ - return SMINTERFACE_ROOTCONSOLE_NAME; -} - -unsigned int RootConsoleMenu::GetInterfaceVersion() -{ - return SMINTERFACE_ROOTCONSOLE_VERSION; -} - -void RootConsoleMenu::GotRootCmd(const ICommandArgs *cmd) -{ - unsigned int argnum = cmd->ArgC(); - - if (argnum >= 2) - { - const char *cmdname = cmd->Arg(1); - - ConsoleEntry *entry; - if (m_Commands.retrieve(cmdname, &entry)) - { - entry->cmd->OnRootConsoleCommand(cmdname, cmd); - return; - } - } - - ConsolePrint("SourceMod Menu:"); - ConsolePrint("Usage: sm [arguments]"); - - List::iterator iter; - ConsoleEntry *pEntry; - for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) - { - pEntry = (*iter); - DrawGenericOption(pEntry->command.c_str(), pEntry->description.c_str()); - } -} - -void RootConsoleMenu::OnRootConsoleCommand(const char *cmdname, const ICommandArgs *command) -{ - if (strcmp(cmdname, "credits") == 0) - { - ConsolePrint(" SourceMod was developed by AlliedModders, LLC."); - ConsolePrint(" Development would not have been possible without the following people:"); - ConsolePrint(" David \"BAILOPAN\" Anderson"); - ConsolePrint(" Matt \"pRED\" Woodrow"); - ConsolePrint(" Scott \"DS\" Ehlert"); - ConsolePrint(" Fyren"); - ConsolePrint(" Nicholas \"psychonic\" Hastings"); - ConsolePrint(" Asher \"asherkin\" Baker"); - ConsolePrint(" Borja \"faluco\" Ferrer"); - ConsolePrint(" Pavol \"PM OnoTo\" Marko"); - ConsolePrint(" Special thanks to Liam, ferret, and Mani"); - ConsolePrint(" Special thanks to Viper and SteamFriends"); - ConsolePrint(" http://www.sourcemod.net/"); - } - else if (strcmp(cmdname, "version") == 0) - { - ConsolePrint(" SourceMod Version Information:"); - ConsolePrint(" SourceMod Version: %s", SOURCEMOD_VERSION); - if (g_pSourcePawn2->IsJitEnabled()) - ConsolePrint(" SourcePawn Engine: %s (build %s)", g_pSourcePawn2->GetEngineName(), g_pSourcePawn2->GetVersionString()); - else - ConsolePrint(" SourcePawn Engine: %s (build %s NO JIT)", g_pSourcePawn2->GetEngineName(), g_pSourcePawn2->GetVersionString()); - ConsolePrint(" SourcePawn API: v1 = %d, v2 = %d", g_pSourcePawn->GetEngineAPIVersion(), g_pSourcePawn2->GetAPIVersion()); - ConsolePrint(" Compiled on: %s", SOURCEMOD_BUILD_TIME); -#if defined(SM_GENERATED_BUILD) - ConsolePrint(" Built from: https://github.com/alliedmodders/sourcemod/commit/%s", SOURCEMOD_SHA); - ConsolePrint(" Build ID: %s:%s", SOURCEMOD_LOCAL_REV, SOURCEMOD_SHA); -#endif - ConsolePrint(" http://www.sourcemod.net/"); - } -} - -static bool sm_dump_handles(int client, const ICommandArgs *args) -{ - if (args->ArgC() < 2) { - bridge->ConsolePrint("Usage: sm_dump_handles or for game logs"); - return true; - } - - if (strcmp(args->Arg(1), "log") == 0) { - auto write_handles_to_game = [] (const char *str) -> void - { - char buffer[1024]; - size_t len = ke::SafeSprintf(buffer, sizeof(buffer)-2, "%s", str); - - buffer[len] = '\n'; - buffer[len+1] = '\0'; - - bridge->LogToGame(buffer); - }; - g_HandleSys.Dump(write_handles_to_game); - return true; - } - - FILE *fp = nullptr; - auto write_handles_to_log = [&fp] (const char *str) -> void - { - fprintf(fp, "%s\n", str); - }; - - char filename[PLATFORM_MAX_PATH]; - const char *arg = args->Arg(1); - g_pSM->BuildPath(Path_Game, filename, sizeof(filename), "%s", arg); - - fp = fopen(filename, "wt"); - if (!fp) { - bridge->ConsolePrint("Failed to open \"%s\" for writing", filename); - return true; - } - - g_HandleSys.Dump(write_handles_to_log); - fclose(fp); - return true; -} +// vim: set ts=4 sw=4 tw=99 noet : +// ============================================================================= +// SourceMod +// Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved. +// ============================================================================= +// +// This program is free software; you can redistribute it and/or modify it under +// the terms of the GNU General Public License, version 3.0, as published by the +// Free Software Foundation. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +// details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . +// +// As a special exception, AlliedModders LLC gives you permission to link the +// code of this program (as well as its derivative works) to "Half-Life 2," the +// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software +// by the Valve Corporation. You must obey the GNU General Public License in +// all respects for all other code used. Additionally, AlliedModders LLC grants +// this exception to all derivative works. AlliedModders LLC defines further +// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), +// or . +#include "rootconsolemenu.h" +#include +#include +#include +#include +#include "handlesys.h" + +RootConsoleMenu g_RootMenu; + +// Some top-level commands that are just thrown in here. +static bool sm_dump_handles(int client, const ICommandArgs *args); + +RootConsoleMenu::RootConsoleMenu() +{ +} + +RootConsoleMenu::~RootConsoleMenu() +{ + List::iterator iter; + for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) + { + delete (*iter); + } + m_Menu.clear(); +} + +void RootConsoleMenu::OnSourceModStartup(bool late) +{ + AddRootConsoleCommand3("version", "Display version information", this); + AddRootConsoleCommand3("credits", "Display credits listing", this); + + bridge->DefineCommand("sm_dump_handles", "Dumps Handle usage to a file for finding Handle leaks", + sm_dump_handles); + bridge->DefineCommand("sm", "SourceMod Menu", [this] (int client, const ICommandArgs *args) -> bool { + GotRootCmd(args); + return true; + }); +} + +void RootConsoleMenu::OnSourceModAllInitialized() +{ + sharesys->AddInterface(NULL, this); +} + +void RootConsoleMenu::OnSourceModShutdown() +{ + RemoveRootConsoleCommand("credits", this); + RemoveRootConsoleCommand("version", this); +} + +void RootConsoleMenu::ConsolePrint(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + bridge->ConsolePrintVa(fmt, ap); + va_end(ap); +} + +bool RootConsoleMenu::AddRootConsoleCommand(const char *cmd, const char *text, IRootConsoleCommand *pHandler) +{ + return false; +} + +bool RootConsoleMenu::AddRootConsoleCommand2(const char *cmd, const char *text, IRootConsoleCommand *pHandler) +{ + return false; +} + +bool RootConsoleMenu::AddRootConsoleCommand3(const char *cmd, + const char *text, + IRootConsoleCommand *pHandler) +{ + if (m_Commands.contains(cmd)) + return false; + + /* Sort this into the menu */ + List::iterator iter = m_Menu.begin(); + ConsoleEntry *pEntry; + bool inserted = false; + while (iter != m_Menu.end()) + { + pEntry = (*iter); + if (strcmp(cmd, pEntry->command.c_str()) < 0) + { + ConsoleEntry *pNew = new ConsoleEntry; + pNew->command.assign(cmd); + pNew->description.assign(text); + pNew->cmd = pHandler; + m_Commands.insert(cmd, pNew); + m_Menu.insert(iter, pNew); + inserted = true; + break; + } + iter++; + } + + if (!inserted) + { + ConsoleEntry *pNew = new ConsoleEntry; + pNew->command.assign(cmd); + pNew->description.assign(text); + pNew->cmd = pHandler; + m_Commands.insert(cmd, pNew); + m_Menu.push_back(pNew); + } + + return true; +} + +bool RootConsoleMenu::RemoveRootConsoleCommand(const char *cmd, IRootConsoleCommand *pHandler) +{ + m_Commands.remove(cmd); + + List::iterator iter; + ConsoleEntry *pEntry; + for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) + { + pEntry = (*iter); + if (pEntry->command.compare(cmd) == 0) + { + delete pEntry; + m_Menu.erase(iter); + break; + } + } + + return true; +} + +void RootConsoleMenu::DrawGenericOption(const char *cmd, const char *text) +{ + char buffer[255]; + size_t len, cmdlen = strlen(cmd); + + len = ke::SafeSprintf(buffer, sizeof(buffer), " %s", cmd); + if (cmdlen < 16) + { + size_t num = 16 - cmdlen; + for (size_t i = 0; i < num; i++) + { + buffer[len++] = ' '; + } + len += snprintf(&buffer[len], sizeof(buffer) - len, " - %s", text); + ConsolePrint("%s", buffer); + } +} + +const char *RootConsoleMenu::GetInterfaceName() +{ + return SMINTERFACE_ROOTCONSOLE_NAME; +} + +unsigned int RootConsoleMenu::GetInterfaceVersion() +{ + return SMINTERFACE_ROOTCONSOLE_VERSION; +} + +void RootConsoleMenu::GotRootCmd(const ICommandArgs *cmd) +{ + unsigned int argnum = cmd->ArgC(); + + if (argnum >= 2) + { + const char *cmdname = cmd->Arg(1); + + ConsoleEntry *entry; + if (m_Commands.retrieve(cmdname, &entry)) + { + entry->cmd->OnRootConsoleCommand(cmdname, cmd); + return; + } + } + + ConsolePrint("SourceMod Menu:"); + ConsolePrint("Usage: sm [arguments]"); + + List::iterator iter; + ConsoleEntry *pEntry; + for (iter=m_Menu.begin(); iter!=m_Menu.end(); iter++) + { + pEntry = (*iter); + DrawGenericOption(pEntry->command.c_str(), pEntry->description.c_str()); + } +} + +void RootConsoleMenu::OnRootConsoleCommand(const char *cmdname, const ICommandArgs *command) +{ + if (strcmp(cmdname, "credits") == 0) + { + ConsolePrint(" SourceMod was developed by AlliedModders, LLC."); + ConsolePrint(" Development would not have been possible without the following people:"); + ConsolePrint(" David \"BAILOPAN\" Anderson"); + ConsolePrint(" Matt \"pRED\" Woodrow"); + ConsolePrint(" Scott \"DS\" Ehlert"); + ConsolePrint(" Fyren"); + ConsolePrint(" Nicholas \"psychonic\" Hastings"); + ConsolePrint(" Asher \"asherkin\" Baker"); + ConsolePrint(" Borja \"faluco\" Ferrer"); + ConsolePrint(" Pavol \"PM OnoTo\" Marko"); + ConsolePrint(" Special thanks to Liam, ferret, and Mani"); + ConsolePrint(" Special thanks to Viper and SteamFriends"); + ConsolePrint(" http://www.sourcemod.net/"); + } + else if (strcmp(cmdname, "version") == 0) + { + ConsolePrint(" SourceMod Version Information:"); + ConsolePrint(" SourceMod Version: %s", SOURCEMOD_VERSION); + if (g_pSourcePawn2->IsJitEnabled()) + ConsolePrint(" SourcePawn Engine: %s (build %s)", g_pSourcePawn2->GetEngineName(), g_pSourcePawn2->GetVersionString()); + else + ConsolePrint(" SourcePawn Engine: %s (build %s NO JIT)", g_pSourcePawn2->GetEngineName(), g_pSourcePawn2->GetVersionString()); + ConsolePrint(" SourcePawn API: v1 = %d, v2 = %d", g_pSourcePawn->GetEngineAPIVersion(), g_pSourcePawn2->GetAPIVersion()); + ConsolePrint(" Compiled on: %s", SOURCEMOD_BUILD_TIME); +#if defined(SM_GENERATED_BUILD) + ConsolePrint(" Built from: https://github.com/alliedmodders/sourcemod/commit/%s", SOURCEMOD_SHA); + ConsolePrint(" Build ID: %s:%s", SOURCEMOD_LOCAL_REV, SOURCEMOD_SHA); +#endif + ConsolePrint(" http://www.sourcemod.net/"); + } +} + +static bool sm_dump_handles(int client, const ICommandArgs *args) +{ + if (args->ArgC() < 2) { + bridge->ConsolePrint("Usage: sm_dump_handles or for game logs"); + return true; + } + + if (strcmp(args->Arg(1), "log") == 0) { + auto write_handles_to_game = [] (const char *str) -> void + { + char buffer[1024]; + size_t len = ke::SafeSprintf(buffer, sizeof(buffer)-2, "%s", str); + + buffer[len] = '\n'; + buffer[len+1] = '\0'; + + bridge->LogToGame(buffer); + }; + g_HandleSys.Dump(write_handles_to_game); + return true; + } + + FILE *fp = nullptr; + auto write_handles_to_log = [&fp] (const char *str) -> void + { + fprintf(fp, "%s\n", str); + }; + + char filename[PLATFORM_MAX_PATH]; + const char *arg = args->Arg(1); + g_pSM->BuildPath(Path_Game, filename, sizeof(filename), "%s", arg); + + fp = fopen(filename, "wt"); + if (!fp) { + bridge->ConsolePrint("Failed to open \"%s\" for writing", filename); + return true; + } + + g_HandleSys.Dump(write_handles_to_log); + fclose(fp); + return true; +} diff --git a/core/logic/RootConsoleMenu.h b/core/logic/rootconsolemenu.h similarity index 100% rename from core/logic/RootConsoleMenu.h rename to core/logic/rootconsolemenu.h diff --git a/core/logic/ShareSys.cpp b/core/logic/sharesys.cpp similarity index 93% rename from core/logic/ShareSys.cpp rename to core/logic/sharesys.cpp index 3119f36c6..5dd02fc23 100644 --- a/core/logic/ShareSys.cpp +++ b/core/logic/sharesys.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,12 +29,12 @@ * Version: $Id$ */ -#include "ShareSys.h" -#include "ExtensionSys.h" +#include "sharesys.h" +#include "extensionsys.h" #include #include "common_logic.h" -#include "PluginSys.h" -#include "HandleSys.h" +#include "pluginsys.h" +#include "handlesys.h" #include using namespace ke; @@ -150,15 +150,15 @@ bool ShareSystem::AddInterface(IExtension *myself, SMInterface *iface) info.owner = myself; info.iface = iface; - + m_Interfaces.push_back(info); return true; } -bool ShareSystem::RequestInterface(const char *iface_name, - unsigned int iface_vers, - IExtension *myself, +bool ShareSystem::RequestInterface(const char *iface_name, + unsigned int iface_vers, + IExtension *myself, SMInterface **pIface) { /* See if the interface exists */ @@ -445,7 +445,7 @@ void ShareSystem::DropCapabilityProvider(IExtension *myself, IFeatureProvider *p m_caps.remove(r); } -FeatureStatus ShareSystem::TestFeature(IPluginRuntime *pRuntime, FeatureType feature, +FeatureStatus ShareSystem::TestFeature(IPluginRuntime *pRuntime, FeatureType feature, const char *name) { switch (feature) diff --git a/core/logic/ShareSys.h b/core/logic/sharesys.h similarity index 95% rename from core/logic/ShareSys.h rename to core/logic/sharesys.h index 18eaf9560..dd916ed61 100644 --- a/core/logic/ShareSys.h +++ b/core/logic/sharesys.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -41,7 +41,7 @@ #include #include #include "common_logic.h" -#include "Native.h" +#include "native.h" using namespace SourceHook; @@ -84,7 +84,7 @@ public: ShareSystem(); public: //IShareSys bool AddInterface(IExtension *myself, SMInterface *pIface); - bool RequestInterface(const char *iface_name, + bool RequestInterface(const char *iface_name, unsigned int iface_vers, IExtension *myself, SMInterface **pIface); diff --git a/core/logic/smn_adt_array.cpp b/core/logic/smn_adt_array.cpp index 3d3a74a84..6e13d5bb5 100644 --- a/core/logic/smn_adt_array.cpp +++ b/core/logic/smn_adt_array.cpp @@ -31,7 +31,7 @@ #include #include "common_logic.h" -#include "CellArray.h" +#include "cellarray.h" #include "stringutil.h" #include diff --git a/core/logic/smn_adt_stack.cpp b/core/logic/smn_adt_stack.cpp index 0a7c87348..caad3142c 100644 --- a/core/logic/smn_adt_stack.cpp +++ b/core/logic/smn_adt_stack.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. -* +* * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,14 +31,14 @@ #include #include "common_logic.h" -#include "CellArray.h" +#include "cellarray.h" #include "handle_helpers.h" #include "stringutil.h" #include HandleType_t htCellStack; -class CellStackHelpers : +class CellStackHelpers : public SMGlobalClass, public IHandleTypeDispatch { @@ -89,7 +89,7 @@ static cell_t PushStackCell(IPluginContext *pContext, const cell_t *params) HandleError err; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -112,7 +112,7 @@ static cell_t PushStackString(IPluginContext *pContext, const cell_t *params) HandleError err; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -138,7 +138,7 @@ static cell_t PushStackArray(IPluginContext *pContext, const cell_t *params) HandleError err; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -172,7 +172,7 @@ static cell_t PopStackCell(IPluginContext *pContext, const cell_t *params) cell_t *blk, *buffer; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -218,7 +218,7 @@ static cell_t PopStackString(IPluginContext *pContext, const cell_t *params) cell_t *blk, *pWritten; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -249,7 +249,7 @@ static cell_t PopStackArray(IPluginContext *pContext, const cell_t *params) CellArray *array; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -282,7 +282,7 @@ static cell_t IsStackEmpty(IPluginContext *pContext, const cell_t *params) CellArray *array; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) + if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -298,7 +298,7 @@ static cell_t IsStackEmpty(IPluginContext *pContext, const cell_t *params) static cell_t ArrayStack_Pop(IPluginContext *pContext, const cell_t *params) { - OpenHandle array(pContext, params[1], htCellStack); + OpenHandle array(pContext, params[1], htCellStack); if (!array.Ok()) return 0; @@ -325,7 +325,7 @@ static cell_t ArrayStack_Pop(IPluginContext *pContext, const cell_t *params) static cell_t ArrayStack_PopString(IPluginContext *pContext, const cell_t *params) { - OpenHandle array(pContext, params[1], htCellStack); + OpenHandle array(pContext, params[1], htCellStack); if (!array.Ok()) return 0; @@ -347,7 +347,7 @@ static cell_t ArrayStack_PopString(IPluginContext *pContext, const cell_t *param static cell_t ArrayStack_PopArray(IPluginContext *pContext, const cell_t *params) { - OpenHandle array(pContext, params[1], htCellStack); + OpenHandle array(pContext, params[1], htCellStack); if (!array.Ok()) return 0; diff --git a/core/logic/smn_console.cpp b/core/logic/smn_console.cpp index 3e70321c9..fd4cf8806 100644 --- a/core/logic/smn_console.cpp +++ b/core/logic/smn_console.cpp @@ -1,355 +1,355 @@ -/** - * vim: set ts=4 sw=4 tw=99 noet : - * ============================================================================= - * SourceMod - * Copyright (C) 2004-2010 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License, version 3.0, as published by the - * Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program. If not, see . - * - * As a special exception, AlliedModders LLC gives you permission to link the - * code of this program (as well as its derivative works) to "Half-Life 2," the - * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software - * by the Valve Corporation. You must obey the GNU General Public License in - * all respects for all other code used. Additionally, AlliedModders LLC grants - * this exception to all derivative works. AlliedModders LLC defines further - * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), - * or . - * - * Version: $Id$ - */ - -#include "common_logic.h" -#include "AdminCache.h" -#include -#include -#include -#include -#include "sprintf.h" -#include -#include - -static cell_t CheckCommandAccess(IPluginContext *pContext, const cell_t *params) -{ - if (params[1] == 0) - { - return 1; - } - - char *cmd; - pContext->LocalToString(params[2], &cmd); - - /* Match up with an admin command if possible */ - FlagBits bits = params[3]; - bool found_command = false; - if (params[0] < 4 || !params[4]) - { - found_command = bridge->LookForCommandAdminFlags(cmd, &bits); - } - - if (!found_command) - { - adminsys->GetCommandOverride(cmd, Override_Command, &bits); - } - - return adminsys->CheckClientCommandAccess(params[1], cmd, bits) ? 1 : 0; -} - -static cell_t CheckAccess(IPluginContext *pContext, const cell_t *params) -{ - char *cmd; - pContext->LocalToString(params[2], &cmd); - - /* Match up with an admin command if possible */ - FlagBits bits = params[3]; - bool found_command = false; - if (params[0] < 4 || !params[4]) - { - found_command = bridge->LookForCommandAdminFlags(cmd, &bits); - } - - if (!found_command) - { - adminsys->GetCommandOverride(cmd, Override_Command, &bits); - } - - return g_Admins.CheckAdminCommandAccess(params[1], cmd, bits) ? 1 : 0; -} - -static cell_t sm_PrintToServer(IPluginContext *pCtx, const cell_t *params) -{ - char buffer[1024]; - char *fmt; - int arg = 2; - - pCtx->LocalToString(params[1], &fmt); - size_t res = atcprintf(buffer, sizeof(buffer) - 2, fmt, pCtx, params, &arg); - - buffer[res++] = '\n'; - buffer[res] = '\0'; - - bridge->ConPrint(buffer); - - return 1; -} - -static cell_t sm_PrintToConsole(IPluginContext *pCtx, const cell_t *params) -{ - int index = params[1]; - if ((index < 0) || (index > playerhelpers->GetMaxClients())) - { - return pCtx->ThrowNativeError("Client index %d is invalid", index); - } - - IGamePlayer *pPlayer = NULL; - if (index != 0) - { - pPlayer = playerhelpers->GetGamePlayer(index); - if (!pPlayer->IsInGame()) - { - return pCtx->ThrowNativeError("Client %d is not in game", index); - } - - /* Silent fail on bots, engine will crash */ - if (pPlayer->IsFakeClient()) - { - return 0; - } - } - - char buffer[1024]; - char *fmt; - int arg = 3; - - pCtx->LocalToString(params[2], &fmt); - size_t res = atcprintf(buffer, sizeof(buffer) - 2, fmt, pCtx, params, &arg); - - buffer[res++] = '\n'; - buffer[res] = '\0'; - - if (index != 0) - { - pPlayer->PrintToConsole(buffer); - } - else { - bridge->ConPrint(buffer); - } - - return 1; -} - -static cell_t sm_ServerCommand(IPluginContext *pContext, const cell_t *params) -{ - g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); - - char buffer[1024]; - size_t len; - { - DetectExceptions eh(pContext); - len = g_pSM->FormatString(buffer, sizeof(buffer) - 2, pContext, params, 1); - if (eh.HasException()) - return 0; - } - - /* One byte for null terminator, one for newline */ - buffer[len++] = '\n'; - buffer[len] = '\0'; - - engine->ServerCommand(buffer); - - return 1; -} - -static cell_t sm_InsertServerCommand(IPluginContext *pContext, const cell_t *params) -{ - g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); - - char buffer[1024]; - size_t len; - { - DetectExceptions eh(pContext); - len = g_pSM->FormatString(buffer, sizeof(buffer) - 2, pContext, params, 1); - if (eh.HasException()) - return 0; - } - - /* One byte for null terminator, one for newline */ - buffer[len++] = '\n'; - buffer[len] = '\0'; - - engine->InsertServerCommand(buffer); - - return 1; -} - -static cell_t sm_ServerExecute(IPluginContext *pContext, const cell_t *params) -{ - engine->ServerExecute(); - - return 1; -} - -static cell_t sm_ClientCommand(IPluginContext *pContext, const cell_t *params) -{ - IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(params[1]); - - if (!pPlayer) - { - return pContext->ThrowNativeError("Client index %d is invalid", params[1]); - } - - if (!pPlayer->IsConnected()) - { - return pContext->ThrowNativeError("Client %d is not connected", params[1]); - } - - g_pSM->SetGlobalTarget(params[1]); - - char buffer[256]; - size_t len; - { - DetectExceptions eh(pContext); - g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); - if (eh.HasException()) - return 0; - } - - engine->ClientCommand(pPlayer->GetEdict(), buffer); - - return 1; -} - -static cell_t FakeClientCommand(IPluginContext *pContext, const cell_t *params) -{ - IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(params[1]); - - if (!pPlayer) - { - return pContext->ThrowNativeError("Client index %d is invalid", params[1]); - } - - if (!pPlayer->IsConnected()) - { - return pContext->ThrowNativeError("Client %d is not connected", params[1]); - } - - g_pSM->SetGlobalTarget(params[1]); - - char buffer[256]; - { - DetectExceptions eh(pContext); - g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); - if (eh.HasException()) - return 0; - } - - engine->FakeClientCommand(pPlayer->GetEdict(), buffer); - - return 1; -} - -static cell_t ReplyToCommand(IPluginContext *pContext, const cell_t *params) -{ - g_pSM->SetGlobalTarget(params[1]); - - /* Build the format string */ - char buffer[1024]; - size_t len; - { - DetectExceptions eh(pContext); - g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); - len = g_pSM->FormatString(buffer, sizeof(buffer) - 2, pContext, params, 2); - if (eh.HasException()) - return 0; - } - - /* If we're printing to the server, shortcut out */ - if (params[1] == 0) - { - /* Print */ - buffer[len++] = '\n'; - buffer[len] = '\0'; - bridge->ConPrint(buffer); - return 1; - } - - IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(params[1]); - - if (!pPlayer) - { - return pContext->ThrowNativeError("Client index %d is invalid", params[1]); - } - - if (!pPlayer->IsConnected()) - { - return pContext->ThrowNativeError("Client %d is not connected", params[1]); - } - - unsigned int replyto = playerhelpers->GetReplyTo(); - if (replyto == SM_REPLY_CONSOLE) - { - buffer[len++] = '\n'; - buffer[len] = '\0'; - pPlayer->PrintToConsole(buffer); - } - else if (replyto == SM_REPLY_CHAT) { - if (len >= 191) - { - len = 191; - } - buffer[len] = '\0'; - gamehelpers->TextMsg(params[1], TEXTMSG_DEST_CHAT, buffer); - } - - return 1; -} - -static cell_t GetCmdReplyTarget(IPluginContext *pContext, const cell_t *params) -{ - return playerhelpers->GetReplyTo(); -} - -static cell_t SetCmdReplyTarget(IPluginContext *pContext, const cell_t *params) -{ - return playerhelpers->SetReplyTo(params[1]); -} - -static cell_t AddServerTag(IPluginContext *pContext, const cell_t *params) -{ - return 0; -} - -static cell_t RemoveServerTag(IPluginContext *pContext, const cell_t *params) -{ - return 0; -} - - -REGISTER_NATIVES(consoleNatives) -{ - {"CheckCommandAccess", CheckCommandAccess}, - {"CheckAccess", CheckAccess}, - {"PrintToServer", sm_PrintToServer}, - {"PrintToConsole", sm_PrintToConsole}, - {"ServerCommand", sm_ServerCommand}, - {"InsertServerCommand", sm_InsertServerCommand}, - {"ServerExecute", sm_ServerExecute}, - {"ClientCommand", sm_ClientCommand}, - {"FakeClientCommand", FakeClientCommand}, - {"ReplyToCommand", ReplyToCommand}, - {"GetCmdReplySource", GetCmdReplyTarget}, - {"SetCmdReplySource", SetCmdReplyTarget}, - {"AddServerTag", AddServerTag}, - {"RemoveServerTag", RemoveServerTag}, - {NULL, NULL} -}; +/** + * vim: set ts=4 sw=4 tw=99 noet : + * ============================================================================= + * SourceMod + * Copyright (C) 2004-2010 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + * + * Version: $Id$ + */ + +#include "common_logic.h" +#include "admincache.h" +#include +#include +#include +#include +#include "sprintf.h" +#include +#include + +static cell_t CheckCommandAccess(IPluginContext *pContext, const cell_t *params) +{ + if (params[1] == 0) + { + return 1; + } + + char *cmd; + pContext->LocalToString(params[2], &cmd); + + /* Match up with an admin command if possible */ + FlagBits bits = params[3]; + bool found_command = false; + if (params[0] < 4 || !params[4]) + { + found_command = bridge->LookForCommandAdminFlags(cmd, &bits); + } + + if (!found_command) + { + adminsys->GetCommandOverride(cmd, Override_Command, &bits); + } + + return adminsys->CheckClientCommandAccess(params[1], cmd, bits) ? 1 : 0; +} + +static cell_t CheckAccess(IPluginContext *pContext, const cell_t *params) +{ + char *cmd; + pContext->LocalToString(params[2], &cmd); + + /* Match up with an admin command if possible */ + FlagBits bits = params[3]; + bool found_command = false; + if (params[0] < 4 || !params[4]) + { + found_command = bridge->LookForCommandAdminFlags(cmd, &bits); + } + + if (!found_command) + { + adminsys->GetCommandOverride(cmd, Override_Command, &bits); + } + + return g_Admins.CheckAdminCommandAccess(params[1], cmd, bits) ? 1 : 0; +} + +static cell_t sm_PrintToServer(IPluginContext *pCtx, const cell_t *params) +{ + char buffer[1024]; + char *fmt; + int arg = 2; + + pCtx->LocalToString(params[1], &fmt); + size_t res = atcprintf(buffer, sizeof(buffer) - 2, fmt, pCtx, params, &arg); + + buffer[res++] = '\n'; + buffer[res] = '\0'; + + bridge->ConPrint(buffer); + + return 1; +} + +static cell_t sm_PrintToConsole(IPluginContext *pCtx, const cell_t *params) +{ + int index = params[1]; + if ((index < 0) || (index > playerhelpers->GetMaxClients())) + { + return pCtx->ThrowNativeError("Client index %d is invalid", index); + } + + IGamePlayer *pPlayer = NULL; + if (index != 0) + { + pPlayer = playerhelpers->GetGamePlayer(index); + if (!pPlayer->IsInGame()) + { + return pCtx->ThrowNativeError("Client %d is not in game", index); + } + + /* Silent fail on bots, engine will crash */ + if (pPlayer->IsFakeClient()) + { + return 0; + } + } + + char buffer[1024]; + char *fmt; + int arg = 3; + + pCtx->LocalToString(params[2], &fmt); + size_t res = atcprintf(buffer, sizeof(buffer) - 2, fmt, pCtx, params, &arg); + + buffer[res++] = '\n'; + buffer[res] = '\0'; + + if (index != 0) + { + pPlayer->PrintToConsole(buffer); + } + else { + bridge->ConPrint(buffer); + } + + return 1; +} + +static cell_t sm_ServerCommand(IPluginContext *pContext, const cell_t *params) +{ + g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); + + char buffer[1024]; + size_t len; + { + DetectExceptions eh(pContext); + len = g_pSM->FormatString(buffer, sizeof(buffer) - 2, pContext, params, 1); + if (eh.HasException()) + return 0; + } + + /* One byte for null terminator, one for newline */ + buffer[len++] = '\n'; + buffer[len] = '\0'; + + engine->ServerCommand(buffer); + + return 1; +} + +static cell_t sm_InsertServerCommand(IPluginContext *pContext, const cell_t *params) +{ + g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); + + char buffer[1024]; + size_t len; + { + DetectExceptions eh(pContext); + len = g_pSM->FormatString(buffer, sizeof(buffer) - 2, pContext, params, 1); + if (eh.HasException()) + return 0; + } + + /* One byte for null terminator, one for newline */ + buffer[len++] = '\n'; + buffer[len] = '\0'; + + engine->InsertServerCommand(buffer); + + return 1; +} + +static cell_t sm_ServerExecute(IPluginContext *pContext, const cell_t *params) +{ + engine->ServerExecute(); + + return 1; +} + +static cell_t sm_ClientCommand(IPluginContext *pContext, const cell_t *params) +{ + IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(params[1]); + + if (!pPlayer) + { + return pContext->ThrowNativeError("Client index %d is invalid", params[1]); + } + + if (!pPlayer->IsConnected()) + { + return pContext->ThrowNativeError("Client %d is not connected", params[1]); + } + + g_pSM->SetGlobalTarget(params[1]); + + char buffer[256]; + size_t len; + { + DetectExceptions eh(pContext); + g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); + if (eh.HasException()) + return 0; + } + + engine->ClientCommand(pPlayer->GetEdict(), buffer); + + return 1; +} + +static cell_t FakeClientCommand(IPluginContext *pContext, const cell_t *params) +{ + IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(params[1]); + + if (!pPlayer) + { + return pContext->ThrowNativeError("Client index %d is invalid", params[1]); + } + + if (!pPlayer->IsConnected()) + { + return pContext->ThrowNativeError("Client %d is not connected", params[1]); + } + + g_pSM->SetGlobalTarget(params[1]); + + char buffer[256]; + { + DetectExceptions eh(pContext); + g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); + if (eh.HasException()) + return 0; + } + + engine->FakeClientCommand(pPlayer->GetEdict(), buffer); + + return 1; +} + +static cell_t ReplyToCommand(IPluginContext *pContext, const cell_t *params) +{ + g_pSM->SetGlobalTarget(params[1]); + + /* Build the format string */ + char buffer[1024]; + size_t len; + { + DetectExceptions eh(pContext); + g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); + len = g_pSM->FormatString(buffer, sizeof(buffer) - 2, pContext, params, 2); + if (eh.HasException()) + return 0; + } + + /* If we're printing to the server, shortcut out */ + if (params[1] == 0) + { + /* Print */ + buffer[len++] = '\n'; + buffer[len] = '\0'; + bridge->ConPrint(buffer); + return 1; + } + + IGamePlayer *pPlayer = playerhelpers->GetGamePlayer(params[1]); + + if (!pPlayer) + { + return pContext->ThrowNativeError("Client index %d is invalid", params[1]); + } + + if (!pPlayer->IsConnected()) + { + return pContext->ThrowNativeError("Client %d is not connected", params[1]); + } + + unsigned int replyto = playerhelpers->GetReplyTo(); + if (replyto == SM_REPLY_CONSOLE) + { + buffer[len++] = '\n'; + buffer[len] = '\0'; + pPlayer->PrintToConsole(buffer); + } + else if (replyto == SM_REPLY_CHAT) { + if (len >= 191) + { + len = 191; + } + buffer[len] = '\0'; + gamehelpers->TextMsg(params[1], TEXTMSG_DEST_CHAT, buffer); + } + + return 1; +} + +static cell_t GetCmdReplyTarget(IPluginContext *pContext, const cell_t *params) +{ + return playerhelpers->GetReplyTo(); +} + +static cell_t SetCmdReplyTarget(IPluginContext *pContext, const cell_t *params) +{ + return playerhelpers->SetReplyTo(params[1]); +} + +static cell_t AddServerTag(IPluginContext *pContext, const cell_t *params) +{ + return 0; +} + +static cell_t RemoveServerTag(IPluginContext *pContext, const cell_t *params) +{ + return 0; +} + + +REGISTER_NATIVES(consoleNatives) +{ + {"CheckCommandAccess", CheckCommandAccess}, + {"CheckAccess", CheckAccess}, + {"PrintToServer", sm_PrintToServer}, + {"PrintToConsole", sm_PrintToConsole}, + {"ServerCommand", sm_ServerCommand}, + {"InsertServerCommand", sm_InsertServerCommand}, + {"ServerExecute", sm_ServerExecute}, + {"ClientCommand", sm_ClientCommand}, + {"FakeClientCommand", FakeClientCommand}, + {"ReplyToCommand", ReplyToCommand}, + {"GetCmdReplySource", GetCmdReplyTarget}, + {"SetCmdReplySource", SetCmdReplyTarget}, + {"AddServerTag", AddServerTag}, + {"RemoveServerTag", RemoveServerTag}, + {NULL, NULL} +}; diff --git a/core/logic/smn_core.cpp b/core/logic/smn_core.cpp index 808ce405a..857e426c9 100644 --- a/core/logic/smn_core.cpp +++ b/core/logic/smn_core.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -33,7 +33,7 @@ #include #include #include "common_logic.h" -#include "Logger.h" +#include "logger.h" #include #include @@ -48,15 +48,15 @@ #include #include #endif -#include -#include -#include -#include -#include - -using namespace SourceMod; -using namespace SourcePawn; - +#include +#include +#include +#include +#include + +using namespace SourceMod; +using namespace SourcePawn; + HandleType_t g_PlIter; @@ -64,7 +64,7 @@ IForward *g_OnLogAction = NULL; static ConVar *sm_datetime_format = NULL; -class CoreNativeHelpers : +class CoreNativeHelpers : public SMGlobalClass, public IHandleTypeDispatch { @@ -77,16 +77,16 @@ public: g_PlIter = handlesys->CreateType("PluginIterator", this, 0, NULL, NULL, g_pCoreIdent, NULL); - g_OnLogAction = forwardsys->CreateForward("OnLogAction", - ET_Hook, - 5, + g_OnLogAction = forwardsys->CreateForward("OnLogAction", + ET_Hook, + 5, NULL, Param_Cell, Param_Cell, Param_Cell, Param_Cell, Param_String); - + sm_datetime_format = bridge->FindConVar("sm_datetime_format"); } void OnHandleDestroy(HandleType_t type, void *object) @@ -132,21 +132,21 @@ void LogAction(Handle_t hndl, int type, int client, int target, const char *mess g_Logger.LogMessage("[%s] %s", logtag, message); } - + static cell_t ThrowError(IPluginContext *pContext, const cell_t *params) { char buffer[512]; g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); - { - DetectExceptions eh(pContext); + { + DetectExceptions eh(pContext); g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 1); - if (eh.HasException()) - return 0; - } + if (eh.HasException()) + return 0; + } - pContext->ReportError("%s", buffer); + pContext->ReportError("%s", buffer); return 0; } @@ -164,8 +164,8 @@ static cell_t GetTime(IPluginContext *pContext, const cell_t *params) #if defined SUBPLATFORM_SECURECRT void _ignore_invalid_parameter( const wchar_t * expression, - const wchar_t * function, - const wchar_t * file, + const wchar_t * function, + const wchar_t * file, unsigned int line, uintptr_t pReserved ) @@ -398,16 +398,16 @@ static cell_t SetFailState(IPluginContext *pContext, const cell_t *params) { char buffer[2048]; - { - DetectExceptions eh(pContext); + { + DetectExceptions eh(pContext); g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 1); - if (eh.HasException()) { + if (eh.HasException()) { pPlugin->SetErrorState(Plugin_Failed, "%s", str); - return 0; - } + return 0; + } pPlugin->SetErrorState(Plugin_Failed, "%s", buffer); pContext->ReportFatalError("%s", buffer); - return 0; + return 0; } } @@ -475,7 +475,7 @@ static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *param return 0; } - pContext->GetRuntime()->UpdateNativeBinding(idx, nullptr, SP_NTVFLAG_OPTIONAL, nullptr); + pContext->GetRuntime()->UpdateNativeBinding(idx, nullptr, SP_NTVFLAG_OPTIONAL, nullptr); return 1; } @@ -517,12 +517,12 @@ static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params) { char buffer[2048]; g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); - { - DetectExceptions eh(pContext); + { + DetectExceptions eh(pContext); g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 3); - if (eh.HasException()) - return 0; - } + if (eh.HasException()) + return 0; + } IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext()); @@ -546,15 +546,15 @@ static cell_t LogToFile(IPluginContext *pContext, const cell_t *params) } char buffer[2048]; - { - DetectExceptions eh(pContext); + { + DetectExceptions eh(pContext); g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); - if (eh.HasException()) { - fclose(fp); - return 0; - } - } + if (eh.HasException()) { + fclose(fp); + return 0; + } + } IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext()); @@ -580,15 +580,15 @@ static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params) } char buffer[2048]; - { - DetectExceptions eh(pContext); + { + DetectExceptions eh(pContext); g_pSM->SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE); g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 2); - if (eh.HasException()) { - fclose(fp); - return 0; - } - } + if (eh.HasException()) { + fclose(fp); + return 0; + } + } g_Logger.LogToOpenFile(fp, "%s", buffer); @@ -603,12 +603,12 @@ static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *par pContext->LocalToString(params[1], &str); IExtension *pExtension = extsys->FindExtensionByFile(str); - + if (!pExtension) { return -2; } - + if (!pExtension->IsLoaded()) { return -1; @@ -627,7 +627,7 @@ static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *par static cell_t FindPluginByNumber(IPluginContext *pContext, const cell_t *params) { IPlugin *pPlugin = scripts->FindPluginByOrder(params[1]); - + if (pPlugin == NULL) { return BAD_HANDLE; @@ -660,27 +660,27 @@ static cell_t RequireFeature(IPluginContext *pContext, const cell_t *params) if (sharesys->TestFeature(pContext->GetRuntime(), type, name) != FeatureStatus_Available) { - char buffer[255]; - char *msg = buffer; - char default_message[255]; + char buffer[255]; + char *msg = buffer; + char default_message[255]; SMPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext()); - - DetectExceptions eh(pContext); - g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 3); - if (eh.HasException()) - buffer[0] = '\0'; - - if (buffer[0] == '\0') { - g_pSM->Format(default_message, sizeof(default_message), "Feature \"%s\" not available", name); - msg = default_message; - } - pPlugin->SetErrorState(Plugin_Error, "%s", msg); - - if (!eh.HasException()) - pContext->ReportFatalError("%s", msg); - return 0; - } - + + DetectExceptions eh(pContext); + g_pSM->FormatString(buffer, sizeof(buffer), pContext, params, 3); + if (eh.HasException()) + buffer[0] = '\0'; + + if (buffer[0] == '\0') { + g_pSM->Format(default_message, sizeof(default_message), "Feature \"%s\" not available", name); + msg = default_message; + } + pPlugin->SetErrorState(Plugin_Error, "%s", msg); + + if (!eh.HasException()) + pContext->ReportFatalError("%s", msg); + return 0; + } + return 1; } @@ -788,4 +788,4 @@ REGISTER_NATIVES(coreNatives) {"LoadFromAddress", LoadFromAddress}, {"StoreToAddress", StoreToAddress}, {NULL, NULL}, -}; +}; diff --git a/core/logic/smn_database.cpp b/core/logic/smn_database.cpp index 410cb5dbc..951c44c8f 100644 --- a/core/logic/smn_database.cpp +++ b/core/logic/smn_database.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,11 +30,11 @@ */ #include "common_logic.h" -#include "Database.h" -#include "ExtensionSys.h" +#include "database.h" +#include "extensionsys.h" #include "stringutil.h" -#include "ISourceMod.h" -#include "AutoHandleRooter.h" +#include +#include #include "common_logic.h" #include #include @@ -68,7 +68,7 @@ struct Transaction ke::Vector entries; }; -class DatabaseHelpers : +class DatabaseHelpers : public SMGlobalClass, public IHandleTypeDispatch { @@ -134,7 +134,7 @@ inline HandleError ReadQueryHndl(Handle_t hndl, IPluginContext *pContext, IQuery sec.pIdentity = g_pCoreIdent; HandleError ret; - + if ((ret = handlesys->ReadHandle(hndl, hStmtType, &sec, (void **)query)) != HandleError_None) { ret = handlesys->ReadHandle(hndl, hCombinedQueryType, &sec, (void **)&c); @@ -185,13 +185,13 @@ inline HandleError ReadDbOrStmtHndl(Handle_t hndl, IPluginContext *pContext, IDa class TQueryOp : public IDBThreadOperation { public: - TQueryOp(IDatabase *db, IPluginFunction *pf, const char *query, cell_t data) : + TQueryOp(IDatabase *db, IPluginFunction *pf, const char *query, cell_t data) : m_pDatabase(db), m_pFunction(pf), m_Query(query), m_Data(data), me(scripts->FindPluginByContext(pf->GetParentContext()->GetContext())), m_pQuery(NULL) { /* We always increase the reference count because this is potentially - * asynchronous. Otherwise the original handle could be closed while + * asynchronous. Otherwise the original handle could be closed while * we're still latched onto it. */ m_pDatabase->IncReferenceCount(); @@ -251,11 +251,11 @@ public: access.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER; Handle_t qh = BAD_HANDLE; - + if (m_pQuery) { CombinedQuery *c = new CombinedQuery(m_pQuery, m_pDatabase); - + qh = handlesys->CreateHandle(hCombinedQueryType, c, me->GetIdentity(), g_pCoreIdent, NULL); if (qh != BAD_HANDLE) { @@ -347,7 +347,7 @@ public: void RunThinkPart() { Handle_t hndl = BAD_HANDLE; - + if (m_pDatabase) { if ((hndl = g_DBMan.CreateHandle(DBHandle_Database, m_pDatabase, me->GetIdentity())) @@ -388,7 +388,7 @@ static cell_t SQL_Connect(IPluginContext *pContext, const cell_t *params) bool persistent = params[2] ? true : false; pContext->LocalToString(params[1], &conf); pContext->LocalToString(params[3], &err); - + IDBDriver *driver; IDatabase *db; if (!g_DBMan.Connect(conf, &driver, &db, persistent, err, maxlength)) @@ -437,9 +437,9 @@ static cell_t ConnectToDbAsync(IPluginContext *pContext, const cell_t *params, A } if (!driver) { - g_pSM->Format(error, - sizeof(error), - "Could not find driver \"%s\"", + g_pSM->Format(error, + sizeof(error), + "Could not find driver \"%s\"", pInfo->driver[0] == '\0' ? g_DBMan.GetDefaultDriverName() : pInfo->driver); } else if (!driver->IsThreadSafe()) { g_pSM->Format(error, @@ -511,7 +511,7 @@ static cell_t SQL_ConnectEx(IPluginContext *pContext, const cell_t *params) return pContext->ThrowNativeError("Invalid driver Handle %x (error: %d)", params[1], err); } } - + char *host, *user, *pass, *database, *error; size_t maxlength = (size_t)params[7]; bool persistent = params[8] ? true : false; @@ -531,7 +531,7 @@ static cell_t SQL_ConnectEx(IPluginContext *pContext, const cell_t *params) info.pass = pass; info.port = port; info.user = user; - + IDatabase *db = driver->Connect(&info, persistent, error, maxlength); if (db) @@ -552,7 +552,7 @@ static cell_t SQL_ConnectEx(IPluginContext *pContext, const cell_t *params) return hndl; } - + return BAD_HANDLE; } @@ -769,7 +769,7 @@ static cell_t SQL_Query(IPluginContext *pContext, const cell_t *params) pContext->LocalToString(params[2], &query); IQuery *qr; - + if (params[0] >= 3 && params[3] != -1) { qr = db->DoQueryEx(query, params[3]); @@ -1435,7 +1435,7 @@ static cell_t SQL_ConnectCustom(IPluginContext *pContext, const cell_t *params) IDatabase *db; pContext->LocalToString(params[2], &buffer); - + db = driver->Connect(&info, params[4] ? true : false, buffer, params[3]); if (db == NULL) { @@ -1515,7 +1515,7 @@ class TTransactOp : public IDBThreadOperation public: TTransactOp(IDatabase *db, Transaction *txn, Handle_t txnHandle, IdentityToken_t *ident, IPluginFunction *onSuccess, IPluginFunction *onError, cell_t data) - : + : db_(db), txn_(txn), ident_(ident), diff --git a/core/logic/smn_datapacks.cpp b/core/logic/smn_datapacks.cpp index 1b588e12e..da83860b8 100644 --- a/core/logic/smn_datapacks.cpp +++ b/core/logic/smn_datapacks.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -32,11 +32,11 @@ #include "common_logic.h" #include #include -#include "CDataPack.h" +#include "cdatapack.h" HandleType_t g_DataPackType; -class DataPackNatives : +class DataPackNatives : public SMGlobalClass, public IHandleTypeDispatch { diff --git a/core/logic/smn_fakenatives.cpp b/core/logic/smn_fakenatives.cpp index c4c7cf8a6..e1752ab61 100644 --- a/core/logic/smn_fakenatives.cpp +++ b/core/logic/smn_fakenatives.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -33,8 +33,8 @@ #include #include #include "common_logic.h" -#include "ShareSys.h" -#include "PluginSys.h" +#include "sharesys.h" +#include "pluginsys.h" #include "sprintf.h" using namespace SourceHook; diff --git a/core/logic/smn_filesystem.cpp b/core/logic/smn_filesystem.cpp index fdf599bad..313aeaa00 100644 --- a/core/logic/smn_filesystem.cpp +++ b/core/logic/smn_filesystem.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -39,7 +39,7 @@ #include #include #include "common_logic.h" -#include "Logger.h" +#include "logger.h" #include "sprintf.h" #include #include "handle_helpers.h" @@ -231,7 +231,7 @@ struct ValveDirectory bool bHandledFirstPath; }; -class FileNatives : +class FileNatives : public SMGlobalClass, public IHandleTypeDispatch, public IPluginsListener @@ -309,29 +309,29 @@ static cell_t sm_OpenDirectory(IPluginContext *pContext, const cell_t *params) pContext->ThrowNativeErrorEx(err, NULL); return 0; } - + if (!path[0]) { return pContext->ThrowNativeError("Invalid path. An empty path string is not valid, use \".\" to refer to the current working directory."); } - + Handle_t handle = 0; - + if (params[0] >= 2 && params[2]) { size_t len = strlen(path); char wildcardedPath[PLATFORM_MAX_PATH]; snprintf(wildcardedPath, sizeof(wildcardedPath), "%s%s*", path, (path[len-1] != '/' && path[len-1] != '\\') ? "/" : ""); - + char *pathID; if ((err=pContext->LocalToStringNULL(params[3], &pathID)) != SP_ERROR_NONE) { pContext->ThrowNativeErrorEx(err, NULL); return 0; } - + ValveDirectory *valveDir = new ValveDirectory; - + const char *pFirst = bridge->filesystem->FindFirstEx(wildcardedPath, pathID, &valveDir->hndl); if (!pFirst) { @@ -343,7 +343,7 @@ static cell_t sm_OpenDirectory(IPluginContext *pContext, const cell_t *params) valveDir->bHandledFirstPath = false; strncpy(valveDir->szFirstPath, pFirst, sizeof(valveDir->szFirstPath)); } - + handle = handlesys->CreateHandle(g_ValveDirType, valveDir, pContext->GetIdentity(), g_pCoreIdent, NULL); } else @@ -359,7 +359,7 @@ static cell_t sm_OpenDirectory(IPluginContext *pContext, const cell_t *params) handle = handlesys->CreateHandle(g_DirType, pDir, pContext->GetIdentity(), g_pCoreIdent, NULL); } - + return handle; } @@ -410,7 +410,7 @@ static cell_t sm_ReadDirEntry(IPluginContext *pContext, const cell_t *params) else if ((herr=handlesys->ReadHandle(hndl, g_ValveDirType, &sec, &pTempDir)) == HandleError_None) { ValveDirectory *valveDir = (ValveDirectory *)pTempDir; - + const char *pEntry = NULL; if (!valveDir->bHandledFirstPath) { @@ -423,15 +423,15 @@ static cell_t sm_ReadDirEntry(IPluginContext *pContext, const cell_t *params) { pEntry = bridge->filesystem->FindNext(valveDir->hndl); } - + valveDir->bHandledFirstPath = true; - + // No more entries if (!pEntry) { return 0; } - + if ((err=pContext->StringToLocalUTF8(params[2], params[3], pEntry, NULL)) != SP_ERROR_NONE) { @@ -450,7 +450,7 @@ static cell_t sm_ReadDirEntry(IPluginContext *pContext, const cell_t *params) *filetype = 1; } else { *filetype = 2; - } + } } else { @@ -558,7 +558,7 @@ static cell_t sm_FileExists(IPluginContext *pContext, const cell_t *params) char *pathID = szDefaultPath; if (params[0] >= 3) pContext->LocalToStringNULL(params[3], &pathID); - + return bridge->filesystem->FileExists(name, pathID) ? 1 : 0; } @@ -594,12 +594,12 @@ static cell_t sm_RenameFile(IPluginContext *pContext, const cell_t *params) char *newpath, *oldpath; pContext->LocalToString(params[1], &newpath); pContext->LocalToString(params[2], &oldpath); - + if (params[0] >= 3 && params[3] == 1) { char *pathID; pContext->LocalToStringNULL(params[4], &pathID); - + bridge->filesystem->RenameFile(oldpath, newpath, pathID); return 1; } @@ -630,7 +630,7 @@ static cell_t sm_DirExists(IPluginContext *pContext, const cell_t *params) { char *pathID; pContext->LocalToStringNULL(params[3], &pathID); - + return bridge->filesystem->IsDirectory(name, pathID) ? 1 : 0; } @@ -672,7 +672,7 @@ static cell_t sm_FileSize(IPluginContext *pContext, const cell_t *params) char *pathID = szDefaultPath; if (params[0] >= 3) pContext->LocalToStringNULL(params[3], &pathID); - + if (!bridge->filesystem->FileExists(name, pathID)) return -1; return bridge->filesystem->Size(name, pathID); @@ -726,23 +726,23 @@ static cell_t sm_CreateDirectory(IPluginContext *pContext, const cell_t *params) { char *name; pContext->LocalToString(params[1], &name); - + if (params[0] >= 3 && params[3] == 1) { char *pathID; pContext->LocalToStringNULL(params[4], &pathID); - + if (bridge->filesystem->IsDirectory(name, pathID)) return 0; - + bridge->filesystem->CreateDirHierarchy(name, pathID); - + if (bridge->filesystem->IsDirectory(name, pathID)) return 1; - + return 0; } - + char realpath[PLATFORM_MAX_PATH]; g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", name); @@ -961,7 +961,7 @@ static cell_t sm_ReadFile(IPluginContext *pContext, const cell_t *params) cell_t *data; pContext->LocalToPhysAddr(params[2], &data); - + size_t read = 0; switch (params[4]) { case 4: @@ -1006,7 +1006,7 @@ static cell_t sm_ReadFileString(IPluginContext *pContext, const cell_t *params) char *buffer; pContext->LocalToString(params[2], &buffer); - + cell_t num_read = 0; if (params[4] != -1) { if (size_t(params[4]) > size_t(params[3])) { @@ -1107,7 +1107,7 @@ static cell_t sm_AddGameLogHook(IPluginContext *pContext, const cell_t *params) } s_FileNatives.AddLogHook(pFunction); - + return 1; } diff --git a/core/logic/smn_float.cpp b/core/logic/smn_float.cpp index 784de6705..5bf0cc502 100644 --- a/core/logic/smn_float.cpp +++ b/core/logic/smn_float.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -33,7 +33,7 @@ #include #include #include "common_logic.h" -#include "MersenneTwister.h" +#include "mersennetwister.h" #include #include #include @@ -350,11 +350,11 @@ public: delete mtrand; } } - + MTRand *RandObjForPlugin(IPluginContext *ctx) { IPlugin *plugin = pluginsys->FindPluginByContext(ctx->GetContext()); - MTRand *mtrand; + MTRand *mtrand; if (!plugin->GetProperty("core.logic.mtrand", (void**)&mtrand)) { mtrand = new MTRand(); diff --git a/core/logic/smn_gameconfigs.cpp b/core/logic/smn_gameconfigs.cpp index eff28ae22..699dcaf06 100644 --- a/core/logic/smn_gameconfigs.cpp +++ b/core/logic/smn_gameconfigs.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,13 +31,13 @@ #include "common_logic.h" #include -#include "GameConfigs.h" +#include "gameconfigs.h" HandleType_t g_GameConfigsType; class GameConfigsNatives : - public IHandleTypeDispatch, - public SMGlobalClass + public IHandleTypeDispatch, + public SMGlobalClass { public: void OnSourceModAllInitialized() diff --git a/core/logic/smn_lang.cpp b/core/logic/smn_lang.cpp index 1f8e24fef..960aebeed 100644 --- a/core/logic/smn_lang.cpp +++ b/core/logic/smn_lang.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,7 +30,7 @@ */ #include "common_logic.h" -#include "Translator.h" +#include "translator.h" #include #include #include @@ -108,12 +108,12 @@ static cell_t sm_GetLanguageInfo(IPluginContext *pContext, const cell_t *params) static cell_t sm_SetClientLanguage(IPluginContext *pContext, const cell_t *params) { IGamePlayer *player = playerhelpers->GetGamePlayer(params[1]); - + if (!player || !player->IsConnected()) { return pContext->ThrowNativeError("Invalid client index %d", params[1]); } - + player->SetLanguageId(params[2]); return 1; diff --git a/core/logic/smn_maplists.cpp b/core/logic/smn_maplists.cpp index 1532f8d53..f5885481d 100644 --- a/core/logic/smn_maplists.cpp +++ b/core/logic/smn_maplists.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -32,7 +32,7 @@ #include #include #include "common_logic.h" -#include "CellArray.h" +#include "cellarray.h" #include #include #include @@ -143,7 +143,7 @@ public: SMCError error; time_t fileTime; SMCStates states = {0, 0}; - + fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime); /* If the file is found and hasn't changed, bail out now. */ @@ -152,8 +152,8 @@ public: return; } - /* If the file wasn't found, and we already have entries, we bail out too. - * This case lets us optimize when a user deletes the config file, so we + /* If the file wasn't found, and we already have entries, we bail out too. + * This case lets us optimize when a user deletes the config file, so we * don't reparse every single time the function is called. */ if (!fileFound && m_MapLists.size() > 0) @@ -174,7 +174,7 @@ public: strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name)); GetMapCycleFilePath(pDefList->path, sizeof(pDefList->path)); - + pDefList->last_modified_time = 0; pDefList->pArray = NULL; pDefList->serial = 0; @@ -328,12 +328,12 @@ public: bool success, free_new_array; free_new_array = false; - + if ((success = GetMapList(&pNewArray, name, &change_serial)) == false) { if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT) { - /* If this list failed, and it's not the default, try the default. + /* If this list failed, and it's not the default, try the default. */ if (strcmp(name, "default") != 0) { @@ -401,9 +401,9 @@ public: } else { - qsort(pNewArray->base(), - pNewArray->size(), - pNewArray->blocksize() * sizeof(cell_t), + qsort(pNewArray->base(), + pNewArray->size(), + pNewArray->blocksize() * sizeof(cell_t), sort_maps_in_adt_array); } @@ -514,7 +514,7 @@ private: { continue; } - + if (strcmp(bridge->GetSourceEngineName(), "insurgency") == 0) { // Insurgency (presumably?) doesn't allow spaces in map names diff --git a/core/logic/smn_menus.cpp b/core/logic/smn_menus.cpp index 96033f4e3..c7e15006e 100644 --- a/core/logic/smn_menus.cpp +++ b/core/logic/smn_menus.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -33,9 +33,9 @@ #include #include #include -#include "DebugReporter.h" +#include "debugreporter.h" #if defined MENU_DEBUG -#include "Logger.h" +#include "logger.h" #endif #include #include @@ -46,7 +46,7 @@ #endif /** - * And God said, "let there be menus," and behold, there were menus. + * And God said, "let there be menus," and behold, there were menus. * God saw the menus and they were good. And the evening and the morning * were the third day. */ @@ -158,7 +158,7 @@ private: * GLOBAL CLASS FOR HELPERS */ -class MenuNativeHelpers : +class MenuNativeHelpers : public SMGlobalClass, public IHandleTypeDispatch, public IPluginsListener @@ -211,7 +211,7 @@ public: * It is extremely important that unloaded plugins don't crash. * Thus, if a plugin unloads, we run through every handler we have. * This means we do almost no runtime work for keeping track of - * our panel handlers (we don't have to store a list of the running + * our panel handlers (we don't have to store a list of the running * ones), but when push comes to shove, we have to scan them all * in case any of them are active. */ @@ -329,7 +329,7 @@ static unsigned int *s_CurSelectPosition = NULL; /** * MENU HANDLER WRAPPER */ -CMenuHandler::CMenuHandler(IPluginFunction *pBasic, int flags) : +CMenuHandler::CMenuHandler(IPluginFunction *pBasic, int flags) : m_pBasic(pBasic), m_Flags(flags), m_pVoteResults(NULL) { /* :TODO: We can probably cache the handle ahead of time */ @@ -350,7 +350,7 @@ void CMenuHandler::OnMenuDisplay(IBaseMenu *menu, int client, IMenuPanel *panel) HandleSecurity sec; sec.pIdentity = g_pCoreIdent; sec.pOwner = m_pBasic->GetParentContext()->GetIdentity(); - + HandleAccess access; handlesys->InitAccessDefaults(NULL, &access); access.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER; diff --git a/core/logic/smn_players.cpp b/core/logic/smn_players.cpp index 32961ab09..d583abfe8 100644 --- a/core/logic/smn_players.cpp +++ b/core/logic/smn_players.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -37,9 +37,9 @@ #include #include #include -#include "GameConfigs.h" -#include "CellArray.h" -#include "AutoHandleRooter.h" +#include "gameconfigs.h" +#include "cellarray.h" +#include #include "stringutil.h" #include #include @@ -64,7 +64,7 @@ static const int kActivityAdmins = 4; // Show admin activity to admins anonymo static const int kActivityAdminsNames = 8; // If 4 is specified, admin names will be shown. static const int kActivityRootNames = 16; // Always show admin names to root users. -class PlayerLogicHelpers : +class PlayerLogicHelpers : public SMGlobalClass, public IPluginsListener, public ICommandTargetProcessor @@ -357,9 +357,9 @@ static cell_t SteamIdToLocal(IPluginContext *pCtx, int index, AuthIdType authTyp { return pCtx->ThrowNativeError("Client %d is not connected", index); } - + const char *authstr; - + switch (authType) { case AuthIdType::Engine: @@ -377,7 +377,7 @@ static cell_t SteamIdToLocal(IPluginContext *pCtx, int index, AuthIdType authTyp { return 0; } - + pCtx->StringToLocal(local_addr, bytes, authstr); break; case AuthIdType::Steam3: @@ -386,30 +386,30 @@ static cell_t SteamIdToLocal(IPluginContext *pCtx, int index, AuthIdType authTyp { return 0; } - + pCtx->StringToLocal(local_addr, bytes, authstr); break; - + case AuthIdType::SteamId64: { if (pPlayer->IsFakeClient() || gamehelpers->IsLANServer()) { return 0; } - + uint64_t steamId = pPlayer->GetSteamId64(validate); if (steamId == 0) { return 0; } - + char szAuth[64]; snprintf(szAuth, sizeof(szAuth), "%" PRIu64, steamId); - + pCtx->StringToLocal(local_addr, bytes, szAuth); } break; - } + } return 1; } @@ -421,7 +421,7 @@ static cell_t sm_GetClientAuthStr(IPluginContext *pCtx, const cell_t *params) { validate = !!params[4]; } - + return SteamIdToLocal(pCtx, params[1], AuthIdType::Steam2, params[2], (size_t)params[3], validate); } diff --git a/core/logic/smn_profiler.cpp b/core/logic/smn_profiler.cpp index 695147ce3..31a5a00f6 100644 --- a/core/logic/smn_profiler.cpp +++ b/core/logic/smn_profiler.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -36,7 +36,7 @@ #include #include #endif -#include "ProfileTools.h" +#include "profiletools.h" #include struct Profiler @@ -60,7 +60,7 @@ struct Profiler HandleType_t g_ProfilerType = 0; -class ProfilerHelpers : +class ProfilerHelpers : public SMGlobalClass, public IHandleTypeDispatch { diff --git a/core/logic/smn_sorting.cpp b/core/logic/smn_sorting.cpp index c60d8bf55..2d69cdba0 100644 --- a/core/logic/smn_sorting.cpp +++ b/core/logic/smn_sorting.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -33,26 +33,26 @@ #include #include #include "common_logic.h" -#include "CellArray.h" +#include "cellarray.h" #include /*********************************** * About the double array hack * - *************************** + *************************** Double arrays in Pawn are vectors offset by the current offset. For example: new array[2][2] In this array, index 0 contains the offset from the current offset which - results in the final vector [2] (at [0][2]). Meaning, to dereference [1][2], + results in the final vector [2] (at [0][2]). Meaning, to dereference [1][2], it is equivalent to: address = &array[1] + array[1] + 2 * sizeof(cell) The fact that each offset is from the _current_ position rather than the _base_ position is very important. It means that if you to try to swap vector positions, - the offsets will no longer match, because their current position has changed. A + the offsets will no longer match, because their current position has changed. A simple and ingenious way around this is to back up the positions in a separate array, then to overwrite each position in the old array with absolute indices. Pseudo C++ code: @@ -72,7 +72,7 @@ for (int i=0; i<2; i++) { //get the # of the vector we want to relocate in - cell vector_index = array[i]; + cell vector_index = array[i]; //get the real address of this vector char *real_address = (char *)array + (vector_index * sizeof(cell)) + old_offsets[vector_index]; //calc and store the new distance offset @@ -97,7 +97,7 @@ void sort_random(cell_t *array, cell_t size) { int n = rand() % (i + 1); - if (array[i] != array[n]) + if (array[i] != array[n]) { array[i] ^= array[n]; array[n] ^= array[i]; @@ -127,7 +127,7 @@ static cell_t sm_SortIntegers(IPluginContext *pContext, const cell_t *params) if (type == Sort_Ascending) { qsort(array, array_size, sizeof(cell_t), sort_ints_asc); - } + } else if (type == Sort_Descending) { qsort(array, array_size, sizeof(cell_t), sort_ints_desc); @@ -144,7 +144,7 @@ int sort_floats_asc(const void *float1, const void *float2) { float r1 = *(float *)float1; float r2 = *(float *)float2; - + if (r1 < r2) { return -1; @@ -201,7 +201,7 @@ int sort_strings_asc(const void *blk1, const void *blk2) { cell_t reloc1 = *(cell_t *)blk1; cell_t reloc2 = *(cell_t *)blk2; - + char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]); char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]); @@ -248,7 +248,7 @@ static cell_t sm_SortStrings(IPluginContext *pContext, const cell_t *params) if (type == Sort_Ascending) { qsort(array, array_size, sizeof(cell_t), sort_strings_asc); - } + } else if (type == Sort_Descending) { qsort(array, array_size, sizeof(cell_t), sort_strings_desc); @@ -392,11 +392,11 @@ static cell_t sm_SortCustom2D(IPluginContext *pContext, const cell_t *params) g_SortInfo.hndl = params[4]; g_SortInfo.array_addr = params[1]; g_SortInfo.eh = &eh; - + /** Same process as in strings, back up the old indices for later fixup */ g_SortInfo.array_base = array; g_SortInfo.array_remap = phys_addr; - + for (int i=0; iHeapPop(amx_addr); g_SortInfo = oldinfo; - + return 1; } @@ -458,14 +458,14 @@ static cell_t sm_SortADTArray(IPluginContext *pContext, const cell_t *params) HandleError err; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray)) + if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); } cell_t order = params[2]; - + if (order == Sort_Random) { sort_adt_random(cArray); @@ -495,7 +495,7 @@ static cell_t sm_SortADTArray(IPluginContext *pContext, const cell_t *params) { qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_asc); } - else + else { qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_desc); } @@ -506,7 +506,7 @@ static cell_t sm_SortADTArray(IPluginContext *pContext, const cell_t *params) { qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_asc); } - else + else { qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_desc); } @@ -549,7 +549,7 @@ static cell_t sm_SortADTArrayCustom(IPluginContext *pContext, const cell_t *para HandleError err; HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent); - if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray)) + if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray)) != HandleError_None) { return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err); @@ -574,7 +574,7 @@ static cell_t sm_SortADTArrayCustom(IPluginContext *pContext, const cell_t *para g_SortInfoADT.array_hndl = params[1]; g_SortInfoADT.hndl = params[3]; g_SortInfoADT.eh = &eh; - + qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_custom); g_SortInfoADT = oldinfo; diff --git a/core/logic/smn_timers.cpp b/core/logic/smn_timers.cpp index 631d4d41f..3eb4333e1 100644 --- a/core/logic/smn_timers.cpp +++ b/core/logic/smn_timers.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,7 +35,7 @@ #include #include #include -#include "DebugReporter.h" +#include "debugreporter.h" #include using namespace SourceHook; @@ -45,7 +45,7 @@ using namespace SourceHook; HandleType_t g_TimerType; -struct TimerInfo +struct TimerInfo { ITimer *Timer; IPluginFunction *Hook; @@ -160,8 +160,8 @@ void TimerNatives::OnTimerEnd(ITimer *pTimer, void *pData) { if ((herr=handlesys->FreeHandle(usrhndl, &sec)) != HandleError_None) { - g_DbgReporter.GenerateError(pInfo->pContext, pInfo->Hook->GetFunctionID(), - SP_ERROR_NATIVE, + g_DbgReporter.GenerateError(pInfo->pContext, pInfo->Hook->GetFunctionID(), + SP_ERROR_NATIVE, "Invalid data handle %x (error %d) passed during timer end with TIMER_DATA_HNDL_CLOSE", usrhndl, herr); } @@ -171,9 +171,9 @@ void TimerNatives::OnTimerEnd(ITimer *pTimer, void *pData) { if ((herr=handlesys->FreeHandle(pInfo->TimerHandle, &sec)) != HandleError_None) { - g_DbgReporter.GenerateError(pInfo->pContext, pInfo->Hook->GetFunctionID(), - SP_ERROR_NATIVE, - "Invalid timer handle %x (error %d) during timer end, displayed function is timer callback, not the stack trace", + g_DbgReporter.GenerateError(pInfo->pContext, pInfo->Hook->GetFunctionID(), + SP_ERROR_NATIVE, + "Invalid timer handle %x (error %d) during timer end, displayed function is timer callback, not the stack trace", pInfo->TimerHandle, herr); } } @@ -220,7 +220,7 @@ static cell_t smn_CreateTimer(IPluginContext *pCtx, const cell_t *params) hndl = handlesys->CreateHandle(g_TimerType, pInfo, pCtx->GetIdentity(), g_pCoreIdent, NULL); - /* If we can't get a handle, the timer isn't refcounted against the plugin and + /* If we can't get a handle, the timer isn't refcounted against the plugin and * we need to bail out to prevent a crash. */ if (hndl == BAD_HANDLE) diff --git a/core/logic/sprintf.cpp b/core/logic/sprintf.cpp index e00381f85..5ee0c057c 100644 --- a/core/logic/sprintf.cpp +++ b/core/logic/sprintf.cpp @@ -1,1264 +1,1264 @@ -// vim: set ts=4 sw=4 tw=99 noet : -// ============================================================================= -// SourceMod -// Copyright (C) 2004-2015 AlliedModders LLC. All rights reserved. -// ============================================================================= -// -// This program is free software; you can redistribute it and/or modify it under -// the terms of the GNU General Public License, version 3.0, as published by the -// Free Software Foundation. -// -// This program is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more -// details. -// -// You should have received a copy of the GNU General Public License along with -// this program. If not, see . -// -// As a special exception, AlliedModders LLC gives you permission to link the -// code of this program (as well as its derivative works) to "Half-Life 2," the -// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software -// by the Valve Corporation. You must obey the GNU General Public License in -// all respects for all other code used. Additionally, AlliedModders LLC grants -// this exception to all derivative works. AlliedModders LLC defines further -// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), -// or . - -#include "common_logic.h" -#include "Translator.h" -#include "sprintf.h" -#include -#include -#include -#include -#include - -using namespace SourceMod; - -#define LADJUST 0x00000004 /* left adjustment */ -#define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */ -#define UPPERDIGITS 0x00000200 /* make alpha digits uppercase */ -#define to_digit(c) ((c) - '0') -#define is_digit(c) ((unsigned)to_digit(c) <= 9) - -#define CHECK_ARGS(x) \ - if ((arg+x) > args) { \ - pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "String formatted incorrectly - parameter %d (total %d)", arg, args); \ - return 0; \ - } - -inline void ReorderTranslationParams(const Translation *pTrans, cell_t *params) -{ - cell_t new_params[MAX_TRANSLATE_PARAMS]; - for (unsigned int i = 0; i < pTrans->fmt_count; i++) - { - new_params[i] = params[pTrans->fmt_order[i]]; - } - memcpy(params, new_params, pTrans->fmt_count * sizeof(cell_t)); -} - -size_t Translate(char *buffer, - size_t maxlen, - IPluginContext *pCtx, - const char *key, - cell_t target, - const cell_t *params, - int *arg, - bool *error) -{ - unsigned int langid; - *error = false; - Translation pTrans; - IPlugin *pl = scripts->FindPluginByContext(pCtx->GetContext()); - unsigned int max_params = 0; - IPhraseCollection *pPhrases; - - pPhrases = pl->GetPhrases(); - -try_serverlang: - if (target == SOURCEMOD_SERVER_LANGUAGE) - { - langid = g_Translator.GetServerLanguage(); - } - else if ((target >= 1) && (target <= bridge->MaxClients())) - { - langid = g_Translator.GetClientLanguage(target); - } - else - { - pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Translation failed: invalid client index %d", target); - goto error_out; - } - - if (pPhrases->FindTranslation(key, langid, &pTrans) != Trans_Okay) - { - if (target != SOURCEMOD_SERVER_LANGUAGE && langid != g_Translator.GetServerLanguage()) - { - target = SOURCEMOD_SERVER_LANGUAGE; - goto try_serverlang; - } - else if (langid != SOURCEMOD_LANGUAGE_ENGLISH) - { - if (pPhrases->FindTranslation(key, SOURCEMOD_LANGUAGE_ENGLISH, &pTrans) != Trans_Okay) - { - pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key); - goto error_out; - } - } - else - { - pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key); - goto error_out; - } - } - - max_params = pTrans.fmt_count; - - if (max_params) - { - cell_t new_params[MAX_TRANSLATE_PARAMS]; - - /* Check if we're going to over the limit */ - if ((*arg) + (max_params - 1) > (size_t)params[0]) - { - pCtx->ThrowNativeErrorEx(SP_ERROR_PARAMS_MAX, - "Translation string formatted incorrectly - missing at least %d parameters", - ((*arg + (max_params - 1)) - params[0]) - ); - goto error_out; - } - - /* If we need to re-order the parameters, do so with a temporary array. - * Otherwise, we could run into trouble with continual formats, a la ShowActivity(). - */ - memcpy(new_params, params, sizeof(cell_t) * (params[0] + 1)); - ReorderTranslationParams(&pTrans, &new_params[*arg]); - - return atcprintf(buffer, maxlen, pTrans.szPhrase, pCtx, new_params, arg); - } - else - { - return atcprintf(buffer, maxlen, pTrans.szPhrase, pCtx, params, arg); - } - -error_out: - *error = true; - return 0; -} - -void AddString(char **buf_p, size_t &maxlen, const char *string, int width, int prec) -{ - int size = 0; - char *buf; - static char nlstr[] = {'(','n','u','l','l',')','\0'}; - - buf = *buf_p; - - if (string == NULL) - { - string = nlstr; - prec = -1; - } - - if (prec >= 0) - { - for (size = 0; size < prec; size++) - { - if (string[size] == '\0') - { - break; - } - } - } - else - { - while (string[size++]); - size--; - } - - if (size > (int)maxlen) - { - size = maxlen; - } - - maxlen -= size; - width -= size; - - while (size--) - { - *buf++ = *string++; - } - - while ((width-- > 0) && maxlen) - { - *buf++ = ' '; - maxlen--; - } - - *buf_p = buf; -} - -void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec, int flags) -{ - int digits; // non-fraction part digits - double tmp; // temporary - char *buf = *buf_p; // output buffer pointer - int val; // temporary - int sign = 0; // 0: positive, 1: negative - int fieldlength; // for padding - int significant_digits = 0; // number of significant digits written - const int MAX_SIGNIFICANT_DIGITS = 16; - - if (ke::IsNaN(fval)) - { - AddString(buf_p, maxlen, "NaN", width, prec); - return; - } - - // default precision - if (prec < 0) - { - prec = 6; - } - - // get the sign - if (fval < 0) - { - fval = -fval; - sign = 1; - } - - // compute whole-part digits count - digits = (int)log10(fval) + 1; - - // Only print 0.something if 0 < fval < 1 - if (digits < 1) - { - digits = 1; - } - - // compute the field length - fieldlength = digits + prec + ((prec > 0) ? 1 : 0) + sign; - - // minus sign BEFORE left padding if padding with zeros - if (sign && maxlen && (flags & ZEROPAD)) - { - *buf++ = '-'; - maxlen--; - } - - // right justify if required - if ((flags & LADJUST) == 0) - { - while ((fieldlength < width) && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - width--; - maxlen--; - } - } - - // minus sign AFTER left padding if padding with spaces - if (sign && maxlen && !(flags & ZEROPAD)) - { - *buf++ = '-'; - maxlen--; - } - - // write the whole part - tmp = pow(10.0, digits-1); - while ((digits--) && maxlen) - { - if (++significant_digits > MAX_SIGNIFICANT_DIGITS) - { - *buf++ = '0'; - } - else - { - val = (int)(fval / tmp); - *buf++ = '0' + val; - fval -= val * tmp; - tmp *= 0.1; - } - maxlen--; - } - - // write the fraction part - if (maxlen && prec) - { - *buf++ = '.'; - maxlen--; - } - - tmp = pow(10.0, prec); - - fval *= tmp; - while (prec-- && maxlen) - { - if (++significant_digits > MAX_SIGNIFICANT_DIGITS) - { - *buf++ = '0'; - } - else - { - tmp *= 0.1; - val = (int)(fval / tmp); - *buf++ = '0' + val; - fval -= val * tmp; - } - maxlen--; - } - - // left justify if required - if (flags & LADJUST) - { - while ((fieldlength < width) && maxlen) - { - // right-padding only with spaces, ZEROPAD is ignored - *buf++ = ' '; - width--; - maxlen--; - } - } - - // update parent's buffer pointer - *buf_p = buf; -} - -void AddBinary(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags) -{ - char text[32]; - int digits; - char *buf; - - digits = 0; - do - { - if (val & 1) - { - text[digits++] = '1'; - } - else - { - text[digits++] = '0'; - } - val >>= 1; - } while (val); - - buf = *buf_p; - - if (!(flags & LADJUST)) - { - while (digits < width && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - width--; - maxlen--; - } - } - - while (digits-- && maxlen) - { - *buf++ = text[digits]; - width--; - maxlen--; - } - - if (flags & LADJUST) - { - while (width-- && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - maxlen--; - } - } - - *buf_p = buf; -} - -void AddUInt(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags) -{ - char text[32]; - int digits; - char *buf; - - digits = 0; - do - { - text[digits++] = '0' + val % 10; - val /= 10; - } while (val); - - buf = *buf_p; - - if (!(flags & LADJUST)) - { - while (digits < width && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - width--; - maxlen--; - } - } - - while (digits-- && maxlen) - { - *buf++ = text[digits]; - width--; - maxlen--; - } - - if (flags & LADJUST) - { - while (width-- && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - maxlen--; - } - } - - *buf_p = buf; -} - -void AddInt(char **buf_p, size_t &maxlen, int val, int width, int flags) -{ - char text[32]; - int digits; - int signedVal; - char *buf; - unsigned int unsignedVal; - - digits = 0; - signedVal = val; - if (val < 0) - { - /* we want the unsigned version */ - unsignedVal = abs(val); - } - else - { - unsignedVal = val; - } - - do - { - text[digits++] = '0' + unsignedVal % 10; - unsignedVal /= 10; - } while (unsignedVal); - - if (signedVal < 0) - { - text[digits++] = '-'; - } - - buf = *buf_p; - - if (!(flags & LADJUST)) - { - while ((digits < width) && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - width--; - maxlen--; - } - } - - while (digits-- && maxlen) - { - *buf++ = text[digits]; - width--; - maxlen--; - } - - if (flags & LADJUST) - { - while (width-- && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - maxlen--; - } - } - - *buf_p = buf; -} - -void AddHex(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags) -{ - char text[32]; - int digits; - char *buf; - char digit; - int hexadjust; - - if (flags & UPPERDIGITS) - { - hexadjust = 'A' - '9' - 1; - } - else - { - hexadjust = 'a' - '9' - 1; - } - - digits = 0; - do - { - digit = ('0' + val % 16); - if (digit > '9') - { - digit += hexadjust; - } - - text[digits++] = digit; - val /= 16; - } while(val); - - buf = *buf_p; - - if (!(flags & LADJUST)) - { - while (digits < width && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - width--; - maxlen--; - } - } - - while (digits-- && maxlen) - { - *buf++ = text[digits]; - width--; - maxlen--; - } - - if (flags & LADJUST) - { - while (width-- && maxlen) - { - *buf++ = (flags & ZEROPAD) ? '0' : ' '; - maxlen--; - } - } - - *buf_p = buf; -} - -bool gnprintf(char *buffer, - size_t maxlen, - const char *format, - IPhraseCollection *pPhrases, - void **params, - unsigned int numparams, - unsigned int &curparam, - size_t *pOutLength, - const char **pFailPhrase) -{ - if (!buffer || !maxlen) - { - if (pOutLength != NULL) - { - *pOutLength = 0; - } - return true; - } - - if (numparams > MAX_TRANSLATE_PARAMS) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - - int arg = 0; - char *buf_p; - char ch; - int flags; - int width; - int prec; - int n; - char sign; - const char *fmt; - size_t llen = maxlen - 1; - - buf_p = buffer; - fmt = format; - - while (true) - { - // run through the format string until we hit a '%' or '\0' - for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++) - { - *buf_p++ = ch; - llen--; - } - if ((ch == '\0') || (llen <= 0)) - { - goto done; - } - - // skip over the '%' - fmt++; - - // reset formatting state - flags = 0; - width = 0; - prec = -1; - sign = '\0'; - -rflag: - ch = *fmt++; -reswitch: - switch(ch) - { - case '-': - { - flags |= LADJUST; - goto rflag; - } - case '.': - { - n = 0; - while(is_digit((ch = *fmt++))) - { - n = 10 * n + (ch - '0'); - } - prec = (n < 0) ? -1 : n; - goto reswitch; - } - case '0': - { - flags |= ZEROPAD; - goto rflag; - } - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - n = 0; - do - { - n = 10 * n + (ch - '0'); - ch = *fmt++; - } while(is_digit(ch)); - width = n; - goto reswitch; - } - case 'c': - { - if (!llen) - { - goto done; - } - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - char *c = (char *)params[curparam]; - curparam++; - *buf_p++ = *c; - llen--; - arg++; - break; - } - case 'b': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - int *value = (int *)params[curparam]; - curparam++; - AddBinary(&buf_p, llen, *value, width, flags); - arg++; - break; - } - case 'd': - case 'i': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - int *value = (int *)params[curparam]; - curparam++; - AddInt(&buf_p, llen, *value, width, flags); - arg++; - break; - } - case 'u': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - unsigned int *value = (unsigned int *)params[curparam]; - curparam++; - AddUInt(&buf_p, llen, *value, width, flags); - arg++; - break; - } - case 'f': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - float *value = (float *)params[curparam]; - curparam++; - AddFloat(&buf_p, llen, *value, width, prec, flags); - arg++; - break; - } - case 's': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - const char *str = (const char *)params[curparam]; - curparam++; - AddString(&buf_p, llen, str, width, prec); - arg++; - break; - } - case 'T': - case 't': - { - int target; - const char *key; - size_t out_length; - Translation trans; - unsigned int lang_id; - - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - key = (const char *)(params[curparam]); - curparam++; - - if (ch == 'T') - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - target = *((int *)(params[curparam])); - curparam++; - } - else - { - target = g_Translator.GetGlobalTarget(); - } - -try_again: - if (target == SOURCEMOD_SERVER_LANGUAGE) - { - lang_id = g_Translator.GetServerLanguage(); - } - else if (target >= 1 && target <= bridge->MaxClients()) - { - lang_id = g_Translator.GetClientLanguage(target); - } - else - { - lang_id = g_Translator.GetServerLanguage(); - } - - if (pPhrases == NULL) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = key; - } - return false; - } - - if (pPhrases->FindTranslation(key, lang_id, &trans) != Trans_Okay) - { - if (target != SOURCEMOD_SERVER_LANGUAGE && lang_id != g_Translator.GetServerLanguage()) - { - target = SOURCEMOD_SERVER_LANGUAGE; - goto try_again; - } - else if (lang_id != SOURCEMOD_LANGUAGE_ENGLISH) - { - if (pPhrases->FindTranslation(key, SOURCEMOD_LANGUAGE_ENGLISH, &trans) != Trans_Okay) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = key; - } - return false; - } - } - else - { - if (pFailPhrase != NULL) - { - *pFailPhrase = key; - } - return false; - } - } - - if (trans.fmt_count) - { - unsigned int i; - void *new_params[MAX_TRANSLATE_PARAMS]; - - if (curparam + trans.fmt_count > numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - - /* Copy the array and re-order the stack */ - memcpy(new_params, params, sizeof(void *) * numparams); - for (i = 0; i < trans.fmt_count; i++) - { - new_params[curparam + i] = const_cast(params[curparam + trans.fmt_order[i]]); - } - - if (!gnprintf(buf_p, - llen, - trans.szPhrase, - pPhrases, - new_params, - numparams, - curparam, - &out_length, - pFailPhrase)) - { - return false; - } - } - else - { - if (!gnprintf(buf_p, - llen, - trans.szPhrase, - pPhrases, - params, - numparams, - curparam, - &out_length, - pFailPhrase)) - { - return false; - } - } - - buf_p += out_length; - llen -= out_length; - - break; - } - case 'X': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - unsigned int *value = (unsigned int *)params[curparam]; - curparam++; - flags |= UPPERDIGITS; - AddHex(&buf_p, llen, *value, width, flags); - arg++; - break; - } - case 'x': - { - if (curparam >= numparams) - { - if (pFailPhrase != NULL) - { - *pFailPhrase = NULL; - } - return false; - } - unsigned int *value = (unsigned int *)params[curparam]; - curparam++; - AddHex(&buf_p, llen, *value, width, flags); - arg++; - break; - } - case '%': - { - if (!llen) - { - goto done; - } - *buf_p++ = ch; - llen--; - break; - } - case '\0': - { - if (!llen) - { - goto done; - } - *buf_p++ = '%'; - llen--; - goto done; - } - default: - { - if (!llen) - { - goto done; - } - *buf_p++ = ch; - llen--; - break; - } - } - } - -done: - *buf_p = '\0'; - - if (pOutLength != NULL) - { - *pOutLength = (maxlen - llen - 1); - } - - return true; -} - -size_t atcprintf(char *buffer, size_t maxlen, const char *format, IPluginContext *pCtx, const cell_t *params, int *param) -{ - if (!buffer || !maxlen) - { - return 0; - } - - int arg; - int args = params[0]; - char *buf_p; - char ch; - int flags; - int width; - int prec; - int n; - char sign; - const char *fmt; - size_t llen = maxlen - 1; - - buf_p = buffer; - arg = *param; - fmt = format; - - while (true) - { - // run through the format string until we hit a '%' or '\0' - for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++) - { - *buf_p++ = ch; - llen--; - } - if ((ch == '\0') || (llen <= 0)) - { - goto done; - } - - // skip over the '%' - fmt++; - - // reset formatting state - flags = 0; - width = 0; - prec = -1; - sign = '\0'; - -rflag: - ch = *fmt++; -reswitch: - switch(ch) - { - case '-': - { - flags |= LADJUST; - goto rflag; - } - case '.': - { - n = 0; - while(is_digit((ch = *fmt++))) - { - n = 10 * n + (ch - '0'); - } - prec = (n < 0) ? -1 : n; - goto reswitch; - } - case '0': - { - flags |= ZEROPAD; - goto rflag; - } - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - n = 0; - do - { - n = 10 * n + (ch - '0'); - ch = *fmt++; - } while(is_digit(ch)); - width = n; - goto reswitch; - } - case 'c': - { - CHECK_ARGS(0); - if (!llen) - { - goto done; - } - char *c; - pCtx->LocalToString(params[arg], &c); - *buf_p++ = *c; - llen--; - arg++; - break; - } - case 'b': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - AddBinary(&buf_p, llen, *value, width, flags); - arg++; - break; - } - case 'd': - case 'i': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - AddInt(&buf_p, llen, static_cast(*value), width, flags); - arg++; - break; - } - case 'u': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - AddUInt(&buf_p, llen, static_cast(*value), width, flags); - arg++; - break; - } - case 'f': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - AddFloat(&buf_p, llen, sp_ctof(*value), width, prec, flags); - arg++; - break; - } - case 'L': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - char buffer[255]; - if (*value) - { - const char *name; - const char *auth; - int userid; - if (!bridge->DescribePlayer(*value, &name, &auth, &userid)) - return pCtx->ThrowNativeError("Client index %d is invalid", *value); - ke::SafeSprintf(buffer, - sizeof(buffer), - "%s<%d><%s><>", - name, - userid, - auth); - } - else - { - ke::SafeSprintf(buffer, - sizeof(buffer), - "Console<0>"); - } - AddString(&buf_p, llen, buffer, width, prec); - arg++; - break; - } - case 'N': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - - const char *name = "Console"; - if (*value) { - if (!bridge->DescribePlayer(*value, &name, nullptr, nullptr)) - return pCtx->ThrowNativeError("Client index %d is invalid", *value); - } - AddString(&buf_p, llen, name, width, prec); - arg++; - break; - } - case 's': - { - CHECK_ARGS(0); - char *str; - pCtx->LocalToString(params[arg], &str); - AddString(&buf_p, llen, str, width, prec); - arg++; - break; - } - case 'T': - { - CHECK_ARGS(1); - char *key; - bool error; - size_t res; - cell_t *target; - pCtx->LocalToString(params[arg++], &key); - pCtx->LocalToPhysAddr(params[arg++], &target); - res = Translate(buf_p, llen, pCtx, key, *target, params, &arg, &error); - if (error) - { - return 0; - } - buf_p += res; - llen -= res; - break; - } - case 't': - { - CHECK_ARGS(0); - char *key; - bool error; - size_t res; - cell_t target = bridge->GetGlobalTarget(); - pCtx->LocalToString(params[arg++], &key); - res = Translate(buf_p, llen, pCtx, key, target, params, &arg, &error); - if (error) - { - return 0; - } - buf_p += res; - llen -= res; - break; - } - case 'X': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - flags |= UPPERDIGITS; - AddHex(&buf_p, llen, static_cast(*value), width, flags); - arg++; - break; - } - case 'x': - { - CHECK_ARGS(0); - cell_t *value; - pCtx->LocalToPhysAddr(params[arg], &value); - AddHex(&buf_p, llen, static_cast(*value), width, flags); - arg++; - break; - } - case '%': - { - if (!llen) - { - goto done; - } - *buf_p++ = ch; - llen--; - break; - } - case '\0': - { - if (!llen) - { - goto done; - } - *buf_p++ = '%'; - llen--; - goto done; - } - default: - { - if (!llen) - { - goto done; - } - *buf_p++ = ch; - llen--; - break; - } - } - } - -done: - *buf_p = '\0'; - *param = arg; - return (maxlen - llen - 1); -} - +// vim: set ts=4 sw=4 tw=99 noet : +// ============================================================================= +// SourceMod +// Copyright (C) 2004-2015 AlliedModders LLC. All rights reserved. +// ============================================================================= +// +// This program is free software; you can redistribute it and/or modify it under +// the terms of the GNU General Public License, version 3.0, as published by the +// Free Software Foundation. +// +// This program is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +// details. +// +// You should have received a copy of the GNU General Public License along with +// this program. If not, see . +// +// As a special exception, AlliedModders LLC gives you permission to link the +// code of this program (as well as its derivative works) to "Half-Life 2," the +// "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software +// by the Valve Corporation. You must obey the GNU General Public License in +// all respects for all other code used. Additionally, AlliedModders LLC grants +// this exception to all derivative works. AlliedModders LLC defines further +// exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), +// or . + +#include "common_logic.h" +#include "translator.h" +#include "sprintf.h" +#include +#include +#include +#include +#include + +using namespace SourceMod; + +#define LADJUST 0x00000004 /* left adjustment */ +#define ZEROPAD 0x00000080 /* zero (as opposed to blank) pad */ +#define UPPERDIGITS 0x00000200 /* make alpha digits uppercase */ +#define to_digit(c) ((c) - '0') +#define is_digit(c) ((unsigned)to_digit(c) <= 9) + +#define CHECK_ARGS(x) \ + if ((arg+x) > args) { \ + pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "String formatted incorrectly - parameter %d (total %d)", arg, args); \ + return 0; \ + } + +inline void ReorderTranslationParams(const Translation *pTrans, cell_t *params) +{ + cell_t new_params[MAX_TRANSLATE_PARAMS]; + for (unsigned int i = 0; i < pTrans->fmt_count; i++) + { + new_params[i] = params[pTrans->fmt_order[i]]; + } + memcpy(params, new_params, pTrans->fmt_count * sizeof(cell_t)); +} + +size_t Translate(char *buffer, + size_t maxlen, + IPluginContext *pCtx, + const char *key, + cell_t target, + const cell_t *params, + int *arg, + bool *error) +{ + unsigned int langid; + *error = false; + Translation pTrans; + IPlugin *pl = scripts->FindPluginByContext(pCtx->GetContext()); + unsigned int max_params = 0; + IPhraseCollection *pPhrases; + + pPhrases = pl->GetPhrases(); + +try_serverlang: + if (target == SOURCEMOD_SERVER_LANGUAGE) + { + langid = g_Translator.GetServerLanguage(); + } + else if ((target >= 1) && (target <= bridge->MaxClients())) + { + langid = g_Translator.GetClientLanguage(target); + } + else + { + pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Translation failed: invalid client index %d", target); + goto error_out; + } + + if (pPhrases->FindTranslation(key, langid, &pTrans) != Trans_Okay) + { + if (target != SOURCEMOD_SERVER_LANGUAGE && langid != g_Translator.GetServerLanguage()) + { + target = SOURCEMOD_SERVER_LANGUAGE; + goto try_serverlang; + } + else if (langid != SOURCEMOD_LANGUAGE_ENGLISH) + { + if (pPhrases->FindTranslation(key, SOURCEMOD_LANGUAGE_ENGLISH, &pTrans) != Trans_Okay) + { + pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key); + goto error_out; + } + } + else + { + pCtx->ThrowNativeErrorEx(SP_ERROR_PARAM, "Language phrase \"%s\" not found", key); + goto error_out; + } + } + + max_params = pTrans.fmt_count; + + if (max_params) + { + cell_t new_params[MAX_TRANSLATE_PARAMS]; + + /* Check if we're going to over the limit */ + if ((*arg) + (max_params - 1) > (size_t)params[0]) + { + pCtx->ThrowNativeErrorEx(SP_ERROR_PARAMS_MAX, + "Translation string formatted incorrectly - missing at least %d parameters", + ((*arg + (max_params - 1)) - params[0]) + ); + goto error_out; + } + + /* If we need to re-order the parameters, do so with a temporary array. + * Otherwise, we could run into trouble with continual formats, a la ShowActivity(). + */ + memcpy(new_params, params, sizeof(cell_t) * (params[0] + 1)); + ReorderTranslationParams(&pTrans, &new_params[*arg]); + + return atcprintf(buffer, maxlen, pTrans.szPhrase, pCtx, new_params, arg); + } + else + { + return atcprintf(buffer, maxlen, pTrans.szPhrase, pCtx, params, arg); + } + +error_out: + *error = true; + return 0; +} + +void AddString(char **buf_p, size_t &maxlen, const char *string, int width, int prec) +{ + int size = 0; + char *buf; + static char nlstr[] = {'(','n','u','l','l',')','\0'}; + + buf = *buf_p; + + if (string == NULL) + { + string = nlstr; + prec = -1; + } + + if (prec >= 0) + { + for (size = 0; size < prec; size++) + { + if (string[size] == '\0') + { + break; + } + } + } + else + { + while (string[size++]); + size--; + } + + if (size > (int)maxlen) + { + size = maxlen; + } + + maxlen -= size; + width -= size; + + while (size--) + { + *buf++ = *string++; + } + + while ((width-- > 0) && maxlen) + { + *buf++ = ' '; + maxlen--; + } + + *buf_p = buf; +} + +void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec, int flags) +{ + int digits; // non-fraction part digits + double tmp; // temporary + char *buf = *buf_p; // output buffer pointer + int val; // temporary + int sign = 0; // 0: positive, 1: negative + int fieldlength; // for padding + int significant_digits = 0; // number of significant digits written + const int MAX_SIGNIFICANT_DIGITS = 16; + + if (ke::IsNaN(fval)) + { + AddString(buf_p, maxlen, "NaN", width, prec); + return; + } + + // default precision + if (prec < 0) + { + prec = 6; + } + + // get the sign + if (fval < 0) + { + fval = -fval; + sign = 1; + } + + // compute whole-part digits count + digits = (int)log10(fval) + 1; + + // Only print 0.something if 0 < fval < 1 + if (digits < 1) + { + digits = 1; + } + + // compute the field length + fieldlength = digits + prec + ((prec > 0) ? 1 : 0) + sign; + + // minus sign BEFORE left padding if padding with zeros + if (sign && maxlen && (flags & ZEROPAD)) + { + *buf++ = '-'; + maxlen--; + } + + // right justify if required + if ((flags & LADJUST) == 0) + { + while ((fieldlength < width) && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + width--; + maxlen--; + } + } + + // minus sign AFTER left padding if padding with spaces + if (sign && maxlen && !(flags & ZEROPAD)) + { + *buf++ = '-'; + maxlen--; + } + + // write the whole part + tmp = pow(10.0, digits-1); + while ((digits--) && maxlen) + { + if (++significant_digits > MAX_SIGNIFICANT_DIGITS) + { + *buf++ = '0'; + } + else + { + val = (int)(fval / tmp); + *buf++ = '0' + val; + fval -= val * tmp; + tmp *= 0.1; + } + maxlen--; + } + + // write the fraction part + if (maxlen && prec) + { + *buf++ = '.'; + maxlen--; + } + + tmp = pow(10.0, prec); + + fval *= tmp; + while (prec-- && maxlen) + { + if (++significant_digits > MAX_SIGNIFICANT_DIGITS) + { + *buf++ = '0'; + } + else + { + tmp *= 0.1; + val = (int)(fval / tmp); + *buf++ = '0' + val; + fval -= val * tmp; + } + maxlen--; + } + + // left justify if required + if (flags & LADJUST) + { + while ((fieldlength < width) && maxlen) + { + // right-padding only with spaces, ZEROPAD is ignored + *buf++ = ' '; + width--; + maxlen--; + } + } + + // update parent's buffer pointer + *buf_p = buf; +} + +void AddBinary(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags) +{ + char text[32]; + int digits; + char *buf; + + digits = 0; + do + { + if (val & 1) + { + text[digits++] = '1'; + } + else + { + text[digits++] = '0'; + } + val >>= 1; + } while (val); + + buf = *buf_p; + + if (!(flags & LADJUST)) + { + while (digits < width && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + width--; + maxlen--; + } + } + + while (digits-- && maxlen) + { + *buf++ = text[digits]; + width--; + maxlen--; + } + + if (flags & LADJUST) + { + while (width-- && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + maxlen--; + } + } + + *buf_p = buf; +} + +void AddUInt(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags) +{ + char text[32]; + int digits; + char *buf; + + digits = 0; + do + { + text[digits++] = '0' + val % 10; + val /= 10; + } while (val); + + buf = *buf_p; + + if (!(flags & LADJUST)) + { + while (digits < width && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + width--; + maxlen--; + } + } + + while (digits-- && maxlen) + { + *buf++ = text[digits]; + width--; + maxlen--; + } + + if (flags & LADJUST) + { + while (width-- && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + maxlen--; + } + } + + *buf_p = buf; +} + +void AddInt(char **buf_p, size_t &maxlen, int val, int width, int flags) +{ + char text[32]; + int digits; + int signedVal; + char *buf; + unsigned int unsignedVal; + + digits = 0; + signedVal = val; + if (val < 0) + { + /* we want the unsigned version */ + unsignedVal = abs(val); + } + else + { + unsignedVal = val; + } + + do + { + text[digits++] = '0' + unsignedVal % 10; + unsignedVal /= 10; + } while (unsignedVal); + + if (signedVal < 0) + { + text[digits++] = '-'; + } + + buf = *buf_p; + + if (!(flags & LADJUST)) + { + while ((digits < width) && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + width--; + maxlen--; + } + } + + while (digits-- && maxlen) + { + *buf++ = text[digits]; + width--; + maxlen--; + } + + if (flags & LADJUST) + { + while (width-- && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + maxlen--; + } + } + + *buf_p = buf; +} + +void AddHex(char **buf_p, size_t &maxlen, unsigned int val, int width, int flags) +{ + char text[32]; + int digits; + char *buf; + char digit; + int hexadjust; + + if (flags & UPPERDIGITS) + { + hexadjust = 'A' - '9' - 1; + } + else + { + hexadjust = 'a' - '9' - 1; + } + + digits = 0; + do + { + digit = ('0' + val % 16); + if (digit > '9') + { + digit += hexadjust; + } + + text[digits++] = digit; + val /= 16; + } while(val); + + buf = *buf_p; + + if (!(flags & LADJUST)) + { + while (digits < width && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + width--; + maxlen--; + } + } + + while (digits-- && maxlen) + { + *buf++ = text[digits]; + width--; + maxlen--; + } + + if (flags & LADJUST) + { + while (width-- && maxlen) + { + *buf++ = (flags & ZEROPAD) ? '0' : ' '; + maxlen--; + } + } + + *buf_p = buf; +} + +bool gnprintf(char *buffer, + size_t maxlen, + const char *format, + IPhraseCollection *pPhrases, + void **params, + unsigned int numparams, + unsigned int &curparam, + size_t *pOutLength, + const char **pFailPhrase) +{ + if (!buffer || !maxlen) + { + if (pOutLength != NULL) + { + *pOutLength = 0; + } + return true; + } + + if (numparams > MAX_TRANSLATE_PARAMS) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + + int arg = 0; + char *buf_p; + char ch; + int flags; + int width; + int prec; + int n; + char sign; + const char *fmt; + size_t llen = maxlen - 1; + + buf_p = buffer; + fmt = format; + + while (true) + { + // run through the format string until we hit a '%' or '\0' + for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++) + { + *buf_p++ = ch; + llen--; + } + if ((ch == '\0') || (llen <= 0)) + { + goto done; + } + + // skip over the '%' + fmt++; + + // reset formatting state + flags = 0; + width = 0; + prec = -1; + sign = '\0'; + +rflag: + ch = *fmt++; +reswitch: + switch(ch) + { + case '-': + { + flags |= LADJUST; + goto rflag; + } + case '.': + { + n = 0; + while(is_digit((ch = *fmt++))) + { + n = 10 * n + (ch - '0'); + } + prec = (n < 0) ? -1 : n; + goto reswitch; + } + case '0': + { + flags |= ZEROPAD; + goto rflag; + } + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + n = 0; + do + { + n = 10 * n + (ch - '0'); + ch = *fmt++; + } while(is_digit(ch)); + width = n; + goto reswitch; + } + case 'c': + { + if (!llen) + { + goto done; + } + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + char *c = (char *)params[curparam]; + curparam++; + *buf_p++ = *c; + llen--; + arg++; + break; + } + case 'b': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + int *value = (int *)params[curparam]; + curparam++; + AddBinary(&buf_p, llen, *value, width, flags); + arg++; + break; + } + case 'd': + case 'i': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + int *value = (int *)params[curparam]; + curparam++; + AddInt(&buf_p, llen, *value, width, flags); + arg++; + break; + } + case 'u': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + unsigned int *value = (unsigned int *)params[curparam]; + curparam++; + AddUInt(&buf_p, llen, *value, width, flags); + arg++; + break; + } + case 'f': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + float *value = (float *)params[curparam]; + curparam++; + AddFloat(&buf_p, llen, *value, width, prec, flags); + arg++; + break; + } + case 's': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + const char *str = (const char *)params[curparam]; + curparam++; + AddString(&buf_p, llen, str, width, prec); + arg++; + break; + } + case 'T': + case 't': + { + int target; + const char *key; + size_t out_length; + Translation trans; + unsigned int lang_id; + + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + key = (const char *)(params[curparam]); + curparam++; + + if (ch == 'T') + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + target = *((int *)(params[curparam])); + curparam++; + } + else + { + target = g_Translator.GetGlobalTarget(); + } + +try_again: + if (target == SOURCEMOD_SERVER_LANGUAGE) + { + lang_id = g_Translator.GetServerLanguage(); + } + else if (target >= 1 && target <= bridge->MaxClients()) + { + lang_id = g_Translator.GetClientLanguage(target); + } + else + { + lang_id = g_Translator.GetServerLanguage(); + } + + if (pPhrases == NULL) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = key; + } + return false; + } + + if (pPhrases->FindTranslation(key, lang_id, &trans) != Trans_Okay) + { + if (target != SOURCEMOD_SERVER_LANGUAGE && lang_id != g_Translator.GetServerLanguage()) + { + target = SOURCEMOD_SERVER_LANGUAGE; + goto try_again; + } + else if (lang_id != SOURCEMOD_LANGUAGE_ENGLISH) + { + if (pPhrases->FindTranslation(key, SOURCEMOD_LANGUAGE_ENGLISH, &trans) != Trans_Okay) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = key; + } + return false; + } + } + else + { + if (pFailPhrase != NULL) + { + *pFailPhrase = key; + } + return false; + } + } + + if (trans.fmt_count) + { + unsigned int i; + void *new_params[MAX_TRANSLATE_PARAMS]; + + if (curparam + trans.fmt_count > numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + + /* Copy the array and re-order the stack */ + memcpy(new_params, params, sizeof(void *) * numparams); + for (i = 0; i < trans.fmt_count; i++) + { + new_params[curparam + i] = const_cast(params[curparam + trans.fmt_order[i]]); + } + + if (!gnprintf(buf_p, + llen, + trans.szPhrase, + pPhrases, + new_params, + numparams, + curparam, + &out_length, + pFailPhrase)) + { + return false; + } + } + else + { + if (!gnprintf(buf_p, + llen, + trans.szPhrase, + pPhrases, + params, + numparams, + curparam, + &out_length, + pFailPhrase)) + { + return false; + } + } + + buf_p += out_length; + llen -= out_length; + + break; + } + case 'X': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + unsigned int *value = (unsigned int *)params[curparam]; + curparam++; + flags |= UPPERDIGITS; + AddHex(&buf_p, llen, *value, width, flags); + arg++; + break; + } + case 'x': + { + if (curparam >= numparams) + { + if (pFailPhrase != NULL) + { + *pFailPhrase = NULL; + } + return false; + } + unsigned int *value = (unsigned int *)params[curparam]; + curparam++; + AddHex(&buf_p, llen, *value, width, flags); + arg++; + break; + } + case '%': + { + if (!llen) + { + goto done; + } + *buf_p++ = ch; + llen--; + break; + } + case '\0': + { + if (!llen) + { + goto done; + } + *buf_p++ = '%'; + llen--; + goto done; + } + default: + { + if (!llen) + { + goto done; + } + *buf_p++ = ch; + llen--; + break; + } + } + } + +done: + *buf_p = '\0'; + + if (pOutLength != NULL) + { + *pOutLength = (maxlen - llen - 1); + } + + return true; +} + +size_t atcprintf(char *buffer, size_t maxlen, const char *format, IPluginContext *pCtx, const cell_t *params, int *param) +{ + if (!buffer || !maxlen) + { + return 0; + } + + int arg; + int args = params[0]; + char *buf_p; + char ch; + int flags; + int width; + int prec; + int n; + char sign; + const char *fmt; + size_t llen = maxlen - 1; + + buf_p = buffer; + arg = *param; + fmt = format; + + while (true) + { + // run through the format string until we hit a '%' or '\0' + for (ch = *fmt; llen && ((ch = *fmt) != '\0') && (ch != '%'); fmt++) + { + *buf_p++ = ch; + llen--; + } + if ((ch == '\0') || (llen <= 0)) + { + goto done; + } + + // skip over the '%' + fmt++; + + // reset formatting state + flags = 0; + width = 0; + prec = -1; + sign = '\0'; + +rflag: + ch = *fmt++; +reswitch: + switch(ch) + { + case '-': + { + flags |= LADJUST; + goto rflag; + } + case '.': + { + n = 0; + while(is_digit((ch = *fmt++))) + { + n = 10 * n + (ch - '0'); + } + prec = (n < 0) ? -1 : n; + goto reswitch; + } + case '0': + { + flags |= ZEROPAD; + goto rflag; + } + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + n = 0; + do + { + n = 10 * n + (ch - '0'); + ch = *fmt++; + } while(is_digit(ch)); + width = n; + goto reswitch; + } + case 'c': + { + CHECK_ARGS(0); + if (!llen) + { + goto done; + } + char *c; + pCtx->LocalToString(params[arg], &c); + *buf_p++ = *c; + llen--; + arg++; + break; + } + case 'b': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + AddBinary(&buf_p, llen, *value, width, flags); + arg++; + break; + } + case 'd': + case 'i': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + AddInt(&buf_p, llen, static_cast(*value), width, flags); + arg++; + break; + } + case 'u': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + AddUInt(&buf_p, llen, static_cast(*value), width, flags); + arg++; + break; + } + case 'f': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + AddFloat(&buf_p, llen, sp_ctof(*value), width, prec, flags); + arg++; + break; + } + case 'L': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + char buffer[255]; + if (*value) + { + const char *name; + const char *auth; + int userid; + if (!bridge->DescribePlayer(*value, &name, &auth, &userid)) + return pCtx->ThrowNativeError("Client index %d is invalid", *value); + ke::SafeSprintf(buffer, + sizeof(buffer), + "%s<%d><%s><>", + name, + userid, + auth); + } + else + { + ke::SafeSprintf(buffer, + sizeof(buffer), + "Console<0>"); + } + AddString(&buf_p, llen, buffer, width, prec); + arg++; + break; + } + case 'N': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + + const char *name = "Console"; + if (*value) { + if (!bridge->DescribePlayer(*value, &name, nullptr, nullptr)) + return pCtx->ThrowNativeError("Client index %d is invalid", *value); + } + AddString(&buf_p, llen, name, width, prec); + arg++; + break; + } + case 's': + { + CHECK_ARGS(0); + char *str; + pCtx->LocalToString(params[arg], &str); + AddString(&buf_p, llen, str, width, prec); + arg++; + break; + } + case 'T': + { + CHECK_ARGS(1); + char *key; + bool error; + size_t res; + cell_t *target; + pCtx->LocalToString(params[arg++], &key); + pCtx->LocalToPhysAddr(params[arg++], &target); + res = Translate(buf_p, llen, pCtx, key, *target, params, &arg, &error); + if (error) + { + return 0; + } + buf_p += res; + llen -= res; + break; + } + case 't': + { + CHECK_ARGS(0); + char *key; + bool error; + size_t res; + cell_t target = bridge->GetGlobalTarget(); + pCtx->LocalToString(params[arg++], &key); + res = Translate(buf_p, llen, pCtx, key, target, params, &arg, &error); + if (error) + { + return 0; + } + buf_p += res; + llen -= res; + break; + } + case 'X': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + flags |= UPPERDIGITS; + AddHex(&buf_p, llen, static_cast(*value), width, flags); + arg++; + break; + } + case 'x': + { + CHECK_ARGS(0); + cell_t *value; + pCtx->LocalToPhysAddr(params[arg], &value); + AddHex(&buf_p, llen, static_cast(*value), width, flags); + arg++; + break; + } + case '%': + { + if (!llen) + { + goto done; + } + *buf_p++ = ch; + llen--; + break; + } + case '\0': + { + if (!llen) + { + goto done; + } + *buf_p++ = '%'; + llen--; + goto done; + } + default: + { + if (!llen) + { + goto done; + } + *buf_p++ = ch; + llen--; + break; + } + } + } + +done: + *buf_p = '\0'; + *param = arg; + return (maxlen - llen - 1); +} + diff --git a/core/logic/stringutil.cpp b/core/logic/stringutil.cpp index 7d5050e2d..064211499 100644 --- a/core/logic/stringutil.cpp +++ b/core/logic/stringutil.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,7 +35,7 @@ #include #include "stringutil.h" #include -#include "TextParsers.h" +#include "textparsers.h" // We're in logic so we don't have this from the SDK. #ifndef MIN @@ -98,7 +98,7 @@ unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search } /** - * NOTE: Do not edit this for the love of god unless you have + * NOTE: Do not edit this for the love of god unless you have * read the test cases and understand the code behind each one. * While I don't guarantee there aren't mistakes, I do guarantee * that plugins will end up relying on tiny idiosyncrasies of this @@ -107,7 +107,7 @@ unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search * There are explicitly more cases than the AMX Mod X version because * we're not doing a blind copy. Each case is specifically optimized * for what needs to be done. Even better, we don't have to error on - * bad buffer sizes. Instead, this function will smartly cut off the + * bad buffer sizes. Instead, this function will smartly cut off the * string in a way that pushes old data out. */ char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen, bool caseSensitive) @@ -127,7 +127,7 @@ char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t se */ if (maxLen == 1) { - /* If the search matches and the replace length is 0, + /* If the search matches and the replace length is 0, * we can just terminate the string and be done. */ if ((caseSensitive ? strcmp(subject, search) : strcasecmp(subject, search)) == 0 && replaceLen == 0) @@ -302,7 +302,7 @@ size_t UTIL_DecodeHexString(unsigned char *buffer, size_t maxlength, const char void UTIL_StripExtension(const char *in, char *out, int outSize) { - // Find the last dot. If it's followed by a dot or a slash, then it's part of a + // Find the last dot. If it's followed by a dot or a slash, then it's part of a // directory specifier like ../../somedir/./blah. // scan backward for '.' @@ -348,7 +348,7 @@ char *UTIL_TrimWhitespace(char *str, size_t &len) } /* Replace first whitespace char (at the end) with null terminator. - * If there is none, we're just replacing the null terminator. + * If there is none, we're just replacing the null terminator. */ *(end + 1) = '\0'; diff --git a/core/logic/TextParsers.cpp b/core/logic/textparsers.cpp similarity index 91% rename from core/logic/TextParsers.cpp rename to core/logic/textparsers.cpp index 5f9cea691..93386169b 100644 --- a/core/logic/TextParsers.cpp +++ b/core/logic/textparsers.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,7 +35,7 @@ #include #include #include -#include "TextParsers.h" +#include "textparsers.h" #include #include @@ -200,7 +200,7 @@ SMCError TextParsers::ParseSMCStream(const char *stream, return result; } -/** +/** * Raw parsing of streams with helper functions */ @@ -286,7 +286,7 @@ const char *rotate(StringInfo info[3]) info[1] = info[0]; info[0] = StringInfo(); } - + return NULL; } @@ -322,9 +322,9 @@ char *lowstring(StringInfo info[3]) return NULL; } -SMCError TextParsers::ParseStream_SMC(void *stream, - STREAMREADER srdr, - ITextListener_SMC *smc, +SMCError TextParsers::ParseStream_SMC(void *stream, + STREAMREADER srdr, + ITextListener_SMC *smc, SMCStates *pStates) { char *reparse_point = NULL; @@ -353,11 +353,11 @@ SMCError TextParsers::ParseStream_SMC(void *stream, /** * The stream reader reads in as much as it can fill the buffer with. - * It then processes the buffer. If the buffer cannot be fully processed, for example, - * a line is left hanging with no newline, then the contents of the buffer is shifted + * It then processes the buffer. If the buffer cannot be fully processed, for example, + * a line is left hanging with no newline, then the contents of the buffer is shifted * down, and the buffer is filled from the stream reader again. * - * What makes this particularly annoying is that we cache pointers everywhere, so when + * What makes this particularly annoying is that we cache pointers everywhere, so when * the shifting process takes place, all those pointers must be shifted as well. */ while (srdr(stream, parse_point, sizeof(in_buf) - (parse_point - in_buf) - 1, &read)) @@ -370,9 +370,9 @@ SMCError TextParsers::ParseStream_SMC(void *stream, /* Check for BOM markings, which is only relevant on the first line. * Not worth it, but it could be moved out of the loop. */ - if (states.line == 1 && - in_buf[0] == (char)0xEF && - in_buf[1] == (char)0xBB && + if (states.line == 1 && + in_buf[0] == (char)0xEF && + in_buf[1] == (char)0xBB && in_buf[2] == (char)0xBF) { /* Move EVERYTHING down :\ */ @@ -413,7 +413,7 @@ SMCError TextParsers::ParseStream_SMC(void *stream, ignoring = false; } - /* Pass the raw line onto the listener. We terminate the line so the receiver + /* Pass the raw line onto the listener. We terminate the line so the receiver * doesn't get tons of useless info. We restore the newline after. */ parse_point[i] = '\0'; @@ -448,8 +448,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, states.col = 0; states.line++; line_begin = &parse_point[i+1]; //Note: safe because this gets relocated later - } - else if (ignoring) + } + else if (ignoring) { if (in_quote) { @@ -470,8 +470,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, err = SMCError_InvalidTokens; goto failed; } - } - else if (c == '\\') + } + else if (c == '\\') { strings[0].special = true; if (i == (read - 1)) @@ -480,8 +480,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, break; } } - } - else if (ml_comment) + } + else if (ml_comment) { if (c == '*') { @@ -503,8 +503,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, } } } - } - else + } + else { /* Check if we're whitespace or not */ if (!g_ws_chartable[(unsigned char)c]) @@ -538,8 +538,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, ignoring = true; eol_comment = true; restage = true; - } - else if (parse_point[i+1] == '*') + } + else if (parse_point[i+1] == '*') { /* inline comment - start ignoring */ ignoring = true; @@ -551,15 +551,15 @@ SMCError TextParsers::ParseStream_SMC(void *stream, */ restage = true; } - } - else + } + else { ignoring = true; eol_comment = true; restage = true; } - } - else if (c == '{') + } + else if (c == '{') { /* If we are staging a string, we must rotate here */ if (strings[0].ptr) @@ -576,7 +576,7 @@ SMCError TextParsers::ParseStream_SMC(void *stream, { err = SMCError_InvalidSection1; goto failed; - } + } else if (strings[1].ptr == NULL) { err = SMCError_InvalidSection2; @@ -590,8 +590,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, } strings[1] = emptystring; curlevel++; - } - else if (c == '}') + } + else if (c == '}') { /* Unlike our matching friend, this can be on the same line as something prior */ if (rotate(strings) != NULL) @@ -615,13 +615,13 @@ SMCError TextParsers::ParseStream_SMC(void *stream, err = (res == SMCResult_HaltFail) ? SMCError_Custom : SMCError_Okay; goto failed; } - } - else if (strings[1].ptr) + } + else if (strings[1].ptr) { err = SMCError_InvalidSection3; goto failed; - } - else if (!curlevel) + } + else if (!curlevel) { err = SMCError_InvalidSection4; goto failed; @@ -634,8 +634,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, goto failed; } curlevel--; - } - else if (c == '"') + } + else if (c == '"') { /* If we get a quote mark, we always restage, but we need to do it beforehand */ if (strings[0].ptr) @@ -650,8 +650,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, strings[0].ptr = &parse_point[i]; in_quote = true; ignoring = true; - } - else if (!strings[0].ptr) + } + else if (!strings[0].ptr) { /* If we have no string, we must start one */ strings[0].ptr = &parse_point[i]; @@ -665,8 +665,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, goto failed; } } - } - else + } + else { /* If we're eating a string and get whitespace, we need to restage. * (Note that if we are quoted, this is being ignored) @@ -683,8 +683,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, /* There's no string, so we must move this one down and eat up another */ strings[0].end = &parse_point[i]; rotate(strings); - } - else if (!strings[1].quoted) + } + else if (!strings[1].quoted) { err = SMCError_InvalidTokens; goto failed; @@ -728,8 +728,8 @@ SMCError TextParsers::ParseStream_SMC(void *stream, parse_point = &parse_point[read]; parse_point -= bytes; } - } - else if (read == sizeof(in_buf) - 1) + } + else if (read == sizeof(in_buf) - 1) { err = SMCError_TokenOverflow; goto failed; @@ -741,15 +741,15 @@ SMCError TextParsers::ParseStream_SMC(void *stream, { err = SMCError_InvalidSection5; goto failed; - } - else if (strings[0].ptr || strings[1].ptr) + } + else if (strings[0].ptr || strings[1].ptr) { err = SMCError_InvalidTokens; goto failed; } - + smc->ReadSMC_ParseEnd(false, false); - + if (pStates != NULL) { *pStates = states; @@ -770,7 +770,7 @@ failed: /** - * INI parser + * INI parser */ bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listener, unsigned int *line, unsigned int *col) @@ -806,9 +806,9 @@ bool TextParsers::ParseFile_INI(const char *file, ITextListener_INI *ini_listene //:TODO: this will only run once, so find a nice way to move it out of the while loop /* If this is the first line, check the first three bytes for BOM */ - if (curline == 1 && - buffer[0] == (char)0xEF && - buffer[1] == (char)0xBB && + if (curline == 1 && + buffer[0] == (char)0xEF && + buffer[1] == (char)0xBB && buffer[2] == (char)0xBF) { /* We have a UTF-8 marked file... skip these bytes */ @@ -1073,7 +1073,7 @@ event_failed: const char *TextParsers::GetSMCErrorString(SMCError err) { - static const char *s_errors[] = + static const char *s_errors[] = { NULL, "Stream failed to open", diff --git a/core/logic/TextParsers.h b/core/logic/textparsers.h similarity index 100% rename from core/logic/TextParsers.h rename to core/logic/textparsers.h diff --git a/core/logic/thread/BaseWorker.cpp b/core/logic/thread/baseworker.cpp similarity index 93% rename from core/logic/thread/BaseWorker.cpp rename to core/logic/thread/baseworker.cpp index 019af377e..c3475f0a0 100644 --- a/core/logic/thread/BaseWorker.cpp +++ b/core/logic/thread/baseworker.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,9 +29,9 @@ * Version: $Id$ */ -#include "BaseWorker.h" +#include "baseworker.h" -BaseWorker::BaseWorker(IThreadWorkerCallbacks *hooks) : +BaseWorker::BaseWorker(IThreadWorkerCallbacks *hooks) : m_perFrame(SM_DEFAULT_THREADS_PER_FRAME), m_state(Worker_Stopped), m_pHooks(hooks) @@ -287,7 +287,7 @@ bool SWThreadHandle::WaitForThread() return false; } -SWThreadHandle::SWThreadHandle(IThreadCreator *parent, const ThreadParams *p, IThread *thread) : +SWThreadHandle::SWThreadHandle(IThreadCreator *parent, const ThreadParams *p, IThread *thread) : m_state(Thread_Paused), m_params(*p), m_parent(parent), pThread(thread) { } diff --git a/core/logic/thread/BaseWorker.h b/core/logic/thread/baseworker.h similarity index 96% rename from core/logic/thread/BaseWorker.h rename to core/logic/thread/baseworker.h index 0feceb5f5..10a31cdd7 100644 --- a/core/logic/thread/BaseWorker.h +++ b/core/logic/thread/baseworker.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -33,7 +33,7 @@ #define _INCLUDE_SOURCEMOD_BASEWORKER_H #include "sh_list.h" -#include "ThreadSupport.h" +#include "threadsupport.h" #define SM_DEFAULT_THREADS_PER_FRAME 1 diff --git a/core/logic/thread/PosixThreads.cpp b/core/logic/thread/posixthreads.cpp similarity index 93% rename from core/logic/thread/PosixThreads.cpp rename to core/logic/thread/posixthreads.cpp index 20a81634c..fba55526c 100644 --- a/core/logic/thread/PosixThreads.cpp +++ b/core/logic/thread/posixthreads.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,8 +30,8 @@ */ #include -#include "PosixThreads.h" -#include "ThreadWorker.h" +#include "posixthreads.h" +#include "threadworker.h" IThreadWorker *PosixThreader::MakeWorker(IThreadWorkerCallbacks *hooks, bool threaded) { @@ -128,7 +128,7 @@ IEventSignal *PosixThreader::MakeEventSignal() * Thread Handles * ******************/ -PosixThreader::ThreadHandle::ThreadHandle(IThreader *parent, IThread *run, const ThreadParams *params) : +PosixThreader::ThreadHandle::ThreadHandle(IThreader *parent, IThread *run, const ThreadParams *params) : m_parent(parent), m_params(*params), m_run(run), m_state(Thread_Paused) { } diff --git a/core/logic/thread/PosixThreads.h b/core/logic/thread/posixthreads.h similarity index 100% rename from core/logic/thread/PosixThreads.h rename to core/logic/thread/posixthreads.h diff --git a/core/logic/thread/ThreadWorker.cpp b/core/logic/thread/threadworker.cpp similarity index 94% rename from core/logic/thread/ThreadWorker.cpp rename to core/logic/thread/threadworker.cpp index 20ce55e30..049fe46d9 100644 --- a/core/logic/thread/ThreadWorker.cpp +++ b/core/logic/thread/threadworker.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * Version: $Id$ */ -#include "ThreadWorker.h" +#include "threadworker.h" ThreadWorker::ThreadWorker(IThreadWorkerCallbacks *hooks) : BaseWorker(hooks), m_Threader(NULL), @@ -39,7 +39,7 @@ ThreadWorker::ThreadWorker(IThreadWorkerCallbacks *hooks) : BaseWorker(hooks), m_state = Worker_Invalid; } -ThreadWorker::ThreadWorker(IThreadWorkerCallbacks *hooks, IThreader *pThreader, unsigned int thinktime) : +ThreadWorker::ThreadWorker(IThreadWorkerCallbacks *hooks, IThreader *pThreader, unsigned int thinktime) : BaseWorker(hooks), m_Threader(pThreader), me(NULL), @@ -52,7 +52,7 @@ ThreadWorker::~ThreadWorker() { if (m_state != Worker_Stopped || m_state != Worker_Invalid) Stop(true); - + if (m_ThreadQueue.size()) Flush(true); } @@ -106,7 +106,7 @@ void ThreadWorker::RunThread(IThreadHandle *pHandle) // If the state changed, loop back and process the new state. if (m_state != oldstate) continue; - + // If the thread queue is now empty, wait for a signal. Otherwise, if // we're on a delay, wait for either a notification or a timeout to // process the next item. If the queue has items and we don't have a diff --git a/core/logic/thread/ThreadWorker.h b/core/logic/thread/threadworker.h similarity index 96% rename from core/logic/thread/ThreadWorker.h rename to core/logic/thread/threadworker.h index dd45f76f1..f0ee6ea3d 100644 --- a/core/logic/thread/ThreadWorker.h +++ b/core/logic/thread/threadworker.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -32,7 +32,7 @@ #ifndef _INCLUDE_SOURCEMOD_THREADWORKER_H #define _INCLUDE_SOURCEMOD_THREADWORKER_H -#include "BaseWorker.h" +#include "baseworker.h" #define DEFAULT_THINK_TIME_MS 20 diff --git a/core/logic/thread/WinThreads.cpp b/core/logic/thread/winthreads.cpp similarity index 94% rename from core/logic/thread/WinThreads.cpp rename to core/logic/thread/winthreads.cpp index 4aca8b052..a1e69bd38 100644 --- a/core/logic/thread/WinThreads.cpp +++ b/core/logic/thread/winthreads.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,8 +30,8 @@ */ #define _WIN32_WINNT 0x0400 -#include "WinThreads.h" -#include "ThreadWorker.h" +#include "winthreads.h" +#include "threadworker.h" IThreadWorker *WinThreader::MakeWorker(IThreadWorkerCallbacks *hooks, bool threaded) { @@ -86,7 +86,7 @@ void WinThreader::ThreadHandle::Run() if (m_state == Thread_Paused) suspend_.Wait(); } - + m_run->RunThread(this); m_state = Thread_Done; m_run->OnTerminate(this, false); @@ -130,7 +130,7 @@ IEventSignal *WinThreader::MakeEventSignal() * Thread Handles * ******************/ -WinThreader::ThreadHandle::ThreadHandle(IThreader *parent, IThread *run, const ThreadParams *params) : +WinThreader::ThreadHandle::ThreadHandle(IThreader *parent, IThread *run, const ThreadParams *params) : m_parent(parent), m_run(run), m_params(*params), m_state(Thread_Paused) { diff --git a/core/logic/thread/WinThreads.h b/core/logic/thread/winthreads.h similarity index 100% rename from core/logic/thread/WinThreads.h rename to core/logic/thread/winthreads.h diff --git a/core/logic/ThreadSupport.cpp b/core/logic/threadsupport.cpp similarity index 92% rename from core/logic/ThreadSupport.cpp rename to core/logic/threadsupport.cpp index 55fd03275..98c00feec 100644 --- a/core/logic/ThreadSupport.cpp +++ b/core/logic/threadsupport.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,13 +29,13 @@ * Version: $Id$ */ #include -#include "ThreadSupport.h" +#include "threadsupport.h" #include "common_logic.h" #if defined PLATFORM_POSIX -#include "thread/PosixThreads.h" +#include "thread/posixthreads.h" #elif defined PLATFORM_WINDOWS -#include "thread/WinThreads.h" +#include "thread/winthreads.h" #endif MainThreader g_MainThreader; diff --git a/core/logic/ThreadSupport.h b/core/logic/threadsupport.h similarity index 100% rename from core/logic/ThreadSupport.h rename to core/logic/threadsupport.h diff --git a/core/logic/Translator.cpp b/core/logic/translator.cpp similarity index 92% rename from core/logic/Translator.cpp rename to core/logic/translator.cpp index 8a2945178..d475da29b 100644 --- a/core/logic/Translator.cpp +++ b/core/logic/translator.cpp @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -34,11 +34,11 @@ #include #include #include -#include "Translator.h" +#include "translator.h" #include #include #include -#include "PhraseCollection.h" +#include "phrasecollection.h" #include "stringutil.h" #include "sprintf.h" #include @@ -158,7 +158,7 @@ void CPhraseFile::ReparseFile() continue; } - g_pSM->BuildPath(Path_SM, + g_pSM->BuildPath(Path_SM, path, PLATFORM_MAX_PATH, "translations/%s/%s", @@ -179,8 +179,8 @@ void CPhraseFile::ReparseFile() msg = m_ParseError.c_str(); } - logger->LogError("[SM] Fatal error encountered parsing translation file \"%s/%s\"", - code, + logger->LogError("[SM] Fatal error encountered parsing translation file \"%s/%s\"", + code, m_File.c_str()); logger->LogError("[SM] Error (line %d, column %d): %s", states.line, @@ -208,8 +208,8 @@ SMCResult CPhraseFile::ReadSMC_NewSection(const SMCStates *states, const char *n m_ParseState = PPS_Phrases; recognized = true; } - } - else if (m_ParseState == PPS_Phrases) + } + else if (m_ParseState == PPS_Phrases) { m_ParseState = PPS_InPhrase; recognized = true; @@ -241,8 +241,8 @@ SMCResult CPhraseFile::ReadSMC_NewSection(const SMCStates *states, const char *n } m_LastPhraseString.assign(name); - } - else if (m_ParseState == PPS_InPhrase) + } + else if (m_ParseState == PPS_InPhrase) { ParseError("Phrase sections may not have sub-sections"); return SMCResult_HaltFail; @@ -267,7 +267,7 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key phrase_t *pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase); /* Duplicate format keys get silently ignored. */ - if (key[0] == '#' + if (key[0] == '#' && strcmp(key, "#format") == 0 && pPhrase->fmt_list == -1) { @@ -297,12 +297,12 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key { pPhrase->fmt_count++; state = Parse_Index; - } - else if (*value == ',') + } + else if (*value == ',') { /* Do nothing */ - } - else + } + else { unsigned int bytes = textparsers->GetUTF8CharBytes(value); if (bytes != 1 || !isalpha(*value)) @@ -310,8 +310,8 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key ParseWarning("Invalid token '%c' in #format property on line %d.", *value, states->line); } } - } - else if (state == Parse_Index) + } + else if (state == Parse_Index) { if (*value == ':') { @@ -322,8 +322,8 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key m_CurPhrase = -1; return SMCResult_Continue; } - } - else + } + else { unsigned int bytes = textparsers->GetUTF8CharBytes(value); if (bytes != 1 || !isdigit(*value)) @@ -335,8 +335,8 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key return SMCResult_Continue; } } - } - else if (state == Parse_Format) + } + else if (state == Parse_Format) { if (*value == '}') { @@ -387,7 +387,7 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key idx_ptr = NULL; } } - else if (state == Parse_Index) + else if (state == Parse_Index) { if (*in_ptr == ':') { @@ -405,7 +405,7 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key m_CurPhrase = -1; return SMCResult_Continue; } - else if (fmt_list[idx - 1] != -1) + else if (fmt_list[idx - 1] != -1) { ParseWarning("Format property contains duplicated index '%d' on line %d, phrase will be ignored.", idx, states->line); m_CurPhrase = -1; @@ -415,12 +415,12 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key state = Parse_Format; out_ptr = NULL; } - else if (!idx_ptr) + else if (!idx_ptr) { idx_ptr = in_ptr; } } - else if (state == Parse_Format) + else if (state == Parse_Format) { if (*in_ptr == '}') { @@ -439,8 +439,8 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key pPhrase->fmt_bytes += strlen(fmt_buf); fmt_list = (int *)m_pMemory->GetAddress(pPhrase->fmt_list); fmt_list[cur_idx - 1] = tmp_idx; - } - else + } + else { if (!out_ptr) { @@ -475,8 +475,8 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key return SMCResult_Continue; } } - } - else + } + else { unsigned int lang; if (!m_pTranslator->GetLanguageByCode(key, &lang)) @@ -488,7 +488,7 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key } /* See how many bytes we need for this string, then allocate. - * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK + * NOTE: THIS SHOULD GUARANTEE THAT WE DO NOT NEED TO NEED TO SIZE CHECK */ size_t len = strlen(value) + pPhrase->fmt_bytes + 1; char *out_buf; @@ -512,7 +512,7 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key if (fmt_list) { int tmp = m_pMemory->CreateMem(pPhrase->fmt_count * sizeof(int), (void **)&fmt_order); - + /* Update pointers */ pPhrase = (phrase_t *)m_pMemory->GetAddress(m_CurPhrase); pTrans = (trans_t *)m_pMemory->GetAddress(pPhrase->trans_tbl); @@ -559,8 +559,8 @@ SMCResult CPhraseFile::ReadSMC_KeyValue(const SMCStates *states, const char *key } /* Skip past the last byte read */ in_ptr++; - } - else if (*in_ptr == '{' && fmt_list != NULL) + } + else if (*in_ptr == '{' && fmt_list != NULL) { /* Search for parameters if this is a formatted string */ const char *scrap_in_point = in_ptr; @@ -628,8 +628,8 @@ SMCResult CPhraseFile::ReadSMC_LeavingSection(const SMCStates *states) m_CurPhrase = -1; m_ParseState = PPS_Phrases; m_LastPhraseString.assign(""); - } - else if (m_ParseState == PPS_Phrases) + } + else if (m_ParseState == PPS_Phrases) { m_ParseState = PPS_None; } @@ -702,10 +702,10 @@ Translator::~Translator() delete m_pStringTab; } -ConfigResult Translator::OnSourceModConfigChanged(const char *key, - const char *value, - ConfigSource source, - char *error, +ConfigResult Translator::OnSourceModConfigChanged(const char *key, + const char *value, + ConfigSource source, + char *error, size_t maxlength) { if (strcasecmp(key, "ServerLang") == 0) @@ -807,7 +807,7 @@ unsigned int Translator::FindOrAddPhraseFile(const char *phrase_file) CPhraseFile *pFile = new CPhraseFile(this, phrase_file); unsigned int idx = (unsigned int)m_Files.size(); - + m_Files.push_back(pFile); pFile->ReparseFile(); @@ -941,7 +941,7 @@ bool Translator::AddLanguage(const char *langcode, const char *description) m_Languages.push_back(pLanguage); } - + m_LAliases.insert(lower, idx); return true; @@ -1035,8 +1035,8 @@ bool CoreTranslate(char *buffer, size_t maxlength, const char *format, unsigned va_end(ap); if (!g_pCorePhrases->FormatString(buffer, - maxlength, - format, + maxlength, + format, params, numparams, pOutLength, diff --git a/core/logic/Translator.h b/core/logic/translator.h similarity index 91% rename from core/logic/Translator.h rename to core/logic/translator.h index cd88728f9..8755ec1d0 100644 --- a/core/logic/Translator.h +++ b/core/logic/translator.h @@ -8,7 +8,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -37,9 +37,9 @@ #include #include #include "sm_memtable.h" -#include "ITextParsers.h" +#include #include -#include "PhraseCollection.h" +#include "phrasecollection.h" /* :TODO: write a templatized version of tries? */ @@ -60,7 +60,7 @@ struct Language int m_CanonicalName; }; -class CPhraseFile : +class CPhraseFile : public ITextListener_SMC, public IPhraseFile { @@ -94,7 +94,7 @@ private: bool m_FileLogged; }; -class Translator : +class Translator : public ITextListener_SMC, public SMGlobalClass, public ITranslator @@ -103,10 +103,10 @@ public: Translator(); ~Translator(); public: // SMGlobalClass - ConfigResult OnSourceModConfigChanged(const char *key, - const char *value, - ConfigSource source, - char *error, + ConfigResult OnSourceModConfigChanged(const char *key, + const char *value, + ConfigSource source, + char *error, size_t maxlength); void OnSourceModAllInitialized(); void OnSourceModLevelChange(const char *mapName); @@ -132,8 +132,8 @@ public: //ITranslator int SetGlobalTarget(int index); int GetGlobalTarget() const; size_t FormatString( - char *buffer, - size_t maxlength, + char *buffer, + size_t maxlength, SourcePawn::IPluginContext *pContext, const cell_t *params, unsigned int param); @@ -163,7 +163,7 @@ private: }; /* Nice little wrapper to handle error logging and whatnot */ -bool CoreTranslate(char *buffer, +bool CoreTranslate(char *buffer, size_t maxlength, const char *format, unsigned int numparams,