1 #include <sourcehook.h>
2 #include "convar_smm.h"
4 #include <tier0/icommandline.h>
5 #include <tier1/utldict.h>
8 #include "../metamod_util.h"
9 #include "provider_ep1.h"
11 #include "metamod_console.h"
12 #include "vsp_listener.h"
15 typedef void (*CONPRINTF_FUNC)(const char *, ...);
23 DLL_IMPORT ICommandLine *CommandLine();
25 CONPRINTF_FUNC ExtractRemotePrinter();
26 bool CacheUserMessages();
27 void ClientCommand(edict_t *pEdict);
28 void _ServerCommand();
30 bool usermsgs_extracted = false;
31 CVector<UsrMsgInfo> usermsgs_list;
32 CONPRINTF_FUNC echo_msg_func = NULL;
34 ISmmAPI *metamod_api = NULL;
35 IVEngineServer *engine = NULL;
36 IServerGameClients *gameclients = NULL;
37 VSPListener g_VspListener;
38 BaseProvider g_Ep1Provider;
39 IMetamodSourceProvider *provider = &g_Ep1Provider;
41 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
43 void BaseProvider::ConsolePrint(const char *str)
45 if (echo_msg_func != NULL)
47 echo_msg_func("%s", str);
55 void BaseProvider::Notify_DLLInit_Pre(void *gamedll,
56 CreateInterfaceFn engineFactory,
57 CreateInterfaceFn serverFactory)
59 server = (IServerGameDLL *)gamedll;
60 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
63 Error("Could not find IVEngineServer! Metamod cannot load.");
66 icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
69 Error("Could not find ICvar! Metamod cannot load.");
73 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
76 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
79 echo_msg_func = ExtractRemotePrinter();
80 usermsgs_extracted = CacheUserMessages();
84 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
87 ConCommandBaseMgr::OneTimeInit(&g_SMConVarAccessor);
90 void BaseProvider::Notify_DLLShutdown_Pre()
92 g_SMConVarAccessor.MarkCommandsAsGameDLL();
93 g_SMConVarAccessor.UnregisterGameDLLCommands();
96 bool BaseProvider::IsRemotePrintingAvailable()
98 return (echo_msg_func != NULL);
101 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
103 engine->ClientPrintf(client, message);
106 void BaseProvider::ServerCommand(const char *cmd)
108 engine->ServerCommand(cmd);
111 const char *BaseProvider::GetConVarString(ConVar *convar)
113 return convar->GetString();
116 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
118 return pCommand->IsCommand();
122 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
124 return (build == SOURCE_ENGINE_ORIGINAL
125 || build == SOURCE_ENGINE_EPISODEONE);
128 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
130 if (key[0] == '-' || key[0] == '+')
132 return CommandLine()->ParmValue(key, defval);
137 if ((val = icvar->GetCommandLineValue(key)) == NULL)
146 int BaseProvider::TryServerGameDLL(const char *iface)
148 if (strncmp(iface, "ServerGameDLL", 13) != 0)
153 return atoi(&iface[13]);
156 bool BaseProvider::LogMessage(const char *buffer)
163 engine->LogPrint(buffer);
168 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
170 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
172 if (hook == ProvidedHook_LevelInit)
174 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
176 else if (hook == ProvidedHook_LevelShutdown)
178 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
180 else if (hook == ProvidedHook_GameInit)
182 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
184 else if (hook == ProvidedHook_DLLShutdown)
186 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
188 else if (hook == ProvidedHook_DLLInit)
190 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
195 return (mfi.thisptroffs >= 0);
198 void BaseProvider::DisplayError(const char *fmt, ...)
204 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
210 void BaseProvider::DisplayWarning(const char *fmt, ...)
216 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
222 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
224 return &g_SMConVarAccessor;
227 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
229 return g_SMConVarAccessor.Register(pCommand);
232 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
234 return g_SMConVarAccessor.Unregister(pCommand);
237 int BaseProvider::GetUserMessageCount()
239 if (!usermsgs_extracted)
244 return (int)usermsgs_list.size();
247 int BaseProvider::FindUserMessage(const char *name, int *size)
249 for (size_t i = 0; i < usermsgs_list.size(); i++)
251 if (usermsgs_list[i].name.compare(name) == 0)
255 *size = usermsgs_list[i].size;
264 const char *BaseProvider::GetUserMessage(int index, int *size)
266 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
273 *size = usermsgs_list[index].size;
276 return usermsgs_list[index].name.c_str();
279 const char *BaseProvider::GetGameDescription()
281 return server->GetGameDescription();
284 ConVar *BaseProvider::CreateConVar(const char *name,
290 if (flags & ConVarFlag_Notify)
292 newflags |= FCVAR_NOTIFY;
294 if (flags & ConVarFlag_Replicated)
296 newflags |= FCVAR_REPLICATED;
298 if (flags & ConVarFlag_SpOnly)
300 newflags |= FCVAR_SPONLY;
303 return new ConVar(name, defval, newflags, help);
306 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
308 g_VspListener.SetLoadable(true);
309 return &g_VspListener;
312 class GlobCommand : public IMetamodSourceCommandInfo
315 unsigned int GetArgCount()
317 return engine->Cmd_Argc() - 1;
320 const char *GetArg(unsigned int num)
322 return engine->Cmd_Argv(num);
325 const char *GetArgString()
327 return engine->Cmd_Args();
331 CON_COMMAND(meta, "Metamod:Source control commands")
337 void ClientCommand(edict_t *pEdict)
341 if (strcmp(cmd.GetArg(0), "meta") == 0)
343 Command_ClientMeta(pEdict, &cmd);
347 //////////////////////////////////////////////////////////////////////////
348 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
349 // (note: you can find the offset by looking for the text //
350 // "Echo text to console", you'll find the callback cmd pushed on the //
352 //////////////////////////////////////////////////////////////////////////
355 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
356 #define ENGINE486_OFFS 40
357 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
358 #define ENGINE686_OFFS 50
359 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
360 #define ENGINEAMD_OFFS 47
361 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
362 #define ENGINEW32_OFFS 38
363 #define IA32_CALL 0xE8
365 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
367 unsigned char *addr1 = (unsigned char *)_addr1;
368 unsigned char *addr2 = (unsigned char *)_addr2;
370 for (size_t i=0; i<len; i++)
376 if (addr1[i] != addr2[i])
385 //Thanks to fysh for the idea of extracting info from "echo" and for
386 // having the original offsets at hand!
387 CONPRINTF_FUNC ExtractRemotePrinter()
389 ConCommandBase *pBase = icvar->GetCommands();
390 unsigned char *ptr = NULL;
391 FnCommandCallback callback = NULL;
396 if (strcmp(pBase->GetName(), "echo") == 0)
398 callback = ((ConCommand *)pBase)->GetCallback();
399 ptr = (unsigned char *)callback;
401 if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
403 offs = ENGINE486_OFFS;
405 else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
407 offs = ENGINE686_OFFS;
409 else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
411 offs = ENGINEAMD_OFFS;
413 #elif defined OS_WIN32 // Only one Windows engine binary so far...
414 if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
416 offs = ENGINEW32_OFFS;
420 if (!offs || ptr[offs - 1] != IA32_CALL)
424 //get the relative offset
425 void *addr = *((void **)(ptr + offs));
426 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
427 return (CONPRINTF_FUNC)((unsigned long)addr + (unsigned long)(ptr + offs) + 4);
429 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
435 //////////////////////////////////////////////////////////////////////
436 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
437 // Signatures necessary in finding the pointer to the CUtlDict that //
438 // stores user message information. //
439 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
440 // message indices. This is our answer to it. Yuck! <:-( //
441 //////////////////////////////////////////////////////////////////////
443 /* General Windows sig */
444 #define MSGCLASS_SIGLEN 7
445 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
446 #define MSGCLASS_OFFS 2
448 /* Dystopia Wimdows hack */
449 #define MSGCLASS2_SIGLEN 16
450 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
451 #define MSGCLASS2_OFFS 11
453 /* Windows frame pointer sig */
454 #define MSGCLASS3_SIGLEN 18
455 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
456 #define MSGCLASS3_OFFS 13
457 #elif defined OS_LINUX
458 /* No frame pointer sig */
459 #define MSGCLASS_SIGLEN 14
460 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
461 #define MSGCLASS_OFFS 9
463 /* Frame pointer sig */
464 #define MSGCLASS2_SIGLEN 16
465 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
466 #define MSGCLASS2_OFFS 11
475 typedef CUtlDict<UserMessage *, int> UserMsgDict;
477 /* This is the ugliest function in all of SourceMM */
478 bool CacheUserMessages()
480 /* Get address of original GetUserMessageInfo() */
481 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
483 /* Oh dear, we have a relative jump on our hands
484 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
486 if (*vfunc == '\xE9')
488 /* Get address from displacement...
490 * Add 5 because it's relative to next instruction:
491 * Opcode <1 byte> + 32-bit displacement <4 bytes>
493 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
496 CUtlDict<UserMessage *, int> *dict = NULL;
498 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
500 /* Get address of CUserMessages instance */
501 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
503 /* Get address of CUserMessages::m_UserMessages */
504 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
506 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
509 /* If we get here, the code is possibly inlined like in Dystopia */
511 /* Get the address of the CUtlRBTree */
512 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
514 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
515 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
516 #elif defined OS_LINUX
517 /* Get address of CUserMessages instance */
518 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
520 /* Get address of CUserMessages::m_UserMessages */
521 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
525 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
527 /* Get address of CUserMessages instance */
528 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
530 /* Get address of CUserMessages::m_UserMessages */
531 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
537 int msg_count = dict->Count();
539 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
540 if (msg_count < 0 || msg_count > 255)
548 /* Cache messages in our CUtlDict */
549 for (int i = 0; i < msg_count; i++)
551 msg = dict->Element(i);
552 u_msg.name = msg->name;
553 u_msg.size = msg->size;
554 usermsgs_list.push_back(u_msg);