3 * =============================================================================
5 * Copyright (C) 2004-2010 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 "sm_globals.h"
33 #include "HalfLife2.h"
34 #include "sourcemm_api.h"
35 #include "HandleSys.h"
36 #include "ConVarManager.h"
37 #include "ConCmdManager.h"
38 #include "PluginSys.h"
39 #include "sm_stringutil.h"
40 #include "PlayerManager.h"
41 #include "ChatTriggers.h"
42 #include "AdminCache.h"
43 #include <inetchannel.h>
45 #include <sm_trie_tpl.h>
46 #include <tier0/dbg.h>
48 #include "ConsoleDetours.h"
49 #include "ConCommandBaseIterator.h"
51 #if SOURCE_ENGINE >= SE_EYE
57 #if SOURCE_ENGINE >= SE_LEFT4DEAD
58 #define NET_SETCONVAR 6
60 #define NET_SETCONVAR 5
65 ConVarBound_Upper = 0,
69 HandleType_t hCmdIterType = 0;
70 HandleType_t htConCmdIter = 0;
75 List<ConCmdInfo *>::iterator iter;
78 class ConsoleHelpers :
80 public IHandleTypeDispatch
83 virtual void OnSourceModAllInitialized()
87 g_HandleSys.InitAccessDefaults(NULL, &access);
89 htConCmdIter = g_HandleSys.CreateType("ConCmdIter", this, 0, NULL, &access, g_pCoreIdent, NULL);
91 access.access[HandleAccess_Clone] = HANDLE_RESTRICT_OWNER | HANDLE_RESTRICT_IDENTITY;
93 hCmdIterType = g_HandleSys.CreateType("CmdIter", this, 0, NULL, &access, g_pCoreIdent, NULL);
95 virtual void OnHandleDestroy(HandleType_t type, void *object)
97 if (type == hCmdIterType)
99 GlobCmdIter *iter = (GlobCmdIter *)object;
102 else if (type == htConCmdIter)
104 ConCommandBaseIterator *iter = (ConCommandBaseIterator * )object;
108 virtual bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
110 if (type == htConCmdIter)
112 *pSize = sizeof(ConCommandBaseIterator);
115 else if (type == hCmdIterType)
117 *pSize = sizeof(GlobCmdIter);
124 class CommandFlagsHelper : public IConCommandTracker
127 void OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
129 m_CmdFlags.remove(name);
131 bool GetFlags(const char *name, int *flags)
133 ConCommandBase **ppCmd;
134 ConCommandBase *pCmd;
135 if ((ppCmd=m_CmdFlags.retrieve(name)))
137 TrackConCommandBase((*ppCmd), this);
138 *flags = (*ppCmd)->GetFlags();
141 else if ((pCmd=FindCommandBase(name)))
143 m_CmdFlags.insert(name, pCmd);
144 TrackConCommandBase(pCmd, this);
145 *flags = pCmd->GetFlags();
153 bool SetFlags(const char *name, int flags)
155 ConCommandBase **ppCmd;
156 ConCommandBase *pCmd;
157 if ((ppCmd=m_CmdFlags.retrieve(name)))
159 (*ppCmd)->SetFlags(flags);
160 TrackConCommandBase((*ppCmd), this);
163 else if ((pCmd=FindCommandBase(name)))
165 m_CmdFlags.insert(name, pCmd);
166 pCmd->SetFlags(flags);
167 TrackConCommandBase(pCmd, this);
176 KTrie<ConCommandBase *> m_CmdFlags;
177 } s_CommandFlagsHelper;
179 #if SOURCE_ENGINE < SE_ORANGEBOX
180 static void ReplicateConVar(ConVar *pConVar)
182 int maxClients = g_Players.GetMaxClients();
185 bf_write buffer(data, sizeof(data));
187 buffer.WriteUBitLong(NET_SETCONVAR, NETMSG_BITS);
189 buffer.WriteString(pConVar->GetName());
190 buffer.WriteString(pConVar->GetString());
192 for (int i = 1; i <= maxClients; i++)
194 CPlayer *pPlayer = g_Players.GetPlayerByIndex(i);
196 if (pPlayer && pPlayer->IsInGame() && !pPlayer->IsFakeClient())
198 if (INetChannel *netchan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(i)))
199 netchan->SendData(buffer);
204 static void NotifyConVar(ConVar *pConVar)
206 IGameEvent *pEvent = gameevents->CreateEvent("server_cvar");
207 pEvent->SetString("cvarname", pConVar->GetName());
208 if (IsFlagSet(pConVar, FCVAR_PROTECTED))
210 pEvent->SetString("cvarvalue", "***PROTECTED***");
214 pEvent->SetString("cvarvalue", pConVar->GetString());
217 gameevents->FireEvent(pEvent);
221 static cell_t sm_CreateConVar(IPluginContext *pContext, const cell_t *params)
223 char *name, *defaultVal, *helpText;
225 pContext->LocalToString(params[1], &name);
227 // While the engine seems to accept a blank convar name, it causes a crash upon server quit
228 if (name == NULL || strcmp(name, "") == 0)
230 return pContext->ThrowNativeError("Convar with blank name is not permitted");
233 pContext->LocalToString(params[2], &defaultVal);
234 pContext->LocalToString(params[3], &helpText);
236 bool hasMin = params[5] ? true : false;
237 bool hasMax = params[7] ? true : false;
238 float min = sp_ctof(params[6]);
239 float max = sp_ctof(params[8]);
241 Handle_t hndl = g_ConVarManager.CreateConVar(pContext, name, defaultVal, helpText, params[4], hasMin, min, hasMax, max);
243 if (hndl == BAD_HANDLE)
245 return pContext->ThrowNativeError("Convar \"%s\" was not created. A console command with the same might already exist.", name);
251 static cell_t sm_FindConVar(IPluginContext *pContext, const cell_t *params)
255 pContext->LocalToString(params[1], &name);
257 return g_ConVarManager.FindConVar(name);
260 static cell_t sm_HookConVarChange(IPluginContext *pContext, const cell_t *params)
262 Handle_t hndl = static_cast<Handle_t>(params[1]);
266 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
269 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
272 IPluginFunction *pFunction = pContext->GetFunctionById(params[2]);
276 return pContext->ThrowNativeError("Invalid function id (%X)", params[2]);
279 g_ConVarManager.HookConVarChange(pConVar, pFunction);
284 static cell_t sm_UnhookConVarChange(IPluginContext *pContext, const cell_t *params)
286 Handle_t hndl = static_cast<Handle_t>(params[1]);
290 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
293 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
296 IPluginFunction *pFunction = pContext->GetFunctionById(params[2]);
300 return pContext->ThrowNativeError("Invalid function id (%X)", params[2]);
303 g_ConVarManager.UnhookConVarChange(pConVar, pFunction);
308 static cell_t sm_GetConVarBool(IPluginContext *pContext, const cell_t *params)
310 Handle_t hndl = static_cast<Handle_t>(params[1]);
314 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
317 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
320 return pConVar->GetBool();
323 static cell_t sm_GetConVarInt(IPluginContext *pContext, const cell_t *params)
325 Handle_t hndl = static_cast<Handle_t>(params[1]);
329 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
332 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
335 return pConVar->GetInt();
338 /* This handles both SetConVarBool() and SetConVarInt() */
339 static cell_t sm_SetConVarNum(IPluginContext *pContext, const cell_t *params)
341 Handle_t hndl = static_cast<Handle_t>(params[1]);
345 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
348 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
351 pConVar->SetValue(params[2]);
353 #if SOURCE_ENGINE < SE_ORANGEBOX
354 /* Should we replicate it? */
355 if (params[3] && IsFlagSet(pConVar, FCVAR_REPLICATED))
357 ReplicateConVar(pConVar);
360 /* Should we notify clients? */
361 if (params[4] && IsFlagSet(pConVar, FCVAR_NOTIFY))
363 NotifyConVar(pConVar);
370 static cell_t sm_GetConVarFloat(IPluginContext *pContext, const cell_t *params)
372 Handle_t hndl = static_cast<Handle_t>(params[1]);
376 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
379 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
382 float value = pConVar->GetFloat();
384 return sp_ftoc(value);
387 static cell_t sm_SetConVarFloat(IPluginContext *pContext, const cell_t *params)
389 Handle_t hndl = static_cast<Handle_t>(params[1]);
393 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
396 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
399 float value = sp_ctof(params[2]);
400 pConVar->SetValue(value);
402 #if SOURCE_ENGINE < SE_ORANGEBOX
403 /* Should we replicate it? */
404 if (params[3] && IsFlagSet(pConVar, FCVAR_REPLICATED))
406 ReplicateConVar(pConVar);
409 /* Should we notify clients? */
410 if (params[4] && IsFlagSet(pConVar, FCVAR_NOTIFY))
412 NotifyConVar(pConVar);
419 static cell_t sm_GetConVarString(IPluginContext *pContext, const cell_t *params)
421 Handle_t hndl = static_cast<Handle_t>(params[1]);
425 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
428 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
431 pContext->StringToLocalUTF8(params[2], params[3], pConVar->GetString(), NULL);
436 static cell_t sm_SetConVarString(IPluginContext *pContext, const cell_t *params)
438 Handle_t hndl = static_cast<Handle_t>(params[1]);
442 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
445 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
449 pContext->LocalToString(params[2], &value);
451 pConVar->SetValue(value);
453 #if SOURCE_ENGINE < SE_ORANGEBOX
454 /* Should we replicate it? */
455 if (params[3] && IsFlagSet(pConVar, FCVAR_REPLICATED))
457 ReplicateConVar(pConVar);
460 /* Should we notify clients? */
461 if (params[4] && IsFlagSet(pConVar, FCVAR_NOTIFY))
463 NotifyConVar(pConVar);
470 static cell_t sm_ResetConVar(IPluginContext *pContext, const cell_t *params)
472 Handle_t hndl = static_cast<Handle_t>(params[1]);
476 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
479 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
484 #if SOURCE_ENGINE < SE_ORANGEBOX
485 /* Should we replicate it? */
486 if (params[3] && IsFlagSet(pConVar, FCVAR_REPLICATED))
488 ReplicateConVar(pConVar);
491 /* Should we notify clients? */
492 if (params[4] && IsFlagSet(pConVar, FCVAR_NOTIFY))
494 NotifyConVar(pConVar);
501 static cell_t GetConVarDefault(IPluginContext *pContext, const cell_t *params)
503 Handle_t hndl = static_cast<Handle_t>(params[1]);
507 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
510 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
514 pContext->StringToLocalUTF8(params[2], params[3], pConVar->GetDefault(), &bytes);
519 static cell_t sm_GetConVarFlags(IPluginContext *pContext, const cell_t *params)
521 Handle_t hndl = static_cast<Handle_t>(params[1]);
525 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
528 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
531 return pConVar->GetFlags();
534 static cell_t sm_SetConVarFlags(IPluginContext *pContext, const cell_t *params)
536 Handle_t hndl = static_cast<Handle_t>(params[1]);
540 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
543 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
546 pConVar->SetFlags(params[2]);
551 static cell_t sm_GetConVarBounds(IPluginContext *pContext, const cell_t *params)
553 Handle_t hndl = static_cast<Handle_t>(params[1]);
557 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
560 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
569 case ConVarBound_Upper:
570 hasBound = pConVar->GetMax(bound);
572 case ConVarBound_Lower:
573 hasBound = pConVar->GetMin(bound);
576 return pContext->ThrowNativeError("Invalid ConVarBounds value %d");
579 pContext->LocalToPhysAddr(params[3], &addr);
580 *addr = sp_ftoc(bound);
585 static cell_t sm_SetConVarBounds(IPluginContext *pContext, const cell_t *params)
587 Handle_t hndl = static_cast<Handle_t>(params[1]);
591 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
594 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
599 case ConVarBound_Upper:
600 pConVar->SetMax(params[3] ? true : false, sp_ctof(params[4]));
602 case ConVarBound_Lower:
603 pConVar->SetMin(params[3] ? true : false, sp_ctof(params[4]));
606 return pContext->ThrowNativeError("Invalid ConVarBounds value %d");
612 static cell_t sm_GetConVarName(IPluginContext *pContext, const cell_t *params)
614 Handle_t hndl = static_cast<Handle_t>(params[1]);
618 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
621 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
624 pContext->StringToLocalUTF8(params[2], params[3], pConVar->GetName(), NULL);
629 static bool s_QueryAlreadyWarned = false;
631 static cell_t sm_QueryClientConVar(IPluginContext *pContext, const cell_t *params)
635 IPluginFunction *pCallback;
637 if (!g_ConVarManager.IsQueryingSupported())
639 if (!s_QueryAlreadyWarned)
641 s_QueryAlreadyWarned = true;
642 return pContext->ThrowNativeError("Game does not support client convar querying (one time warning)");
648 pPlayer = g_Players.GetPlayerByIndex(params[1]);
652 return pContext->ThrowNativeError("Client index %d is invalid", params[1]);
655 if (!pPlayer->IsConnected())
657 return pContext->ThrowNativeError("Client %d is not connected", params[1]);
660 /* Trying a query on a bot results in callback not be fired, so don't bother */
661 if (pPlayer->IsFakeClient())
666 pContext->LocalToString(params[2], &name);
667 pCallback = pContext->GetFunctionById(params[3]);
671 return pContext->ThrowNativeError("Invalid function id (%X)", params[3]);
674 return g_ConVarManager.QueryClientConVar(pPlayer->GetEdict(), name, pCallback, params[4]);
677 static cell_t sm_RegServerCmd(IPluginContext *pContext, const cell_t *params)
680 IPluginFunction *pFunction;
682 pContext->LocalToString(params[1], &name);
684 if (strcasecmp(name, "sm") == 0)
686 return pContext->ThrowNativeError("Cannot register \"sm\" command");
689 pContext->LocalToString(params[3], &help);
690 pFunction = pContext->GetFunctionById(params[2]);
694 return pContext->ThrowNativeError("Invalid function id (%X)", params[2]);
697 if (!g_ConCmds.AddServerCommand(pFunction, name, help, params[4]))
699 return pContext->ThrowNativeError("Command \"%s\" could not be created. A convar with the same name already exists.", name);
705 static cell_t sm_RegConsoleCmd(IPluginContext *pContext, const cell_t *params)
708 IPluginFunction *pFunction;
710 pContext->LocalToString(params[1], &name);
712 if (strcasecmp(name, "sm") == 0)
714 return pContext->ThrowNativeError("Cannot register \"sm\" command");
717 pContext->LocalToString(params[3], &help);
718 pFunction = pContext->GetFunctionById(params[2]);
722 return pContext->ThrowNativeError("Invalid function id (%X)", params[2]);
725 if (!g_ConCmds.AddConsoleCommand(pFunction, name, help, params[4]))
727 return pContext->ThrowNativeError("Command \"%s\" could not be created. A convar with the same name already exists.", name);
733 static cell_t sm_RegAdminCmd(IPluginContext *pContext, const cell_t *params)
737 IPluginFunction *pFunction;
738 FlagBits flags = params[3];
739 int cmdflags = params[6];
741 pContext->LocalToString(params[1], &name);
743 if (strcasecmp(name, "sm") == 0)
745 return pContext->ThrowNativeError("Cannot register \"sm\" command");
748 pContext->LocalToString(params[4], &help);
749 pContext->LocalToString(params[5], (char **)&group);
750 pFunction = pContext->GetFunctionById(params[2]);
752 if (group[0] == '\0')
754 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
755 group = pPlugin->GetFilename();
760 return pContext->ThrowNativeError("Invalid function id (%X)", params[2]);
763 if (!g_ConCmds.AddAdminCommand(pFunction, name, group, flags, help, cmdflags))
765 return pContext->ThrowNativeError("Command \"%s\" could not be created. A convar with the same name already exists.", name);
771 static cell_t sm_GetCmdArgs(IPluginContext *pContext, const cell_t *params)
773 const CCommand *pCmd = g_HL2.PeekCommandStack();
777 return pContext->ThrowNativeError("No command callback available");
780 return pCmd->ArgC() - 1;
783 static cell_t sm_GetCmdArg(IPluginContext *pContext, const cell_t *params)
785 const CCommand *pCmd = g_HL2.PeekCommandStack();
789 return pContext->ThrowNativeError("No command callback available");
794 const char *arg = pCmd->Arg(params[1]);
796 pContext->StringToLocalUTF8(params[2], params[3], arg ? arg : "", &length);
798 return (cell_t)length;
801 static cell_t sm_GetCmdArgString(IPluginContext *pContext, const cell_t *params)
803 const CCommand *pCmd = g_HL2.PeekCommandStack();
807 return pContext->ThrowNativeError("No command callback available");
810 const char *args = pCmd->ArgS();
818 pContext->StringToLocalUTF8(params[1], params[2], args, &length);
820 return (cell_t)length;
823 static cell_t sm_PrintToServer(IPluginContext *pCtx, const cell_t *params)
829 pCtx->LocalToString(params[1], &fmt);
830 size_t res = atcprintf(buffer, sizeof(buffer)-2, fmt, pCtx, params, &arg);
832 buffer[res++] = '\n';
835 META_CONPRINT(buffer);
840 static cell_t sm_PrintToConsole(IPluginContext *pCtx, const cell_t *params)
842 int index = params[1];
843 if ((index < 0) || (index > g_Players.GetMaxClients()))
845 return pCtx->ThrowNativeError("Client index %d is invalid", index);
848 CPlayer *pPlayer = NULL;
851 pPlayer = g_Players.GetPlayerByIndex(index);
852 if (!pPlayer->IsInGame())
854 return pCtx->ThrowNativeError("Client %d is not in game", index);
857 /* Silent fail on bots, engine will crash */
858 if (pPlayer->IsFakeClient())
868 pCtx->LocalToString(params[2], &fmt);
869 size_t res = atcprintf(buffer, sizeof(buffer)-2, fmt, pCtx, params, &arg);
871 buffer[res++] = '\n';
876 engine->ClientPrintf(pPlayer->GetEdict(), buffer);
878 META_CONPRINT(buffer);
884 static cell_t sm_ServerCommand(IPluginContext *pContext, const cell_t *params)
886 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
889 size_t len = g_SourceMod.FormatString(buffer, sizeof(buffer)-2, pContext, params, 1);
891 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
896 /* One byte for null terminator, one for newline */
897 buffer[len++] = '\n';
900 engine->ServerCommand(buffer);
905 char *g_ServerCommandBuffer = NULL;
906 cell_t g_ServerCommandBufferLength;
908 bool g_ShouldCatchSpew = false;
910 #if SOURCE_ENGINE < SE_LEFT4DEAD2
911 SpewOutputFunc_t g_OriginalSpewOutputFunc = NULL;
913 SpewRetval_t SourcemodSpewOutputFunc(SpewType_t spewType, tchar const *pMsg)
915 if (g_ServerCommandBuffer)
917 V_strcat(g_ServerCommandBuffer, pMsg, g_ServerCommandBufferLength);
920 if (g_OriginalSpewOutputFunc)
922 return g_OriginalSpewOutputFunc(spewType, pMsg);
924 return SPEW_CONTINUE;
928 class CSourcemodLoggingListener: public ILoggingListener
931 void Log(const LoggingContext_t *pContext, const tchar *pMessage)
933 if (g_ServerCommandBuffer)
935 V_strcat(g_ServerCommandBuffer, pMessage, g_ServerCommandBufferLength);
938 } g_SourcemodLoggingListener;
941 CON_COMMAND(sm_conhook_start, "")
943 if (!g_ShouldCatchSpew)
945 Warning("You shouldn't run this command!\n");
949 #if SOURCE_ENGINE < SE_LEFT4DEAD2
950 g_OriginalSpewOutputFunc = GetSpewOutputFunc();
951 SpewOutputFunc(SourcemodSpewOutputFunc);
953 #if SOURCE_ENGINE < SE_ALIENSWARM
954 LoggingSystem_PushLoggingState(false);
956 LoggingSystem_PushLoggingState(false, false);
958 LoggingSystem_RegisterLoggingListener(&g_SourcemodLoggingListener);
962 CON_COMMAND(sm_conhook_stop, "")
964 if (!g_ShouldCatchSpew)
966 Warning("You shouldn't run this command!\n");
970 #if SOURCE_ENGINE < SE_LEFT4DEAD2
971 SpewOutputFunc(g_OriginalSpewOutputFunc);
973 LoggingSystem_PopLoggingState(false);
976 g_ShouldCatchSpew = false;
979 static cell_t sm_ServerCommandEx(IPluginContext *pContext, const cell_t *params)
981 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
984 size_t len = g_SourceMod.FormatString(buffer, sizeof(buffer)-2, pContext, params, 3);
986 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
991 /* One byte for null terminator, one for newline */
992 buffer[len++] = '\n';
995 pContext->LocalToString(params[1], &g_ServerCommandBuffer);
996 g_ServerCommandBufferLength = params[2];
998 if (g_ServerCommandBufferLength > 0)
1000 g_ServerCommandBuffer[0] = '\0';
1003 engine->ServerExecute();
1005 g_ShouldCatchSpew = true;
1006 engine->ServerCommand("sm_conhook_start\n");
1007 engine->ServerCommand(buffer);
1008 engine->ServerCommand("sm_conhook_stop\n");
1010 engine->ServerExecute();
1012 if (g_ServerCommandBufferLength > 0)
1014 g_ServerCommandBuffer[g_ServerCommandBufferLength-1] = '\0';
1017 g_ServerCommandBuffer = NULL;
1018 g_ServerCommandBufferLength = 0;
1023 static cell_t sm_InsertServerCommand(IPluginContext *pContext, const cell_t *params)
1025 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
1028 size_t len = g_SourceMod.FormatString(buffer, sizeof(buffer)-2, pContext, params, 1);
1030 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
1035 /* One byte for null terminator, one for newline */
1036 buffer[len++] = '\n';
1039 InsertServerCommand(buffer);
1044 static cell_t sm_ServerExecute(IPluginContext *pContext, const cell_t *params)
1046 engine->ServerExecute();
1051 static cell_t sm_ClientCommand(IPluginContext *pContext, const cell_t *params)
1053 CPlayer *pPlayer = g_Players.GetPlayerByIndex(params[1]);
1057 return pContext->ThrowNativeError("Client index %d is invalid", params[1]);
1060 if (!pPlayer->IsConnected())
1062 return pContext->ThrowNativeError("Client %d is not connected", params[1]);
1065 g_SourceMod.SetGlobalTarget(params[1]);
1068 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
1070 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
1075 engine->ClientCommand(pPlayer->GetEdict(), "%s", buffer);
1080 static cell_t FakeClientCommand(IPluginContext *pContext, const cell_t *params)
1082 CPlayer *pPlayer = g_Players.GetPlayerByIndex(params[1]);
1086 return pContext->ThrowNativeError("Client index %d is invalid", params[1]);
1089 if (!pPlayer->IsConnected())
1091 return pContext->ThrowNativeError("Client %d is not connected", params[1]);
1095 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
1097 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
1102 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), buffer);
1107 static cell_t FakeClientCommandEx(IPluginContext *pContext, const cell_t *params)
1109 CPlayer *pPlayer = g_Players.GetPlayerByIndex(params[1]);
1113 return pContext->ThrowNativeError("Client index %d is invalid", params[1]);
1116 if (!pPlayer->IsConnected())
1118 return pContext->ThrowNativeError("Client %d is not connected", params[1]);
1122 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
1124 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
1129 g_HL2.AddToFakeCliCmdQueue(params[1], engine->GetPlayerUserId(pPlayer->GetEdict()), buffer);
1134 static cell_t ReplyToCommand(IPluginContext *pContext, const cell_t *params)
1136 g_SourceMod.SetGlobalTarget(params[1]);
1138 /* Build the format string */
1140 size_t len = g_SourceMod.FormatString(buffer, sizeof(buffer)-2, pContext, params, 2);
1142 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
1147 /* If we're printing to the server, shortcut out */
1151 buffer[len++] = '\n';
1153 META_CONPRINT(buffer);
1157 CPlayer *pPlayer = g_Players.GetPlayerByIndex(params[1]);
1161 return pContext->ThrowNativeError("Client index %d is invalid", params[1]);
1164 if (!pPlayer->IsConnected())
1166 return pContext->ThrowNativeError("Client %d is not connected", params[1]);
1169 g_SourceMod.SetGlobalTarget(params[1]);
1171 unsigned int replyto = g_ChatTriggers.GetReplyTo();
1172 if (replyto == SM_REPLY_CONSOLE)
1174 buffer[len++] = '\n';
1176 engine->ClientPrintf(pPlayer->GetEdict(), buffer);
1177 } else if (replyto == SM_REPLY_CHAT) {
1183 g_HL2.TextMsg(params[1], HUD_PRINTTALK, buffer);
1189 static cell_t GetCmdReplyTarget(IPluginContext *pContext, const cell_t *params)
1191 return g_ChatTriggers.GetReplyTo();
1194 static cell_t SetCmdReplyTarget(IPluginContext *pContext, const cell_t *params)
1196 return g_ChatTriggers.SetReplyTo(params[1]);
1199 static cell_t GetCommandIterator(IPluginContext *pContext, const cell_t *params)
1201 GlobCmdIter *iter = new GlobCmdIter;
1202 iter->started = false;
1204 Handle_t hndl = g_HandleSys.CreateHandle(hCmdIterType, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
1205 if (hndl == BAD_HANDLE)
1213 static cell_t ReadCommandIterator(IPluginContext *pContext, const cell_t *params)
1217 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
1219 if ((err = g_HandleSys.ReadHandle(params[1], hCmdIterType, &sec, (void **)&iter))
1220 != HandleError_None)
1222 return pContext->ThrowNativeError("Invalid GlobCmdIter Handle %x", params[1]);
1225 const List<ConCmdInfo *> &cmds = g_ConCmds.GetCommandList();
1229 iter->iter = cmds.begin();
1230 iter->started = true;
1233 while (iter->iter != cmds.end()
1234 && !(*(iter->iter))->sourceMod)
1239 if (iter->iter == cmds.end())
1244 ConCmdInfo *pInfo = (*(iter->iter));
1246 pContext->StringToLocalUTF8(params[2], params[3], pInfo->pCmd->GetName(), NULL);
1247 pContext->StringToLocalUTF8(params[5], params[6], pInfo->pCmd->GetHelpText(), NULL);
1250 pContext->LocalToPhysAddr(params[4], &addr);
1251 *addr = pInfo->admin.eflags;
1258 static cell_t CheckCommandAccess(IPluginContext *pContext, const cell_t *params)
1266 pContext->LocalToString(params[2], &cmd);
1268 /* Match up with an admin command if possible */
1269 FlagBits bits = params[3];
1270 bool found_command = false;
1271 if (params[0] < 4 || !params[4])
1273 found_command = g_ConCmds.LookForCommandAdminFlags(cmd, &bits);
1278 g_Admins.GetCommandOverride(cmd, Override_Command, &bits);
1281 return g_ConCmds.CheckClientCommandAccess(params[1], cmd, bits) ? 1 : 0;
1284 static cell_t CheckAccess(IPluginContext *pContext, const cell_t *params)
1287 pContext->LocalToString(params[2], &cmd);
1289 /* Match up with an admin command if possible */
1290 FlagBits bits = params[3];
1291 bool found_command = false;
1292 if (params[0] < 4 || !params[4])
1294 found_command = g_ConCmds.LookForCommandAdminFlags(cmd, &bits);
1299 g_Admins.GetCommandOverride(cmd, Override_Command, &bits);
1302 return g_ConCmds.CheckAdminCommandAccess(params[1], cmd, bits) ? 1 : 0;
1305 static cell_t IsChatTrigger(IPluginContext *pContext, const cell_t *params)
1307 return g_ChatTriggers.IsChatTrigger() ? 1 : 0;
1310 static cell_t SetCommandFlags(IPluginContext *pContext, const cell_t *params)
1313 pContext->LocalToString(params[1], &name);
1315 return (s_CommandFlagsHelper.SetFlags(name, params[2])) ? 1 : 0;
1318 static cell_t GetCommandFlags(IPluginContext *pContext, const cell_t *params)
1322 pContext->LocalToString(params[1], &name);
1324 return (s_CommandFlagsHelper.GetFlags(name, &flags)) ? flags : -1;
1327 static cell_t FindFirstConCommand(IPluginContext *pContext, const cell_t *params)
1330 ConCommandBaseIterator *pIter;
1331 cell_t *pIsCmd, *pFlags;
1332 const ConCommandBase *pConCmd;
1335 pContext->LocalToPhysAddr(params[3], &pIsCmd);
1336 pContext->LocalToPhysAddr(params[4], &pFlags);
1338 pIter = new ConCommandBaseIterator();
1340 if (!pIter->IsValid())
1346 pConCmd = pIter->Get();
1348 pContext->StringToLocalUTF8(params[1], params[2], pConCmd->GetName(), NULL);
1349 *pIsCmd = pConCmd->IsCommand() ? 1 : 0;
1350 *pFlags = pConCmd->GetFlags();
1354 desc = pConCmd->GetHelpText();
1355 pContext->StringToLocalUTF8(params[5], params[6], (desc && desc[0]) ? desc : "", NULL);
1358 if ((hndl = g_HandleSys.CreateHandle(htConCmdIter, pIter, pContext->GetIdentity(), g_pCoreIdent, NULL))
1368 static cell_t FindNextConCommand(IPluginContext *pContext, const cell_t *params)
1371 ConCommandBaseIterator *pIter;
1372 cell_t *pIsCmd, *pFlags;
1374 const ConCommandBase *pConCmd;
1375 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
1377 if ((err = g_HandleSys.ReadHandle(params[1], htConCmdIter, &sec, (void **)&pIter)) != HandleError_None)
1379 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", params[1], err);
1382 if (!pIter->IsValid())
1388 if (!pIter->IsValid())
1392 pConCmd = pIter->Get();
1394 pContext->LocalToPhysAddr(params[4], &pIsCmd);
1395 pContext->LocalToPhysAddr(params[5], &pFlags);
1397 pContext->StringToLocalUTF8(params[2], params[3], pConCmd->GetName(), NULL);
1398 *pIsCmd = pConCmd->IsCommand() ? 1 : 0;
1399 *pFlags = pConCmd->GetFlags();
1403 desc = pConCmd->GetHelpText();
1404 pContext->StringToLocalUTF8(params[6], params[7], (desc && desc[0]) ? desc : "", NULL);
1410 static cell_t SendConVarValue(IPluginContext *pContext, const cell_t *params)
1412 Handle_t hndl = static_cast<Handle_t>(params[2]);
1417 pContext->LocalToString(params[3], &value);
1419 if ((err=g_ConVarManager.ReadConVarHandle(hndl, &pConVar))
1420 != HandleError_None)
1422 return pContext->ThrowNativeError("Invalid convar handle %x (error %d)", hndl, err);
1426 bf_write buffer(data, sizeof(data));
1428 buffer.WriteUBitLong(NET_SETCONVAR, NETMSG_BITS);
1429 buffer.WriteByte(1);
1430 buffer.WriteString(pConVar->GetName());
1431 buffer.WriteString(value);
1433 CPlayer *pPlayer = g_Players.GetPlayerByIndex(params[1]);
1437 return pContext->ThrowNativeError("Client index %d is invalid", params[1]);
1440 if (!pPlayer->IsConnected())
1442 return pContext->ThrowNativeError("Client %d is not connected", params[1]);
1445 if (pPlayer->IsFakeClient())
1447 return pContext->ThrowNativeError("Client %d is fake and cannot be targeted", params[1]);
1450 INetChannel *netchan = static_cast<INetChannel *>(engine->GetPlayerNetInfo(params[1]));
1451 if (netchan == NULL)
1456 netchan->SendData(buffer);
1461 static cell_t AddServerTag(IPluginContext *pContext, const cell_t *params)
1466 static cell_t RemoveServerTag(IPluginContext *pContext, const cell_t *params)
1471 static cell_t AddCommandListener(IPluginContext *pContext, const cell_t *params)
1474 IPluginFunction *pFunction;
1476 pContext->LocalToString(params[2], &name);
1478 if (strcasecmp(name, "sm") == 0)
1480 g_Logger.LogError("Request to register \"sm\" command denied.");
1484 pFunction = pContext->GetFunctionById(params[1]);
1487 return pContext->ThrowNativeError("Invalid function id (%X)", params[1]);
1489 if (!g_ConsoleDetours.AddListener(pFunction, name[0] == '\0' ? NULL : name))
1490 return pContext->ThrowNativeError("This game does not support command listeners");
1495 static cell_t RemoveCommandListener(IPluginContext *pContext, const cell_t *params)
1498 IPluginFunction *pFunction;
1500 pContext->LocalToString(params[2], &name);
1501 pFunction = pContext->GetFunctionById(params[1]);
1503 return pContext->ThrowNativeError("Invalid function id (%X)", params[1]);
1505 if (!g_ConsoleDetours.RemoveListener(pFunction, name[0] == '\0' ? NULL : name))
1506 return pContext->ThrowNativeError("No matching callback was registered");
1511 REGISTER_NATIVES(consoleNatives)
1513 {"CreateConVar", sm_CreateConVar},
1514 {"FindConVar", sm_FindConVar},
1515 {"HookConVarChange", sm_HookConVarChange},
1516 {"UnhookConVarChange", sm_UnhookConVarChange},
1517 {"GetConVarBool", sm_GetConVarBool},
1518 {"SetConVarBool", sm_SetConVarNum},
1519 {"GetConVarInt", sm_GetConVarInt},
1520 {"SetConVarInt", sm_SetConVarNum},
1521 {"GetConVarFloat", sm_GetConVarFloat},
1522 {"SetConVarFloat", sm_SetConVarFloat},
1523 {"GetConVarString", sm_GetConVarString},
1524 {"SetConVarString", sm_SetConVarString},
1525 {"GetConVarFlags", sm_GetConVarFlags},
1526 {"SetConVarFlags", sm_SetConVarFlags},
1527 {"ResetConVar", sm_ResetConVar},
1528 {"GetConVarName", sm_GetConVarName},
1529 {"GetConVarBounds", sm_GetConVarBounds},
1530 {"SetConVarBounds", sm_SetConVarBounds},
1531 {"QueryClientConVar", sm_QueryClientConVar},
1532 {"GetConVarDefault", GetConVarDefault},
1533 {"RegServerCmd", sm_RegServerCmd},
1534 {"RegConsoleCmd", sm_RegConsoleCmd},
1535 {"GetCmdArgString", sm_GetCmdArgString},
1536 {"GetCmdArgs", sm_GetCmdArgs},
1537 {"GetCmdArg", sm_GetCmdArg},
1538 {"PrintToServer", sm_PrintToServer},
1539 {"PrintToConsole", sm_PrintToConsole},
1540 {"RegAdminCmd", sm_RegAdminCmd},
1541 {"ServerCommand", sm_ServerCommand},
1542 {"ServerCommandEx", sm_ServerCommandEx},
1543 {"InsertServerCommand", sm_InsertServerCommand},
1544 {"ServerExecute", sm_ServerExecute},
1545 {"ClientCommand", sm_ClientCommand},
1546 {"FakeClientCommand", FakeClientCommand},
1547 {"ReplyToCommand", ReplyToCommand},
1548 {"GetCmdReplySource", GetCmdReplyTarget},
1549 {"SetCmdReplySource", SetCmdReplyTarget},
1550 {"GetCommandIterator", GetCommandIterator},
1551 {"ReadCommandIterator", ReadCommandIterator},
1552 {"CheckCommandAccess", CheckCommandAccess},
1553 {"CheckAccess", CheckAccess},
1554 {"FakeClientCommandEx", FakeClientCommandEx},
1555 {"IsChatTrigger", IsChatTrigger},
1556 {"SetCommandFlags", SetCommandFlags},
1557 {"GetCommandFlags", GetCommandFlags},
1558 {"FindFirstConCommand", FindFirstConCommand},
1559 {"FindNextConCommand", FindNextConCommand},
1560 {"SendConVarValue", SendConVarValue},
1561 {"AddServerTag", AddServerTag},
1562 {"RemoveServerTag", RemoveServerTag},
1563 {"AddCommandListener", AddCommandListener},
1564 {"RemoveCommandListener", RemoveCommandListener},