4 * ======================================================
6 * Copyright (C) 2004-2008 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.
30 #include "../metamod_oslink.h"
31 #include <sourcehook.h>
34 #include <tier0/icommandline.h>
35 #include <tier1/utldict.h>
36 #include <sh_vector.h>
37 #include <sh_string.h>
38 #include "../metamod_util.h"
39 #include "provider_ep2.h"
41 #include "metamod_console.h"
42 #include "vsp_listener.h"
43 #include <filesystem.h>
46 typedef void (*CONPRINTF_FUNC)(const char *, ...);
52 UsrMsgInfo(int s, const char *t) : size(s), name(t)
60 DLL_IMPORT ICommandLine *CommandLine();
62 bool CacheUserMessages();
63 void ClientCommand(edict_t *pEdict, const CCommand &args);
64 void LocalCommand_Meta(const CCommand &args);
65 void _ServerCommand();
67 bool usermsgs_extracted = false;
68 CVector<UsrMsgInfo> usermsgs_list;
70 ISmmAPI *metamod_api = NULL;
71 IVEngineServer *engine = NULL;
72 IServerGameClients *gameclients = NULL;
73 VSPListener g_VspListener;
74 BaseProvider g_Ep1Provider;
75 IMetamodSourceProvider *provider = &g_Ep1Provider;
76 List<ConCommandBase *> conbases_unreg;
77 IFileSystem *baseFs = NULL;
78 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
80 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
82 bool AssumeUserMessages()
89 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
91 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
98 void BaseProvider::ConsolePrint(const char *str)
103 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
104 CreateInterfaceFn serverFactory)
106 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
109 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
112 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
115 DisplayError("Could not find ICvar! Metamod cannot load.");
120 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
123 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
126 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
129 ::LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
133 RegisterConCommandBase(&meta_local_cmd);
134 conbases_unreg.push_back(&meta_local_cmd);
136 if ((usermsgs_extracted = CacheUserMessages()) == false)
138 usermsgs_extracted = AssumeUserMessages();
143 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
147 void BaseProvider::Notify_DLLShutdown_Pre()
149 List<ConCommandBase *>::iterator iter;
151 for (iter = conbases_unreg.begin();
152 iter != conbases_unreg.end();
155 UnregisterConCommandBase((*iter));
159 bool BaseProvider::IsRemotePrintingAvailable()
164 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
166 engine->ClientPrintf(client, message);
169 void BaseProvider::ServerCommand(const char *cmd)
171 engine->ServerCommand(cmd);
174 const char *BaseProvider::GetConVarString(ConVar *convar)
181 return convar->GetString();
184 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
186 convar->SetValue(str);
189 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
191 return pCommand->IsCommand();
195 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
197 return (build == SOURCE_ENGINE_ORIGINAL
198 || build == SOURCE_ENGINE_EPISODEONE);
201 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
203 if (key[0] == '-' || key[0] == '+')
205 return CommandLine_Tier0()->ParmValue(key, defval);
210 if ((val = icvar->GetCommandLineValue(key)) == NULL)
221 int BaseProvider::TryServerGameDLL(const char *iface)
223 if (strncmp(iface, "ServerGameDLL", 13) != 0)
228 return atoi(&iface[13]);
231 bool BaseProvider::LogMessage(const char *buffer)
238 engine->LogPrint(buffer);
243 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
245 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
247 if (hook == ProvidedHook_LevelInit)
249 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
251 else if (hook == ProvidedHook_LevelShutdown)
253 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
255 else if (hook == ProvidedHook_GameInit)
257 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
259 else if (hook == ProvidedHook_DLLShutdown)
261 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
263 else if (hook == ProvidedHook_DLLInit)
265 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
270 return (mfi.thisptroffs >= 0);
273 void BaseProvider::DisplayError(const char *fmt, ...)
279 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
285 void BaseProvider::DisplayWarning(const char *fmt, ...)
291 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
297 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
299 return &g_SMConVarAccessor;
302 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
304 return g_SMConVarAccessor.Register(pCommand);
307 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
309 return g_SMConVarAccessor.Unregister(pCommand);
312 int BaseProvider::GetUserMessageCount()
314 if (!usermsgs_extracted)
319 return (int)usermsgs_list.size();
322 int BaseProvider::FindUserMessage(const char *name, int *size)
324 for (size_t i = 0; i < usermsgs_list.size(); i++)
326 if (usermsgs_list[i].name.compare(name) == 0)
330 *size = usermsgs_list[i].size;
339 const char *BaseProvider::GetUserMessage(int index, int *size)
341 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
348 *size = usermsgs_list[index].size;
351 return usermsgs_list[index].name.c_str();
354 const char *BaseProvider::GetGameDescription()
356 return server->GetGameDescription();
359 int BaseProvider::DetermineSourceEngine(const char *game)
361 return SOURCE_ENGINE_ORANGEBOX;
364 ConVar *BaseProvider::CreateConVar(const char *name,
370 if (flags & ConVarFlag_Notify)
372 newflags |= FCVAR_NOTIFY;
374 if (flags & ConVarFlag_SpOnly)
376 newflags |= FCVAR_SPONLY;
379 ConVar *pVar = new ConVar(name, defval, newflags, help);
381 RegisterConCommandBase(pVar);
382 conbases_unreg.push_back(pVar);
387 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
394 g_VspListener.SetLoadable(true);
395 return &g_VspListener;
398 bool BaseProvider::IsAlternatelyLoaded()
400 return g_VspListener.IsRootLoadMethod();
403 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
411 const char *plugin_file, *p_alias;
413 pValues = new KeyValues("Metamod Plugin");
415 if (!pValues->LoadFromFile(baseFs, file))
417 pValues->deleteThis();
421 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
423 pValues->deleteThis();
427 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
429 UTIL_Format(alias, alias_len, "%s", p_alias);
433 UTIL_Format(alias, alias_len, "");
436 /* Attempt to find a file extension */
437 if (UTIL_GetExtension(plugin_file) == NULL)
439 g_pMetamod->PathFormat(path,
442 g_pMetamod->GetBaseDir(),
444 #if defined WIN32 || defined _WIN32
453 g_pMetamod->PathFormat(path,
456 g_pMetamod->GetBaseDir(),
460 pValues->deleteThis();
465 class GlobCommand : public IMetamodSourceCommandInfo
468 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
472 unsigned int GetArgCount()
474 return m_cmd->ArgC() - 1;
477 const char *GetArg(unsigned int num)
479 return m_cmd->Arg(num);
482 const char *GetArgString()
484 return m_cmd->ArgS();
487 const CCommand *m_cmd;
490 void LocalCommand_Meta(const CCommand &args)
492 GlobCommand cmd(&args);
496 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
498 GlobCommand cmd(&_cmd);
500 if (strcmp(cmd.GetArg(0), "meta") == 0)
502 Command_ClientMeta(pEdict, &cmd);
503 RETURN_META(MRES_SUPERCEDE);
506 RETURN_META(MRES_IGNORED);
509 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
511 unsigned char *addr1 = (unsigned char *)_addr1;
512 unsigned char *addr2 = (unsigned char *)_addr2;
514 for (size_t i=0; i<len; i++)
520 if (addr1[i] != addr2[i])
529 //////////////////////////////////////////////////////////////////////
530 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
531 // Signatures necessary in finding the pointer to the CUtlDict that //
532 // stores user message information. //
533 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
534 // message indices. This is our answer to it. Yuck! <:-( //
535 //////////////////////////////////////////////////////////////////////
537 /* General Windows sig */
538 #define MSGCLASS_SIGLEN 7
539 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
540 #define MSGCLASS_OFFS 2
542 /* Dystopia Wimdows hack */
543 #define MSGCLASS2_SIGLEN 16
544 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
545 #define MSGCLASS2_OFFS 11
547 /* Windows frame pointer sig */
548 #define MSGCLASS3_SIGLEN 18
549 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
550 #define MSGCLASS3_OFFS 13
551 #elif defined OS_LINUX
552 /* No frame pointer sig */
553 #define MSGCLASS_SIGLEN 14
554 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
555 #define MSGCLASS_OFFS 9
557 /* Frame pointer sig */
558 #define MSGCLASS2_SIGLEN 16
559 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
560 #define MSGCLASS2_OFFS 11
569 typedef CUtlDict<UserMessage *, int> UserMsgDict;
571 /* This is the ugliest function in all of SourceMM */
572 bool CacheUserMessages()
574 /* Get address of original GetUserMessageInfo() */
575 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
577 /* Oh dear, we have a relative jump on our hands
578 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
580 if (*vfunc == '\xE9')
582 /* Get address from displacement...
584 * Add 5 because it's relative to next instruction:
585 * Opcode <1 byte> + 32-bit displacement <4 bytes>
587 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
590 CUtlDict<UserMessage *, int> *dict = NULL;
592 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
594 /* Get address of CUserMessages instance */
595 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
597 /* Get address of CUserMessages::m_UserMessages */
598 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
600 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
603 /* If we get here, the code is possibly inlined like in Dystopia */
605 /* Get the address of the CUtlRBTree */
606 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
608 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
609 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
610 #elif defined OS_LINUX
611 /* Get address of CUserMessages instance */
612 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
614 /* Get address of CUserMessages::m_UserMessages */
615 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
619 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
621 /* Get address of CUserMessages instance */
622 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
624 /* Get address of CUserMessages::m_UserMessages */
625 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
629 #if !defined OS_WIN32
633 if (GetFileOfAddress(vfunc, path, sizeof(path)))
635 void *handle = dlopen(path, RTLD_NOW);
638 void *addr = dlsym(handle, "usermessages");
643 dict = (UserMsgDict *)*(void **)addr;
652 int msg_count = dict->Count();
654 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
655 if (msg_count < 0 || msg_count > 255)
663 /* Cache messages in our CUtlDict */
664 for (int i = 0; i < msg_count; i++)
666 msg = dict->Element(i);
667 u_msg.name = msg->name;
668 u_msg.size = msg->size;
669 usermsgs_list.push_back(u_msg);