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_Replicated)
336 newflags |= FCVAR_REPLICATED;
338 if (flags & ConVarFlag_SpOnly)
340 newflags |= FCVAR_SPONLY;
343 return new ConVar(name, defval, newflags, help);
346 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
348 g_VspListener.SetLoadable(true);
349 return &g_VspListener;
352 bool BaseProvider::IsAlternatelyLoaded(/* =0 */)
357 class GlobCommand : public IMetamodSourceCommandInfo
360 unsigned int GetArgCount()
362 return engine->Cmd_Argc() - 1;
365 const char *GetArg(unsigned int num)
367 return engine->Cmd_Argv(num);
370 const char *GetArgString()
372 return engine->Cmd_Args();
376 CON_COMMAND(meta, "Metamod:Source control commands")
382 void ClientCommand(edict_t *pEdict)
386 if (strcmp(cmd.GetArg(0), "meta") == 0)
388 Command_ClientMeta(pEdict, &cmd);
392 //////////////////////////////////////////////////////////////////////////
393 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
394 // (note: you can find the offset by looking for the text //
395 // "Echo text to console", you'll find the callback cmd pushed on the //
397 //////////////////////////////////////////////////////////////////////////
400 #define ENGINE486_SIG "\x55\x89\xE5\x53\x83\xEC\x14\xBB"
401 #define ENGINE486_OFFS 40
402 #define ENGINE686_SIG "\x53\x83\xEC\x08\xBB\x01\x00\x00"
403 #define ENGINE686_OFFS 50
404 #define ENGINEAMD_SIG "\x53\x51\xBB\x01\x00\x00\x00\x51"
405 #define ENGINEAMD_OFFS 47
406 #define ENGINEW32_SIG "\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
407 #define ENGINEW32_OFFS 38
408 #define IA32_CALL 0xE8
410 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
412 unsigned char *addr1 = (unsigned char *)_addr1;
413 unsigned char *addr2 = (unsigned char *)_addr2;
415 for (size_t i=0; i<len; i++)
421 if (addr1[i] != addr2[i])
430 //Thanks to fysh for the idea of extracting info from "echo" and for
431 // having the original offsets at hand!
432 CONPRINTF_FUNC ExtractRemotePrinter()
434 ConCommandBase *pBase = icvar->GetCommands();
435 unsigned char *ptr = NULL;
436 FnCommandCallback callback = NULL;
441 if (strcmp(pBase->GetName(), "echo") == 0)
443 callback = ((ConCommand *)pBase)->GetCallback();
444 ptr = (unsigned char *)callback;
446 if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
448 offs = ENGINE486_OFFS;
450 else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
452 offs = ENGINE686_OFFS;
454 else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
456 offs = ENGINEAMD_OFFS;
458 #elif defined OS_WIN32 // Only one Windows engine binary so far...
459 if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
461 offs = ENGINEW32_OFFS;
465 if (!offs || ptr[offs - 1] != IA32_CALL)
469 //get the relative offset
470 void *addr = *((void **)(ptr + offs));
471 //add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
472 return (CONPRINTF_FUNC)((unsigned long)addr + (unsigned long)(ptr + offs) + 4);
474 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
480 //////////////////////////////////////////////////////////////////////
481 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
482 // Signatures necessary in finding the pointer to the CUtlDict that //
483 // stores user message information. //
484 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
485 // message indices. This is our answer to it. Yuck! <:-( //
486 //////////////////////////////////////////////////////////////////////
488 /* General Windows sig */
489 #define MSGCLASS_SIGLEN 7
490 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
491 #define MSGCLASS_OFFS 2
493 /* Dystopia Wimdows hack */
494 #define MSGCLASS2_SIGLEN 16
495 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
496 #define MSGCLASS2_OFFS 11
498 /* Windows frame pointer sig */
499 #define MSGCLASS3_SIGLEN 18
500 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
501 #define MSGCLASS3_OFFS 13
502 #elif defined OS_LINUX
503 /* No frame pointer sig */
504 #define MSGCLASS_SIGLEN 14
505 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
506 #define MSGCLASS_OFFS 9
508 /* Frame pointer sig */
509 #define MSGCLASS2_SIGLEN 16
510 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
511 #define MSGCLASS2_OFFS 11
520 typedef CUtlDict<UserMessage *, int> UserMsgDict;
522 /* This is the ugliest function in all of SourceMM */
523 bool CacheUserMessages()
525 /* Get address of original GetUserMessageInfo() */
526 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
528 /* Oh dear, we have a relative jump on our hands
529 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
531 if (*vfunc == '\xE9')
533 /* Get address from displacement...
535 * Add 5 because it's relative to next instruction:
536 * Opcode <1 byte> + 32-bit displacement <4 bytes>
538 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
541 CUtlDict<UserMessage *, int> *dict = NULL;
543 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
545 /* Get address of CUserMessages instance */
546 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
548 /* Get address of CUserMessages::m_UserMessages */
549 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
551 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
554 /* If we get here, the code is possibly inlined like in Dystopia */
556 /* Get the address of the CUtlRBTree */
557 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
559 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
560 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
561 #elif defined OS_LINUX
562 /* Get address of CUserMessages instance */
563 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
565 /* Get address of CUserMessages::m_UserMessages */
566 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
570 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
572 /* Get address of CUserMessages instance */
573 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
575 /* Get address of CUserMessages::m_UserMessages */
576 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
582 int msg_count = dict->Count();
584 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
585 if (msg_count < 0 || msg_count > 255)
593 /* Cache messages in our CUtlDict */
594 for (int i = 0; i < msg_count; i++)
596 msg = dict->Element(i);
597 u_msg.name = msg->name;
598 u_msg.size = msg->size;
599 usermsgs_list.push_back(u_msg);