3 * =============================================================================
5 * Copyright (C) 2004-2008 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 "ConCmdManager.h"
33 #include "sm_srvcmds.h"
34 #include "AdminCache.h"
35 #include "sm_stringutil.h"
36 #include "PlayerManager.h"
37 #include "Translator.h"
38 #include "HalfLife2.h"
39 #include "ChatTriggers.h"
41 ConCmdManager g_ConCmds;
43 #if defined ORANGEBOX_BUILD
44 SH_DECL_HOOK1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
46 SH_DECL_HOOK0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
49 SH_DECL_HOOK1_void(IServerGameClients, SetCommandClient, SH_NOATTRIB, false, int);
57 typedef List<PlCmdInfo> CmdList;
59 void AddToPlCmdList(CmdList *pList, const PlCmdInfo &info);
61 ConCmdManager::ConCmdManager() : m_Strings(1024)
63 m_pCmds = sm_trie_create();
64 m_pCmdGrps = sm_trie_create();
68 ConCmdManager::~ConCmdManager()
70 sm_trie_destroy(m_pCmds);
71 sm_trie_destroy(m_pCmdGrps);
74 void ConCmdManager::OnSourceModAllInitialized()
76 g_PluginSys.AddPluginsListener(this);
77 g_RootMenu.AddRootConsoleCommand("cmds", "List console commands", this);
78 SH_ADD_HOOK_MEMFUNC(IServerGameClients, SetCommandClient, serverClients, this, &ConCmdManager::SetCommandClient, false);
81 void ConCmdManager::OnSourceModShutdown()
83 /* All commands should already be removed by the time we're done */
84 SH_REMOVE_HOOK_MEMFUNC(IServerGameClients, SetCommandClient, serverClients, this, &ConCmdManager::SetCommandClient, false);
85 g_RootMenu.RemoveRootConsoleCommand("cmds", this);
88 void ConCmdManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
90 /* Whoa, first get its information struct */
93 if (!sm_trie_retrieve(m_pCmds, name, (void **)&pInfo))
98 RemoveConCmds(pInfo->srvhooks);
99 RemoveConCmds(pInfo->conhooks);
101 RemoveConCmd(pInfo, name, is_read_safe, false);
104 void ConCmdManager::RemoveConCmds(List<CmdHook *> &cmdlist)
106 List<CmdHook *>::iterator iter = cmdlist.begin();
108 while (iter != cmdlist.end())
110 CmdHook *pHook = (*iter);
111 IPluginContext *pContext = pHook->pf->GetParentContext();
112 IPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
113 CmdList *pList = NULL;
116 if (!pPlugin->GetProperty("CommandList", (void **)&pList, false) || !pList)
121 CmdList::iterator p_iter = pList->begin();
122 while (p_iter != pList->end())
124 PlCmdInfo &cmd = (*p_iter);
125 if (cmd.pHook == pHook)
127 p_iter = pList->erase(p_iter);
135 delete pHook->pAdmin;
138 iter = cmdlist.erase(iter);
142 void ConCmdManager::RemoveConCmds(List<CmdHook *> &cmdlist, IPluginContext *pContext)
144 List<CmdHook *>::iterator iter = cmdlist.begin();
147 while (iter != cmdlist.end())
150 if (pHook->pf->GetParentContext() == pContext)
152 delete pHook->pAdmin;
154 iter = cmdlist.erase(iter);
163 void ConCmdManager::OnPluginDestroyed(IPlugin *plugin)
166 List<ConCmdInfo *> removed;
167 if (plugin->GetProperty("CommandList", (void **)&pList, true))
169 IPluginContext *pContext = plugin->GetBaseContext();
170 CmdList::iterator iter;
172 * Only bother if there's an actual command list on this plugin...
174 for (iter=pList->begin();
178 PlCmdInfo &cmd = (*iter);
179 ConCmdInfo *pInfo = cmd.pInfo;
181 /* Has this chain already been fully cleaned/removed? */
182 if (removed.find(pInfo) != removed.end())
187 /* Remove any hooks from us on this command */
188 RemoveConCmds(pInfo->conhooks, pContext);
189 RemoveConCmds(pInfo->srvhooks, pContext);
191 /* See if there are still hooks */
192 if (pInfo->srvhooks.size())
196 if (pInfo->conhooks.size())
201 /* Remove the command, it should be safe now */
202 RemoveConCmd(pInfo, pInfo->pCmd->GetName(), true, true);
203 removed.push_back(pInfo);
208 #if defined ORANGEBOX_BUILD
209 void CommandCallback(const CCommand &command)
212 void CommandCallback()
217 g_HL2.PushCommandStack(&command);
219 g_ConCmds.InternalDispatch(command);
221 g_HL2.PopCommandStack();
224 void ConCmdManager::SetCommandClient(int client)
226 m_CmdClient = client + 1;
229 ResultType ConCmdManager::DispatchClientCommand(int client, const char *cmd, int args, ResultType type)
232 if (sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
234 cell_t result = type;
235 cell_t tempres = result;
236 List<CmdHook *>::iterator iter;
238 for (iter=pInfo->conhooks.begin();
239 iter!=pInfo->conhooks.end();
243 if (!pHook->pf->IsRunnable())
247 if (pHook->pAdmin && !CheckAccess(client, cmd, pHook->pAdmin))
249 if (result < Pl_Handled)
255 pHook->pf->PushCell(client);
256 pHook->pf->PushCell(args);
257 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
259 if (tempres > result)
263 if (result == Pl_Stop)
269 type = (ResultType)result;
275 void ConCmdManager::InternalDispatch(const CCommand &command)
277 int client = m_CmdClient;
281 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
282 if (!pPlayer || !pPlayer->IsConnected())
289 * Note: Console commands will EITHER go through IServerGameDLL::ClientCommand,
290 * OR this dispatch. They will NEVER go through both.
292 * Whether or not it goes through the callback is determined by FCVAR_GAMEDLL
294 const char *cmd = g_HL2.CurrentCommandName();
297 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
302 /* This is a hack to prevent say triggers from firing on messages that were
303 * blocked because of flooding. We won't remove this, but the hack will get
304 * "nicer" when we expose explicit say hooks.
306 if (g_ChatTriggers.WasFloodedMessage())
311 cell_t result = Pl_Continue;
312 int args = command.ArgC() - 1;
314 List<CmdHook *>::iterator iter;
317 /* Execute server-only commands if viable */
318 if (client == 0 && pInfo->srvhooks.size())
320 cell_t tempres = result;
321 for (iter=pInfo->srvhooks.begin();
322 iter!=pInfo->srvhooks.end();
326 if (!pHook->pf->IsRunnable())
330 pHook->pf->PushCell(args);
331 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
333 if (tempres > result)
337 if (result == Pl_Stop)
344 /* Check if there's an early stop */
345 if (result >= Pl_Stop)
347 if (!pInfo->sourceMod)
349 RETURN_META(MRES_SUPERCEDE);
355 /* Execute console commands */
356 if (pInfo->conhooks.size())
358 cell_t tempres = result;
359 for (iter=pInfo->conhooks.begin();
360 iter!=pInfo->conhooks.end();
364 if (!pHook->pf->IsRunnable())
370 && !CheckAccess(client, cmd, pHook->pAdmin))
372 if (result < Pl_Handled)
379 /* On a listen server, sometimes the server host's client index can be set as 0.
380 * So index 1 is passed to the command callback to correct this potential problem.
382 if (!engine->IsDedicatedServer())
384 client = g_Players.ListenClient();
387 pHook->pf->PushCell(client);
388 pHook->pf->PushCell(args);
390 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
392 if (tempres > result)
396 if (result == Pl_Stop)
404 if (result >= Pl_Handled)
406 if (!pInfo->sourceMod)
408 RETURN_META(MRES_SUPERCEDE);
414 bool ConCmdManager::CheckCommandAccess(int client, const char *cmd, FlagBits cmdflags)
416 if (cmdflags == 0 || client == 0)
421 /* If running listen server, then client 1 is the server host and should have 'root' access */
422 if (client == 1 && !engine->IsDedicatedServer())
427 CPlayer *player = g_Players.GetPlayerByIndex(client);
429 || player->GetEdict() == NULL
430 || player->IsFakeClient())
435 AdminId adm = player->GetAdminId();
436 if (adm != INVALID_ADMIN_ID)
438 FlagBits bits = g_Admins.GetAdminFlags(adm, Access_Effective);
440 /* root knows all, WHOA */
441 if ((bits & ADMFLAG_ROOT) == ADMFLAG_ROOT)
446 /* Check for overrides
447 * :TODO: is it worth optimizing this?
449 unsigned int groups = g_Admins.GetAdminGroupCount(adm);
452 bool override = false;
453 for (unsigned int i=0; i<groups; i++)
455 gid = g_Admins.GetAdminGroup(adm, i, NULL);
456 /* First get group-level override */
457 override = g_Admins.GetGroupCommandOverride(gid, cmd, Override_CommandGroup, &rule);
458 /* Now get the specific command override */
459 if (g_Admins.GetGroupCommandOverride(gid, cmd, Override_Command, &rule))
465 if (rule == Command_Allow)
469 else if (rule == Command_Deny)
476 /* See if our other flags match */
477 if ((bits & cmdflags) == cmdflags)
486 bool ConCmdManager::CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin)
488 if (CheckCommandAccess(client, cmd, pAdmin->eflags))
493 edict_t *pEdict = engine->PEntityOfEntIndex(client);
495 /* If we got here, the command failed... */
497 if (!CoreTranslate(buffer, sizeof(buffer), "%T", 2, NULL, "No Access", &client))
499 UTIL_Format(buffer, sizeof(buffer), "You do not have access to this command");
502 unsigned int replyto = g_ChatTriggers.GetReplyTo();
503 if (replyto == SM_REPLY_CONSOLE)
505 char fullbuffer[192];
506 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.\n", buffer);
507 engine->ClientPrintf(pEdict, fullbuffer);
509 else if (replyto == SM_REPLY_CHAT)
511 char fullbuffer[192];
512 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.", buffer);
513 g_HL2.TextMsg(client, HUD_PRINTTALK, fullbuffer);
519 bool ConCmdManager::AddConsoleCommand(IPluginFunction *pFunction,
521 const char *description,
524 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
531 CmdHook *pHook = new CmdHook();
533 pHook->pf = pFunction;
534 if (description && description[0])
536 pHook->helptext.assign(description);
538 pInfo->conhooks.push_back(pHook);
540 /* Add to the plugin */
542 IPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pFunction->GetParentContext()->GetContext());
543 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
545 pList = new CmdList();
546 pPlugin->SetProperty("CommandList", pList);
550 info.type = Cmd_Console;
552 AddToPlCmdList(pList, info);
557 bool ConCmdManager::AddAdminCommand(IPluginFunction *pFunction,
561 const char *description,
564 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
571 CmdHook *pHook = new CmdHook();
572 AdminCmdInfo *pAdmin = new AdminCmdInfo();
574 pHook->pf = pFunction;
575 if (description && description[0])
577 pHook->helptext.assign(description);
579 pHook->pAdmin = pAdmin;
583 if (!sm_trie_retrieve(m_pCmdGrps, group, (void **)&object))
585 grpid = m_Strings.AddString(group);
586 sm_trie_insert(m_pCmdGrps, group, (void *)grpid);
593 pAdmin->cmdGrpId = grpid;
594 pAdmin->flags = adminflags;
596 /* First get the command group override, if any */
597 bool override = g_Admins.GetCommandOverride(group,
598 Override_CommandGroup,
601 /* Next get the command override, if any */
602 if (g_Admins.GetCommandOverride(name,
609 /* Assign normal flags if there were no overrides */
612 pAdmin->eflags = pAdmin->flags;
615 /* Finally, add the hook */
616 pInfo->conhooks.push_back(pHook);
617 pInfo->admin = *(pHook->pAdmin);
618 pInfo->is_admin_set = true;
620 /* Now add to the plugin */
622 IPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pFunction->GetParentContext()->GetContext());
623 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
625 pList = new CmdList();
626 pPlugin->SetProperty("CommandList", pList);
630 info.type = Cmd_Admin;
632 AddToPlCmdList(pList, info);
637 bool ConCmdManager::AddServerCommand(IPluginFunction *pFunction,
639 const char *description,
643 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
650 CmdHook *pHook = new CmdHook();
652 pHook->pf = pFunction;
653 if (description && description[0])
655 pHook->helptext.assign(description);
658 pInfo->srvhooks.push_back(pHook);
660 /* Add to the plugin */
662 IPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pFunction->GetParentContext()->GetContext());
663 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
665 pList = new CmdList();
666 pPlugin->SetProperty("CommandList", pList);
670 info.type = Cmd_Server;
672 AddToPlCmdList(pList, info);
677 void AddToPlCmdList(CmdList *pList, const PlCmdInfo &info)
679 CmdList::iterator iter = pList->begin();
680 bool inserted = false;
681 const char *orig = NULL;
683 orig = info.pInfo->pCmd->GetName();
685 /* Insert this into the help list, SORTED alphabetically. */
686 while (iter != pList->end())
688 PlCmdInfo &obj = (*iter);
689 const char *cmd = obj.pInfo->pCmd->GetName();
690 if (strcmp(orig, cmd) < 0)
692 pList->insert(iter, info);
701 pList->push_back(info);
705 void ConCmdManager::AddToCmdList(ConCmdInfo *info)
707 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
709 bool inserted = false;
710 const char *orig = NULL;
712 orig = info->pCmd->GetName();
714 /* Insert this into the help list, SORTED alphabetically. */
715 while (iter != m_CmdList.end())
717 const char *cmd = NULL;
719 cmd = pInfo->pCmd->GetName();
720 if (strcmp(orig, cmd) < 0)
722 m_CmdList.insert(iter, info);
731 m_CmdList.push_back(info);
735 void ConCmdManager::UpdateAdminCmdFlags(const char *cmd, OverrideType type, FlagBits bits, bool remove)
739 if (type == Override_Command)
741 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
746 List<CmdHook *>::iterator iter;
749 for (iter=pInfo->conhooks.begin(); iter!=pInfo->conhooks.end(); iter++)
756 pHook->pAdmin->eflags = bits;
758 pHook->pAdmin->eflags = pHook->pAdmin->flags;
760 pInfo->admin = *(pHook->pAdmin);
763 pInfo->is_admin_set = true;
765 else if (type == Override_CommandGroup)
768 if (!sm_trie_retrieve(m_pCmdGrps, cmd, &object))
772 int grpid = (int)object;
774 /* This is bad :( loop through all commands */
775 List<ConCmdInfo *>::iterator iter;
777 for (iter=m_CmdList.begin(); iter!=m_CmdList.end(); iter++)
780 for (List<CmdHook *>::iterator citer=pInfo->conhooks.begin();
781 citer!=pInfo->conhooks.end();
785 if (pHook->pAdmin && pHook->pAdmin->cmdGrpId == grpid)
789 pHook->pAdmin->eflags = bits;
791 pHook->pAdmin->eflags = pHook->pAdmin->flags;
793 pInfo->admin = *(pHook->pAdmin);
797 pInfo->is_admin_set = true;
801 void ConCmdManager::RemoveConCmd(ConCmdInfo *info, const char *name, bool is_read_safe, bool untrack)
803 /* Remove from the trie */
804 sm_trie_delete(m_pCmds, name);
806 /* Remove console-specific information
807 * This should always be true as of right now
813 /* Unlink from SourceMM */
814 g_SMAPI->UnregisterConCommandBase(g_PLAPI, info->pCmd);
815 /* Delete the command's memory */
816 char *new_help = const_cast<char *>(info->pCmd->GetHelpText());
817 char *new_name = const_cast<char *>(info->pCmd->GetName());
826 /* Remove the external hook */
827 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, info->pCmd, CommandCallback, false);
831 UntrackConCommandBase(info->pCmd, this);
836 /* Remove from list */
837 m_CmdList.remove(info);
842 bool ConCmdManager::LookForSourceModCommand(const char *cmd)
846 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
851 return pInfo->sourceMod && (pInfo->conhooks.size() > 0);
854 bool ConCmdManager::LookForCommandAdminFlags(const char *cmd, FlagBits *pFlags)
858 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
863 *pFlags = pInfo->admin.eflags;
865 return pInfo->is_admin_set;
868 ConCmdInfo *ConCmdManager::AddOrFindCommand(const char *name, const char *description, int flags)
871 if (!sm_trie_retrieve(m_pCmds, name, (void **)&pInfo))
873 pInfo = new ConCmdInfo();
874 /* Find the commandopan */
875 ConCommandBase *pBase = icvar->GetCommands();
876 ConCommand *pCmd = NULL;
879 if (strcmp(pBase->GetName(), name) == 0)
881 /* Don't want to return convar with same name */
882 if (!pBase->IsCommand())
887 pCmd = (ConCommand *)pBase;
890 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
895 /* Note that we have to duplicate because the source might not be
896 * a static string, and these expect static memory.
902 char *new_name = sm_strdup(name);
903 char *new_help = sm_strdup(description);
904 pCmd = new ConCommand(new_name, CommandCallback, new_help, flags);
905 pInfo->sourceMod = true;
909 TrackConCommandBase(pCmd, this);
910 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, pCmd, CommandCallback, false);
914 pInfo->is_admin_set = false;
916 sm_trie_insert(m_pCmds, name, pInfo);
923 void ConCmdManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
925 if (command.ArgC() >= 3)
927 const char *text = command.Arg(2);
929 CPlugin *pPlugin = g_PluginSys.FindPluginByConsoleArg(text);
933 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", text);
937 const sm_plugininfo_t *plinfo = pPlugin->GetPublicInfo();
938 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : pPlugin->GetFilename();
941 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
943 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
948 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
952 CmdList::iterator iter;
953 const char *type = NULL;
956 g_RootMenu.ConsolePrint("[SM] Listing %d commands for: %s", pList->size(), plname);
957 g_RootMenu.ConsolePrint(" %-17.16s %-8.7s %s", "[Name]", "[Type]", "[Help]");
958 for (iter=pList->begin();
962 PlCmdInfo &cmd = (*iter);
963 if (cmd.type == Cmd_Server)
967 else if (cmd.type == Cmd_Console)
971 else if (cmd.type == Cmd_Admin)
975 name = cmd.pInfo->pCmd->GetName();
976 if (cmd.pHook->helptext.size())
978 help = cmd.pHook->helptext.c_str();
982 help = cmd.pInfo->pCmd->GetHelpText();
984 g_RootMenu.ConsolePrint(" %-17.16s %-12.11s %s", name, type, help);
990 g_RootMenu.ConsolePrint("[SM] Usage: sm cmds <plugin #>");