3 * =============================================================================
5 * Copyright (C) 2004-2008 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 SOURCE_ENGINE <= SE_DARKMESSIAH
45 #define CallGlobalChangeCallbacks CallGlobalChangeCallback
48 #if SOURCE_ENGINE >= SE_ORANGEBOX
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 #if SOURCE_ENGINE != SE_DARKMESSIAH
55 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
56 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
59 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
60 typedef List<const ConVar *> ConVarList;
61 KTrie<ConVarInfo *> convar_cache;
63 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
67 ConVarManager::~ConVarManager()
71 void ConVarManager::OnSourceModStartup(bool late)
75 /* Set up access rights for the 'ConVar' handle type */
76 sec.access[HandleAccess_Read] = 0;
77 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
78 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
80 /* Create the 'ConVar' handle type */
81 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
84 void ConVarManager::OnSourceModAllInitialized()
87 * Episode 2 has this function by default, but the older versions do not.
89 #if SOURCE_ENGINE == SE_EPISODEONE
90 if (g_SMAPI->GetGameDLLVersion() >= 6)
92 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
93 m_bIsDLLQueryHooked = true;
97 SH_ADD_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
99 /* Add the 'convars' option to the 'sm' console command */
100 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
103 void ConVarManager::OnSourceModShutdown()
105 List<ConVarInfo *>::iterator iter = m_ConVars.begin();
106 HandleSecurity sec(NULL, g_pCoreIdent);
108 /* Iterate list of ConVarInfo structures, remove every one of them */
109 while (iter != m_ConVars.end())
111 ConVarInfo *pInfo = (*iter);
113 iter = m_ConVars.erase(iter);
115 g_HandleSys.FreeHandle(pInfo->handle, &sec);
116 if (pInfo->pChangeForward != NULL)
118 g_Forwards.ReleaseForward(pInfo->pChangeForward);
120 if (pInfo->sourceMod)
122 /* If we created it, we won't be tracking it, therefore it is
123 * safe to remove everything in one go.
125 META_UNREGCVAR(pInfo->pVar);
126 delete [] pInfo->pVar->GetName();
127 delete [] pInfo->pVar->GetHelpText();
128 delete [] pInfo->pVar->GetDefault();
133 /* If we didn't create it, we might be tracking it. Also,
134 * it could be unreadable.
136 UntrackConCommandBase(pInfo->pVar, this);
139 /* It's not safe to read the name here, so we simply delete the
140 * the info struct and clear the lookup cache at the end.
144 convar_cache.clear();
146 #if SOURCE_ENGINE != SE_DARKMESSIAH
148 if (m_bIsDLLQueryHooked)
150 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
151 m_bIsDLLQueryHooked = false;
153 else if (m_bIsVSPQueryHooked)
155 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
156 m_bIsVSPQueryHooked = false;
160 SH_REMOVE_HOOK_STATICFUNC(ICvar, CallGlobalChangeCallbacks, icvar, OnConVarChanged, false);
162 /* Remove the 'convars' option from the 'sm' console command */
163 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
165 /* Remove the 'ConVar' handle type */
166 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
170 * Orange Box will never use this.
172 void ConVarManager::OnSourceModVSPReceived()
175 * Don't bother if the DLL is already hooked.
177 if (m_bIsDLLQueryHooked)
182 /* For later MM:S versions, use the updated API, since it's cleaner. */
183 #if defined METAMOD_PLAPI_VERSION
184 int engine = g_SMAPI->GetSourceEngineBuild();
185 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
190 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
196 #if SOURCE_ENGINE != SE_DARKMESSIAH
197 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
198 m_bIsVSPQueryHooked = true;
202 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
204 ConVarInfo **pLookup = convar_cache.retrieve(name);
216 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
218 /* Only check convars that have not been created by SourceMod's core */
220 if (!convar_cache_lookup(name, &pInfo))
225 HandleSecurity sec(NULL, g_pCoreIdent);
227 /* Remove it from our cache */
228 m_ConVars.remove(pInfo);
229 convar_cache.remove(name);
231 /* Now make sure no plugins are referring to this pointer */
232 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
233 while (pl_iter->MorePlugins())
235 IPlugin *pl = pl_iter->GetPlugin();
237 ConVarList *pConVarList;
238 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
239 && pConVarList != NULL)
241 pConVarList->remove(pInfo->pVar);
244 pl_iter->NextPlugin();
248 g_HandleSys.FreeHandle(pInfo->handle, &sec);
252 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
254 ConVarList *pConVarList;
256 /* If plugin has a convar list, free its memory */
257 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
263 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
267 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
269 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
273 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
275 int argcount = command.ArgC();
278 /* Get plugin index that was passed */
279 const char *arg = command.Arg(2);
281 /* Get plugin object */
282 CPlugin *plugin = g_PluginSys.FindPluginByConsoleArg(arg);
286 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
290 /* Get plugin name */
291 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
292 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
294 ConVarList *pConVarList;
295 ConVarList::iterator iter;
297 /* If no convar list... */
298 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
300 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
304 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
305 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
307 /* Iterate convar list and display each one */
308 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
310 const ConVar *pConVar = (*iter);
311 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
317 /* Display usage of subcommand */
318 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
321 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)
323 ConVar *pConVar = NULL;
324 ConVarInfo *pInfo = NULL;
327 /* Find out if the convar exists already */
328 pConVar = icvar->FindVar(name);
330 /* If the convar already exists... */
333 /* Add convar to plugin's list */
334 AddConVarToPluginList(pContext, pConVar);
336 /* First find out if we already have a handle to it */
337 if (convar_cache_lookup(name, &pInfo))
339 return pInfo->handle;
343 /* Create and initialize ConVarInfo structure */
344 pInfo = new ConVarInfo();
345 pInfo->sourceMod = false;
346 pInfo->pChangeForward = NULL;
347 pInfo->pVar = pConVar;
349 /* If we don't, then create a new handle from the convar */
350 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
351 if (hndl == BAD_HANDLE)
357 pInfo->handle = hndl;
359 /* Insert struct into caches */
360 m_ConVars.push_back(pInfo);
361 convar_cache.insert(name, pInfo);
362 TrackConCommandBase(pConVar, this);
368 /* Prevent creating a convar that has the same name as a console command */
369 if (FindCommand(name))
374 /* Create and initialize ConVarInfo structure */
375 pInfo = new ConVarInfo();
376 pInfo->handle = hndl;
377 pInfo->sourceMod = true;
378 pInfo->pChangeForward = NULL;
380 /* Create a handle from the new convar */
381 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
382 if (hndl == BAD_HANDLE)
388 pInfo->handle = hndl;
390 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
391 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
392 pInfo->pVar = pConVar;
394 /* Add convar to plugin's list */
395 AddConVarToPluginList(pContext, pConVar);
397 /* Insert struct into caches */
398 m_ConVars.push_back(pInfo);
399 convar_cache.insert(name, pInfo);
404 Handle_t ConVarManager::FindConVar(const char *name)
406 ConVar *pConVar = NULL;
410 /* Search for convar */
411 pConVar = icvar->FindVar(name);
413 /* If it doesn't exist, then return an invalid handle */
419 /* At this point, the convar exists. So, find out if we already have a handle */
420 if (convar_cache_lookup(name, &pInfo))
422 return pInfo->handle;
425 /* Create and initialize ConVarInfo structure */
426 pInfo = new ConVarInfo();
427 pInfo->sourceMod = false;
428 pInfo->pChangeForward = NULL;
429 pInfo->pVar = pConVar;
431 /* If we don't have a handle, then create a new one */
432 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
433 if (hndl == BAD_HANDLE)
439 pInfo->handle = hndl;
441 /* Insert struct into our caches */
442 m_ConVars.push_back(pInfo);
443 convar_cache.insert(name, pInfo);
444 TrackConCommandBase(pConVar, this);
449 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
453 if (FindConVar(name) == BAD_HANDLE)
458 /* Find the convar in the lookup trie */
459 if (convar_cache_lookup(name, &pInfo))
461 pInfo->changeListeners.push_back(pListener);
465 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
469 /* Find the convar in the lookup trie */
470 if (convar_cache_lookup(name, &pInfo))
472 pInfo->changeListeners.remove(pListener);
476 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
479 IChangeableForward *pForward;
481 /* Find the convar in the lookup trie */
482 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
484 /* Get the forward */
485 pForward = pInfo->pChangeForward;
487 /* If forward does not exist, create it */
490 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
491 pInfo->pChangeForward = pForward;
494 /* Add function to forward's list */
495 pForward->AddFunction(pFunction);
499 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
502 IChangeableForward *pForward;
503 IPluginContext *pContext = pFunction->GetParentContext();
505 /* Find the convar in the lookup trie */
506 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
508 /* Get the forward */
509 pForward = pInfo->pChangeForward;
511 /* If the forward doesn't exist, we can't unhook anything */
514 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
518 /* Remove the function from the forward's list */
519 if (!pForward->RemoveFunction(pFunction))
521 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
525 /* If the forward now has 0 functions in it... */
526 if (pForward->GetFunctionCount() == 0)
528 /* Free this forward */
529 g_Forwards.ReleaseForward(pForward);
530 pInfo->pChangeForward = NULL;
535 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
537 QueryCvarCookie_t cookie = 0;
539 #if SOURCE_ENGINE != SE_DARKMESSIAH
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);
561 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
563 ConVarList *pConVarList;
564 ConVarList::iterator iter;
565 bool inserted = false;
566 const char *orig = pConVar->GetName();
568 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
570 /* Check plugin for an existing convar list */
571 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
573 pConVarList = new ConVarList();
574 plugin->SetProperty("ConVarList", pConVarList);
576 else if (pConVarList->find(pConVar) != pConVarList->end())
578 /* If convar is already in list, then don't add it */
582 /* Insert convar into list which is sorted alphabetically */
583 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
585 if (strcmp(orig, (*iter)->GetName()) < 0)
587 pConVarList->insert(iter, pConVar);
595 pConVarList->push_back(pConVar);
599 #if SOURCE_ENGINE >= SE_ORANGEBOX
600 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
602 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
605 /* If the values are the same, exit early in order to not trigger callbacks */
606 if (strcmp(pConVar->GetString(), oldValue) == 0)
613 /* Find the convar in the lookup trie */
614 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
619 IChangeableForward *pForward = pInfo->pChangeForward;
621 if (pInfo->changeListeners.size() != 0)
623 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
624 i != pInfo->changeListeners.end();
627 #if SOURCE_ENGINE >= SE_ORANGEBOX
628 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
630 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
635 if (pForward != NULL)
637 /* Now call forwards in plugins that have hooked this */
638 pForward->PushCell(pInfo->handle);
639 pForward->PushString(oldValue);
640 pForward->PushString(pConVar->GetString());
641 pForward->Execute(NULL);
645 bool ConVarManager::IsQueryingSupported()
647 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
650 #if SOURCE_ENGINE != SE_DARKMESSIAH
651 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
653 IPluginFunction *pCallback = NULL;
655 List<ConVarQuery>::iterator iter;
657 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
659 ConVarQuery &query = (*iter);
660 if (query.cookie == cookie)
662 pCallback = query.pCallback;
672 pCallback->PushCell(cookie);
673 pCallback->PushCell(IndexOfEdict(pPlayer));
674 pCallback->PushCell(result);
675 pCallback->PushString(cvarName);
677 if (result == eQueryCvarValueStatus_ValueIntact)
679 pCallback->PushString(cvarValue);
683 pCallback->PushString("\0");
686 pCallback->PushCell(value);
687 pCallback->Execute(&ret);
689 m_ConVarQueries.erase(iter);
694 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
699 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)