2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2009 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>.
30 #include "ConVarManager.h"
31 #include "HalfLife2.h"
32 #include "PluginSys.h"
33 #include "ForwardSys.h"
34 #include "HandleSys.h"
35 #include "sm_srvcmds.h"
36 #include "sm_stringutil.h"
37 #include <sh_vector.h>
38 #include <sm_trie_tpl.h>
40 ConVarManager g_ConVarManager;
42 #if SOURCE_ENGINE <= SE_DARKMESSIAH
43 #define CallGlobalChangeCallbacks CallGlobalChangeCallback
46 #if SOURCE_ENGINE >= SE_ORANGEBOX
47 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
49 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *);
52 #if SOURCE_ENGINE != SE_DARKMESSIAH
53 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
54 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 SOURCE_ENGINE == SE_EPISODEONE
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 g_PluginSys.AddPluginsListener(this);
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 g_PluginSys.RemovePluginsListener(this);
167 /* Remove the 'ConVar' handle type */
168 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
172 * Orange Box will never use this.
174 void ConVarManager::OnSourceModVSPReceived()
177 * Don't bother if the DLL is already hooked.
179 if (m_bIsDLLQueryHooked)
184 /* For later MM:S versions, use the updated API, since it's cleaner. */
185 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
186 int engine = g_SMAPI->GetSourceEngineBuild();
187 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
192 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
198 #if SOURCE_ENGINE != SE_DARKMESSIAH
199 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
200 m_bIsVSPQueryHooked = true;
204 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
206 ConVarInfo **pLookup = convar_cache.retrieve(name);
218 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
220 /* Only check convars that have not been created by SourceMod's core */
222 if (!convar_cache_lookup(name, &pInfo))
227 HandleSecurity sec(NULL, g_pCoreIdent);
229 /* Remove it from our cache */
230 m_ConVars.remove(pInfo);
231 convar_cache.remove(name);
233 /* Now make sure no plugins are referring to this pointer */
234 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
235 while (pl_iter->MorePlugins())
237 IPlugin *pl = pl_iter->GetPlugin();
239 ConVarList *pConVarList;
240 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
241 && pConVarList != NULL)
243 pConVarList->remove(pInfo->pVar);
246 pl_iter->NextPlugin();
250 g_HandleSys.FreeHandle(pInfo->handle, &sec);
254 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
256 ConVarList *pConVarList;
257 List<ConVarQuery>::iterator iter;
259 /* If plugin has a convar list, free its memory */
260 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
265 /* Remove convar queries for this plugin that haven't returned results yet */
266 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
268 ConVarQuery &query = (*iter);
269 if (query.pCallback->GetParentRuntime() == plugin->GetRuntime())
271 m_ConVarQueries.erase(iter);
276 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
280 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
282 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
286 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
288 int argcount = command.ArgC();
291 /* Get plugin index that was passed */
292 const char *arg = command.Arg(2);
294 /* Get plugin object */
295 CPlugin *plugin = g_PluginSys.FindPluginByConsoleArg(arg);
299 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
303 /* Get plugin name */
304 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
305 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
307 ConVarList *pConVarList;
308 ConVarList::iterator iter;
310 /* If no convar list... */
311 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
313 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
317 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
318 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
320 /* Iterate convar list and display each one */
321 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
323 const ConVar *pConVar = (*iter);
324 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
330 /* Display usage of subcommand */
331 g_RootMenu.ConsolePrint("[SM] Usage: sm cvars <plugin #>");
334 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)
336 ConVar *pConVar = NULL;
337 ConVarInfo *pInfo = NULL;
340 /* Find out if the convar exists already */
341 pConVar = icvar->FindVar(name);
343 /* If the convar already exists... */
346 /* Add convar to plugin's list */
347 AddConVarToPluginList(pContext, pConVar);
349 /* First find out if we already have a handle to it */
350 if (convar_cache_lookup(name, &pInfo))
352 return pInfo->handle;
356 /* Create and initialize ConVarInfo structure */
357 pInfo = new ConVarInfo();
358 pInfo->sourceMod = false;
359 pInfo->pChangeForward = NULL;
360 pInfo->pVar = pConVar;
362 /* If we don't, then create a new handle from the convar */
363 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
364 if (hndl == BAD_HANDLE)
370 pInfo->handle = hndl;
372 /* Insert struct into caches */
373 m_ConVars.push_back(pInfo);
374 convar_cache.insert(name, pInfo);
375 TrackConCommandBase(pConVar, this);
381 /* Prevent creating a convar that has the same name as a console command */
382 if (FindCommand(name))
387 /* Create and initialize ConVarInfo structure */
388 pInfo = new ConVarInfo();
389 pInfo->handle = hndl;
390 pInfo->sourceMod = true;
391 pInfo->pChangeForward = NULL;
393 /* Create a handle from the new convar */
394 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
395 if (hndl == BAD_HANDLE)
401 pInfo->handle = hndl;
403 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
404 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
405 pInfo->pVar = pConVar;
407 /* Add convar to plugin's list */
408 AddConVarToPluginList(pContext, pConVar);
410 /* Insert struct into caches */
411 m_ConVars.push_back(pInfo);
412 convar_cache.insert(name, pInfo);
417 Handle_t ConVarManager::FindConVar(const char *name)
419 ConVar *pConVar = NULL;
423 /* Search for convar */
424 pConVar = icvar->FindVar(name);
426 /* If it doesn't exist, then return an invalid handle */
432 /* At this point, the convar exists. So, find out if we already have a handle */
433 if (convar_cache_lookup(name, &pInfo))
435 return pInfo->handle;
438 /* Create and initialize ConVarInfo structure */
439 pInfo = new ConVarInfo();
440 pInfo->sourceMod = false;
441 pInfo->pChangeForward = NULL;
442 pInfo->pVar = pConVar;
444 /* If we don't have a handle, then create a new one */
445 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
446 if (hndl == BAD_HANDLE)
452 pInfo->handle = hndl;
454 /* Insert struct into our caches */
455 m_ConVars.push_back(pInfo);
456 convar_cache.insert(name, pInfo);
457 TrackConCommandBase(pConVar, this);
462 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
466 if (FindConVar(name) == BAD_HANDLE)
471 /* Find the convar in the lookup trie */
472 if (convar_cache_lookup(name, &pInfo))
474 pInfo->changeListeners.push_back(pListener);
478 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
482 /* Find the convar in the lookup trie */
483 if (convar_cache_lookup(name, &pInfo))
485 pInfo->changeListeners.remove(pListener);
489 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
492 IChangeableForward *pForward;
494 /* Find the convar in the lookup trie */
495 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
497 /* Get the forward */
498 pForward = pInfo->pChangeForward;
500 /* If forward does not exist, create it */
503 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
504 pInfo->pChangeForward = pForward;
507 /* Add function to forward's list */
508 pForward->AddFunction(pFunction);
512 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
515 IChangeableForward *pForward;
516 IPluginContext *pContext = pFunction->GetParentContext();
518 /* Find the convar in the lookup trie */
519 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
521 /* Get the forward */
522 pForward = pInfo->pChangeForward;
524 /* If the forward doesn't exist, we can't unhook anything */
527 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
531 /* Remove the function from the forward's list */
532 if (!pForward->RemoveFunction(pFunction))
534 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
538 /* If the forward now has 0 functions in it... */
539 if (pForward->GetFunctionCount() == 0)
541 /* Free this forward */
542 g_Forwards.ReleaseForward(pForward);
543 pInfo->pChangeForward = NULL;
548 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
550 QueryCvarCookie_t cookie = 0;
552 #if SOURCE_ENGINE != SE_DARKMESSIAH
553 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
554 if (m_bIsDLLQueryHooked)
556 cookie = engine->StartQueryCvarValue(pPlayer, name);
558 else if (m_bIsVSPQueryHooked)
560 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
564 return InvalidQueryCvarCookie;
567 ConVarQuery query = {cookie, pCallback, hndl};
568 m_ConVarQueries.push_back(query);
574 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
576 ConVarList *pConVarList;
577 ConVarList::iterator iter;
578 bool inserted = false;
579 const char *orig = pConVar->GetName();
581 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
583 /* Check plugin for an existing convar list */
584 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
586 pConVarList = new ConVarList();
587 plugin->SetProperty("ConVarList", pConVarList);
589 else if (pConVarList->find(pConVar) != pConVarList->end())
591 /* If convar is already in list, then don't add it */
595 /* Insert convar into list which is sorted alphabetically */
596 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
598 if (strcmp(orig, (*iter)->GetName()) < 0)
600 pConVarList->insert(iter, pConVar);
608 pConVarList->push_back(pConVar);
612 #if SOURCE_ENGINE >= SE_ORANGEBOX
613 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
615 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
618 /* If the values are the same, exit early in order to not trigger callbacks */
619 if (strcmp(pConVar->GetString(), oldValue) == 0)
626 /* Find the convar in the lookup trie */
627 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
632 IChangeableForward *pForward = pInfo->pChangeForward;
634 if (pInfo->changeListeners.size() != 0)
636 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
637 i != pInfo->changeListeners.end();
640 #if SOURCE_ENGINE >= SE_ORANGEBOX
641 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
643 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
648 if (pForward != NULL)
650 /* Now call forwards in plugins that have hooked this */
651 pForward->PushCell(pInfo->handle);
652 pForward->PushString(oldValue);
653 pForward->PushString(pConVar->GetString());
654 pForward->Execute(NULL);
658 bool ConVarManager::IsQueryingSupported()
660 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
663 #if SOURCE_ENGINE != SE_DARKMESSIAH
664 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
666 IPluginFunction *pCallback = NULL;
668 List<ConVarQuery>::iterator iter;
670 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
672 ConVarQuery &query = (*iter);
673 if (query.cookie == cookie)
675 pCallback = query.pCallback;
685 pCallback->PushCell(cookie);
686 pCallback->PushCell(IndexOfEdict(pPlayer));
687 pCallback->PushCell(result);
688 pCallback->PushString(cvarName);
690 if (result == eQueryCvarValueStatus_ValueIntact)
692 pCallback->PushString(cvarValue);
696 pCallback->PushString("\0");
699 pCallback->PushCell(value);
700 pCallback->Execute(&ret);
702 m_ConVarQueries.erase(iter);
707 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
712 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)