core/ConVarManager.cpp
author Ruben Gonzalez <drifter01620@gmail.com>
Thu Feb 13 12:12:36 2014 -0500 (2014-02-13)
changeset 4251 9290c598d3cb
parent 4139 de7d1cd00703
child 4257 fbe69cd9afdf
permissions -rw-r--r--
Update CSSDM gdc patch bytes (NPOTB)
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2009 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  */
    29 
    30 #include "ConVarManager.h"
    31 #include "HalfLife2.h"
    32 #include "sm_srvcmds.h"
    33 #include "sm_stringutil.h"
    34 #include <sh_vector.h>
    35 #include <sm_namehashset.h>
    36 #include "logic_bridge.h"
    37 
    38 ConVarManager g_ConVarManager;
    39 
    40 #if SOURCE_ENGINE >= SE_ORANGEBOX
    41 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
    42 #else
    43 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallback, SH_NOATTRIB, false, ConVar *, const char *);
    44 #endif
    45 
    46 #if SOURCE_ENGINE == SE_DOTA
    47 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, CEntityIndex, EQueryCvarValueStatus, const char *, const char *);
    48 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, CEntityIndex, EQueryCvarValueStatus, const char *, const char *);
    49 #elif SOURCE_ENGINE != SE_DARKMESSIAH
    50 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
    51 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
    52 #endif
    53 
    54 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
    55 typedef List<const ConVar *> ConVarList;
    56 NameHashSet<ConVarInfo *> convar_cache;
    57 
    58 class ConVarReentrancyGuard
    59 {
    60 	ConVar *cvar;
    61 	ConVarReentrancyGuard *up;
    62 public:
    63 	static ConVarReentrancyGuard *chain;
    64 
    65 	ConVarReentrancyGuard(ConVar *cvar)
    66 		: cvar(cvar), up(chain)
    67 	{
    68 		chain = this;
    69 	}
    70 
    71 	~ConVarReentrancyGuard()
    72 	{
    73 		assert(chain == this);
    74 		chain = up;
    75 	}
    76 
    77 	static bool IsCvarInChain(ConVar *cvar)
    78 	{
    79 		ConVarReentrancyGuard *guard = chain;
    80 		while (guard != NULL)
    81 		{
    82 			if (guard->cvar == cvar)
    83 				return true;
    84 			guard = guard->up;
    85 		}
    86 		return false;
    87 	}
    88 };
    89 
    90 ConVarReentrancyGuard *ConVarReentrancyGuard::chain = NULL;
    91 
    92 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
    93 {
    94 }
    95 
    96 ConVarManager::~ConVarManager()
    97 {
    98 }
    99 
   100 void ConVarManager::OnSourceModStartup(bool late)
   101 {
   102 	HandleAccess sec;
   103 
   104 	/* Set up access rights for the 'ConVar' handle type */
   105 	sec.access[HandleAccess_Read] = 0;
   106 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
   107 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
   108 
   109 	/* Create the 'ConVar' handle type */
   110 	m_ConVarType = handlesys->CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
   111 }
   112 
   113 void ConVarManager::OnSourceModAllInitialized()
   114 {
   115 	/**
   116 	 * Episode 2 has this function by default, but the older versions do not.
   117 	 */
   118 #if SOURCE_ENGINE == SE_EPISODEONE
   119 	if (g_SMAPI->GetGameDLLVersion() >= 6)
   120 	{
   121 		SH_ADD_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
   122 		m_bIsDLLQueryHooked = true;
   123 	}
   124 #endif
   125 
   126 #if SOURCE_ENGINE >= SE_ORANGEBOX
   127 	SH_ADD_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
   128 #else
   129 	SH_ADD_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
   130 #endif
   131 
   132 	scripts->AddPluginsListener(this);
   133 
   134 	/* Add the 'convars' option to the 'sm' console command */
   135 	g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
   136 }
   137 
   138 void ConVarManager::OnSourceModShutdown()
   139 {
   140 	List<ConVarInfo *>::iterator iter = m_ConVars.begin();
   141 	HandleSecurity sec(NULL, g_pCoreIdent);
   142 
   143 	/* Iterate list of ConVarInfo structures, remove every one of them */
   144 	while (iter != m_ConVars.end())
   145 	{
   146 		ConVarInfo *pInfo = (*iter);
   147 
   148 		iter = m_ConVars.erase(iter);
   149 
   150 		handlesys->FreeHandle(pInfo->handle, &sec);
   151 		if (pInfo->pChangeForward != NULL)
   152 		{
   153 			forwardsys->ReleaseForward(pInfo->pChangeForward);
   154 		}
   155 		if (pInfo->sourceMod)
   156 		{
   157 			/* If we created it, we won't be tracking it, therefore it is 
   158 			 * safe to remove everything in one go.
   159 			 */
   160 			META_UNREGCVAR(pInfo->pVar);
   161 			delete [] pInfo->pVar->GetName();
   162 			delete [] pInfo->pVar->GetHelpText();
   163 			delete [] pInfo->pVar->GetDefault();
   164 			delete pInfo->pVar;
   165 		}
   166 		else
   167 		{
   168 			/* If we didn't create it, we might be tracking it.  Also, 
   169 			 * it could be unreadable.
   170 			 */
   171 			UntrackConCommandBase(pInfo->pVar, this);
   172 		}
   173 
   174 		/* It's not safe to read the name here, so we simply delete the 
   175 		 * the info struct and clear the lookup cache at the end.
   176 		 */
   177 		delete pInfo;
   178 	}
   179 	convar_cache.clear();
   180 
   181 #if SOURCE_ENGINE != SE_DARKMESSIAH
   182 	/* Unhook things */
   183 	if (m_bIsDLLQueryHooked)
   184 	{
   185 		SH_REMOVE_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
   186 		m_bIsDLLQueryHooked = false;
   187 	}
   188 	else if (m_bIsVSPQueryHooked)
   189 	{
   190 #if SOURCE_ENGINE != SE_DOTA
   191 		SH_REMOVE_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
   192 #endif
   193 		m_bIsVSPQueryHooked = false;
   194 	}
   195 #endif
   196 
   197 #if SOURCE_ENGINE >= SE_ORANGEBOX
   198 	SH_REMOVE_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
   199 #else
   200 	SH_REMOVE_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
   201 #endif
   202 
   203 	/* Remove the 'convars' option from the 'sm' console command */
   204 	g_RootMenu.RemoveRootConsoleCommand("cvars", this);
   205 
   206 	scripts->RemovePluginsListener(this);
   207 
   208 	/* Remove the 'ConVar' handle type */
   209 	handlesys->RemoveType(m_ConVarType, g_pCoreIdent);
   210 }
   211 
   212 /**
   213  * Orange Box will never use this.
   214  */
   215 void ConVarManager::OnSourceModVSPReceived()
   216 {
   217 	/**
   218 	 * Don't bother if the DLL is already hooked.
   219 	 */
   220 	if (m_bIsDLLQueryHooked)
   221 	{
   222 		return;
   223 	}
   224 
   225 	/* For later MM:S versions, use the updated API, since it's cleaner. */
   226 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
   227 	int engine = g_SMAPI->GetSourceEngineBuild();
   228 	if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
   229 	{
   230 		return;
   231 	}
   232 #else
   233 	if (g_HL2.IsOriginalEngine() || vsp_version < 2)
   234 	{
   235 		return;
   236 	}
   237 #endif
   238 
   239 #if SOURCE_ENGINE != SE_DARKMESSIAH && SOURCE_ENGINE != SE_DOTA
   240 	SH_ADD_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
   241 	m_bIsVSPQueryHooked = true;
   242 #endif
   243 }
   244 
   245 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
   246 {
   247 	return convar_cache.retrieve(name, pVar);
   248 }
   249 
   250 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
   251 {
   252 	/* Only check convars that have not been created by SourceMod's core */
   253 	ConVarInfo *pInfo;
   254 	if (!convar_cache_lookup(name, &pInfo))
   255 	{
   256 		return;
   257 	}
   258 
   259 	HandleSecurity sec(NULL, g_pCoreIdent);
   260 
   261 	/* Remove it from our cache */
   262 	m_ConVars.remove(pInfo);
   263 	convar_cache.remove(name);
   264 
   265 	/* Now make sure no plugins are referring to this pointer */
   266 	IPluginIterator *pl_iter = scripts->GetPluginIterator();
   267 	while (pl_iter->MorePlugins())
   268 	{
   269 		IPlugin *pl = pl_iter->GetPlugin();
   270 
   271 		ConVarList *pConVarList;
   272 		if (pl->GetProperty("ConVarList", (void **)&pConVarList, true) 
   273 			&& pConVarList != NULL)
   274 		{
   275 			pConVarList->remove(pInfo->pVar);
   276 		}
   277 
   278 		pl_iter->NextPlugin();
   279 	}
   280 
   281 	/* Free resources */
   282 	handlesys->FreeHandle(pInfo->handle, &sec);
   283 	delete pInfo;
   284 }
   285 
   286 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
   287 {
   288 	ConVarList *pConVarList;
   289 	List<ConVarQuery>::iterator iter;
   290 
   291 	/* If plugin has a convar list, free its memory */
   292 	if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
   293 	{
   294 		delete pConVarList;
   295 	}
   296 
   297 	const IPluginRuntime * pRuntime = plugin->GetRuntime();
   298 
   299 	/* Remove convar queries for this plugin that haven't returned results yet */
   300 	for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end();)
   301 	{
   302 		ConVarQuery &query = (*iter);
   303 		if (query.pCallback->GetParentRuntime() == pRuntime)
   304 		{
   305 			iter = m_ConVarQueries.erase(iter);
   306 			continue;
   307 		}
   308 
   309 		++iter;
   310 	}
   311 }
   312 
   313 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
   314 {
   315 }
   316 
   317 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
   318 {
   319 	*pSize = sizeof(ConVar) + sizeof(ConVarInfo);
   320 	return true;
   321 }
   322 
   323 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
   324 {
   325 	int argcount = command.ArgC();
   326 	if (argcount >= 3)
   327 	{
   328 		bool wantReset = false;
   329 		
   330 		/* Get plugin index that was passed */
   331 		const char *arg = command.Arg(2);
   332 		if (argcount >= 4 && strcmp(arg, "reset") == 0)
   333 		{
   334 			wantReset = true;
   335 			arg = command.Arg(3);
   336 		}
   337 		
   338 		/* Get plugin object */
   339 		IPlugin *plugin = scripts->FindPluginByConsoleArg(arg);
   340 
   341 		if (!plugin)
   342 		{
   343 			g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
   344 			return;
   345 		}
   346 
   347 		/* Get plugin name */
   348 		const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
   349 		const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
   350 
   351 		ConVarList *pConVarList;
   352 		ConVarList::iterator iter;
   353 
   354 		/* If no convar list... */
   355 		if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   356 		{
   357 			g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
   358 			return;
   359 		}
   360 
   361 		if (!wantReset)
   362 		{
   363 			g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
   364 			g_RootMenu.ConsolePrint("  %-32.31s %s", "[Name]", "[Value]");
   365 		}
   366 		
   367 		/* Iterate convar list and display/reset each one */
   368 		for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   369 		{
   370 			/*const */ConVar *pConVar = const_cast<ConVar *>(*iter);
   371 			if (!wantReset)
   372 			{
   373 				g_RootMenu.ConsolePrint("  %-32.31s %s", pConVar->GetName(), pConVar->GetString()); 
   374 			} else {
   375 				pConVar->Revert();
   376 			}
   377 		}
   378 		
   379 		if (wantReset)
   380 		{
   381 			g_RootMenu.ConsolePrint("[SM] Reset %d convars for: %s", pConVarList->size(), plname);
   382 		}
   383 
   384 		return;
   385 	}
   386 
   387 	/* Display usage of subcommand */
   388 	g_RootMenu.ConsolePrint("[SM] Usage: sm cvars [reset] <plugin #>");
   389 }
   390 
   391 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)
   392 {
   393 	ConVar *pConVar = NULL;
   394 	ConVarInfo *pInfo = NULL;
   395 	Handle_t hndl = 0;
   396 
   397 	/* Find out if the convar exists already */
   398 	pConVar = icvar->FindVar(name);
   399 
   400 	/* If the convar already exists... */
   401 	if (pConVar)
   402 	{
   403 		/* Add convar to plugin's list */
   404 		AddConVarToPluginList(pContext, pConVar);
   405 
   406 		/* First find out if we already have a handle to it */
   407 		if (convar_cache_lookup(name, &pInfo))
   408 		{
   409 			return pInfo->handle;
   410 		}
   411 		else
   412 		{
   413 			/* Create and initialize ConVarInfo structure */
   414 			pInfo = new ConVarInfo();
   415 			pInfo->sourceMod = false;
   416 			pInfo->pChangeForward = NULL;
   417 			pInfo->pVar = pConVar;
   418 
   419 			/* If we don't, then create a new handle from the convar */
   420 			hndl = handlesys->CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
   421 			if (hndl == BAD_HANDLE)
   422 			{
   423 				delete pInfo;
   424 				return BAD_HANDLE;
   425 			}
   426 
   427 			pInfo->handle = hndl;
   428 
   429 			/* Insert struct into caches */
   430 			m_ConVars.push_back(pInfo);
   431 			convar_cache.insert(name, pInfo);
   432 			TrackConCommandBase(pConVar, this);
   433 
   434 			return hndl;
   435 		}
   436 	}
   437 
   438 	/* Prevent creating a convar that has the same name as a console command */
   439 	if (FindCommand(name))
   440 	{
   441 		return BAD_HANDLE;
   442 	}
   443 
   444 	/* Create and initialize ConVarInfo structure */
   445 	pInfo = new ConVarInfo();
   446 	pInfo->handle = hndl;
   447 	pInfo->sourceMod = true;
   448 	pInfo->pChangeForward = NULL;
   449 
   450 	/* Create a handle from the new convar */
   451 	hndl = handlesys->CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
   452 	if (hndl == BAD_HANDLE)
   453 	{
   454 		delete pInfo;
   455 		return BAD_HANDLE;
   456 	}
   457 
   458 	pInfo->handle = hndl;
   459 
   460 	/* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
   461 	pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
   462 	pInfo->pVar = pConVar;
   463 
   464 	/* Add convar to plugin's list */
   465 	AddConVarToPluginList(pContext, pConVar);
   466 
   467 	/* Insert struct into caches */
   468 	m_ConVars.push_back(pInfo);
   469 	convar_cache.insert(name, pInfo);
   470 
   471 	return hndl;
   472 }
   473 
   474 Handle_t ConVarManager::FindConVar(const char *name)
   475 {
   476 	ConVar *pConVar = NULL;
   477 	ConVarInfo *pInfo;
   478 	Handle_t hndl;
   479 
   480 	/* Search for convar */
   481 	pConVar = icvar->FindVar(name);
   482 
   483 	/* If it doesn't exist, then return an invalid handle */
   484 	if (!pConVar)
   485 	{
   486 		return BAD_HANDLE;
   487 	}
   488 
   489 	/* At this point, the convar exists. So, find out if we already have a handle */
   490 	if (convar_cache_lookup(name, &pInfo))
   491 	{
   492 		return pInfo->handle;
   493 	}
   494 
   495 	/* Create and initialize ConVarInfo structure */
   496 	pInfo = new ConVarInfo();
   497 	pInfo->sourceMod = false;
   498 	pInfo->pChangeForward = NULL;
   499 	pInfo->pVar = pConVar;
   500 
   501 	/* If we don't have a handle, then create a new one */
   502 	hndl = handlesys->CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
   503 	if (hndl == BAD_HANDLE)
   504 	{
   505 		delete pInfo;
   506 		return BAD_HANDLE;
   507 	}
   508 
   509 	pInfo->handle = hndl;
   510 
   511 	/* Insert struct into our caches */
   512 	m_ConVars.push_back(pInfo);
   513 	convar_cache.insert(name, pInfo);
   514 	TrackConCommandBase(pConVar, this);
   515 
   516 	return hndl;
   517 }
   518 
   519 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
   520 {
   521 	ConVarInfo *pInfo;
   522 
   523 	if (FindConVar(name) == BAD_HANDLE)
   524 	{
   525 		return;
   526 	}
   527 
   528 	/* Find the convar in the lookup trie */
   529 	if (convar_cache_lookup(name, &pInfo))
   530 	{
   531 		pInfo->changeListeners.push_back(pListener);
   532 	}
   533 }
   534 
   535 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
   536 {
   537 	ConVarInfo *pInfo;
   538 
   539 	/* Find the convar in the lookup trie */
   540 	if (convar_cache_lookup(name, &pInfo))
   541 	{
   542 		pInfo->changeListeners.remove(pListener);
   543 	}
   544 }
   545 
   546 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
   547 {
   548 	ConVarInfo *pInfo;
   549 	IChangeableForward *pForward;
   550 
   551 	/* Find the convar in the lookup trie */
   552 	if (convar_cache_lookup(pConVar->GetName(), &pInfo))
   553 	{
   554 		/* Get the forward */
   555 		pForward = pInfo->pChangeForward;
   556 
   557 		/* If forward does not exist, create it */
   558 		if (!pForward)
   559 		{
   560 			pForward = forwardsys->CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
   561 			pInfo->pChangeForward = pForward;
   562 		}
   563 
   564 		/* Add function to forward's list */
   565 		pForward->AddFunction(pFunction);
   566 	}
   567 }
   568 
   569 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
   570 {
   571 	ConVarInfo *pInfo;
   572 	IChangeableForward *pForward;
   573 	IPluginContext *pContext = pFunction->GetParentContext();
   574 
   575 	/* Find the convar in the lookup trie */
   576 	if (convar_cache_lookup(pConVar->GetName(), &pInfo))
   577 	{
   578 		/* Get the forward */
   579 		pForward = pInfo->pChangeForward;
   580 
   581 		/* If the forward doesn't exist, we can't unhook anything */
   582 		if (!pForward)
   583 		{
   584 			pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
   585 			return;
   586 		}
   587 
   588 		/* Remove the function from the forward's list */
   589 		if (!pForward->RemoveFunction(pFunction))
   590 		{
   591 			pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
   592 			return;
   593 		}
   594 
   595 		/* If the forward now has 0 functions in it... */
   596 		if (pForward->GetFunctionCount() == 0 &&
   597 			!ConVarReentrancyGuard::IsCvarInChain(pConVar))
   598 		{
   599 			/* Free this forward */
   600 			forwardsys->ReleaseForward(pForward);
   601 			pInfo->pChangeForward = NULL;
   602 		}
   603 	}
   604 }
   605 
   606 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
   607 {
   608 	QueryCvarCookie_t cookie = 0;
   609 
   610 #if SOURCE_ENGINE != SE_DARKMESSIAH
   611 	/* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
   612 	if (m_bIsDLLQueryHooked)
   613 	{
   614 #if SOURCE_ENGINE == SE_DOTA
   615 		cookie = engine->StartQueryCvarValue(CEntityIndex(IndexOfEdict(pPlayer)), name);
   616 #else
   617 		cookie = engine->StartQueryCvarValue(pPlayer, name);	
   618 #endif
   619 	}
   620 #if SOURCE_ENGINE != SE_DOTA
   621 	else if (m_bIsVSPQueryHooked)
   622 	{
   623 		cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
   624 	}
   625 #endif
   626 	else
   627 	{
   628 		return InvalidQueryCvarCookie;
   629 	}
   630 
   631 	ConVarQuery query = {cookie, pCallback, (cell_t)hndl};
   632 	m_ConVarQueries.push_back(query);
   633 #endif
   634 
   635 	return cookie;
   636 }
   637 
   638 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
   639 {
   640 	ConVarList *pConVarList;
   641 	ConVarList::iterator iter;
   642 	bool inserted = false;
   643 	const char *orig = pConVar->GetName();
   644 
   645 	IPlugin *plugin = scripts->FindPluginByContext(pContext->GetContext());
   646 
   647 	/* Check plugin for an existing convar list */
   648 	if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   649 	{
   650 		pConVarList = new ConVarList();
   651 		plugin->SetProperty("ConVarList", pConVarList);
   652 	}
   653 	else if (pConVarList->find(pConVar) != pConVarList->end())
   654 	{
   655 		/* If convar is already in list, then don't add it */
   656 		return;
   657 	}
   658 
   659 	/* Insert convar into list which is sorted alphabetically */
   660 	for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   661 	{
   662 		if (strcmp(orig, (*iter)->GetName()) < 0)
   663 		{
   664 			pConVarList->insert(iter, pConVar);
   665 			inserted = true;
   666 			break;
   667 		}
   668 	}
   669 
   670 	if (!inserted)
   671 	{
   672 		pConVarList->push_back(pConVar);
   673 	}
   674 }
   675 
   676 #if SOURCE_ENGINE >= SE_ORANGEBOX
   677 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
   678 #else
   679 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
   680 #endif
   681 {
   682 	/* If the values are the same, exit early in order to not trigger callbacks */
   683 	if (strcmp(pConVar->GetString(), oldValue) == 0)
   684 	{
   685 		return;
   686 	}
   687 
   688 	ConVarInfo *pInfo;
   689 
   690 	/* Find the convar in the lookup trie */
   691 	if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
   692 	{
   693 		return;
   694 	}
   695 
   696 	IChangeableForward *pForward = pInfo->pChangeForward;
   697 
   698 	if (pInfo->changeListeners.size() != 0)
   699 	{
   700 		for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
   701 			 i != pInfo->changeListeners.end();
   702 			 i++)
   703 		{
   704 #if SOURCE_ENGINE >= SE_ORANGEBOX
   705 			(*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
   706 #else
   707 			(*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
   708 #endif
   709 		}
   710 	}
   711 
   712 	if (pForward != NULL)
   713 	{
   714 		ConVarReentrancyGuard guard(pConVar);
   715 
   716 		/* Now call forwards in plugins that have hooked this */
   717 		pForward->PushCell(pInfo->handle);
   718 		pForward->PushString(oldValue);
   719 		pForward->PushString(pConVar->GetString());
   720 		pForward->Execute(NULL);
   721 	}
   722 }
   723 
   724 bool ConVarManager::IsQueryingSupported()
   725 {
   726 	return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
   727 }
   728 
   729 #if SOURCE_ENGINE != SE_DARKMESSIAH
   730 #if SOURCE_ENGINE == SE_DOTA
   731 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, CEntityIndex player, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
   732 #else
   733 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
   734 #endif // SE_DOTA
   735 {
   736 	IPluginFunction *pCallback = NULL;
   737 	cell_t value = 0;
   738 	List<ConVarQuery>::iterator iter;
   739 
   740 	for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
   741 	{
   742 		ConVarQuery &query = (*iter);
   743 		if (query.cookie == cookie)
   744 		{
   745 			pCallback = query.pCallback;
   746 			value = query.value;
   747 			break;
   748 		}
   749 	}
   750 
   751 	if (pCallback)
   752 	{
   753 		cell_t ret;
   754 
   755 		pCallback->PushCell(cookie);
   756 #if SOURCE_ENGINE == SE_DOTA
   757 		pCallback->PushCell(player.Get());
   758 #else
   759 		pCallback->PushCell(IndexOfEdict(pPlayer));
   760 #endif
   761 		pCallback->PushCell(result);
   762 		pCallback->PushString(cvarName);
   763 
   764 		if (result == eQueryCvarValueStatus_ValueIntact)
   765 		{
   766 			pCallback->PushString(cvarValue);
   767 		}
   768 		else
   769 		{
   770 			pCallback->PushString("\0");
   771 		}
   772 
   773 		pCallback->PushCell(value);
   774 		pCallback->Execute(&ret);
   775 
   776 		m_ConVarQueries.erase(iter);
   777 	}
   778 }
   779 #endif
   780 
   781 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
   782 {
   783 	ConVarInfo *pInfo;
   784 	HandleError error;
   785 	
   786 	if ((error = handlesys->ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)
   787 	{
   788 		return error;
   789 	}
   790 
   791 	if (pVar)
   792 	{
   793 		*pVar = pInfo->pVar;
   794 	}
   795 
   796 	return error;
   797 }