3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
15 #include "ConVarManager.h"
16 #include "HalfLife2.h"
17 #include "PluginSys.h"
18 #include "ForwardSys.h"
19 #include "HandleSys.h"
20 #include "sm_srvcmds.h"
21 #include "sm_stringutil.h"
22 #include <sh_vector.h>
24 ConVarManager g_ConVarManager;
26 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
27 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
29 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
30 typedef List<const ConVar *> ConVarList;
32 ConVarManager::ConVarManager() : m_ConVarType(0), m_VSPIface(NULL), m_CanQueryConVars(false)
34 #if PLAPI_VERSION < 12
35 m_IgnoreHandle = false;
38 /* Create a convar lookup trie */
39 m_ConVarCache = sm_trie_create();
42 ConVarManager::~ConVarManager()
44 List<ConVarInfo *>::iterator iter;
46 /* Destroy our convar lookup trie */
47 sm_trie_destroy(m_ConVarCache);
49 /* Destroy all the ConVarInfo structures */
50 for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
58 void ConVarManager::OnSourceModAllInitialized()
60 /* Only valid with ServerGameDLL006 or greater */
61 if (g_SMAPI->GetGameDLLVersion() >= 6)
63 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
64 m_CanQueryConVars = true;
69 /* Set up access rights for the 'ConVar' handle type */
70 sec.access[HandleAccess_Read] = 0;
71 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
72 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
74 /* Create the 'ConVar' handle type */
75 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
77 /* Add the 'convars' option to the 'sm' console command */
78 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
81 void ConVarManager::OnSourceModShutdown()
83 if (m_CanQueryConVars)
85 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
86 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, m_VSPIface, this, &ConVarManager::OnQueryCvarValueFinished, false);
89 IChangeableForward *fwd;
90 List<ConVarInfo *>::iterator i;
92 /* Iterate list of ConVarInfo structures */
93 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
95 fwd = (*i)->pChangeForward;
97 /* Free any convar-change forwards that still exist */
100 g_Forwards.ReleaseForward(fwd);
104 /* Remove the 'convars' option from the 'sm' console command */
105 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
107 /* Remove the 'ConVar' handle type */
108 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
111 void ConVarManager::OnSourceModVSPReceived(IServerPluginCallbacks *iface)
113 /* This will be called after OnSourceModAllInitialized(), so...
115 * If we haven't been able to hook the IServerGameDLL version at this point,
116 * then use hook IServerPluginCallbacks version from the engine.
119 /* The Ship currently only supports ServerPluginCallbacks001, but we need 002 */
120 if (g_IsOriginalEngine)
125 if (!m_CanQueryConVars)
129 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, iface, this, &ConVarManager::OnQueryCvarValueFinished, false);
130 m_CanQueryConVars = true;
134 #if PLAPI_VERSION >= 12
135 void ConVarManager::OnUnlinkConCommandBase(PluginId id, ConCommandBase *pCommand)
137 /* Only check convars that have not been created by SourceMod's core */
138 if (id != g_PLID && !pCommand->IsCommand())
141 const char *cvarName = pCommand->GetName();
142 HandleSecurity sec(NULL, g_pCoreIdent);
143 bool handleExists = sm_trie_retrieve(m_ConVarCache, cvarName, reinterpret_cast<void **>(&pInfo));
147 g_HandleSys.FreeHandle(pInfo->handle, &sec);
148 sm_trie_delete(m_ConVarCache, cvarName);
149 m_ConVars.remove(pInfo);
156 /* I truly detest this code */
157 void ConVarManager::OnMetamodPluginUnloaded(PluginId id)
160 const char *cvarName;
161 HandleSecurity sec(NULL, g_pCoreIdent);
163 List<ConVarInfo *>::iterator i;
164 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
167 cvarName = pInfo->name;
169 if (cvarName && !icvar->FindVar(cvarName))
171 m_IgnoreHandle = true;
172 g_HandleSys.FreeHandle(pInfo->handle, &sec);
174 sm_trie_delete(m_ConVarCache, cvarName);
183 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
185 ConVarList *pConVarList;
187 /* If plugin has a convar list, free its memory */
188 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
194 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
196 #if PLAPI_VERSION < 12
197 /* Lovely workaround for our workaround! */
200 m_IgnoreHandle = false;
206 ConVar *pConVar = static_cast<ConVar *>(object);
208 /* Find convar in lookup trie */
209 sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
211 /* If convar was created by SourceMod plugin... */
214 /* Delete string allocations */
215 delete [] pConVar->GetName();
216 delete [] pConVar->GetDefault();
217 delete [] pConVar->GetHelpText();
219 /* Then unlink it from SourceMM */
220 g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
224 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
228 /* Get plugin index that was passed */
229 int id = atoi(g_RootMenu.GetArgument(2));
231 /* Get plugin object */
232 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
236 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
240 /* Get plugin name */
241 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
242 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
244 ConVarList *pConVarList;
245 ConVarList::iterator iter;
247 /* If no convar list... */
248 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
250 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
254 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
255 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
257 /* Iterate convar list and display each one */
258 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
260 const ConVar *pConVar = (*iter);
261 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
267 /* Display usage of subcommand */
268 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
271 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)
273 ConVar *pConVar = NULL;
274 ConVarInfo *pInfo = NULL;
277 /* Find out if the convar exists already */
278 pConVar = icvar->FindVar(name);
280 /* If the convar already exists... */
283 /* Add convar to plugin's list */
284 AddConVarToPluginList(pContext, pConVar);
286 /* First find out if we already have a handle to it */
287 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
289 return pInfo->handle;
291 /* If we don't, then create a new handle from the convar */
292 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
294 /* Create and initialize ConVarInfo structure */
295 pInfo = new ConVarInfo();
296 pInfo->handle = hndl;
297 pInfo->sourceMod = false;
298 pInfo->pChangeForward = NULL;
299 pInfo->origCallback = pConVar->GetCallback();
300 #if PLAPI_VERSION < 12
301 pInfo->name = sm_strdup(pConVar->GetName());
304 /* Insert struct into caches */
305 m_ConVars.push_back(pInfo);
306 sm_trie_insert(m_ConVarCache, name, pInfo);
312 /* To prevent creating a convar that has the same name as a console command... ugh */
313 ConCommandBase *pBase = icvar->GetCommands();
317 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
322 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
325 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
326 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
328 /* Add convar to plugin's list */
329 AddConVarToPluginList(pContext, pConVar);
331 /* Create a handle from the new convar */
332 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
334 /* Create and initialize ConVarInfo structure */
335 pInfo = new ConVarInfo();
336 pInfo->handle = hndl;
337 pInfo->sourceMod = true;
338 pInfo->pChangeForward = NULL;
339 pInfo->origCallback = NULL;
341 /* Insert struct into caches */
342 m_ConVars.push_back(pInfo);
343 sm_trie_insert(m_ConVarCache, name, pInfo);
348 Handle_t ConVarManager::FindConVar(const char *name)
350 ConVar *pConVar = NULL;
354 /* Search for convar */
355 pConVar = icvar->FindVar(name);
357 /* If it doesn't exist, then return an invalid handle */
363 /* At this point, the convar exists. So, find out if we already have a handle */
364 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
366 return pInfo->handle;
369 /* If we don't have a handle, then create a new one */
370 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
372 /* Create and initialize ConVarInfo structure */
373 pInfo = new ConVarInfo();
374 pInfo->handle = hndl;
375 pInfo->sourceMod = false;
376 pInfo->pChangeForward = NULL;
377 pInfo->origCallback = pConVar->GetCallback();
378 #if PLAPI_VERSION < 12
379 pInfo->name = sm_strdup(pConVar->GetName());
382 /* Insert struct into our caches */
383 m_ConVars.push_back(pInfo);
384 sm_trie_insert(m_ConVarCache, name, pInfo);
389 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
392 IChangeableForward *pForward;
394 /* Find the convar in the lookup trie */
395 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
397 /* Get the forward */
398 pForward = pInfo->pChangeForward;
400 /* If forward does not exist, create it */
403 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
404 pInfo->pChangeForward = pForward;
406 /* Install our own callback */
407 pConVar->InstallChangeCallback(OnConVarChanged);
410 /* Add function to forward's list */
411 pForward->AddFunction(pFunction);
415 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
418 IChangeableForward *pForward;
419 IPluginContext *pContext = pFunction->GetParentContext();
421 /* Find the convar in the lookup trie */
422 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
424 /* Get the forward */
425 pForward = pInfo->pChangeForward;
427 /* If the forward doesn't exist, we can't unhook anything */
430 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
434 /* Remove the function from the forward's list */
435 if (!pForward->RemoveFunction(pFunction))
437 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
441 /* If the forward now has 0 functions in it... */
442 if (pForward->GetFunctionCount() == 0)
444 /* Free this forward */
445 g_Forwards.ReleaseForward(pForward);
446 pInfo->pChangeForward = NULL;
448 /* Put back the original convar callback */
449 pConVar->InstallChangeCallback(pInfo->origCallback);
454 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
456 QueryCvarCookie_t cookie;
458 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
461 cookie = engine->StartQueryCvarValue(pPlayer, name);
463 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
466 ConVarQuery query = {cookie, pCallback, hndl};
467 m_ConVarQueries.push_back(query);
472 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
474 ConVarList *pConVarList;
475 ConVarList::iterator iter;
476 bool inserted = false;
477 const char *orig = pConVar->GetName();
479 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
481 /* Check plugin for an existing convar list */
482 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
484 pConVarList = new ConVarList();
485 plugin->SetProperty("ConVarList", pConVarList);
486 } else if (pConVarList->find(pConVar) != pConVarList->end()) {
487 /* If convar is already in list, then don't add it */
491 /* Insert convar into list which is sorted alphabetically */
492 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
494 if (strcmp(orig, (*iter)->GetName()) < 0)
496 pConVarList->insert(iter, pConVar);
504 pConVarList->push_back(pConVar);
508 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
510 /* If the values are the same, exit early in order to not trigger callbacks */
511 if (strcmp(pConVar->GetString(), oldValue) == 0)
516 Trie *pCache = g_ConVarManager.GetConVarCache();
519 /* Find the convar in the lookup trie */
520 sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
522 FnChangeCallback origCallback = pInfo->origCallback;
523 IChangeableForward *pForward = pInfo->pChangeForward;
525 /* If there was a change callback installed previously, call it */
528 origCallback(pConVar, oldValue);
531 /* Now call forwards in plugins that have hooked this */
532 pForward->PushCell(pInfo->handle);
533 pForward->PushString(oldValue);
534 pForward->PushString(pConVar->GetString());
535 pForward->Execute(NULL);
538 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
540 IPluginFunction *pCallback = NULL;
542 List<ConVarQuery>::iterator iter;
544 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
546 ConVarQuery &query = (*iter);
548 if (query.cookie == cookie)
550 pCallback = query.pCallback;
561 pCallback->PushCell(cookie);
562 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
563 pCallback->PushCell(result);
564 pCallback->PushString(cvarName);
566 if (result == eQueryCvarValueStatus_ValueIntact)
568 pCallback->PushString(cvarValue);
570 pCallback->PushString("\0");
573 pCallback->PushCell(value);
574 pCallback->Execute(&ret);
576 m_ConVarQueries.erase(iter);
581 static int s_YamagramState = 0;
583 void _YamagramPrinterTwoPointOhOh(int yamagram)
588 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
589 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
590 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
591 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
592 g_RootMenu.ConsolePrint("-------------------------------");
593 _YamagramPrinterTwoPointOhOh(1);
596 g_RootMenu.ConsolePrint("Question Ichi (1)");
597 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
598 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
601 g_RootMenu.ConsolePrint("Question Ni (2)");
602 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
603 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
606 g_RootMenu.ConsolePrint("Question San (3)");
607 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
608 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
611 g_RootMenu.ConsolePrint("Question Yon (4)");
612 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
613 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
616 g_RootMenu.ConsolePrint("Question Go (5)");
617 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
618 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
621 g_RootMenu.ConsolePrint("Question Roku (6)");
622 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
623 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
626 g_RootMenu.ConsolePrint("Question Nana (7)");
627 g_RootMenu.ConsolePrint("What is my name?");
628 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
634 s_YamagramState = yamagram;
637 void _IntExt_CallYamagrams()
639 bool correct = false;
640 const char *arg = engine->Cmd_Args();
642 if (!arg || arg[0] == '\0')
644 _YamagramPrinterTwoPointOhOh(s_YamagramState);
648 switch (s_YamagramState)
651 correct = !strcasecmp(arg, "eating grass");
654 correct = !strcasecmp(arg, "sombrero");
657 correct = !strcasecmp(arg, "david bailopan anderson");
660 correct = !strcasecmp(arg, "kaitei no kairan");
663 correct = !strcasecmp(arg, "life and death");
666 correct = !strcasecmp(arg, "because gabe wanted it that way");
669 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
670 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
671 g_RootMenu.ConsolePrint("-------------------------------");
672 _YamagramPrinterTwoPointOhOh(7);
677 correct = !strcasecmp(arg, "damaged soul");
680 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
681 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
682 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
683 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
684 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
694 if (s_YamagramState > 0)
698 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
699 g_RootMenu.ConsolePrint("-------------------------------");
702 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
707 _YamagramPrinterTwoPointOhOh(s_YamagramState);
710 void _IntExt_EnableYamagrams()
712 static ConCommand *pCmd = NULL;
715 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
716 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
718 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
722 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
724 if (strcmp(oldValue, "Good morning, DS-san.") == 0
725 && strcmp(pConVar->GetString(), "Good night, talking desk lamp.") == 0)
727 _IntExt_EnableYamagrams();