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>
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_ep2.h"
40 #include "metamod_console.h"
41 #include "vsp_listener.h"
42 #include <filesystem.h>
45 typedef void (*CONPRINTF_FUNC)(const char *, ...);
53 DLL_IMPORT ICommandLine *CommandLine();
55 bool CacheUserMessages();
56 void ClientCommand(edict_t *pEdict, const CCommand &args);
57 void LocalCommand_Meta(const CCommand &args);
58 void _ServerCommand();
60 bool usermsgs_extracted = false;
61 CVector<UsrMsgInfo> usermsgs_list;
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;
69 List<ConCommandBase *> conbases_unreg;
70 IFileSystem *baseFs = NULL;
71 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
73 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
75 void BaseProvider::ConsolePrint(const char *str)
80 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
81 CreateInterfaceFn serverFactory)
83 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
86 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
89 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
92 DisplayError("Could not find ICvar! Metamod cannot load.");
97 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
100 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
103 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
106 ::LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
110 RegisterConCommandBase(&meta_local_cmd);
111 conbases_unreg.push_back(&meta_local_cmd);
113 usermsgs_extracted = CacheUserMessages();
117 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
121 void BaseProvider::Notify_DLLShutdown_Pre()
123 List<ConCommandBase *>::iterator iter;
125 for (iter = conbases_unreg.begin();
126 iter != conbases_unreg.end();
129 UnregisterConCommandBase((*iter));
133 bool BaseProvider::IsRemotePrintingAvailable()
138 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
140 engine->ClientPrintf(client, message);
143 void BaseProvider::ServerCommand(const char *cmd)
145 engine->ServerCommand(cmd);
148 const char *BaseProvider::GetConVarString(ConVar *convar)
155 return convar->GetString();
158 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
160 convar->SetValue(str);
163 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
165 return pCommand->IsCommand();
169 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
171 return (build == SOURCE_ENGINE_ORIGINAL
172 || build == SOURCE_ENGINE_EPISODEONE);
175 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
177 if (key[0] == '-' || key[0] == '+')
179 return CommandLine_Tier0()->ParmValue(key, defval);
184 if ((val = icvar->GetCommandLineValue(key)) == NULL)
195 int BaseProvider::TryServerGameDLL(const char *iface)
197 if (strncmp(iface, "ServerGameDLL", 13) != 0)
202 return atoi(&iface[13]);
205 bool BaseProvider::LogMessage(const char *buffer)
212 engine->LogPrint(buffer);
217 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
219 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
221 if (hook == ProvidedHook_LevelInit)
223 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
225 else if (hook == ProvidedHook_LevelShutdown)
227 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
229 else if (hook == ProvidedHook_GameInit)
231 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
233 else if (hook == ProvidedHook_DLLShutdown)
235 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
237 else if (hook == ProvidedHook_DLLInit)
239 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
244 return (mfi.thisptroffs >= 0);
247 void BaseProvider::DisplayError(const char *fmt, ...)
253 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
259 void BaseProvider::DisplayWarning(const char *fmt, ...)
265 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
271 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
273 return &g_SMConVarAccessor;
276 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
278 return g_SMConVarAccessor.Register(pCommand);
281 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
283 return g_SMConVarAccessor.Unregister(pCommand);
286 int BaseProvider::GetUserMessageCount()
288 if (!usermsgs_extracted)
293 return (int)usermsgs_list.size();
296 int BaseProvider::FindUserMessage(const char *name, int *size)
298 for (size_t i = 0; i < usermsgs_list.size(); i++)
300 if (usermsgs_list[i].name.compare(name) == 0)
304 *size = usermsgs_list[i].size;
313 const char *BaseProvider::GetUserMessage(int index, int *size)
315 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
322 *size = usermsgs_list[index].size;
325 return usermsgs_list[index].name.c_str();
328 const char *BaseProvider::GetGameDescription()
330 return server->GetGameDescription();
333 int BaseProvider::DetermineSourceEngine(const char *game)
335 return SOURCE_ENGINE_ORANGEBOX;
338 ConVar *BaseProvider::CreateConVar(const char *name,
344 if (flags & ConVarFlag_Notify)
346 newflags |= FCVAR_NOTIFY;
348 if (flags & ConVarFlag_Replicated)
350 newflags |= FCVAR_REPLICATED;
352 if (flags & ConVarFlag_SpOnly)
354 newflags |= FCVAR_SPONLY;
357 ConVar *pVar = new ConVar(name, defval, newflags, help);
359 RegisterConCommandBase(pVar);
360 conbases_unreg.push_back(pVar);
365 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
367 g_VspListener.SetLoadable(true);
368 return &g_VspListener;
371 bool BaseProvider::IsAlternatelyLoaded()
373 return g_VspListener.IsRootLoadMethod();
376 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
384 const char *plugin_file, *p_alias;
386 pValues = new KeyValues("Metamod Plugin");
388 if (!pValues->LoadFromFile(baseFs, file))
390 pValues->deleteThis();
394 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
396 pValues->deleteThis();
400 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
402 UTIL_Format(alias, alias_len, "%s", p_alias);
406 UTIL_Format(alias, alias_len, "");
409 /* Attempt to find a file extension */
410 if (UTIL_GetExtension(plugin_file) == NULL)
412 g_pMetamod->PathFormat(path,
415 g_pMetamod->GetBaseDir(),
417 #if defined WIN32 || defined _WIN32
426 g_pMetamod->PathFormat(path,
429 g_pMetamod->GetBaseDir(),
433 pValues->deleteThis();
438 class GlobCommand : public IMetamodSourceCommandInfo
441 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
445 unsigned int GetArgCount()
447 return m_cmd->ArgC() - 1;
450 const char *GetArg(unsigned int num)
452 return m_cmd->Arg(num);
455 const char *GetArgString()
457 return m_cmd->ArgS();
460 const CCommand *m_cmd;
463 void LocalCommand_Meta(const CCommand &args)
465 GlobCommand cmd(&args);
469 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
471 GlobCommand cmd(&_cmd);
473 if (strcmp(cmd.GetArg(0), "meta") == 0)
475 Command_ClientMeta(pEdict, &cmd);
476 RETURN_META(MRES_SUPERCEDE);
479 RETURN_META(MRES_IGNORED);
482 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
484 unsigned char *addr1 = (unsigned char *)_addr1;
485 unsigned char *addr2 = (unsigned char *)_addr2;
487 for (size_t i=0; i<len; i++)
493 if (addr1[i] != addr2[i])
502 //////////////////////////////////////////////////////////////////////
503 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
504 // Signatures necessary in finding the pointer to the CUtlDict that //
505 // stores user message information. //
506 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
507 // message indices. This is our answer to it. Yuck! <:-( //
508 //////////////////////////////////////////////////////////////////////
510 /* General Windows sig */
511 #define MSGCLASS_SIGLEN 7
512 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
513 #define MSGCLASS_OFFS 2
515 /* Dystopia Wimdows hack */
516 #define MSGCLASS2_SIGLEN 16
517 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
518 #define MSGCLASS2_OFFS 11
520 /* Windows frame pointer sig */
521 #define MSGCLASS3_SIGLEN 18
522 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
523 #define MSGCLASS3_OFFS 13
524 #elif defined OS_LINUX
525 /* No frame pointer sig */
526 #define MSGCLASS_SIGLEN 14
527 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
528 #define MSGCLASS_OFFS 9
530 /* Frame pointer sig */
531 #define MSGCLASS2_SIGLEN 16
532 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
533 #define MSGCLASS2_OFFS 11
542 typedef CUtlDict<UserMessage *, int> UserMsgDict;
544 /* This is the ugliest function in all of SourceMM */
545 bool CacheUserMessages()
547 /* Get address of original GetUserMessageInfo() */
548 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
550 /* Oh dear, we have a relative jump on our hands
551 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
553 if (*vfunc == '\xE9')
555 /* Get address from displacement...
557 * Add 5 because it's relative to next instruction:
558 * Opcode <1 byte> + 32-bit displacement <4 bytes>
560 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
563 CUtlDict<UserMessage *, int> *dict = NULL;
565 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
567 /* Get address of CUserMessages instance */
568 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
570 /* Get address of CUserMessages::m_UserMessages */
571 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
573 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
576 /* If we get here, the code is possibly inlined like in Dystopia */
578 /* Get the address of the CUtlRBTree */
579 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
581 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
582 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
583 #elif defined OS_LINUX
584 /* Get address of CUserMessages instance */
585 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
587 /* Get address of CUserMessages::m_UserMessages */
588 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
592 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
594 /* Get address of CUserMessages instance */
595 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
597 /* Get address of CUserMessages::m_UserMessages */
598 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
602 #if !defined OS_WIN32
606 if (GetFileOfAddress(vfunc, path, sizeof(path)))
608 void *handle = dlopen(path, RTLD_NOW);
611 void *addr = dlsym(handle, "usermessages");
612 dict = (UserMsgDict *)*(void **)addr;
621 int msg_count = dict->Count();
623 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
624 if (msg_count < 0 || msg_count > 255)
632 /* Cache messages in our CUtlDict */
633 for (int i = 0; i < msg_count; i++)
635 msg = dict->Element(i);
636 u_msg.name = msg->name;
637 u_msg.size = msg->size;
638 usermsgs_list.push_back(u_msg);