reworked antiflood. it now has some logic in core to take care of loading order nastiness, and to fully prevent trigger spamming
3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
32 #include "ConVarManager.h"
33 #include "HalfLife2.h"
34 #include "PluginSys.h"
35 #include "ForwardSys.h"
36 #include "HandleSys.h"
37 #include "sm_srvcmds.h"
38 #include "sm_stringutil.h"
39 #include <sh_vector.h>
40 #include <sm_trie_tpl.h>
42 ConVarManager g_ConVarManager;
44 #if !defined ORANGEBOX_BUILD
45 #define CallGlobalChangeCallbacks CallGlobalChangeCallback
48 #if defined ORANGEBOX_BUILD
49 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
51 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *);
54 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
55 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
57 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
58 typedef List<const ConVar *> ConVarList;
59 KTrie<ConVarInfo *> convar_cache;
61 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
65 ConVarManager::~ConVarManager()
69 void ConVarManager::OnSourceModStartup(bool late)
73 /* Set up access rights for the 'ConVar' handle type */
74 sec.access[HandleAccess_Read] = 0;
75 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
76 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
78 /* Create the 'ConVar' handle type */
79 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
82 void ConVarManager::OnSourceModAllInitialized()
85 * Episode 2 has this function by default, but the older versions do not.
87 #if !defined ORANGEBOX_BUILD
88 if (g_SMAPI->GetGameDLLVersion() >= 6)
90 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
91 m_bIsDLLQueryHooked = true;
95 SH_ADD_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
97 /* Add the 'convars' option to the 'sm' console command */
98 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
101 void ConVarManager::OnSourceModShutdown()
103 List<ConVarInfo *>::iterator iter = m_ConVars.begin();
104 HandleSecurity sec(NULL, g_pCoreIdent);
106 /* Iterate list of ConVarInfo structures, remove every one of them */
107 while (iter != m_ConVars.end())
109 ConVarInfo *pInfo = (*iter);
111 iter = m_ConVars.erase(iter);
113 g_HandleSys.FreeHandle(pInfo->handle, &sec);
114 if (pInfo->pChangeForward != NULL)
116 g_Forwards.ReleaseForward(pInfo->pChangeForward);
118 if (pInfo->sourceMod)
120 /* If we created it, we won't be tracking it, therefore it is
121 * safe to remove everything in one go.
123 META_UNREGCVAR(pInfo->pVar);
124 delete [] pInfo->pVar->GetName();
125 delete [] pInfo->pVar->GetHelpText();
126 delete [] pInfo->pVar->GetDefault();
131 /* If we didn't create it, we might be tracking it. Also,
132 * it could be unreadable.
134 UntrackConCommandBase(pInfo->pVar, this);
137 /* It's not safe to read the name here, so we simply delete the
138 * the info struct and clear the lookup cache at the end.
142 convar_cache.clear();
145 if (m_bIsDLLQueryHooked)
147 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
148 m_bIsDLLQueryHooked = false;
150 else if (m_bIsVSPQueryHooked)
152 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
153 m_bIsVSPQueryHooked = false;
156 SH_REMOVE_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
158 /* Remove the 'convars' option from the 'sm' console command */
159 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
161 /* Remove the 'ConVar' handle type */
162 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
166 * Orange Box will never use this.
168 void ConVarManager::OnSourceModVSPReceived()
171 * Don't bother if the DLL is already hooked.
173 if (m_bIsDLLQueryHooked)
178 /* For later MM:S versions, use the updated API, since it's cleaner. */
179 #if defined METAMOD_PLAPI_VERSION
180 int engine = g_SMAPI->GetSourceEngineBuild();
181 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
186 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
192 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
193 m_bIsVSPQueryHooked = true;
196 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
198 ConVarInfo **pLookup = convar_cache.retrieve(name);
210 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
212 /* Only check convars that have not been created by SourceMod's core */
214 if (!convar_cache_lookup(name, &pInfo))
219 HandleSecurity sec(NULL, g_pCoreIdent);
221 /* Remove it from our cache */
222 m_ConVars.remove(pInfo);
223 convar_cache.remove(name);
225 /* Now make sure no plugins are referring to this pointer */
226 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
227 while (pl_iter->MorePlugins())
229 IPlugin *pl = pl_iter->GetPlugin();
231 ConVarList *pConVarList;
232 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
233 && pConVarList != NULL)
235 pConVarList->remove(pInfo->pVar);
238 pl_iter->NextPlugin();
242 g_HandleSys.FreeHandle(pInfo->handle, &sec);
246 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
248 ConVarList *pConVarList;
250 /* If plugin has a convar list, free its memory */
251 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
257 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
261 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
263 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
267 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
269 int argcount = command.ArgC();
272 /* Get plugin index that was passed */
273 const char *arg = command.Arg(2);
275 /* Get plugin object */
276 CPlugin *plugin = g_PluginSys.FindPluginByConsoleArg(arg);
280 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
284 /* Get plugin name */
285 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
286 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
288 ConVarList *pConVarList;
289 ConVarList::iterator iter;
291 /* If no convar list... */
292 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
294 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
298 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
299 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
301 /* Iterate convar list and display each one */
302 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
304 const ConVar *pConVar = (*iter);
305 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
311 /* Display usage of subcommand */
312 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
315 Handle_t ConVarManager::CreateConVar(IPluginContext *pContext, const char *name, const char *defaultVal, const char *description, int flags, bool hasMin, float min, bool hasMax, float max)
317 ConVar *pConVar = NULL;
318 ConVarInfo *pInfo = NULL;
321 /* Find out if the convar exists already */
322 pConVar = icvar->FindVar(name);
324 /* If the convar already exists... */
327 /* Add convar to plugin's list */
328 AddConVarToPluginList(pContext, pConVar);
330 /* First find out if we already have a handle to it */
331 if (convar_cache_lookup(name, &pInfo))
333 return pInfo->handle;
337 /* Create and initialize ConVarInfo structure */
338 pInfo = new ConVarInfo();
339 pInfo->sourceMod = false;
340 pInfo->pChangeForward = NULL;
341 pInfo->pVar = pConVar;
343 /* If we don't, then create a new handle from the convar */
344 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
345 if (hndl == BAD_HANDLE)
351 pInfo->handle = hndl;
353 /* Insert struct into caches */
354 m_ConVars.push_back(pInfo);
355 convar_cache.insert(name, pInfo);
356 TrackConCommandBase(pConVar, this);
362 /* To prevent creating a convar that has the same name as a console command... ugh */
363 ConCommandBase *pBase = icvar->GetCommands();
367 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
372 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
375 /* Create and initialize ConVarInfo structure */
376 pInfo = new ConVarInfo();
377 pInfo->handle = hndl;
378 pInfo->sourceMod = true;
379 pInfo->pChangeForward = NULL;
381 /* Create a handle from the new convar */
382 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
383 if (hndl == BAD_HANDLE)
389 pInfo->handle = hndl;
391 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
392 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
393 pInfo->pVar = pConVar;
395 /* Add convar to plugin's list */
396 AddConVarToPluginList(pContext, pConVar);
398 /* Insert struct into caches */
399 m_ConVars.push_back(pInfo);
400 convar_cache.insert(name, pInfo);
405 Handle_t ConVarManager::FindConVar(const char *name)
407 ConVar *pConVar = NULL;
411 /* Search for convar */
412 pConVar = icvar->FindVar(name);
414 /* If it doesn't exist, then return an invalid handle */
420 /* At this point, the convar exists. So, find out if we already have a handle */
421 if (convar_cache_lookup(name, &pInfo))
423 return pInfo->handle;
426 /* Create and initialize ConVarInfo structure */
427 pInfo = new ConVarInfo();
428 pInfo->sourceMod = false;
429 pInfo->pChangeForward = NULL;
430 pInfo->pVar = pConVar;
432 /* If we don't have a handle, then create a new one */
433 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
434 if (hndl == BAD_HANDLE)
440 pInfo->handle = hndl;
442 /* Insert struct into our caches */
443 m_ConVars.push_back(pInfo);
444 convar_cache.insert(name, pInfo);
445 TrackConCommandBase(pConVar, this);
450 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
454 if (FindConVar(name) == BAD_HANDLE)
459 /* Find the convar in the lookup trie */
460 if (convar_cache_lookup(name, &pInfo))
462 pInfo->changeListeners.push_back(pListener);
466 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
470 /* Find the convar in the lookup trie */
471 if (convar_cache_lookup(name, &pInfo))
473 pInfo->changeListeners.remove(pListener);
477 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
480 IChangeableForward *pForward;
482 /* Find the convar in the lookup trie */
483 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
485 /* Get the forward */
486 pForward = pInfo->pChangeForward;
488 /* If forward does not exist, create it */
491 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
492 pInfo->pChangeForward = pForward;
495 /* Add function to forward's list */
496 pForward->AddFunction(pFunction);
500 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
503 IChangeableForward *pForward;
504 IPluginContext *pContext = pFunction->GetParentContext();
506 /* Find the convar in the lookup trie */
507 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
509 /* Get the forward */
510 pForward = pInfo->pChangeForward;
512 /* If the forward doesn't exist, we can't unhook anything */
515 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
519 /* Remove the function from the forward's list */
520 if (!pForward->RemoveFunction(pFunction))
522 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
526 /* If the forward now has 0 functions in it... */
527 if (pForward->GetFunctionCount() == 0)
529 /* Free this forward */
530 g_Forwards.ReleaseForward(pForward);
531 pInfo->pChangeForward = NULL;
536 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
538 QueryCvarCookie_t cookie;
540 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
541 if (m_bIsDLLQueryHooked)
543 cookie = engine->StartQueryCvarValue(pPlayer, name);
545 else if (m_bIsVSPQueryHooked)
547 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
551 return InvalidQueryCvarCookie;
554 ConVarQuery query = {cookie, pCallback, hndl};
555 m_ConVarQueries.push_back(query);
560 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
562 ConVarList *pConVarList;
563 ConVarList::iterator iter;
564 bool inserted = false;
565 const char *orig = pConVar->GetName();
567 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
569 /* Check plugin for an existing convar list */
570 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
572 pConVarList = new ConVarList();
573 plugin->SetProperty("ConVarList", pConVarList);
575 else if (pConVarList->find(pConVar) != pConVarList->end())
577 /* If convar is already in list, then don't add it */
581 /* Insert convar into list which is sorted alphabetically */
582 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
584 if (strcmp(orig, (*iter)->GetName()) < 0)
586 pConVarList->insert(iter, pConVar);
594 pConVarList->push_back(pConVar);
598 #if defined ORANGEBOX_BUILD
599 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
601 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
604 /* If the values are the same, exit early in order to not trigger callbacks */
605 if (strcmp(pConVar->GetString(), oldValue) == 0)
612 /* Find the convar in the lookup trie */
613 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
618 IChangeableForward *pForward = pInfo->pChangeForward;
620 if (pInfo->changeListeners.size() != 0)
622 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
623 i != pInfo->changeListeners.end();
626 #if defined ORANGEBOX_BUILD
627 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
629 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
634 if (pForward != NULL)
636 /* Now call forwards in plugins that have hooked this */
637 pForward->PushCell(pInfo->handle);
638 pForward->PushString(oldValue);
639 pForward->PushString(pConVar->GetString());
640 pForward->Execute(NULL);
644 bool ConVarManager::IsQueryingSupported()
646 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
649 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
651 IPluginFunction *pCallback = NULL;
653 List<ConVarQuery>::iterator iter;
655 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
657 ConVarQuery &query = (*iter);
658 if (query.cookie == cookie)
660 pCallback = query.pCallback;
670 pCallback->PushCell(cookie);
671 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
672 pCallback->PushCell(result);
673 pCallback->PushString(cvarName);
675 if (result == eQueryCvarValueStatus_ValueIntact)
677 pCallback->PushString(cvarValue);
681 pCallback->PushString("\0");
684 pCallback->PushCell(value);
685 pCallback->Execute(&ret);
687 m_ConVarQueries.erase(iter);
691 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
696 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)