4 * ======================================================
6 * Copyright (C) 2004-2007 AlliedModders LLC and authors.
8 * ======================================================
10 * This software is provided 'as-is', without any express or implied warranty.
11 * In no event will the authors be held liable for any damages arising from
12 * the use of this software.
14 * Permission is granted to anyone to use this software for any purpose,
15 * including commercial applications, and to alter it and redistribute it
16 * freely, subject to the following restrictions:
18 * 1. The origin of this software must not be misrepresented; you must not
19 * claim that you wrote the original software. If you use this software in a
20 * product, an acknowledgment in the product documentation would be
21 * appreciated but is not required.
22 * 2. Altered source versions must be plainly marked as such, and must not be
23 * misrepresented as being the original software.
24 * 3. This notice may not be removed or altered from any source distribution.
29 #include "../metamod_oslink.h"
30 #include <sourcehook.h>
31 #include "convar_smm.h"
33 #include <tier0/icommandline.h>
34 #include <tier1/utldict.h>
35 #include <sh_vector.h>
36 #include <sh_string.h>
37 #include "../metamod_util.h"
38 #include "provider_ep1.h"
40 #include "metamod_console.h"
41 #include "vsp_listener.h"
44 typedef void (*CONPRINTF_FUNC)(const char *, ...);
52 DLL_IMPORT ICommandLine *CommandLine();
54 CONPRINTF_FUNC ExtractRemotePrinter();
55 bool CacheUserMessages();
56 void ClientCommand(edict_t *pEdict);
57 void _ServerCommand();
59 bool usermsgs_extracted = false;
60 CVector<UsrMsgInfo> usermsgs_list;
61 CONPRINTF_FUNC echo_msg_func = NULL;
63 ISmmAPI *metamod_api = NULL;
64 IVEngineServer *engine = NULL;
65 IServerGameClients *gameclients = NULL;
66 VSPListener g_VspListener;
67 BaseProvider g_Ep1Provider;
68 IMetamodSourceProvider *provider = &g_Ep1Provider;
70 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
72 void BaseProvider::ConsolePrint(const char *str)
74 if (echo_msg_func != NULL)
76 echo_msg_func("%s", str);
84 void BaseProvider::Notify_DLLInit_Pre(
85 CreateInterfaceFn engineFactory,
86 CreateInterfaceFn serverFactory)
88 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
91 Error("Could not find IVEngineServer! Metamod cannot load.");
94 icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
97 Error("Could not find ICvar! Metamod cannot load.");
101 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
104 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
107 echo_msg_func = ExtractRemotePrinter();
108 usermsgs_extracted = CacheUserMessages();
112 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
115 ConCommandBaseMgr::OneTimeInit(&g_SMConVarAccessor);
118 void BaseProvider::Notify_DLLShutdown_Pre()
120 g_SMConVarAccessor.MarkCommandsAsGameDLL();
121 g_SMConVarAccessor.UnregisterGameDLLCommands();
124 bool BaseProvider::IsRemotePrintingAvailable()
126 return (echo_msg_func != NULL);
129 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
131 engine->ClientPrintf(client, message);
134 void BaseProvider::ServerCommand(const char *cmd)
136 engine->ServerCommand(cmd);
139 const char *BaseProvider::GetConVarString(ConVar *convar)
141 return convar->GetString();
144 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
146 return pCommand->IsCommand();
150 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
152 return (build == SOURCE_ENGINE_ORIGINAL
153 || build == SOURCE_ENGINE_EPISODEONE);
156 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
158 if (key[0] == '-' || key[0] == '+')
160 return CommandLine()->ParmValue(key, defval);
165 if ((val = icvar->GetCommandLineValue(key)) == NULL)
174 int BaseProvider::TryServerGameDLL(const char *iface)
176 if (strncmp(iface, "ServerGameDLL", 13) != 0)
181 return atoi(&iface[13]);
184 bool BaseProvider::LogMessage(const char *buffer)
191 engine->LogPrint(buffer);
196 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
198 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
200 if (hook == ProvidedHook_LevelInit)
202 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
204 else if (hook == ProvidedHook_LevelShutdown)
206 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
208 else if (hook == ProvidedHook_GameInit)
210 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
212 else if (hook == ProvidedHook_DLLShutdown)
214 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
216 else if (hook == ProvidedHook_DLLInit)
218 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
223 return (mfi.thisptroffs >= 0);
226 void BaseProvider::DisplayError(const char *fmt, ...)
232 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
238 void BaseProvider::DisplayWarning(const char *fmt, ...)
244 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
250 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
252 return &g_SMConVarAccessor;
255 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
257 return g_SMConVarAccessor.Register(pCommand);
260 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
262 return g_SMConVarAccessor.Unregister(pCommand);
265 int BaseProvider::GetUserMessageCount()
267 if (!usermsgs_extracted)
272 return (int)usermsgs_list.size();
275 int BaseProvider::FindUserMessage(const char *name, int *size)
277 for (size_t i = 0; i < usermsgs_list.size(); i++)
279 if (usermsgs_list[i].name.compare(name) == 0)
283 *size = usermsgs_list[i].size;
292 const char *BaseProvider::GetUserMessage(int index, int *size)
294 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
301 *size = usermsgs_list[index].size;
304 return usermsgs_list[index].name.c_str();
307 const char *BaseProvider::GetGameDescription()
309 return server->GetGameDescription();
312 int BaseProvider::DetermineSourceEngine(const char *game)
314 if (strcmp(game, "ship") == 0)
316 return SOURCE_ENGINE_ORIGINAL;
320 return SOURCE_ENGINE_EPISODEONE;
324 ConVar *BaseProvider::CreateConVar(const char *name,
330 if (flags & ConVarFlag_Notify)
332 newflags |= FCVAR_NOTIFY;
334 if (flags & ConVarFlag_SpOnly)
336 newflags |= FCVAR_SPONLY;
339 return new ConVar(name, defval, newflags, help);
342 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
344 g_VspListener.SetLoadable(true);
345 return &g_VspListener;
348 bool BaseProvider::IsAlternatelyLoaded(/* =0 */)
353 class GlobCommand : public IMetamodSourceCommandInfo
356 unsigned int GetArgCount()
358 return engine->Cmd_Argc() - 1;
361 const char *GetArg(unsigned int num)
363 return engine->Cmd_Argv(num);
366 const char *GetArgString()
368 return engine->Cmd_Args();
372 CON_COMMAND(meta, "Metamod:Source control commands")
378 void ClientCommand(edict_t *pEdict)
382 if (strcmp(cmd.GetArg(0), "meta") == 0)
384 Command_ClientMeta(pEdict, &cmd);
388 //////////////////////////////////////////////////////////////////////////
389 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
390 // (note: you can find the offset by looking for the text //
391 // "Echo text to console", you'll find the callback cmd pushed on the //
393 //////////////////////////////////////////////////////////////////////////
396 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
397 #define ENGINE486_OFFS 40
398 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
399 #define ENGINE686_OFFS 50
400 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
401 #define ENGINEAMD_OFFS 47
402 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
403 #define ENGINEW32_OFFS 38
404 #define IA32_CALL 0xE8
406 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
408 unsigned char *addr1 = (unsigned char *)_addr1;
409 unsigned char *addr2 = (unsigned char *)_addr2;
411 for (size_t i=0; i<len; i++)
417 if (addr1[i] != addr2[i])
426 //Thanks to fysh for the idea of extracting info from "echo" and for
427 // having the original offsets at hand!
428 CONPRINTF_FUNC ExtractRemotePrinter()
430 ConCommandBase *pBase = icvar->GetCommands();
431 unsigned char *ptr = NULL;
432 FnCommandCallback callback = NULL;
437 if (strcmp(pBase->GetName(), "echo") == 0)
439 callback = ((ConCommand *)pBase)->GetCallback();
440 ptr = (unsigned char *)callback;
442 if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
444 offs = ENGINE486_OFFS;
446 else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
448 offs = ENGINE686_OFFS;
450 else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
452 offs = ENGINEAMD_OFFS;
454 #elif defined OS_WIN32 // Only one Windows engine binary so far...
455 if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
457 offs = ENGINEW32_OFFS;
461 if (!offs || ptr[offs - 1] != IA32_CALL)
465 //get the relative offset
466 void *addr = *((void **)(ptr + offs));
467 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
468 return (CONPRINTF_FUNC)((unsigned long)addr + (unsigned long)(ptr + offs) + 4);
470 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
476 //////////////////////////////////////////////////////////////////////
477 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
478 // Signatures necessary in finding the pointer to the CUtlDict that //
479 // stores user message information. //
480 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
481 // message indices. This is our answer to it. Yuck! <:-( //
482 //////////////////////////////////////////////////////////////////////
484 /* General Windows sig */
485 #define MSGCLASS_SIGLEN 7
486 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
487 #define MSGCLASS_OFFS 2
489 /* Dystopia Wimdows hack */
490 #define MSGCLASS2_SIGLEN 16
491 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
492 #define MSGCLASS2_OFFS 11
494 /* Windows frame pointer sig */
495 #define MSGCLASS3_SIGLEN 18
496 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
497 #define MSGCLASS3_OFFS 13
498 #elif defined OS_LINUX
499 /* No frame pointer sig */
500 #define MSGCLASS_SIGLEN 14
501 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
502 #define MSGCLASS_OFFS 9
504 /* Frame pointer sig */
505 #define MSGCLASS2_SIGLEN 16
506 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
507 #define MSGCLASS2_OFFS 11
516 typedef CUtlDict<UserMessage *, int> UserMsgDict;
518 /* This is the ugliest function in all of SourceMM */
519 bool CacheUserMessages()
521 /* Get address of original GetUserMessageInfo() */
522 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
524 /* Oh dear, we have a relative jump on our hands
525 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
527 if (*vfunc == '\xE9')
529 /* Get address from displacement...
531 * Add 5 because it's relative to next instruction:
532 * Opcode <1 byte> + 32-bit displacement <4 bytes>
534 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
537 CUtlDict<UserMessage *, int> *dict = NULL;
539 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
541 /* Get address of CUserMessages instance */
542 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
544 /* Get address of CUserMessages::m_UserMessages */
545 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
547 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
550 /* If we get here, the code is possibly inlined like in Dystopia */
552 /* Get the address of the CUtlRBTree */
553 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
555 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
556 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
557 #elif defined OS_LINUX
558 /* Get address of CUserMessages instance */
559 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
561 /* Get address of CUserMessages::m_UserMessages */
562 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
566 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
568 /* Get address of CUserMessages instance */
569 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
571 /* Get address of CUserMessages::m_UserMessages */
572 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
578 int msg_count = dict->Count();
580 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
581 if (msg_count < 0 || msg_count > 255)
589 /* Cache messages in our CUtlDict */
590 for (int i = 0; i < msg_count; i++)
592 msg = dict->Element(i);
593 u_msg.name = msg->name;
594 u_msg.size = msg->size;
595 usermsgs_list.push_back(u_msg);