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 "PlayerManager.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;
50 ConVarManager::ConVarManager() : m_ConVarType(0), m_VSPIface(NULL), m_CanQueryConVars(false)
52 #if PLAPI_VERSION < 12
53 m_IgnoreHandle = false;
56 /* Create a convar lookup trie */
57 m_ConVarCache = sm_trie_create();
60 ConVarManager::~ConVarManager()
62 List<ConVarInfo *>::iterator iter;
64 /* Destroy our convar lookup trie */
65 sm_trie_destroy(m_ConVarCache);
67 /* Destroy all the ConVarInfo structures */
68 for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
76 void ConVarManager::OnSourceModAllInitialized()
78 /* Only valid with ServerGameDLL006 or greater */
79 if (g_SMAPI->GetGameDLLVersion() >= 6)
81 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
82 m_CanQueryConVars = true;
87 /* Set up access rights for the 'ConVar' handle type */
88 sec.access[HandleAccess_Read] = 0;
89 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
90 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
92 /* Create the 'ConVar' handle type */
93 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
95 /* Add the 'convars' option to the 'sm' console command */
96 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
99 void ConVarManager::OnSourceModShutdown()
101 if (m_CanQueryConVars)
103 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
104 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, m_VSPIface, this, &ConVarManager::OnQueryCvarValueFinished, false);
107 IChangeableForward *fwd;
108 List<ConVarInfo *>::iterator i;
110 /* Iterate list of ConVarInfo structures */
111 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
113 fwd = (*i)->pChangeForward;
115 /* Free any convar-change forwards that still exist */
118 g_Forwards.ReleaseForward(fwd);
122 /* Remove the 'convars' option from the 'sm' console command */
123 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
125 /* Remove the 'ConVar' handle type */
126 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
129 void ConVarManager::OnSourceModVSPReceived(IServerPluginCallbacks *iface)
131 /* This will be called after OnSourceModAllInitialized(), so...
133 * If we haven't been able to hook the IServerGameDLL version at this point,
134 * then use hook IServerPluginCallbacks version from the engine.
137 /* The Ship currently only supports ServerPluginCallbacks001, but we need 002 */
138 if (g_IsOriginalEngine)
143 if (!m_CanQueryConVars)
147 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, iface, this, &ConVarManager::OnQueryCvarValueFinished, false);
148 m_CanQueryConVars = true;
152 #if PLAPI_VERSION >= 12
153 void ConVarManager::OnUnlinkConCommandBase(PluginId id, ConCommandBase *pCommand)
155 /* Only check convars that have not been created by SourceMod's core */
156 if (id != g_PLID && !pCommand->IsCommand())
159 const char *cvarName = pCommand->GetName();
160 HandleSecurity sec(NULL, g_pCoreIdent);
161 bool handleExists = sm_trie_retrieve(m_ConVarCache, cvarName, reinterpret_cast<void **>(&pInfo));
165 g_HandleSys.FreeHandle(pInfo->handle, &sec);
166 sm_trie_delete(m_ConVarCache, cvarName);
167 m_ConVars.remove(pInfo);
174 /* I truly detest this code */
175 void ConVarManager::OnMetamodPluginUnloaded(PluginId id)
178 const char *cvarName;
179 HandleSecurity sec(NULL, g_pCoreIdent);
181 List<ConVarInfo *>::iterator i;
182 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
185 cvarName = pInfo->name;
187 if (cvarName && !icvar->FindVar(cvarName))
189 m_IgnoreHandle = true;
190 g_HandleSys.FreeHandle(pInfo->handle, &sec);
192 sm_trie_delete(m_ConVarCache, cvarName);
201 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
203 ConVarList *pConVarList;
205 /* If plugin has a convar list, free its memory */
206 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
212 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
214 #if PLAPI_VERSION < 12
215 /* Lovely workaround for our workaround! */
218 m_IgnoreHandle = false;
224 ConVar *pConVar = static_cast<ConVar *>(object);
226 /* Find convar in lookup trie */
227 sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
229 /* If convar was created by SourceMod plugin... */
232 /* Delete string allocations */
233 delete [] pConVar->GetName();
234 delete [] pConVar->GetDefault();
235 delete [] pConVar->GetHelpText();
237 /* Then unlink it from SourceMM */
238 g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
242 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
246 /* Get plugin index that was passed */
247 int id = atoi(g_RootMenu.GetArgument(2));
249 /* Get plugin object */
250 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
254 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
258 /* Get plugin name */
259 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
260 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
262 ConVarList *pConVarList;
263 ConVarList::iterator iter;
265 /* If no convar list... */
266 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
268 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
272 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
273 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
275 /* Iterate convar list and display each one */
276 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
278 const ConVar *pConVar = (*iter);
279 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
285 /* Display usage of subcommand */
286 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
289 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)
291 ConVar *pConVar = NULL;
292 ConVarInfo *pInfo = NULL;
295 /* Find out if the convar exists already */
296 pConVar = icvar->FindVar(name);
298 /* If the convar already exists... */
301 /* Add convar to plugin's list */
302 AddConVarToPluginList(pContext, pConVar);
304 /* First find out if we already have a handle to it */
305 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
307 return pInfo->handle;
309 /* If we don't, then create a new handle from the convar */
310 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
312 /* Create and initialize ConVarInfo structure */
313 pInfo = new ConVarInfo();
314 pInfo->handle = hndl;
315 pInfo->sourceMod = false;
316 pInfo->pChangeForward = NULL;
317 pInfo->origCallback = pConVar->GetCallback();
318 #if PLAPI_VERSION < 12
319 pInfo->name = sm_strdup(pConVar->GetName());
322 /* Insert struct into caches */
323 m_ConVars.push_back(pInfo);
324 sm_trie_insert(m_ConVarCache, name, pInfo);
330 /* To prevent creating a convar that has the same name as a console command... ugh */
331 ConCommandBase *pBase = icvar->GetCommands();
335 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
340 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
343 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
344 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
346 /* Add convar to plugin's list */
347 AddConVarToPluginList(pContext, pConVar);
349 /* Create a handle from the new convar */
350 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
352 /* Create and initialize ConVarInfo structure */
353 pInfo = new ConVarInfo();
354 pInfo->handle = hndl;
355 pInfo->sourceMod = true;
356 pInfo->pChangeForward = NULL;
357 pInfo->origCallback = NULL;
358 #if PLAPI_VERSION < 12
362 /* Insert struct into caches */
363 m_ConVars.push_back(pInfo);
364 sm_trie_insert(m_ConVarCache, name, pInfo);
369 Handle_t ConVarManager::FindConVar(const char *name)
371 ConVar *pConVar = NULL;
375 /* Search for convar */
376 pConVar = icvar->FindVar(name);
378 /* If it doesn't exist, then return an invalid handle */
384 /* At this point, the convar exists. So, find out if we already have a handle */
385 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
387 return pInfo->handle;
390 /* If we don't have a handle, then create a new one */
391 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
393 /* Create and initialize ConVarInfo structure */
394 pInfo = new ConVarInfo();
395 pInfo->handle = hndl;
396 pInfo->sourceMod = false;
397 pInfo->pChangeForward = NULL;
398 pInfo->origCallback = pConVar->GetCallback();
399 #if PLAPI_VERSION < 12
400 pInfo->name = sm_strdup(pConVar->GetName());
403 /* Insert struct into our caches */
404 m_ConVars.push_back(pInfo);
405 sm_trie_insert(m_ConVarCache, name, pInfo);
410 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
413 IChangeableForward *pForward;
415 /* Find the convar in the lookup trie */
416 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
418 /* Get the forward */
419 pForward = pInfo->pChangeForward;
421 /* If forward does not exist, create it */
424 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
425 pInfo->pChangeForward = pForward;
427 /* Install our own callback */
428 pConVar->InstallChangeCallback(OnConVarChanged);
431 /* Add function to forward's list */
432 pForward->AddFunction(pFunction);
436 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
439 IChangeableForward *pForward;
440 IPluginContext *pContext = pFunction->GetParentContext();
442 /* Find the convar in the lookup trie */
443 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
445 /* Get the forward */
446 pForward = pInfo->pChangeForward;
448 /* If the forward doesn't exist, we can't unhook anything */
451 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
455 /* Remove the function from the forward's list */
456 if (!pForward->RemoveFunction(pFunction))
458 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
462 /* If the forward now has 0 functions in it... */
463 if (pForward->GetFunctionCount() == 0)
465 /* Free this forward */
466 g_Forwards.ReleaseForward(pForward);
467 pInfo->pChangeForward = NULL;
469 /* Put back the original convar callback */
470 pConVar->InstallChangeCallback(pInfo->origCallback);
475 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
477 QueryCvarCookie_t cookie;
479 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
482 cookie = engine->StartQueryCvarValue(pPlayer, name);
484 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
487 ConVarQuery query = {cookie, pCallback, hndl};
488 m_ConVarQueries.push_back(query);
493 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
495 ConVarList *pConVarList;
496 ConVarList::iterator iter;
497 bool inserted = false;
498 const char *orig = pConVar->GetName();
500 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
502 /* Check plugin for an existing convar list */
503 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
505 pConVarList = new ConVarList();
506 plugin->SetProperty("ConVarList", pConVarList);
507 } else if (pConVarList->find(pConVar) != pConVarList->end()) {
508 /* If convar is already in list, then don't add it */
512 /* Insert convar into list which is sorted alphabetically */
513 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
515 if (strcmp(orig, (*iter)->GetName()) < 0)
517 pConVarList->insert(iter, pConVar);
525 pConVarList->push_back(pConVar);
529 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
531 /* If the values are the same, exit early in order to not trigger callbacks */
532 if (strcmp(pConVar->GetString(), oldValue) == 0)
537 Trie *pCache = g_ConVarManager.GetConVarCache();
540 /* Find the convar in the lookup trie */
541 sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
543 FnChangeCallback origCallback = pInfo->origCallback;
544 IChangeableForward *pForward = pInfo->pChangeForward;
546 /* If there was a change callback installed previously, call it */
549 origCallback(pConVar, oldValue);
552 /* Now call forwards in plugins that have hooked this */
553 pForward->PushCell(pInfo->handle);
554 pForward->PushString(oldValue);
555 pForward->PushString(pConVar->GetString());
556 pForward->Execute(NULL);
559 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
561 IPluginFunction *pCallback = NULL;
563 List<ConVarQuery>::iterator iter;
565 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
567 ConVarQuery &query = (*iter);
568 if (query.cookie == cookie)
570 pCallback = query.pCallback;
575 g_Players.HandleLangQuery(engine->GetPlayerUserId(pPlayer), (result == eQueryCvarValueStatus_ValueIntact) ? cvarValue : "", cookie);
576 m_ConVarQueries.erase(iter);
588 pCallback->PushCell(cookie);
589 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
590 pCallback->PushCell(result);
591 pCallback->PushString(cvarName);
593 if (result == eQueryCvarValueStatus_ValueIntact)
595 pCallback->PushString(cvarValue);
597 pCallback->PushString("\0");
600 pCallback->PushCell(value);
601 pCallback->Execute(&ret);
603 m_ConVarQueries.erase(iter);
608 static int s_YamagramState = 0;
610 void _YamagramPrinterTwoPointOhOh(int yamagram)
615 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
616 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
617 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
618 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
619 g_RootMenu.ConsolePrint("-------------------------------");
620 _YamagramPrinterTwoPointOhOh(1);
623 g_RootMenu.ConsolePrint("Question Ichi (1)");
624 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
625 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
628 g_RootMenu.ConsolePrint("Question Ni (2)");
629 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
630 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
633 g_RootMenu.ConsolePrint("Question San (3)");
634 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
635 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
638 g_RootMenu.ConsolePrint("Question Yon (4)");
639 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
640 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
643 g_RootMenu.ConsolePrint("Question Go (5)");
644 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
645 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
648 g_RootMenu.ConsolePrint("Question Roku (6)");
649 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
650 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
653 g_RootMenu.ConsolePrint("Question Nana (7)");
654 g_RootMenu.ConsolePrint("What is my name?");
655 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
661 s_YamagramState = yamagram;
664 void _IntExt_CallYamagrams()
666 bool correct = false;
667 const char *arg = engine->Cmd_Args();
669 if (!arg || arg[0] == '\0')
671 _YamagramPrinterTwoPointOhOh(s_YamagramState);
675 switch (s_YamagramState)
678 correct = !strcasecmp(arg, "eating grass");
681 correct = !strcasecmp(arg, "sombrero");
684 correct = !strcasecmp(arg, "david bailopan anderson");
687 correct = !strcasecmp(arg, "kaitei no kairan");
690 correct = !strcasecmp(arg, "life and death");
693 correct = !strcasecmp(arg, "because gabe wanted it that way");
696 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
697 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
698 g_RootMenu.ConsolePrint("-------------------------------");
699 _YamagramPrinterTwoPointOhOh(7);
704 correct = !strcasecmp(arg, "damaged soul");
707 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
708 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
709 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
710 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
711 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
721 if (s_YamagramState > 0)
725 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
726 g_RootMenu.ConsolePrint("-------------------------------");
729 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
734 _YamagramPrinterTwoPointOhOh(s_YamagramState);
737 void _IntExt_EnableYamagrams()
739 static ConCommand *pCmd = NULL;
742 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
743 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
745 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
749 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
751 if (strcmp(oldValue, "Good morning, DS-san.") == 0
752 && strcmp(pConVar->GetString(), "Good night, talking desk lamp.") == 0)
754 _IntExt_EnableYamagrams();