3 * =============================================================================
5 * Copyright (C) 2004-2007 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 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
45 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
47 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
48 typedef List<const ConVar *> ConVarList;
49 KTrie<ConVarInfo *> convar_cache;
51 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
55 ConVarManager::~ConVarManager()
59 void ConVarManager::OnSourceModAllInitialized()
62 * Episode 2 has this function by default, but the older versions do not.
64 #if !defined ORANGEBOX_BUILD
65 if (g_SMAPI->GetGameDLLVersion() >= 6)
67 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
68 m_bIsDLLQueryHooked = true;
74 /* Set up access rights for the 'ConVar' handle type */
75 sec.access[HandleAccess_Read] = 0;
76 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
77 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
79 /* Create the 'ConVar' handle type */
80 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
82 /* Add the 'convars' option to the 'sm' console command */
83 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
86 void ConVarManager::OnSourceModShutdown()
88 List<ConVarInfo *>::iterator iter = m_ConVars.begin();
89 HandleSecurity sec(NULL, g_pCoreIdent);
91 /* Iterate list of ConVarInfo structures, remove every one of them */
92 while (iter != m_ConVars.end())
94 ConVarInfo *pInfo = (*iter);
96 iter = m_ConVars.erase(iter);
98 g_HandleSys.FreeHandle(pInfo->handle, &sec);
99 if (pInfo->pChangeForward != NULL)
101 g_Forwards.ReleaseForward(pInfo->pChangeForward);
103 if (pInfo->sourceMod)
105 /* If we created it, we won't be tracking it, therefore it is
106 * safe to remove everything in one go.
108 META_UNREGCVAR(pInfo->pVar);
109 delete [] pInfo->pVar->GetName();
110 delete [] pInfo->pVar->GetHelpText();
111 delete [] pInfo->pVar->GetDefault();
116 /* If we didn't create it, we might be tracking it. Also,
117 * it could be unreadable.
119 UntrackConCommandBase(pInfo->pVar, this);
122 /* It's not safe to read the name here, so we simply delete the
123 * the info struct and clear the lookup cache at the end.
127 convar_cache.clear();
130 if (m_bIsDLLQueryHooked)
132 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
133 m_bIsDLLQueryHooked = false;
135 else if (m_bIsVSPQueryHooked)
137 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
138 m_bIsVSPQueryHooked = false;
141 /* Remove the 'convars' option from the 'sm' console command */
142 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
144 /* Remove the 'ConVar' handle type */
145 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
149 * Orange Box will never use this.
151 void ConVarManager::OnSourceModVSPReceived()
154 * Don't bother if the DLL is already hooked.
156 if (m_bIsDLLQueryHooked)
161 /* For later MM:S versions, use the updated API, since it's cleaner. */
162 #if defined METAMOD_PLAPI_VERSION
163 int engine = g_SMAPI->GetSourceEngineBuild();
164 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
169 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
175 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, this, &ConVarManager::OnQueryCvarValueFinished, false);
176 m_bIsVSPQueryHooked = true;
179 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
181 ConVarInfo **pLookup = convar_cache.retrieve(name);
193 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
195 /* Only check convars that have not been created by SourceMod's core */
197 if (!convar_cache_lookup(name, &pInfo))
202 HandleSecurity sec(NULL, g_pCoreIdent);
204 /* Remove it from our cache */
205 m_ConVars.remove(pInfo);
206 convar_cache.remove(name);
208 /* Now make sure no plugins are referring to this pointer */
209 IPluginIterator *pl_iter = g_PluginSys.GetPluginIterator();
210 while (pl_iter->MorePlugins())
212 IPlugin *pl = pl_iter->GetPlugin();
214 ConVarList *pConVarList;
215 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
216 && pConVarList != NULL)
218 pConVarList->remove(pInfo->pVar);
221 pl_iter->NextPlugin();
225 g_HandleSys.FreeHandle(pInfo->handle, &sec);
229 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
231 ConVarList *pConVarList;
233 /* If plugin has a convar list, free its memory */
234 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
240 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
244 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
246 int argcount = command.ArgC();
249 /* Get plugin index that was passed */
250 int id = atoi(command.Arg(2));
252 /* Get plugin object */
253 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
257 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
261 /* Get plugin name */
262 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
263 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
265 ConVarList *pConVarList;
266 ConVarList::iterator iter;
268 /* If no convar list... */
269 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
271 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
275 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
276 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
278 /* Iterate convar list and display each one */
279 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
281 const ConVar *pConVar = (*iter);
282 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
288 /* Display usage of subcommand */
289 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
292 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)
294 ConVar *pConVar = NULL;
295 ConVarInfo *pInfo = NULL;
298 /* Find out if the convar exists already */
299 pConVar = icvar->FindVar(name);
301 /* If the convar already exists... */
304 /* Add convar to plugin's list */
305 AddConVarToPluginList(pContext, pConVar);
307 /* First find out if we already have a handle to it */
308 if (convar_cache_lookup(name, &pInfo))
310 return pInfo->handle;
314 /* Create and initialize ConVarInfo structure */
315 pInfo = new ConVarInfo();
316 pInfo->sourceMod = false;
317 pInfo->pChangeForward = NULL;
318 pInfo->origCallback = pConVar->GetCallback();
319 pInfo->pVar = pConVar;
321 /* If we don't, then create a new handle from the convar */
322 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
323 if (hndl == BAD_HANDLE)
329 pInfo->handle = hndl;
331 /* Insert struct into caches */
332 m_ConVars.push_back(pInfo);
333 convar_cache.insert(name, pInfo);
334 TrackConCommandBase(pConVar, this);
340 /* To prevent creating a convar that has the same name as a console command... ugh */
341 ConCommandBase *pBase = icvar->GetCommands();
345 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
350 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
353 /* Create and initialize ConVarInfo structure */
354 pInfo = new ConVarInfo();
355 pInfo->handle = hndl;
356 pInfo->sourceMod = true;
357 pInfo->pChangeForward = NULL;
358 pInfo->origCallback = NULL;
360 /* Create a handle from the new convar */
361 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
362 if (hndl == BAD_HANDLE)
368 pInfo->handle = hndl;
370 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
371 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
372 pInfo->pVar = pConVar;
374 /* Add convar to plugin's list */
375 AddConVarToPluginList(pContext, pConVar);
377 /* Insert struct into caches */
378 m_ConVars.push_back(pInfo);
379 convar_cache.insert(name, pInfo);
384 Handle_t ConVarManager::FindConVar(const char *name)
386 ConVar *pConVar = NULL;
390 /* Search for convar */
391 pConVar = icvar->FindVar(name);
393 /* If it doesn't exist, then return an invalid handle */
399 /* At this point, the convar exists. So, find out if we already have a handle */
400 if (convar_cache_lookup(name, &pInfo))
402 return pInfo->handle;
405 /* Create and initialize ConVarInfo structure */
406 pInfo = new ConVarInfo();
407 pInfo->sourceMod = false;
408 pInfo->pChangeForward = NULL;
409 pInfo->origCallback = pConVar->GetCallback();
410 pInfo->pVar = pConVar;
412 /* If we don't have a handle, then create a new one */
413 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
414 if (hndl == BAD_HANDLE)
420 pInfo->handle = hndl;
422 /* Insert struct into our caches */
423 m_ConVars.push_back(pInfo);
424 convar_cache.insert(name, pInfo);
425 TrackConCommandBase(pConVar, this);
430 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
433 IChangeableForward *pForward;
435 /* Find the convar in the lookup trie */
436 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
438 /* Get the forward */
439 pForward = pInfo->pChangeForward;
441 /* If forward does not exist, create it */
444 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
445 pInfo->pChangeForward = pForward;
447 /* Install our own callback */
448 pConVar->InstallChangeCallback(OnConVarChanged);
451 /* Add function to forward's list */
452 pForward->AddFunction(pFunction);
456 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
459 IChangeableForward *pForward;
460 IPluginContext *pContext = pFunction->GetParentContext();
462 /* Find the convar in the lookup trie */
463 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
465 /* Get the forward */
466 pForward = pInfo->pChangeForward;
468 /* If the forward doesn't exist, we can't unhook anything */
471 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
475 /* Remove the function from the forward's list */
476 if (!pForward->RemoveFunction(pFunction))
478 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
482 /* If the forward now has 0 functions in it... */
483 if (pForward->GetFunctionCount() == 0)
485 /* Free this forward */
486 g_Forwards.ReleaseForward(pForward);
487 pInfo->pChangeForward = NULL;
489 /* Put back the original convar callback */
490 pConVar->InstallChangeCallback(pInfo->origCallback);
495 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
497 QueryCvarCookie_t cookie;
499 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
500 if (m_bIsDLLQueryHooked)
502 cookie = engine->StartQueryCvarValue(pPlayer, name);
504 else if (m_bIsVSPQueryHooked)
506 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
510 return InvalidQueryCvarCookie;
513 ConVarQuery query = {cookie, pCallback, hndl};
514 m_ConVarQueries.push_back(query);
519 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
521 ConVarList *pConVarList;
522 ConVarList::iterator iter;
523 bool inserted = false;
524 const char *orig = pConVar->GetName();
526 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
528 /* Check plugin for an existing convar list */
529 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
531 pConVarList = new ConVarList();
532 plugin->SetProperty("ConVarList", pConVarList);
534 else if (pConVarList->find(pConVar) != pConVarList->end())
536 /* If convar is already in list, then don't add it */
540 /* Insert convar into list which is sorted alphabetically */
541 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
543 if (strcmp(orig, (*iter)->GetName()) < 0)
545 pConVarList->insert(iter, pConVar);
553 pConVarList->push_back(pConVar);
557 #if defined ORANGEBOX_BUILD
558 void ConVarManager::OnConVarChanged(IConVar *pIConVar, const char *oldValue, float flOldValue)
560 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
563 /* If the values are the same, exit early in order to not trigger callbacks */
564 #if defined ORANGEBOX_BUILD
565 ConVar *pConVar = (ConVar *)pIConVar;
567 if (strcmp(pConVar->GetString(), oldValue) == 0)
574 /* Find the convar in the lookup trie */
575 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
580 FnChangeCallback_t origCallback = pInfo->origCallback;
581 IChangeableForward *pForward = pInfo->pChangeForward;
583 /* If there was a change callback installed previously, call it */
586 #if defined ORANGEBOX_BUILD
587 origCallback(pConVar, oldValue, flOldValue);
589 origCallback(pConVar, oldValue);
593 /* Now call forwards in plugins that have hooked this */
594 pForward->PushCell(pInfo->handle);
595 pForward->PushString(oldValue);
596 pForward->PushString(reinterpret_cast<ConVar *>(pConVar)->GetString());
597 pForward->Execute(NULL);
600 bool ConVarManager::IsQueryingSupported()
602 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
605 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
607 IPluginFunction *pCallback = NULL;
609 List<ConVarQuery>::iterator iter;
611 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
613 ConVarQuery &query = (*iter);
614 if (query.cookie == cookie)
616 pCallback = query.pCallback;
626 pCallback->PushCell(cookie);
627 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
628 pCallback->PushCell(result);
629 pCallback->PushString(cvarName);
631 if (result == eQueryCvarValueStatus_ValueIntact)
633 pCallback->PushString(cvarValue);
637 pCallback->PushString("\0");
640 pCallback->PushCell(value);
641 pCallback->Execute(&ret);
643 m_ConVarQueries.erase(iter);
647 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
652 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)
665 static int s_YamagramState = 0;
667 void _YamagramPrinterTwoPointOhOh(int yamagram)
672 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
673 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
674 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
675 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
676 g_RootMenu.ConsolePrint("-------------------------------");
677 _YamagramPrinterTwoPointOhOh(1);
680 g_RootMenu.ConsolePrint("Question Ichi (1)");
681 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
682 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
685 g_RootMenu.ConsolePrint("Question Ni (2)");
686 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
687 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
690 g_RootMenu.ConsolePrint("Question San (3)");
691 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
692 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
695 g_RootMenu.ConsolePrint("Question Yon (4)");
696 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
697 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
700 g_RootMenu.ConsolePrint("Question Go (5)");
701 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
702 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
705 g_RootMenu.ConsolePrint("Question Roku (6)");
706 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
707 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
710 g_RootMenu.ConsolePrint("Question Nana (7)");
711 g_RootMenu.ConsolePrint("What is my name?");
712 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
718 s_YamagramState = yamagram;
721 #if defined ORANGEBOX_BUILD
722 void _IntExt_CallYamagrams(const CCommand &cmd)
725 void _IntExt_CallYamagrams()
729 bool correct = false;
730 const char *arg = cmd.ArgS();
732 if (!arg || arg[0] == '\0')
734 _YamagramPrinterTwoPointOhOh(s_YamagramState);
738 switch (s_YamagramState)
741 correct = !strcasecmp(arg, "eating grass");
744 correct = !strcasecmp(arg, "sombrero");
747 correct = !strcasecmp(arg, "david bailopan anderson");
750 correct = !strcasecmp(arg, "kaitei no kairan");
753 correct = !strcasecmp(arg, "life and death");
756 correct = !strcasecmp(arg, "because gabe wanted it that way");
759 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
760 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
761 g_RootMenu.ConsolePrint("-------------------------------");
762 _YamagramPrinterTwoPointOhOh(7);
767 correct = !strcasecmp(arg, "damaged soul");
770 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
771 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
772 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
773 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
774 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
784 if (s_YamagramState > 0)
788 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
789 g_RootMenu.ConsolePrint("-------------------------------");
792 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
797 _YamagramPrinterTwoPointOhOh(s_YamagramState);
800 void _IntExt_EnableYamagrams()
802 static ConCommand *pCmd = NULL;
805 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
806 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
808 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
812 #if defined ORANGEBOX_BUILD
813 void _IntExt_OnHostnameChanged(IConVar *pConVar, const char *oldValue, float flOldValue)
815 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
818 if (strcmp(oldValue, "Good morning, DS-san.") == 0
819 && strcmp(reinterpret_cast<ConVar *>(pConVar)->GetString(), "Good night, talking desk lamp.") == 0)
821 _IntExt_EnableYamagrams();