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>
47 typedef void (*CONPRINTF_FUNC)(const char *, ...);
53 UsrMsgInfo(int s, const char *t) : size(s), name(t)
61 DLL_IMPORT ICommandLine *CommandLine();
63 bool CacheUserMessages();
64 void ClientCommand(edict_t *pEdict, const CCommand &args);
65 void LocalCommand_Meta(const CCommand &args);
66 void _ServerCommand();
68 static bool usermsgs_extracted = false;
69 static CVector<UsrMsgInfo> usermsgs_list;
70 static VSPListener g_VspListener;
71 static BaseProvider g_Ep1Provider;
72 static List<ConCommandBase *> conbases_unreg;
75 IFileSystem *baseFs = NULL;
76 IServerGameDLL *server = NULL;
77 IVEngineServer *engine = NULL;
78 IServerGameClients *gameclients = NULL;
79 IMetamodSourceProvider *provider = &g_Ep1Provider;
80 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
82 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
84 bool AssumeUserMessages()
91 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
93 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
100 void BaseProvider::ConsolePrint(const char *str)
105 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
106 CreateInterfaceFn serverFactory)
108 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
111 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
114 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
117 DisplayError("Could not find ICvar! Metamod cannot load.");
122 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
125 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
128 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
131 mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
135 RegisterConCommandBase(&meta_local_cmd);
136 conbases_unreg.push_back(&meta_local_cmd);
138 if ((usermsgs_extracted = CacheUserMessages()) == false)
140 usermsgs_extracted = AssumeUserMessages();
145 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
149 void BaseProvider::Notify_DLLShutdown_Pre()
151 List<ConCommandBase *>::iterator iter;
153 for (iter = conbases_unreg.begin();
154 iter != conbases_unreg.end();
157 UnregisterConCommandBase((*iter));
161 bool BaseProvider::IsRemotePrintingAvailable()
166 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
168 engine->ClientPrintf(client, message);
171 void BaseProvider::ServerCommand(const char *cmd)
173 engine->ServerCommand(cmd);
176 const char *BaseProvider::GetConVarString(ConVar *convar)
183 return convar->GetString();
186 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
188 convar->SetValue(str);
191 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
193 return pCommand->IsCommand();
197 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
199 return (build == SOURCE_ENGINE_ORIGINAL
200 || build == SOURCE_ENGINE_EPISODEONE);
203 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
205 if (key[0] == '-' || key[0] == '+')
207 return CommandLine_Tier0()->ParmValue(key, defval);
212 if ((val = icvar->GetCommandLineValue(key)) == NULL)
223 int BaseProvider::TryServerGameDLL(const char *iface)
225 if (strncmp(iface, "ServerGameDLL", 13) != 0)
230 return atoi(&iface[13]);
233 bool BaseProvider::LogMessage(const char *buffer)
240 engine->LogPrint(buffer);
245 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
247 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
249 if (hook == ProvidedHook_LevelInit)
251 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
253 else if (hook == ProvidedHook_LevelShutdown)
255 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
257 else if (hook == ProvidedHook_GameInit)
259 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
261 else if (hook == ProvidedHook_DLLShutdown)
263 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
265 else if (hook == ProvidedHook_DLLInit)
267 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
272 return (mfi.thisptroffs >= 0);
275 void BaseProvider::DisplayError(const char *fmt, ...)
281 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
287 void BaseProvider::DisplayWarning(const char *fmt, ...)
293 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
299 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
301 return &g_SMConVarAccessor;
304 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
306 return g_SMConVarAccessor.Register(pCommand);
309 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
311 return g_SMConVarAccessor.Unregister(pCommand);
314 int BaseProvider::GetUserMessageCount()
316 if (!usermsgs_extracted)
321 return (int)usermsgs_list.size();
324 int BaseProvider::FindUserMessage(const char *name, int *size)
326 for (size_t i = 0; i < usermsgs_list.size(); i++)
328 if (usermsgs_list[i].name.compare(name) == 0)
332 *size = usermsgs_list[i].size;
341 const char *BaseProvider::GetUserMessage(int index, int *size)
343 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
350 *size = usermsgs_list[index].size;
353 return usermsgs_list[index].name.c_str();
356 const char *BaseProvider::GetGameDescription()
358 return server->GetGameDescription();
361 int BaseProvider::DetermineSourceEngine(const char *game)
363 #if SOURCE_ENGINE == SE_LEFT4DEAD
364 return SOURCE_ENGINE_LEFT4DEAD;
366 return SOURCE_ENGINE_ORANGEBOX;
370 ConVar *BaseProvider::CreateConVar(const char *name,
376 if (flags & ConVarFlag_Notify)
378 newflags |= FCVAR_NOTIFY;
380 if (flags & ConVarFlag_SpOnly)
382 newflags |= FCVAR_SPONLY;
385 ConVar *pVar = new ConVar(name, defval, newflags, help);
387 RegisterConCommandBase(pVar);
388 conbases_unreg.push_back(pVar);
393 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
400 g_VspListener.SetLoadable(true);
401 return &g_VspListener;
404 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
412 const char *plugin_file, *p_alias;
414 pValues = new KeyValues("Metamod Plugin");
416 if (!pValues->LoadFromFile(baseFs, file))
418 pValues->deleteThis();
422 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
424 pValues->deleteThis();
428 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
430 UTIL_Format(alias, alias_len, "%s", p_alias);
434 UTIL_Format(alias, alias_len, "");
437 /* Attempt to find a file extension */
438 if (UTIL_GetExtension(plugin_file) == NULL)
440 g_pMetamod->PathFormat(path,
443 g_pMetamod->GetBaseDir(),
445 #if defined WIN32 || defined _WIN32
454 g_pMetamod->PathFormat(path,
457 g_pMetamod->GetBaseDir(),
461 pValues->deleteThis();
466 class GlobCommand : public IMetamodSourceCommandInfo
469 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
473 unsigned int GetArgCount()
475 return m_cmd->ArgC() - 1;
478 const char *GetArg(unsigned int num)
480 return m_cmd->Arg(num);
483 const char *GetArgString()
485 return m_cmd->ArgS();
488 const CCommand *m_cmd;
491 void LocalCommand_Meta(const CCommand &args)
493 GlobCommand cmd(&args);
497 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
499 GlobCommand cmd(&_cmd);
501 if (strcmp(cmd.GetArg(0), "meta") == 0)
503 Command_ClientMeta(pEdict, &cmd);
504 RETURN_META(MRES_SUPERCEDE);
507 RETURN_META(MRES_IGNORED);
510 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
512 unsigned char *addr1 = (unsigned char *)_addr1;
513 unsigned char *addr2 = (unsigned char *)_addr2;
515 for (size_t i=0; i<len; i++)
521 if (addr1[i] != addr2[i])
530 //////////////////////////////////////////////////////////////////////
531 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
532 // Signatures necessary in finding the pointer to the CUtlDict that //
533 // stores user message information. //
534 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
535 // message indices. This is our answer to it. Yuck! <:-( //
536 //////////////////////////////////////////////////////////////////////
538 /* General Windows sig */
539 #define MSGCLASS_SIGLEN 7
540 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
541 #define MSGCLASS_OFFS 2
543 /* Dystopia Wimdows hack */
544 #define MSGCLASS2_SIGLEN 16
545 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
546 #define MSGCLASS2_OFFS 11
548 /* Windows frame pointer sig */
549 #define MSGCLASS3_SIGLEN 18
550 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
551 #define MSGCLASS3_OFFS 13
552 #elif defined OS_LINUX
553 /* No frame pointer sig */
554 #define MSGCLASS_SIGLEN 14
555 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
556 #define MSGCLASS_OFFS 9
558 /* Frame pointer sig */
559 #define MSGCLASS2_SIGLEN 16
560 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
561 #define MSGCLASS2_OFFS 11
570 typedef CUtlDict<UserMessage *, int> UserMsgDict;
572 /* This is the ugliest function in all of SourceMM */
573 bool CacheUserMessages()
575 /* Get address of original GetUserMessageInfo() */
576 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
578 /* Oh dear, we have a relative jump on our hands
579 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
581 if (*vfunc == '\xE9')
583 /* Get address from displacement...
585 * Add 5 because it's relative to next instruction:
586 * Opcode <1 byte> + 32-bit displacement <4 bytes>
588 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
591 CUtlDict<UserMessage *, int> *dict = NULL;
593 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
595 /* Get address of CUserMessages instance */
596 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
598 /* Get address of CUserMessages::m_UserMessages */
599 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
601 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
604 /* If we get here, the code is possibly inlined like in Dystopia */
606 /* Get the address of the CUtlRBTree */
607 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
609 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
610 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
611 #elif defined OS_LINUX
612 /* Get address of CUserMessages instance */
613 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
615 /* Get address of CUserMessages::m_UserMessages */
616 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
620 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
622 /* Get address of CUserMessages instance */
623 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
625 /* Get address of CUserMessages::m_UserMessages */
626 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
630 #if !defined OS_WIN32
634 if (GetFileOfAddress(vfunc, path, sizeof(path)))
636 void *handle = dlopen(path, RTLD_NOW);
639 void *addr = dlsym(handle, "usermessages");
644 dict = (UserMsgDict *)*(void **)addr;
653 int msg_count = dict->Count();
655 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
656 if (msg_count < 0 || msg_count > 255)
664 /* Cache messages in our CUtlDict */
665 for (int i = 0; i < msg_count; i++)
667 msg = dict->Element(i);
668 u_msg.name = msg->name;
669 u_msg.size = msg->size;
670 usermsgs_list.push_back(u_msg);