2 * vim: set ts=4 sw=4 tw=99 noet :
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)
68 ConCmdManager::~ConCmdManager()
72 void ConCmdManager::OnSourceModAllInitialized()
74 scripts->AddPluginsListener(this);
75 g_RootMenu.AddRootConsoleCommand("cmds", "List console commands", this);
76 SH_ADD_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &ConCmdManager::SetCommandClient), false);
79 void ConCmdManager::OnSourceModShutdown()
81 scripts->RemovePluginsListener(this);
82 /* All commands should already be removed by the time we're done */
83 SH_REMOVE_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &ConCmdManager::SetCommandClient), false);
84 g_RootMenu.RemoveRootConsoleCommand("cmds", this);
87 void ConCmdManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
89 /* Whoa, first get its information struct */
92 if (!m_Cmds.retrieve(name, &pInfo))
95 RemoveConCmds(pInfo->srvhooks);
96 RemoveConCmds(pInfo->conhooks);
98 RemoveConCmd(pInfo, name, is_read_safe, false);
101 void ConCmdManager::RemoveConCmds(List<CmdHook *> &cmdlist)
103 List<CmdHook *>::iterator iter = cmdlist.begin();
105 while (iter != cmdlist.end())
107 CmdHook *pHook = (*iter);
108 IPluginContext *pContext = pHook->pf->GetParentContext();
109 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
110 CmdList *pList = NULL;
113 if (!pPlugin->GetProperty("CommandList", (void **)&pList, false) || !pList)
118 CmdList::iterator p_iter = pList->begin();
119 while (p_iter != pList->end())
121 PlCmdInfo &cmd = (*p_iter);
122 if (cmd.pHook == pHook)
124 p_iter = pList->erase(p_iter);
132 delete pHook->pAdmin;
135 iter = cmdlist.erase(iter);
139 void ConCmdManager::RemoveConCmds(List<CmdHook *> &cmdlist, IPluginContext *pContext)
141 List<CmdHook *>::iterator iter = cmdlist.begin();
144 while (iter != cmdlist.end())
147 if (pHook->pf->GetParentContext() == pContext)
149 delete pHook->pAdmin;
151 iter = cmdlist.erase(iter);
160 void ConCmdManager::OnPluginDestroyed(IPlugin *plugin)
163 List<ConCmdInfo *> removed;
164 if (plugin->GetProperty("CommandList", (void **)&pList, true))
166 IPluginContext *pContext = plugin->GetBaseContext();
167 CmdList::iterator iter;
169 * Only bother if there's an actual command list on this plugin...
171 for (iter=pList->begin();
175 PlCmdInfo &cmd = (*iter);
176 ConCmdInfo *pInfo = cmd.pInfo;
178 /* Has this chain already been fully cleaned/removed? */
179 if (removed.find(pInfo) != removed.end())
184 /* Remove any hooks from us on this command */
185 RemoveConCmds(pInfo->conhooks, pContext);
186 RemoveConCmds(pInfo->srvhooks, pContext);
188 /* See if there are still hooks */
189 if (pInfo->srvhooks.size())
193 if (pInfo->conhooks.size())
198 /* Remove the command, it should be safe now */
199 RemoveConCmd(pInfo, pInfo->pCmd->GetName(), true, true);
200 removed.push_back(pInfo);
205 #if SOURCE_ENGINE == SE_DOTA
206 void CommandCallback(const CCommandContext &context, const CCommand &command)
208 #elif SOURCE_ENGINE >= SE_ORANGEBOX
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 ConCmdInfo *ConCmdManager::FindInTrie(const char *name)
232 if (!m_Cmds.retrieve(name, &pInfo))
237 ConCmdList::iterator ConCmdManager::FindInList(const char *cmd)
239 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
241 while (iter != m_CmdList.end())
243 if (strcasecmp((*iter)->pCmd->GetName(), cmd) == 0)
251 ResultType ConCmdManager::DispatchClientCommand(int client, const char *cmd, int args, ResultType type)
255 if ((pInfo = FindInTrie(cmd)) == NULL)
257 ConCmdList::iterator item = FindInList(cmd);
258 if (item == m_CmdList.end())
263 cell_t result = type;
264 cell_t tempres = result;
265 List<CmdHook *>::iterator iter;
267 for (iter=pInfo->conhooks.begin();
268 iter!=pInfo->conhooks.end();
272 if (!pHook->pf->IsRunnable())
276 if (pHook->pAdmin && !CheckAccess(client, cmd, pHook->pAdmin))
278 if (result < Pl_Handled)
284 pHook->pf->PushCell(client);
285 pHook->pf->PushCell(args);
286 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
288 if (tempres > result)
292 if (result == Pl_Stop)
299 type = (ResultType)result;
304 void ConCmdManager::InternalDispatch(const CCommand &command)
306 int client = m_CmdClient;
310 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
311 if (!pPlayer || !pPlayer->IsConnected())
318 * Note: Console commands will EITHER go through IServerGameDLL::ClientCommand,
319 * OR this dispatch. They will NEVER go through both.
321 * Whether or not it goes through the callback is determined by FCVAR_GAMEDLL
323 const char *cmd = g_HL2.CurrentCommandName();
325 ConCmdInfo *pInfo = FindInTrie(cmd);
328 /* Unfortunately, we now have to do a slow lookup because Valve made client commands
329 * case-insensitive. We can't even use our sortedness.
331 if (client == 0 && !engine->IsDedicatedServer())
334 ConCmdList::iterator item = FindInList(cmd);
335 if (item == m_CmdList.end())
341 /* This is a hack to prevent say triggers from firing on messages that were
342 * blocked because of flooding. We won't remove this, but the hack will get
343 * "nicer" when we expose explicit say hooks.
345 if (g_ChatTriggers.WasFloodedMessage())
350 cell_t result = Pl_Continue;
351 int args = command.ArgC() - 1;
353 List<CmdHook *>::iterator iter;
356 /* Execute server-only commands if viable */
357 if (client == 0 && pInfo->srvhooks.size())
359 cell_t tempres = result;
360 for (iter=pInfo->srvhooks.begin();
361 iter!=pInfo->srvhooks.end();
365 if (!pHook->pf->IsRunnable())
369 pHook->pf->PushCell(args);
370 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
372 if (tempres > result)
376 if (result == Pl_Stop)
383 /* Check if there's an early stop */
384 if (result >= Pl_Stop)
386 if (!pInfo->sourceMod)
388 RETURN_META(MRES_SUPERCEDE);
394 /* Execute console commands */
395 if (pInfo->conhooks.size())
397 cell_t tempres = result;
398 for (iter=pInfo->conhooks.begin();
399 iter!=pInfo->conhooks.end();
403 if (!pHook->pf->IsRunnable())
409 && !CheckAccess(client, cmd, pHook->pAdmin))
411 if (result < Pl_Handled)
418 /* On a listen server, sometimes the server host's client index can be set as 0.
419 * So index 1 is passed to the command callback to correct this potential problem.
421 if (!engine->IsDedicatedServer())
423 client = g_Players.ListenClient();
426 pHook->pf->PushCell(client);
427 pHook->pf->PushCell(args);
429 if (pHook->pf->Execute(&tempres) == SP_ERROR_NONE)
431 if (tempres > result)
435 if (result == Pl_Stop)
443 if (result >= Pl_Handled)
445 if (!pInfo->sourceMod)
447 RETURN_META(MRES_SUPERCEDE);
453 bool ConCmdManager::CheckClientCommandAccess(int client, const char *cmd, FlagBits cmdflags)
455 if (cmdflags == 0 || client == 0)
460 /* If running listen server, then client 1 is the server host and should have 'root' access */
461 if (client == 1 && !engine->IsDedicatedServer())
466 CPlayer *player = g_Players.GetPlayerByIndex(client);
468 || player->GetEdict() == NULL
469 || player->IsFakeClient())
474 return CheckAdminCommandAccess(player->GetAdminId(), cmd, cmdflags);
477 bool ConCmdManager::CheckAdminCommandAccess(AdminId adm, const char *cmd, FlagBits cmdflags)
479 if (adm != INVALID_ADMIN_ID)
481 FlagBits bits = g_Admins.GetAdminFlags(adm, Access_Effective);
483 /* root knows all, WHOA */
484 if ((bits & ADMFLAG_ROOT) == ADMFLAG_ROOT)
489 /* Check for overrides
490 * :TODO: is it worth optimizing this?
492 unsigned int groups = g_Admins.GetAdminGroupCount(adm);
495 bool override = false;
496 for (unsigned int i=0; i<groups; i++)
498 gid = g_Admins.GetAdminGroup(adm, i, NULL);
499 /* First get group-level override */
500 override = g_Admins.GetGroupCommandOverride(gid, cmd, Override_CommandGroup, &rule);
501 /* Now get the specific command override */
502 if (g_Admins.GetGroupCommandOverride(gid, cmd, Override_Command, &rule))
508 if (rule == Command_Allow)
512 else if (rule == Command_Deny)
519 /* See if our other flags match */
520 if ((bits & cmdflags) == cmdflags)
529 bool ConCmdManager::CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin)
531 if (CheckClientCommandAccess(client, cmd, pAdmin->eflags))
536 #if SOURCE_ENGINE != SE_DOTA
537 edict_t *pEdict = PEntityOfEntIndex(client);
540 /* If we got here, the command failed... */
542 if (!logicore.CoreTranslate(buffer, sizeof(buffer), "%T", 2, NULL, "No Access", &client))
544 UTIL_Format(buffer, sizeof(buffer), "You do not have access to this command");
547 unsigned int replyto = g_ChatTriggers.GetReplyTo();
548 if (replyto == SM_REPLY_CONSOLE)
550 char fullbuffer[192];
551 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.\n", buffer);
552 #if SOURCE_ENGINE == SE_DOTA
553 engine->ClientPrintf(client, fullbuffer);
555 engine->ClientPrintf(pEdict, fullbuffer);
558 else if (replyto == SM_REPLY_CHAT)
560 char fullbuffer[192];
561 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.", buffer);
562 g_HL2.TextMsg(client, HUD_PRINTTALK, fullbuffer);
568 bool ConCmdManager::AddAdminCommand(IPluginFunction *pFunction,
572 const char *description,
575 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
582 CmdHook *pHook = new CmdHook();
583 AdminCmdInfo *pAdmin = new AdminCmdInfo();
585 pHook->pf = pFunction;
586 if (description && description[0])
588 pHook->helptext.assign(description);
590 pHook->pAdmin = pAdmin;
593 if (!m_CmdGrps.retrieve(group, &grpid))
595 grpid = m_Strings.AddString(group);
596 m_CmdGrps.insert(group, grpid);
599 pAdmin->cmdGrpId = grpid;
600 pAdmin->flags = adminflags;
602 /* First get the command group override, if any */
603 bool override = g_Admins.GetCommandOverride(group,
604 Override_CommandGroup,
607 /* Next get the command override, if any */
608 if (g_Admins.GetCommandOverride(name,
615 /* Assign normal flags if there were no overrides */
618 pAdmin->eflags = pAdmin->flags;
621 /* Finally, add the hook */
622 pInfo->conhooks.push_back(pHook);
623 pInfo->admin = *(pHook->pAdmin);
625 /* Now add to the plugin */
627 IPlugin *pPlugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
628 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
630 pList = new CmdList();
631 pPlugin->SetProperty("CommandList", pList);
635 info.type = Cmd_Admin;
637 AddToPlCmdList(pList, info);
642 bool ConCmdManager::AddServerCommand(IPluginFunction *pFunction,
644 const char *description,
648 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
655 CmdHook *pHook = new CmdHook();
657 pHook->pf = pFunction;
658 if (description && description[0])
660 pHook->helptext.assign(description);
663 pInfo->srvhooks.push_back(pHook);
665 /* Add to the plugin */
667 IPlugin *pPlugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
668 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
670 pList = new CmdList();
671 pPlugin->SetProperty("CommandList", pList);
675 info.type = Cmd_Server;
677 AddToPlCmdList(pList, info);
682 void AddToPlCmdList(CmdList *pList, const PlCmdInfo &info)
684 CmdList::iterator iter = pList->begin();
685 bool inserted = false;
686 const char *orig = NULL;
688 orig = info.pInfo->pCmd->GetName();
690 /* Insert this into the help list, SORTED alphabetically. */
691 while (iter != pList->end())
693 PlCmdInfo &obj = (*iter);
694 const char *cmd = obj.pInfo->pCmd->GetName();
695 if (strcmp(orig, cmd) < 0)
697 pList->insert(iter, info);
706 pList->push_back(info);
710 void ConCmdManager::AddToCmdList(ConCmdInfo *info)
712 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
714 bool inserted = false;
715 const char *orig = NULL;
717 orig = info->pCmd->GetName();
719 /* Insert this into the help list, SORTED alphabetically. */
720 while (iter != m_CmdList.end())
722 const char *cmd = NULL;
724 cmd = pInfo->pCmd->GetName();
725 if (strcmp(orig, cmd) < 0)
727 m_CmdList.insert(iter, info);
736 m_CmdList.push_back(info);
740 void ConCmdManager::UpdateAdminCmdFlags(const char *cmd, OverrideType type, FlagBits bits, bool remove)
744 if (type == Override_Command)
746 if (!m_Cmds.retrieve(cmd, &pInfo))
749 List<CmdHook *>::iterator iter;
752 for (iter=pInfo->conhooks.begin(); iter!=pInfo->conhooks.end(); iter++)
759 pHook->pAdmin->eflags = bits;
761 pHook->pAdmin->eflags = pHook->pAdmin->flags;
763 pInfo->admin = *(pHook->pAdmin);
767 else if (type == Override_CommandGroup)
770 if (!m_CmdGrps.retrieve(cmd, &grpid))
773 /* This is bad :( loop through all commands */
774 List<ConCmdInfo *>::iterator iter;
776 for (iter=m_CmdList.begin(); iter!=m_CmdList.end(); iter++)
779 for (List<CmdHook *>::iterator citer=pInfo->conhooks.begin();
780 citer!=pInfo->conhooks.end();
784 if (pHook->pAdmin && pHook->pAdmin->cmdGrpId == grpid)
788 pHook->pAdmin->eflags = bits;
790 pHook->pAdmin->eflags = pHook->pAdmin->flags;
792 pInfo->admin = *(pHook->pAdmin);
799 void ConCmdManager::RemoveConCmd(ConCmdInfo *info, const char *name, bool is_read_safe, bool untrack)
801 /* Remove from the trie */
804 /* Remove console-specific information
805 * This should always be true as of right now
811 /* Unlink from SourceMM */
812 g_SMAPI->UnregisterConCommandBase(g_PLAPI, info->pCmd);
813 /* Delete the command's memory */
814 char *new_help = const_cast<char *>(info->pCmd->GetHelpText());
815 char *new_name = const_cast<char *>(info->pCmd->GetName());
824 /* Remove the external hook */
825 SH_REMOVE_HOOK(ConCommand, Dispatch, info->pCmd, SH_STATIC(CommandCallback), false);
829 UntrackConCommandBase(info->pCmd, this);
834 /* Remove from list */
835 m_CmdList.remove(info);
840 bool ConCmdManager::LookForSourceModCommand(const char *cmd)
843 if (!m_Cmds.retrieve(cmd, &pInfo))
846 return pInfo->sourceMod && (pInfo->conhooks.size() > 0);
849 bool ConCmdManager::LookForCommandAdminFlags(const char *cmd, FlagBits *pFlags)
852 if (!m_Cmds.retrieve(cmd, &pInfo))
855 *pFlags = pInfo->admin.eflags;
859 ConCmdInfo *ConCmdManager::AddOrFindCommand(const char *name, const char *description, int flags)
862 if (!m_Cmds.retrieve(name, &pInfo))
864 ConCmdList::iterator item = FindInList(name);
865 if (item != m_CmdList.end())
868 pInfo = new ConCmdInfo();
869 /* Find the commandopan */
870 ConCommand *pCmd = FindCommand(name);
874 /* Note that we have to duplicate because the source might not be
875 * a static string, and these expect static memory.
881 char *new_name = sm_strdup(name);
882 char *new_help = sm_strdup(description);
883 pCmd = new ConCommand(new_name, CommandCallback, new_help, flags);
884 pInfo->sourceMod = true;
888 TrackConCommandBase(pCmd, this);
889 SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CommandCallback), false);
894 m_Cmds.insert(name, pInfo);
901 void ConCmdManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
903 if (command.ArgC() >= 3)
905 const char *text = command.Arg(2);
907 IPlugin *pPlugin = scripts->FindPluginByConsoleArg(text);
911 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", text);
915 const sm_plugininfo_t *plinfo = pPlugin->GetPublicInfo();
916 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : pPlugin->GetFilename();
919 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
921 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
926 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
930 CmdList::iterator iter;
931 const char *type = NULL;
934 g_RootMenu.ConsolePrint("[SM] Listing %d commands for: %s", pList->size(), plname);
935 g_RootMenu.ConsolePrint(" %-17.16s %-8.7s %s", "[Name]", "[Type]", "[Help]");
936 for (iter=pList->begin();
940 PlCmdInfo &cmd = (*iter);
941 if (cmd.type == Cmd_Server)
945 else if (cmd.type == Cmd_Admin)
947 type = (cmd.pInfo->admin.eflags == 0)?"console":"admin";
949 name = cmd.pInfo->pCmd->GetName();
950 if (cmd.pHook->helptext.size())
952 help = cmd.pHook->helptext.c_str();
956 help = cmd.pInfo->pCmd->GetHelpText();
958 g_RootMenu.ConsolePrint(" %-17.16s %-12.11s %s", name, type, help);
964 g_RootMenu.ConsolePrint("[SM] Usage: sm cmds <plugin #>");