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 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
246 *pSize = sizeof(ConVar);
250 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
252 int argcount = command.ArgC();
255 /* Get plugin index that was passed */
256 int id = atoi(command.Arg(2));
258 /* Get plugin object */
259 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
263 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
267 /* Get plugin name */
268 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
269 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
271 ConVarList *pConVarList;
272 ConVarList::iterator iter;
274 /* If no convar list... */
275 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
277 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
281 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
282 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
284 /* Iterate convar list and display each one */
285 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
287 const ConVar *pConVar = (*iter);
288 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
294 /* Display usage of subcommand */
295 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
298 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)
300 ConVar *pConVar = NULL;
301 ConVarInfo *pInfo = NULL;
304 /* Find out if the convar exists already */
305 pConVar = icvar->FindVar(name);
307 /* If the convar already exists... */
310 /* Add convar to plugin's list */
311 AddConVarToPluginList(pContext, pConVar);
313 /* First find out if we already have a handle to it */
314 if (convar_cache_lookup(name, &pInfo))
316 return pInfo->handle;
320 /* Create and initialize ConVarInfo structure */
321 pInfo = new ConVarInfo();
322 pInfo->sourceMod = false;
323 pInfo->pChangeForward = NULL;
324 pInfo->origCallback = pConVar->GetCallback();
325 pInfo->pVar = pConVar;
327 /* If we don't, then create a new handle from the convar */
328 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
329 if (hndl == BAD_HANDLE)
335 pInfo->handle = hndl;
337 /* Insert struct into caches */
338 m_ConVars.push_back(pInfo);
339 convar_cache.insert(name, pInfo);
340 TrackConCommandBase(pConVar, this);
346 /* To prevent creating a convar that has the same name as a console command... ugh */
347 ConCommandBase *pBase = icvar->GetCommands();
351 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
356 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
359 /* Create and initialize ConVarInfo structure */
360 pInfo = new ConVarInfo();
361 pInfo->handle = hndl;
362 pInfo->sourceMod = true;
363 pInfo->pChangeForward = NULL;
364 pInfo->origCallback = NULL;
366 /* Create a handle from the new convar */
367 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
368 if (hndl == BAD_HANDLE)
374 pInfo->handle = hndl;
376 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
377 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
378 pInfo->pVar = pConVar;
380 /* Add convar to plugin's list */
381 AddConVarToPluginList(pContext, pConVar);
383 /* Insert struct into caches */
384 m_ConVars.push_back(pInfo);
385 convar_cache.insert(name, pInfo);
390 Handle_t ConVarManager::FindConVar(const char *name)
392 ConVar *pConVar = NULL;
396 /* Search for convar */
397 pConVar = icvar->FindVar(name);
399 /* If it doesn't exist, then return an invalid handle */
405 /* At this point, the convar exists. So, find out if we already have a handle */
406 if (convar_cache_lookup(name, &pInfo))
408 return pInfo->handle;
411 /* Create and initialize ConVarInfo structure */
412 pInfo = new ConVarInfo();
413 pInfo->sourceMod = false;
414 pInfo->pChangeForward = NULL;
415 pInfo->origCallback = pConVar->GetCallback();
416 pInfo->pVar = pConVar;
418 /* If we don't have a handle, then create a new one */
419 hndl = g_HandleSys.CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
420 if (hndl == BAD_HANDLE)
426 pInfo->handle = hndl;
428 /* Insert struct into our caches */
429 m_ConVars.push_back(pInfo);
430 convar_cache.insert(name, pInfo);
431 TrackConCommandBase(pConVar, this);
436 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
439 IChangeableForward *pForward;
441 /* Find the convar in the lookup trie */
442 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
444 /* Get the forward */
445 pForward = pInfo->pChangeForward;
447 /* If forward does not exist, create it */
450 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
451 pInfo->pChangeForward = pForward;
453 /* Install our own callback */
454 pConVar->InstallChangeCallback(OnConVarChanged);
457 /* Add function to forward's list */
458 pForward->AddFunction(pFunction);
462 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
465 IChangeableForward *pForward;
466 IPluginContext *pContext = pFunction->GetParentContext();
468 /* Find the convar in the lookup trie */
469 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
471 /* Get the forward */
472 pForward = pInfo->pChangeForward;
474 /* If the forward doesn't exist, we can't unhook anything */
477 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
481 /* Remove the function from the forward's list */
482 if (!pForward->RemoveFunction(pFunction))
484 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
488 /* If the forward now has 0 functions in it... */
489 if (pForward->GetFunctionCount() == 0)
491 /* Free this forward */
492 g_Forwards.ReleaseForward(pForward);
493 pInfo->pChangeForward = NULL;
495 /* Put back the original convar callback */
496 pConVar->InstallChangeCallback(pInfo->origCallback);
501 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
503 QueryCvarCookie_t cookie;
505 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
506 if (m_bIsDLLQueryHooked)
508 cookie = engine->StartQueryCvarValue(pPlayer, name);
510 else if (m_bIsVSPQueryHooked)
512 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
516 return InvalidQueryCvarCookie;
519 ConVarQuery query = {cookie, pCallback, hndl};
520 m_ConVarQueries.push_back(query);
525 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
527 ConVarList *pConVarList;
528 ConVarList::iterator iter;
529 bool inserted = false;
530 const char *orig = pConVar->GetName();
532 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
534 /* Check plugin for an existing convar list */
535 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
537 pConVarList = new ConVarList();
538 plugin->SetProperty("ConVarList", pConVarList);
540 else if (pConVarList->find(pConVar) != pConVarList->end())
542 /* If convar is already in list, then don't add it */
546 /* Insert convar into list which is sorted alphabetically */
547 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
549 if (strcmp(orig, (*iter)->GetName()) < 0)
551 pConVarList->insert(iter, pConVar);
559 pConVarList->push_back(pConVar);
563 #if defined ORANGEBOX_BUILD
564 void ConVarManager::OnConVarChanged(IConVar *pIConVar, const char *oldValue, float flOldValue)
566 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
569 /* If the values are the same, exit early in order to not trigger callbacks */
570 #if defined ORANGEBOX_BUILD
571 ConVar *pConVar = (ConVar *)pIConVar;
573 if (strcmp(pConVar->GetString(), oldValue) == 0)
580 /* Find the convar in the lookup trie */
581 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
586 FnChangeCallback_t origCallback = pInfo->origCallback;
587 IChangeableForward *pForward = pInfo->pChangeForward;
589 /* If there was a change callback installed previously, call it */
592 #if defined ORANGEBOX_BUILD
593 origCallback(pConVar, oldValue, flOldValue);
595 origCallback(pConVar, oldValue);
599 /* Now call forwards in plugins that have hooked this */
600 pForward->PushCell(pInfo->handle);
601 pForward->PushString(oldValue);
602 pForward->PushString(reinterpret_cast<ConVar *>(pConVar)->GetString());
603 pForward->Execute(NULL);
606 bool ConVarManager::IsQueryingSupported()
608 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
611 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
613 IPluginFunction *pCallback = NULL;
615 List<ConVarQuery>::iterator iter;
617 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
619 ConVarQuery &query = (*iter);
620 if (query.cookie == cookie)
622 pCallback = query.pCallback;
632 pCallback->PushCell(cookie);
633 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
634 pCallback->PushCell(result);
635 pCallback->PushString(cvarName);
637 if (result == eQueryCvarValueStatus_ValueIntact)
639 pCallback->PushString(cvarValue);
643 pCallback->PushString("\0");
646 pCallback->PushCell(value);
647 pCallback->Execute(&ret);
649 m_ConVarQueries.erase(iter);
653 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
658 if ((error = g_HandleSys.ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)
671 static int s_YamagramState = 0;
673 void _YamagramPrinterTwoPointOhOh(int yamagram)
678 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
679 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
680 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
681 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
682 g_RootMenu.ConsolePrint("-------------------------------");
683 _YamagramPrinterTwoPointOhOh(1);
686 g_RootMenu.ConsolePrint("Question Ichi (1)");
687 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
688 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
691 g_RootMenu.ConsolePrint("Question Ni (2)");
692 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
693 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
696 g_RootMenu.ConsolePrint("Question San (3)");
697 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
698 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
701 g_RootMenu.ConsolePrint("Question Yon (4)");
702 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
703 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
706 g_RootMenu.ConsolePrint("Question Go (5)");
707 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
708 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
711 g_RootMenu.ConsolePrint("Question Roku (6)");
712 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
713 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
716 g_RootMenu.ConsolePrint("Question Nana (7)");
717 g_RootMenu.ConsolePrint("What is my name?");
718 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
724 s_YamagramState = yamagram;
727 #if defined ORANGEBOX_BUILD
728 void _IntExt_CallYamagrams(const CCommand &cmd)
731 void _IntExt_CallYamagrams()
735 bool correct = false;
736 const char *arg = cmd.ArgS();
738 if (!arg || arg[0] == '\0')
740 _YamagramPrinterTwoPointOhOh(s_YamagramState);
744 switch (s_YamagramState)
747 correct = !strcasecmp(arg, "eating grass");
750 correct = !strcasecmp(arg, "sombrero");
753 correct = !strcasecmp(arg, "david bailopan anderson");
756 correct = !strcasecmp(arg, "kaitei no kairan");
759 correct = !strcasecmp(arg, "life and death");
762 correct = !strcasecmp(arg, "because gabe wanted it that way");
765 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
766 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
767 g_RootMenu.ConsolePrint("-------------------------------");
768 _YamagramPrinterTwoPointOhOh(7);
773 correct = !strcasecmp(arg, "damaged soul");
776 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
777 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
778 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
779 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
780 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
790 if (s_YamagramState > 0)
794 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
795 g_RootMenu.ConsolePrint("-------------------------------");
798 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
803 _YamagramPrinterTwoPointOhOh(s_YamagramState);
806 void _IntExt_EnableYamagrams()
808 static ConCommand *pCmd = NULL;
811 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
812 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
814 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
818 #if defined ORANGEBOX_BUILD
819 void _IntExt_OnHostnameChanged(IConVar *pConVar, const char *oldValue, float flOldValue)
821 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
824 if (strcmp(oldValue, "Good morning, DS-san.") == 0
825 && strcmp(reinterpret_cast<ConVar *>(pConVar)->GetString(), "Good night, talking desk lamp.") == 0)
827 _IntExt_EnableYamagrams();