Build against MM:S 1.10.
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 "HalfLife2.h"
38 #include "ChatTriggers.h"
39 #include "logic_bridge.h"
41 ConCmdManager g_ConCmds;
43 #if SOURCE_ENGINE == SE_DOTA
44 SH_DECL_HOOK2_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommandContext &, const CCommand &);
45 #elif SOURCE_ENGINE >= SE_ORANGEBOX
46 SH_DECL_HOOK1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
48 SH_DECL_HOOK0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
51 SH_DECL_HOOK1_void(IServerGameClients, SetCommandClient, SH_NOATTRIB, false, int);
59 typedef List<PlCmdInfo> CmdList;
61 void AddToPlCmdList(CmdList *pList, const PlCmdInfo &info);
63 ConCmdManager::ConCmdManager() : m_Strings(1024)
65 m_pCmds = sm_trie_create();
66 m_pCmdGrps = sm_trie_create();
70 ConCmdManager::~ConCmdManager()
72 sm_trie_destroy(m_pCmds);
73 sm_trie_destroy(m_pCmdGrps);
76 void ConCmdManager::OnSourceModAllInitialized()
78 scripts->AddPluginsListener(this);
79 g_RootMenu.AddRootConsoleCommand("cmds", "List console commands", this);
80 SH_ADD_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &ConCmdManager::SetCommandClient), false);
83 void ConCmdManager::OnSourceModShutdown()
85 scripts->RemovePluginsListener(this);
86 /* All commands should already be removed by the time we're done */
87 SH_REMOVE_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &ConCmdManager::SetCommandClient), false);
88 g_RootMenu.RemoveRootConsoleCommand("cmds", this);
91 void ConCmdManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
93 /* Whoa, first get its information struct */
96 if (!sm_trie_retrieve(m_pCmds, name, (void **)&pInfo))
101 RemoveConCmds(pInfo->srvhooks);
102 RemoveConCmds(pInfo->conhooks);
104 RemoveConCmd(pInfo, name, is_read_safe, false);
107 void ConCmdManager::RemoveConCmds(List<CmdHook *> &cmdlist)
109 List<CmdHook *>::iterator iter = cmdlist.begin();
111 while (iter != cmdlist.end())
113 CmdHook *pHook = (*iter);
114 IPluginContext *pContext = pHook->pf->GetParentContext();
115 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
116 CmdList *pList = NULL;
119 if (!pPlugin->GetProperty("CommandList", (void **)&pList, false) || !pList)
124 CmdList::iterator p_iter = pList->begin();
125 while (p_iter != pList->end())
127 PlCmdInfo &cmd = (*p_iter);
128 if (cmd.pHook == pHook)
130 p_iter = pList->erase(p_iter);
138 delete pHook->pAdmin;
141 iter = cmdlist.erase(iter);
145 void ConCmdManager::RemoveConCmds(List<CmdHook *> &cmdlist, IPluginContext *pContext)
147 List<CmdHook *>::iterator iter = cmdlist.begin();
150 while (iter != cmdlist.end())
153 if (pHook->pf->GetParentContext() == pContext)
155 delete pHook->pAdmin;
157 iter = cmdlist.erase(iter);
166 void ConCmdManager::OnPluginDestroyed(IPlugin *plugin)
169 List<ConCmdInfo *> removed;
170 if (plugin->GetProperty("CommandList", (void **)&pList, true))
172 IPluginContext *pContext = plugin->GetBaseContext();
173 CmdList::iterator iter;
175 * Only bother if there's an actual command list on this plugin...
177 for (iter=pList->begin();
181 PlCmdInfo &cmd = (*iter);
182 ConCmdInfo *pInfo = cmd.pInfo;
184 /* Has this chain already been fully cleaned/removed? */
185 if (removed.find(pInfo) != removed.end())
190 /* Remove any hooks from us on this command */
191 RemoveConCmds(pInfo->conhooks, pContext);
192 RemoveConCmds(pInfo->srvhooks, pContext);
194 /* See if there are still hooks */
195 if (pInfo->srvhooks.size())
199 if (pInfo->conhooks.size())
204 /* Remove the command, it should be safe now */
205 RemoveConCmd(pInfo, pInfo->pCmd->GetName(), true, true);
206 removed.push_back(pInfo);
211 #if SOURCE_ENGINE == SE_DOTA
212 void CommandCallback(const CCommandContext &context, const CCommand &command)
214 #elif SOURCE_ENGINE >= SE_ORANGEBOX
215 void CommandCallback(const CCommand &command)
218 void CommandCallback()
223 g_HL2.PushCommandStack(&command);
225 g_ConCmds.InternalDispatch(command);
227 g_HL2.PopCommandStack();
230 void ConCmdManager::SetCommandClient(int client)
232 m_CmdClient = client + 1;
235 ConCmdInfo *ConCmdManager::FindInTrie(const char *name)
238 if (!sm_trie_retrieve(m_pCmds, name, (void **)&pInfo))
243 ConCmdList::iterator ConCmdManager::FindInList(const char *cmd)
245 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
247 while (iter != m_CmdList.end())
249 if (strcasecmp((*iter)->pCmd->GetName(), cmd) == 0)
257 ResultType ConCmdManager::DispatchClientCommand(int client, const char *cmd, int args, ResultType type)
261 if ((pInfo = FindInTrie(cmd)) == NULL)
263 ConCmdList::iterator item = FindInList(cmd);
264 if (item == m_CmdList.end())
269 cell_t result = type;
270 cell_t tempres = result;
271 List<CmdHook *>::iterator iter;
273 for (iter=pInfo->conhooks.begin();
274 iter!=pInfo->conhooks.end();
278 if (!pHook->pf->IsRunnable())
282 if (pHook->pAdmin && !CheckAccess(client, cmd, pHook->pAdmin))
284 if (result < Pl_Handled)
290 pHook->pf->PushCell(client);
291 pHook->pf->PushCell(args);
292 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
294 if (tempres > result)
298 if (result == Pl_Stop)
305 type = (ResultType)result;
310 void ConCmdManager::InternalDispatch(const CCommand &command)
312 int client = m_CmdClient;
316 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
317 if (!pPlayer || !pPlayer->IsConnected())
324 * Note: Console commands will EITHER go through IServerGameDLL::ClientCommand,
325 * OR this dispatch. They will NEVER go through both.
327 * Whether or not it goes through the callback is determined by FCVAR_GAMEDLL
329 const char *cmd = g_HL2.CurrentCommandName();
331 ConCmdInfo *pInfo = FindInTrie(cmd);
334 /* Unfortunately, we now have to do a slow lookup because Valve made client commands
335 * case-insensitive. We can't even use our sortedness.
337 if (client == 0 && !engine->IsDedicatedServer())
340 ConCmdList::iterator item = FindInList(cmd);
341 if (item == m_CmdList.end())
347 /* This is a hack to prevent say triggers from firing on messages that were
348 * blocked because of flooding. We won't remove this, but the hack will get
349 * "nicer" when we expose explicit say hooks.
351 if (g_ChatTriggers.WasFloodedMessage())
356 cell_t result = Pl_Continue;
357 int args = command.ArgC() - 1;
359 List<CmdHook *>::iterator iter;
362 /* Execute server-only commands if viable */
363 if (client == 0 && pInfo->srvhooks.size())
365 cell_t tempres = result;
366 for (iter=pInfo->srvhooks.begin();
367 iter!=pInfo->srvhooks.end();
371 if (!pHook->pf->IsRunnable())
375 pHook->pf->PushCell(args);
376 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
378 if (tempres > result)
382 if (result == Pl_Stop)
389 /* Check if there's an early stop */
390 if (result >= Pl_Stop)
392 if (!pInfo->sourceMod)
394 RETURN_META(MRES_SUPERCEDE);
400 /* Execute console commands */
401 if (pInfo->conhooks.size())
403 cell_t tempres = result;
404 for (iter=pInfo->conhooks.begin();
405 iter!=pInfo->conhooks.end();
409 if (!pHook->pf->IsRunnable())
415 && !CheckAccess(client, cmd, pHook->pAdmin))
417 if (result < Pl_Handled)
424 /* On a listen server, sometimes the server host's client index can be set as 0.
425 * So index 1 is passed to the command callback to correct this potential problem.
427 if (!engine->IsDedicatedServer())
429 client = g_Players.ListenClient();
432 pHook->pf->PushCell(client);
433 pHook->pf->PushCell(args);
435 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
437 if (tempres > result)
441 if (result == Pl_Stop)
449 if (result >= Pl_Handled)
451 if (!pInfo->sourceMod)
453 RETURN_META(MRES_SUPERCEDE);
459 bool ConCmdManager::CheckClientCommandAccess(int client, const char *cmd, FlagBits cmdflags)
461 if (cmdflags == 0 || client == 0)
466 /* If running listen server, then client 1 is the server host and should have 'root' access */
467 if (client == 1 && !engine->IsDedicatedServer())
472 CPlayer *player = g_Players.GetPlayerByIndex(client);
474 || player->GetEdict() == NULL
475 || player->IsFakeClient())
480 return CheckAdminCommandAccess(player->GetAdminId(), cmd, cmdflags);
483 bool ConCmdManager::CheckAdminCommandAccess(AdminId adm, const char *cmd, FlagBits cmdflags)
485 if (adm != INVALID_ADMIN_ID)
487 FlagBits bits = g_Admins.GetAdminFlags(adm, Access_Effective);
489 /* root knows all, WHOA */
490 if ((bits & ADMFLAG_ROOT) == ADMFLAG_ROOT)
495 /* Check for overrides
496 * :TODO: is it worth optimizing this?
498 unsigned int groups = g_Admins.GetAdminGroupCount(adm);
501 bool override = false;
502 for (unsigned int i=0; i<groups; i++)
504 gid = g_Admins.GetAdminGroup(adm, i, NULL);
505 /* First get group-level override */
506 override = g_Admins.GetGroupCommandOverride(gid, cmd, Override_CommandGroup, &rule);
507 /* Now get the specific command override */
508 if (g_Admins.GetGroupCommandOverride(gid, cmd, Override_Command, &rule))
514 if (rule == Command_Allow)
518 else if (rule == Command_Deny)
525 /* See if our other flags match */
526 if ((bits & cmdflags) == cmdflags)
535 bool ConCmdManager::CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin)
537 if (CheckClientCommandAccess(client, cmd, pAdmin->eflags))
542 #if SOURCE_ENGINE != SE_DOTA
543 edict_t *pEdict = PEntityOfEntIndex(client);
546 /* If we got here, the command failed... */
548 if (!logicore.CoreTranslate(buffer, sizeof(buffer), "%T", 2, NULL, "No Access", &client))
550 UTIL_Format(buffer, sizeof(buffer), "You do not have access to this command");
553 unsigned int replyto = g_ChatTriggers.GetReplyTo();
554 if (replyto == SM_REPLY_CONSOLE)
556 char fullbuffer[192];
557 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.\n", buffer);
558 #if SOURCE_ENGINE == SE_DOTA
559 engine->ClientPrintf(client, fullbuffer);
561 engine->ClientPrintf(pEdict, fullbuffer);
564 else if (replyto == SM_REPLY_CHAT)
566 char fullbuffer[192];
567 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.", buffer);
568 g_HL2.TextMsg(client, HUD_PRINTTALK, fullbuffer);
574 bool ConCmdManager::AddAdminCommand(IPluginFunction *pFunction,
578 const char *description,
581 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
588 CmdHook *pHook = new CmdHook();
589 AdminCmdInfo *pAdmin = new AdminCmdInfo();
591 pHook->pf = pFunction;
592 if (description && description[0])
594 pHook->helptext.assign(description);
596 pHook->pAdmin = pAdmin;
600 if (!sm_trie_retrieve(m_pCmdGrps, group, (void **)&object))
602 grpid = m_Strings.AddString(group);
603 sm_trie_insert(m_pCmdGrps, group, (void *)grpid);
610 pAdmin->cmdGrpId = grpid;
611 pAdmin->flags = adminflags;
613 /* First get the command group override, if any */
614 bool override = g_Admins.GetCommandOverride(group,
615 Override_CommandGroup,
618 /* Next get the command override, if any */
619 if (g_Admins.GetCommandOverride(name,
626 /* Assign normal flags if there were no overrides */
629 pAdmin->eflags = pAdmin->flags;
632 /* Finally, add the hook */
633 pInfo->conhooks.push_back(pHook);
634 pInfo->admin = *(pHook->pAdmin);
636 /* Now add to the plugin */
638 IPlugin *pPlugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
639 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
641 pList = new CmdList();
642 pPlugin->SetProperty("CommandList", pList);
646 info.type = Cmd_Admin;
648 AddToPlCmdList(pList, info);
653 bool ConCmdManager::AddServerCommand(IPluginFunction *pFunction,
655 const char *description,
659 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
666 CmdHook *pHook = new CmdHook();
668 pHook->pf = pFunction;
669 if (description && description[0])
671 pHook->helptext.assign(description);
674 pInfo->srvhooks.push_back(pHook);
676 /* Add to the plugin */
678 IPlugin *pPlugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
679 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
681 pList = new CmdList();
682 pPlugin->SetProperty("CommandList", pList);
686 info.type = Cmd_Server;
688 AddToPlCmdList(pList, info);
693 void AddToPlCmdList(CmdList *pList, const PlCmdInfo &info)
695 CmdList::iterator iter = pList->begin();
696 bool inserted = false;
697 const char *orig = NULL;
699 orig = info.pInfo->pCmd->GetName();
701 /* Insert this into the help list, SORTED alphabetically. */
702 while (iter != pList->end())
704 PlCmdInfo &obj = (*iter);
705 const char *cmd = obj.pInfo->pCmd->GetName();
706 if (strcmp(orig, cmd) < 0)
708 pList->insert(iter, info);
717 pList->push_back(info);
721 void ConCmdManager::AddToCmdList(ConCmdInfo *info)
723 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
725 bool inserted = false;
726 const char *orig = NULL;
728 orig = info->pCmd->GetName();
730 /* Insert this into the help list, SORTED alphabetically. */
731 while (iter != m_CmdList.end())
733 const char *cmd = NULL;
735 cmd = pInfo->pCmd->GetName();
736 if (strcmp(orig, cmd) < 0)
738 m_CmdList.insert(iter, info);
747 m_CmdList.push_back(info);
751 void ConCmdManager::UpdateAdminCmdFlags(const char *cmd, OverrideType type, FlagBits bits, bool remove)
755 if (type == Override_Command)
757 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
762 List<CmdHook *>::iterator iter;
765 for (iter=pInfo->conhooks.begin(); iter!=pInfo->conhooks.end(); iter++)
772 pHook->pAdmin->eflags = bits;
774 pHook->pAdmin->eflags = pHook->pAdmin->flags;
776 pInfo->admin = *(pHook->pAdmin);
780 else if (type == Override_CommandGroup)
783 if (!sm_trie_retrieve(m_pCmdGrps, cmd, &object))
787 int grpid = (int)object;
789 /* This is bad :( loop through all commands */
790 List<ConCmdInfo *>::iterator iter;
792 for (iter=m_CmdList.begin(); iter!=m_CmdList.end(); iter++)
795 for (List<CmdHook *>::iterator citer=pInfo->conhooks.begin();
796 citer!=pInfo->conhooks.end();
800 if (pHook->pAdmin && pHook->pAdmin->cmdGrpId == grpid)
804 pHook->pAdmin->eflags = bits;
806 pHook->pAdmin->eflags = pHook->pAdmin->flags;
808 pInfo->admin = *(pHook->pAdmin);
815 void ConCmdManager::RemoveConCmd(ConCmdInfo *info, const char *name, bool is_read_safe, bool untrack)
817 /* Remove from the trie */
818 sm_trie_delete(m_pCmds, name);
820 /* Remove console-specific information
821 * This should always be true as of right now
827 /* Unlink from SourceMM */
828 g_SMAPI->UnregisterConCommandBase(g_PLAPI, info->pCmd);
829 /* Delete the command's memory */
830 char *new_help = const_cast<char *>(info->pCmd->GetHelpText());
831 char *new_name = const_cast<char *>(info->pCmd->GetName());
840 /* Remove the external hook */
841 SH_REMOVE_HOOK(ConCommand, Dispatch, info->pCmd, SH_STATIC(CommandCallback), false);
845 UntrackConCommandBase(info->pCmd, this);
850 /* Remove from list */
851 m_CmdList.remove(info);
856 bool ConCmdManager::LookForSourceModCommand(const char *cmd)
860 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
865 return pInfo->sourceMod && (pInfo->conhooks.size() > 0);
868 bool ConCmdManager::LookForCommandAdminFlags(const char *cmd, FlagBits *pFlags)
872 if (!sm_trie_retrieve(m_pCmds, cmd, (void **)&pInfo))
877 *pFlags = pInfo->admin.eflags;
882 ConCmdInfo *ConCmdManager::AddOrFindCommand(const char *name, const char *description, int flags)
885 if (!sm_trie_retrieve(m_pCmds, name, (void **)&pInfo))
887 ConCmdList::iterator item = FindInList(name);
888 if (item != m_CmdList.end())
891 pInfo = new ConCmdInfo();
892 /* Find the commandopan */
893 ConCommand *pCmd = FindCommand(name);
897 /* Note that we have to duplicate because the source might not be
898 * a static string, and these expect static memory.
904 char *new_name = sm_strdup(name);
905 char *new_help = sm_strdup(description);
906 pCmd = new ConCommand(new_name, CommandCallback, new_help, flags);
907 pInfo->sourceMod = true;
911 TrackConCommandBase(pCmd, this);
912 SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CommandCallback), false);
917 sm_trie_insert(m_pCmds, name, pInfo);
924 void ConCmdManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
926 if (command.ArgC() >= 3)
928 const char *text = command.Arg(2);
930 IPlugin *pPlugin = scripts->FindPluginByConsoleArg(text);
934 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", text);
938 const sm_plugininfo_t *plinfo = pPlugin->GetPublicInfo();
939 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : pPlugin->GetFilename();
942 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
944 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
949 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
953 CmdList::iterator iter;
954 const char *type = NULL;
957 g_RootMenu.ConsolePrint("[SM] Listing %d commands for: %s", pList->size(), plname);
958 g_RootMenu.ConsolePrint(" %-17.16s %-8.7s %s", "[Name]", "[Type]", "[Help]");
959 for (iter=pList->begin();
963 PlCmdInfo &cmd = (*iter);
964 if (cmd.type == Cmd_Server)
968 else if (cmd.type == Cmd_Admin)
970 type = (cmd.pInfo->admin.eflags == 0)?"console":"admin";
972 name = cmd.pInfo->pCmd->GetName();
973 if (cmd.pHook->helptext.size())
975 help = cmd.pHook->helptext.c_str();
979 help = cmd.pInfo->pCmd->GetHelpText();
981 g_RootMenu.ConsolePrint(" %-17.16s %-12.11s %s", name, type, help);
987 g_RootMenu.ConsolePrint("[SM] Usage: sm cmds <plugin #>");