core/ConVarManager.cpp
author David Anderson <dvander@alliedmods.net>
Mon Mar 19 01:44:09 2007 +0000 (2007-03-19)
changeset 647 1e29dcc9ca97
parent 628 b11949f893a5
child 653 ef60870067ff
permissions -rw-r--r--
fixed a potential bug with kicking players during authorization
     1 /**
     2 * ===============================================================
     3 * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     4 * ===============================================================
     5 *
     6 * This file is not open source and may not be copied without explicit
     7 * written permission of AlliedModders LLC.  This file may not be redistributed 
     8 * in whole or significant part.
     9 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    10 *
    11 * Version: $Id$
    12 */
    13 
    14 #include "ConVarManager.h"
    15 #include "PluginSys.h"
    16 #include "ForwardSys.h"
    17 #include "HandleSys.h"
    18 #include "sm_srvcmds.h"
    19 #include "sm_stringutil.h"
    20 #include <sh_vector.h>
    21 
    22 ConVarManager g_ConVarManager;
    23 
    24 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
    25 typedef List<const ConVar *> ConVarList;
    26 
    27 ConVarManager::ConVarManager() : m_ConVarType(0)
    28 {
    29 	/* Create a convar lookup trie */
    30 	m_ConVarCache = sm_trie_create();
    31 }
    32 
    33 ConVarManager::~ConVarManager()
    34 {
    35 	List<ConVarInfo *>::iterator iter;
    36 
    37 	/* Destroy our convar lookup trie */
    38 	sm_trie_destroy(m_ConVarCache);
    39 
    40 	/* Destroy all the ConVarInfo structures */
    41 	for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
    42 	{
    43 		delete (*iter);
    44 	}
    45 
    46 	m_ConVars.clear();
    47 }
    48 
    49 void ConVarManager::OnSourceModAllInitialized()
    50 {
    51 	HandleAccess sec;
    52 
    53 	/* Set up access rights for the 'ConVar' handle type */
    54 	sec.access[HandleAccess_Read] = 0;
    55 	sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
    56 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
    57 
    58 	/* Create the 'ConVar' handle type */
    59 	m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
    60 
    61 	/* Add the 'convars' option to the 'sm' console command */
    62 	g_RootMenu.AddRootConsoleCommand("convars", "View convars created by a plugin", this);
    63 }
    64 
    65 void ConVarManager::OnSourceModShutdown()
    66 {
    67 	IChangeableForward *fwd;
    68 	List<ConVarInfo *>::iterator i;
    69 
    70 	/* Iterate list of ConVarInfo structures */
    71 	for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
    72 	{
    73 		fwd = (*i)->changeForward;
    74 
    75 		/* Free any convar-change forwards that still exist */
    76 		if (fwd)
    77 		{
    78 			g_Forwards.ReleaseForward(fwd);
    79 		}
    80 	}
    81 
    82 	/* Remove the 'convars' option from the 'sm' console command */
    83 	g_RootMenu.RemoveRootConsoleCommand("convars", this);
    84 
    85 	/* Remove the 'ConVar' handle type */
    86 	g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
    87 }
    88 
    89 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
    90 {
    91 	ConVarList *pConVarList;
    92 
    93 	/* If plugin has a convar list, free its memory */
    94 	if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
    95 	{
    96 		delete pConVarList;
    97 	}
    98 }
    99 
   100 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
   101 {
   102 	ConVarInfo *info;
   103 	ConVar *pConVar = static_cast<ConVar *>(object);
   104 
   105 	/* Find convar in lookup trie */
   106 	sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
   107 
   108 	/* If convar was created by SourceMod plugin... */
   109 	if (info->sourceMod)
   110 	{
   111 		/* Delete string allocations */
   112 		delete [] pConVar->GetName(); 
   113 		delete [] pConVar->GetDefault();
   114 		delete [] pConVar->GetHelpText();
   115 
   116 		/* Then unlink it from SourceMM */
   117 		g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
   118 	}
   119 }
   120 
   121 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
   122 {
   123 	if (argcount >= 3)
   124 	{
   125 		/* Get plugin index that was passed */
   126 		int id = atoi(g_RootMenu.GetArgument(2));
   127 		
   128 		/* Get plugin object */
   129 		CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
   130 
   131 		if (!plugin)
   132 		{
   133 			g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
   134 			return;
   135 		}
   136 
   137 		/* Get plugin name */
   138 		const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
   139 		const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
   140 
   141 		ConVarList *pConVarList;
   142 		ConVarList::iterator iter;
   143 
   144 		/* If no convar list... */
   145 		if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   146 		{
   147 			g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
   148 			return;
   149 		}
   150 
   151 		g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
   152 		g_RootMenu.ConsolePrint("  %-32.31s %s", "[Name]", "[Value]");
   153 
   154 		/* Iterate convar list and display each one */
   155 		for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   156 		{
   157 			const ConVar *pConVar = (*iter);
   158 			g_RootMenu.ConsolePrint("  %-32.31s %s", pConVar->GetName(), pConVar->GetString()); 
   159 		}
   160 
   161 		return;
   162 	}
   163 
   164 	/* Display usage of subcommand */
   165 	g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
   166 }
   167 
   168 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)
   169 {
   170 	ConVar *pConVar = NULL;
   171 	ConVarInfo *pInfo = NULL;
   172 	Handle_t hndl = 0;
   173 
   174 	/* Find out if the convar exists already */
   175 	pConVar = icvar->FindVar(name);
   176 
   177 	/* If the convar already exists... */
   178 	if (pConVar)
   179 	{
   180 		/* First find out if we already have a handle to it */
   181 		if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
   182 		{
   183 			return pInfo->handle;
   184 		} else {
   185 			/* If we don't, then create a new handle from the convar */
   186 			hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
   187 
   188 			/* Create and initialize ConVarInfo structure */
   189 			pInfo = new ConVarInfo();
   190 			pInfo->handle = hndl;
   191 			pInfo->sourceMod = false;
   192 			pInfo->changeForward = NULL;
   193 			pInfo->origCallback = pConVar->GetCallback();
   194 
   195 			/* Insert struct into caches */
   196 			m_ConVars.push_back(pInfo);
   197 			sm_trie_insert(m_ConVarCache, name, pInfo);
   198 
   199 			return hndl;
   200 		}
   201 	}
   202 
   203 	// To prevent creating a convar that has the same name as a console command... ugh
   204 	ConCommandBase *pBase = icvar->GetCommands();
   205 
   206 	while (pBase)
   207 	{
   208 		if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
   209 		{
   210 			return BAD_HANDLE;
   211 		}
   212 
   213 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   214 	}
   215 
   216 	/* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
   217 	pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
   218 
   219 	/* Add convar to plugin's list */
   220 	AddConVarToPluginList(pContext, pConVar);
   221 
   222 	/* Create a handle from the new convar */
   223 	hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
   224 
   225 	/* Create and initialize ConVarInfo structure */
   226 	pInfo = new ConVarInfo();
   227 	pInfo->handle = hndl;
   228 	pInfo->sourceMod = true;
   229 	pInfo->changeForward = NULL;
   230 	pInfo->origCallback = NULL;
   231 
   232 	/* Insert struct into caches */
   233 	m_ConVars.push_back(pInfo);
   234 	sm_trie_insert(m_ConVarCache, name, pInfo);
   235 
   236 	return hndl;
   237 }
   238 
   239 Handle_t ConVarManager::FindConVar(const char *name)
   240 {
   241 	ConVar *pConVar = NULL;
   242 	ConVarInfo *pInfo;
   243 	Handle_t hndl;
   244 
   245 	/* Search for convar */
   246 	pConVar = icvar->FindVar(name);
   247 
   248 	/* If it doesn't exist, then return an invalid handle */
   249 	if (!pConVar)
   250 	{
   251 		return BAD_HANDLE;
   252 	}
   253 
   254 	/* At this point, the convar exists. So, find out if we already have a handle */
   255 	if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
   256 	{
   257 		return pInfo->handle;
   258 	}
   259 
   260 	/* If we don't have a handle, then create a new one */
   261 	hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
   262 
   263 	/* Create and initilize ConVarInfo structure */
   264 	pInfo = new ConVarInfo();
   265 	pInfo->handle = hndl;
   266 	pInfo->sourceMod = false;
   267 	pInfo->changeForward = NULL;
   268 	pInfo->origCallback = pConVar->GetCallback();
   269 
   270 	/* Insert struct into our caches */
   271 	m_ConVars.push_back(pInfo);
   272 	sm_trie_insert(m_ConVarCache, name, pInfo);
   273 
   274 	return hndl;
   275 }
   276 
   277 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
   278 {
   279 	ConVarInfo *pInfo;
   280 	IChangeableForward *pForward;
   281 
   282 	/* Find the convar in the lookup trie */
   283 	if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
   284 	{
   285 		/* Get the forward */
   286 		pForward = pInfo->changeForward;
   287 
   288 		/* If forward does not exist, create it */
   289 		if (!pForward)
   290 		{
   291 			pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
   292 			pInfo->changeForward = pForward;
   293 
   294 			/* Install our own callback */
   295 			pConVar->InstallChangeCallback(OnConVarChanged);
   296 		}
   297 
   298 		/* Add function to forward's list */
   299 		pForward->AddFunction(pFunction);
   300 	}
   301 }
   302 
   303 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
   304 {
   305 	ConVarInfo *pInfo;
   306 	IChangeableForward *pForward;
   307 	IPluginContext *pContext = pFunction->GetParentContext();
   308 
   309 	/* Find the convar in the lookup trie */
   310 	if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
   311 	{
   312 		/* Get the forward */
   313 		pForward = pInfo->changeForward;
   314 
   315 		/* If the forward doesn't exist, we can't unhook anything */
   316 		if (!pForward)
   317 		{
   318 			pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
   319 			return;
   320 		}
   321 
   322 		/* Remove the function from the forward's list */
   323 		if (!pForward->RemoveFunction(pFunction))
   324 		{
   325 			pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
   326 			return;
   327 		}
   328 
   329 		/* If the forward now has 0 functions in it... */
   330 		if (pForward->GetFunctionCount() == 0)
   331 		{
   332 			/* Free this forward */
   333 			g_Forwards.ReleaseForward(pForward);
   334 			pInfo->changeForward = NULL;
   335 
   336 			/* Put back the original convar callback */
   337 			pConVar->InstallChangeCallback(pInfo->origCallback);
   338 		}
   339 	}
   340 }
   341 
   342 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
   343 {
   344 	ConVarList *pConVarList;
   345 	ConVarList::iterator iter;
   346 	bool inserted = false;
   347 	const char *orig = pConVar->GetName();
   348 
   349 	IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
   350 
   351 	/* Check plugin for an existing convar list */
   352 	if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
   353 	{
   354 		pConVarList = new ConVarList();
   355 		plugin->SetProperty("ConVarList", pConVarList);
   356 	}
   357 
   358 	/* Insert convar into list which is sorted alphabetically */
   359 	for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
   360 	{
   361 		if (strcmp(orig, (*iter)->GetName()) < 0)
   362 		{
   363 			pConVarList->insert(iter, pConVar);
   364 			inserted = true;
   365 			break;
   366 		}
   367 	}
   368 
   369 	if (!inserted)
   370 	{
   371 		pConVarList->push_back(pConVar);
   372 	}
   373 }
   374 
   375 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
   376 {
   377 	/* If the values are the same, exit early in order to not trigger callbacks */
   378 	if (strcmp(pConVar->GetString(), oldValue) == 0)
   379 	{
   380 		return;
   381 	}
   382 
   383 	Trie *pCache = g_ConVarManager.GetConVarCache();
   384 	ConVarInfo *pInfo;
   385 
   386 	/* Find the convar in the lookup trie */
   387 	sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
   388 
   389 	FnChangeCallback origCallback = pInfo->origCallback;
   390 	IChangeableForward *pForward = pInfo->changeForward;
   391 
   392 	/* If there was a change callback installed previously, call it */
   393 	if (origCallback)
   394 	{
   395 		origCallback(pConVar, oldValue);
   396 	}
   397 
   398 	/* Now call forwards in plugins that have hooked this */
   399 	pForward->PushCell(pInfo->handle);
   400 	pForward->PushString(oldValue);
   401 	pForward->PushString(pConVar->GetString());
   402 	pForward->Execute(NULL);
   403 }
   404 
   405 static int s_YamagramState = 0;
   406 
   407 void _YamagramPrinterTwoPointOhOh(int yamagram)
   408 {
   409 	switch (yamagram)
   410 	{
   411 	case 0:
   412 		g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
   413 		g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
   414 		g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
   415 		g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
   416 		g_RootMenu.ConsolePrint("-------------------------------");
   417 		_YamagramPrinterTwoPointOhOh(1);
   418 		return;
   419 	case 1:
   420 		g_RootMenu.ConsolePrint("Question Ichi (1)");
   421 		g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
   422 		g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
   423 		break;
   424 	case 2:
   425 		g_RootMenu.ConsolePrint("Question Ni (2)");
   426 		g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
   427 		g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
   428 		break;
   429 	case 3:
   430 		g_RootMenu.ConsolePrint("Question San (3)");
   431 		g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
   432 		g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
   433 		break;
   434 	case 4:
   435 		g_RootMenu.ConsolePrint("Question Yon (4)");
   436 		g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
   437 		g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
   438 		break;
   439 	case 5:
   440 		g_RootMenu.ConsolePrint("Question Go (5)");
   441 		g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
   442 		g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
   443 		break;
   444 	case 6:
   445 		g_RootMenu.ConsolePrint("Question Roku (6)");
   446 		g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
   447 		g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
   448 		break;
   449 	case 7:
   450 		g_RootMenu.ConsolePrint("Question Nana (7)");
   451 		g_RootMenu.ConsolePrint("What is my name?");
   452 		g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
   453 		break;
   454 	default:
   455 		break;
   456 	}
   457 
   458 	s_YamagramState = yamagram;
   459 }
   460 
   461 void _IntExt_CallYamagrams()
   462 {
   463 	bool correct = false;
   464 	const char *arg = engine->Cmd_Args();
   465 
   466 	if (!arg || arg[0] == '\0')
   467 	{
   468 		_YamagramPrinterTwoPointOhOh(s_YamagramState);
   469 		return;
   470 	}
   471 
   472 	switch (s_YamagramState)
   473 	{
   474 	case 1:
   475 		correct = !strcasecmp(arg, "eating grass");
   476 		break;
   477 	case 2:
   478 		correct = !strcasecmp(arg, "sombrero");
   479 		break;
   480 	case 3:
   481 		correct = !strcasecmp(arg, "david bailopan anderson");
   482 		break;
   483 	case 4:
   484 		correct = !strcasecmp(arg, "kaitei no kairan");
   485 		break;
   486 	case 5:
   487 		correct = !strcasecmp(arg, "life and death");
   488 		break;
   489 	case 6:
   490 		correct = !strcasecmp(arg, "because gabe wanted it that way");
   491 		if (correct)
   492 		{
   493 			g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
   494 			g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
   495 			g_RootMenu.ConsolePrint("-------------------------------");
   496 			_YamagramPrinterTwoPointOhOh(7);
   497 			return;
   498 		}
   499 		break;
   500 	case 7:
   501 		correct = !strcasecmp(arg, "damaged soul");
   502 		if (correct)
   503 		{
   504 			g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
   505 			g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
   506 			g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
   507 			g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
   508 			g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
   509 
   510 			s_YamagramState = 0;
   511 			return;
   512 		}
   513 		break;
   514 	default:
   515 		break;
   516 	}
   517 
   518 	if (s_YamagramState > 0)
   519 	{
   520 		if (correct)
   521 		{
   522 			g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
   523 			g_RootMenu.ConsolePrint("-------------------------------");
   524 			s_YamagramState++;
   525 		} else {
   526 			g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
   527 			return;
   528 		}
   529 	}
   530 
   531 	_YamagramPrinterTwoPointOhOh(s_YamagramState);
   532 }
   533 
   534 void _IntExt_EnableYamagrams()
   535 {
   536 	static ConCommand *pCmd = NULL;
   537 	if (!pCmd)
   538 	{
   539 		pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
   540 		g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
   541 	} else {
   542 		g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
   543 	}
   544 }
   545 
   546 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
   547 {
   548 	if (strcmp(oldValue, "Good morning, DS-san.") == 0
   549 		&& strcmp(pConVar->GetString(), "Good night, talking desk lamp.") == 0)
   550 	{
   551 		_IntExt_EnableYamagrams();
   552 	}
   553 }