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);
53 typedef ke::LinkedList<CmdHook *> PluginHookList;
54 void RegisterInPlugin(CmdHook *hook);
56 ConCmdManager::ConCmdManager() : m_Strings(1024)
61 ConCmdManager::~ConCmdManager()
65 void ConCmdManager::OnSourceModAllInitialized()
67 scripts->AddPluginsListener(this);
68 g_RootMenu.AddRootConsoleCommand("cmds", "List console commands", this);
69 SH_ADD_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &ConCmdManager::SetCommandClient), false);
72 void ConCmdManager::OnSourceModShutdown()
74 scripts->RemovePluginsListener(this);
75 /* All commands should already be removed by the time we're done */
76 SH_REMOVE_HOOK(IServerGameClients, SetCommandClient, serverClients, SH_MEMBER(this, &ConCmdManager::SetCommandClient), false);
77 g_RootMenu.RemoveRootConsoleCommand("cmds", this);
80 void ConCmdManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
82 /* Whoa, first get its information struct */
85 if (!m_Cmds.retrieve(name, &pInfo))
88 CmdHookList::iterator iter = pInfo->hooks.begin();
89 while (iter != pInfo->hooks.end())
91 CmdHook *hook = *iter;
93 IPluginContext *pContext = hook->pf->GetParentContext();
94 IPlugin *pPlugin = scripts->FindPluginByContext(pContext->GetContext());
96 // The list is guaranteed to exist.
98 pPlugin->GetProperty("CommandList", (void **)&list, false);
99 for (PluginHookList::iterator hiter = list->begin(); hiter != list->end(); hiter++)
108 iter = pInfo->hooks.erase(iter);
112 RemoveConCmd(pInfo, name, is_read_safe, false);
115 void ConCmdManager::OnPluginDestroyed(IPlugin *plugin)
117 PluginHookList *pList;
118 if (!plugin->GetProperty("CommandList", (void **)&pList, true))
121 PluginHookList::iterator iter = pList->begin();
122 while (iter != pList->end())
124 CmdHook *hook = *iter;
126 hook->info->hooks.remove(hook);
128 if (hook->info->hooks.empty())
129 RemoveConCmd(hook->info, hook->info->pCmd->GetName(), true, true);
131 iter = pList->erase(iter);
138 #if SOURCE_ENGINE == SE_DOTA
139 void CommandCallback(const CCommandContext &context, const CCommand &command)
141 #elif SOURCE_ENGINE >= SE_ORANGEBOX
142 void CommandCallback(const CCommand &command)
145 void CommandCallback()
150 g_HL2.PushCommandStack(&command);
152 g_ConCmds.InternalDispatch(command);
154 g_HL2.PopCommandStack();
157 void ConCmdManager::SetCommandClient(int client)
159 m_CmdClient = client + 1;
162 ConCmdInfo *ConCmdManager::FindInTrie(const char *name)
165 if (!m_Cmds.retrieve(name, &pInfo))
170 ConCmdList::iterator ConCmdManager::FindInList(const char *cmd)
172 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
174 while (iter != m_CmdList.end())
176 if (strcasecmp((*iter)->pCmd->GetName(), cmd) == 0)
184 ResultType ConCmdManager::DispatchClientCommand(int client, const char *cmd, int args, ResultType type)
188 if ((pInfo = FindInTrie(cmd)) == NULL)
190 ConCmdList::iterator item = FindInList(cmd);
191 if (item == m_CmdList.end())
196 cell_t result = type;
197 for (CmdHookList::iterator iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
199 CmdHook *hook = *iter;
201 if (hook->type == CmdHook::Server || !hook->pf->IsRunnable())
204 if (hook->admin && !CheckAccess(client, cmd, hook->admin))
206 if (result < Pl_Handled)
211 hook->pf->PushCell(client);
212 hook->pf->PushCell(args);
214 cell_t tempres = result;
215 if (hook->pf->Execute(&tempres) == SP_ERROR_NONE)
217 if (tempres > result)
219 if (result == Pl_Stop)
224 return (ResultType)result;
227 void ConCmdManager::InternalDispatch(const CCommand &command)
229 int client = m_CmdClient;
233 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
234 if (!pPlayer || !pPlayer->IsConnected())
239 * Note: Console commands will EITHER go through IServerGameDLL::ClientCommand,
240 * OR this dispatch. They will NEVER go through both.
242 * Whether or not it goes through the callback is determined by FCVAR_GAMEDLL
244 const char *cmd = g_HL2.CurrentCommandName();
246 ConCmdInfo *pInfo = FindInTrie(cmd);
249 /* Unfortunately, we now have to do a slow lookup because Valve made client commands
250 * case-insensitive. We can't even use our sortedness.
252 if (client == 0 && !engine->IsDedicatedServer())
255 ConCmdList::iterator item = FindInList(cmd);
256 if (item == m_CmdList.end())
262 /* This is a hack to prevent say triggers from firing on messages that were
263 * blocked because of flooding. We won't remove this, but the hack will get
264 * "nicer" when we expose explicit say hooks.
266 if (g_ChatTriggers.WasFloodedMessage())
269 cell_t result = Pl_Continue;
270 int args = command.ArgC() - 1;
272 // On a listen server, sometimes the server host's client index can be set
273 // as 0. So index 1 is passed to the command callback to correct this
274 // potential problem.
275 int realClient = (!engine->IsDedicatedServer() && client == 0)
276 ? g_Players.ListenClient()
278 int dedicatedClient = engine->IsDedicatedServer() ? 0 : g_Players.ListenClient();
280 for (CmdHookList::iterator iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
282 CmdHook *hook = *iter;
284 if (!hook->pf->IsRunnable())
287 if (hook->type == CmdHook::Server)
289 // Don't execute unless we're in the server console.
290 if (realClient != dedicatedClient)
293 // Check admin rights if needed. realClient isn't needed since we
294 // should bypass admin checks if client == 0 anyway.
295 if (client && hook->admin && !CheckAccess(client, cmd, hook->admin))
297 if (result < Pl_Handled)
302 // Client hooks get a client argument.
303 hook->pf->PushCell(realClient);
306 hook->pf->PushCell(args);
308 cell_t tempres = result;
309 if (hook->pf->Execute(&tempres) == SP_ERROR_NONE)
311 if (tempres > result)
313 if (result == Pl_Stop)
318 if (result >= Pl_Handled)
320 if (!pInfo->sourceMod)
321 RETURN_META(MRES_SUPERCEDE);
326 bool ConCmdManager::CheckClientCommandAccess(int client, const char *cmd, FlagBits cmdflags)
328 if (cmdflags == 0 || client == 0)
333 /* If running listen server, then client 1 is the server host and should have 'root' access */
334 if (client == 1 && !engine->IsDedicatedServer())
339 CPlayer *player = g_Players.GetPlayerByIndex(client);
341 || player->GetEdict() == NULL
342 || player->IsFakeClient())
347 return CheckAdminCommandAccess(player->GetAdminId(), cmd, cmdflags);
350 bool ConCmdManager::CheckAdminCommandAccess(AdminId adm, const char *cmd, FlagBits cmdflags)
352 if (adm != INVALID_ADMIN_ID)
354 FlagBits bits = g_Admins.GetAdminFlags(adm, Access_Effective);
356 /* root knows all, WHOA */
357 if ((bits & ADMFLAG_ROOT) == ADMFLAG_ROOT)
362 /* Check for overrides
363 * :TODO: is it worth optimizing this?
365 unsigned int groups = g_Admins.GetAdminGroupCount(adm);
368 bool override = false;
369 for (unsigned int i=0; i<groups; i++)
371 gid = g_Admins.GetAdminGroup(adm, i, NULL);
372 /* First get group-level override */
373 override = g_Admins.GetGroupCommandOverride(gid, cmd, Override_CommandGroup, &rule);
374 /* Now get the specific command override */
375 if (g_Admins.GetGroupCommandOverride(gid, cmd, Override_Command, &rule))
381 if (rule == Command_Allow)
385 else if (rule == Command_Deny)
392 /* See if our other flags match */
393 if ((bits & cmdflags) == cmdflags)
402 bool ConCmdManager::CheckAccess(int client, const char *cmd, AdminCmdInfo *pAdmin)
404 if (CheckClientCommandAccess(client, cmd, pAdmin->eflags))
409 #if SOURCE_ENGINE != SE_DOTA
410 edict_t *pEdict = PEntityOfEntIndex(client);
413 /* If we got here, the command failed... */
415 if (!logicore.CoreTranslate(buffer, sizeof(buffer), "%T", 2, NULL, "No Access", &client))
417 UTIL_Format(buffer, sizeof(buffer), "You do not have access to this command");
420 unsigned int replyto = g_ChatTriggers.GetReplyTo();
421 if (replyto == SM_REPLY_CONSOLE)
423 char fullbuffer[192];
424 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.\n", buffer);
425 #if SOURCE_ENGINE == SE_DOTA
426 engine->ClientPrintf(client, fullbuffer);
428 engine->ClientPrintf(pEdict, fullbuffer);
431 else if (replyto == SM_REPLY_CHAT)
433 char fullbuffer[192];
434 UTIL_Format(fullbuffer, sizeof(fullbuffer), "[SM] %s.", buffer);
435 g_HL2.TextMsg(client, HUD_PRINTTALK, fullbuffer);
441 bool ConCmdManager::AddAdminCommand(IPluginFunction *pFunction,
445 const char *description,
448 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
453 CmdHook *pHook = new CmdHook(CmdHook::Client, pInfo, pFunction, description);
455 pHook->admin = new AdminCmdInfo();
458 if (!m_CmdGrps.retrieve(group, &grpid))
460 grpid = m_Strings.AddString(group);
461 m_CmdGrps.insert(group, grpid);
464 pHook->admin->cmdGrpId = grpid;
465 pHook->admin->flags = adminflags;
467 /* First get the command group override, if any */
468 bool override = g_Admins.GetCommandOverride(group,
469 Override_CommandGroup,
470 &(pHook->admin->eflags));
472 /* Next get the command override, if any */
473 if (g_Admins.GetCommandOverride(name,
475 &(pHook->admin->eflags)))
480 /* Assign normal flags if there were no overrides */
482 pHook->admin->eflags = pHook->admin->flags;
483 pInfo->eflags = pHook->admin->eflags;
485 pInfo->hooks.append(pHook);
486 RegisterInPlugin(pHook);
490 bool ConCmdManager::AddServerCommand(IPluginFunction *pFunction,
492 const char *description,
496 ConCmdInfo *pInfo = AddOrFindCommand(name, description, flags);
501 CmdHook *pHook = new CmdHook(CmdHook::Server, pInfo, pFunction, description);
503 pInfo->hooks.append(pHook);
504 RegisterInPlugin(pHook);
508 void RegisterInPlugin(CmdHook *hook)
510 PluginHookList *pList;
512 IPlugin *pPlugin = scripts->FindPluginByContext(hook->pf->GetParentContext());
513 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
515 pList = new PluginHookList();
516 pPlugin->SetProperty("CommandList", pList);
519 const char *orig = hook->info->pCmd->GetName();
521 /* Insert this into the help list, SORTED alphabetically. */
522 PluginHookList::iterator iter = pList->begin();
523 while (iter != pList->end())
525 const char *cmd = (*iter)->info->pCmd->GetName();
526 if (strcmp(orig, cmd) < 0)
528 pList->insertBefore(iter, hook);
537 void ConCmdManager::AddToCmdList(ConCmdInfo *info)
539 List<ConCmdInfo *>::iterator iter = m_CmdList.begin();
541 bool inserted = false;
542 const char *orig = NULL;
544 orig = info->pCmd->GetName();
546 /* Insert this into the help list, SORTED alphabetically. */
547 while (iter != m_CmdList.end())
549 const char *cmd = NULL;
551 cmd = pInfo->pCmd->GetName();
552 if (strcmp(orig, cmd) < 0)
554 m_CmdList.insert(iter, info);
563 m_CmdList.push_back(info);
567 void ConCmdManager::UpdateAdminCmdFlags(const char *cmd, OverrideType type, FlagBits bits, bool remove)
569 if (type == Override_Command)
572 if (!m_Cmds.retrieve(cmd, &pInfo))
575 for (CmdHookList::iterator iter = pInfo->hooks.begin(); iter != pInfo->hooks.end(); iter++)
581 iter->admin->eflags = bits;
583 iter->admin->eflags = iter->admin->flags;
584 pInfo->eflags = iter->admin->eflags;
587 else if (type == Override_CommandGroup)
590 if (!m_CmdGrps.retrieve(cmd, &grpid))
593 /* This is bad :( loop through all commands */
594 List<ConCmdInfo *>::iterator iter;
595 for (iter=m_CmdList.begin(); iter!=m_CmdList.end(); iter++)
597 ConCmdInfo *pInfo = *iter;
598 for (CmdHookList::iterator citer = pInfo->hooks.begin(); citer != pInfo->hooks.end(); citer++)
600 CmdHook *hook = (*citer);
601 if (!hook->admin || hook->admin->cmdGrpId != grpid)
605 hook->admin->eflags = bits;
607 hook->admin->eflags = hook->admin->flags;
608 pInfo->eflags = hook->admin->eflags;
614 void ConCmdManager::RemoveConCmd(ConCmdInfo *info, const char *name, bool is_read_safe, bool untrack)
616 /* Remove from the trie */
619 /* Remove console-specific information
620 * This should always be true as of right now
626 /* Unlink from SourceMM */
627 g_SMAPI->UnregisterConCommandBase(g_PLAPI, info->pCmd);
628 /* Delete the command's memory */
629 char *new_help = const_cast<char *>(info->pCmd->GetHelpText());
630 char *new_name = const_cast<char *>(info->pCmd->GetName());
639 /* Remove the external hook */
640 SH_REMOVE_HOOK(ConCommand, Dispatch, info->pCmd, SH_STATIC(CommandCallback), false);
644 UntrackConCommandBase(info->pCmd, this);
649 /* Remove from list */
650 m_CmdList.remove(info);
655 bool ConCmdManager::LookForSourceModCommand(const char *cmd)
658 if (!m_Cmds.retrieve(cmd, &pInfo))
661 return pInfo->sourceMod && !pInfo->hooks.empty();
664 bool ConCmdManager::LookForCommandAdminFlags(const char *cmd, FlagBits *pFlags)
667 if (!m_Cmds.retrieve(cmd, &pInfo))
670 *pFlags = pInfo->eflags;
674 ConCmdInfo *ConCmdManager::AddOrFindCommand(const char *name, const char *description, int flags)
677 if (!m_Cmds.retrieve(name, &pInfo))
679 ConCmdList::iterator item = FindInList(name);
680 if (item != m_CmdList.end())
683 pInfo = new ConCmdInfo();
684 /* Find the commandopan */
685 ConCommand *pCmd = FindCommand(name);
689 /* Note that we have to duplicate because the source might not be
690 * a static string, and these expect static memory.
696 char *new_name = sm_strdup(name);
697 char *new_help = sm_strdup(description);
698 pCmd = new ConCommand(new_name, CommandCallback, new_help, flags);
699 pInfo->sourceMod = true;
703 TrackConCommandBase(pCmd, this);
704 SH_ADD_HOOK(ConCommand, Dispatch, pCmd, SH_STATIC(CommandCallback), false);
709 m_Cmds.insert(name, pInfo);
716 void ConCmdManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
718 if (command.ArgC() >= 3)
720 const char *text = command.Arg(2);
722 IPlugin *pPlugin = scripts->FindPluginByConsoleArg(text);
726 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", text);
730 const sm_plugininfo_t *plinfo = pPlugin->GetPublicInfo();
731 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : pPlugin->GetFilename();
733 PluginHookList *pList;
734 if (!pPlugin->GetProperty("CommandList", (void **)&pList))
736 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
741 g_RootMenu.ConsolePrint("[SM] No commands found for: %s", plname);
745 const char *type = NULL;
748 g_RootMenu.ConsolePrint("[SM] Listing commands for: %s", plname);
749 g_RootMenu.ConsolePrint(" %-17.16s %-8.7s %s", "[Name]", "[Type]", "[Help]");
750 for (PluginHookList::iterator iter = pList->begin(); iter != pList->end(); iter++)
752 CmdHook *hook = *iter;
753 if (hook->type == CmdHook::Server)
756 type = hook->info->eflags == 0 ? "console" : "admin";
758 name = hook->info->pCmd->GetName();
759 if (hook->helptext.length())
760 help = hook->helptext.chars();
762 help = hook->info->pCmd->GetHelpText();
763 g_RootMenu.ConsolePrint(" %-17.16s %-12.11s %s", name, type, help);
769 g_RootMenu.ConsolePrint("[SM] Usage: sm cmds <plugin #>");