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 *, ...);
51 UsrMsgInfo(int s, const char *t) : size(s), name(t)
59 DLL_IMPORT ICommandLine *CommandLine();
61 bool CacheUserMessages();
62 void ClientCommand(edict_t *pEdict, const CCommand &args);
63 void LocalCommand_Meta(const CCommand &args);
64 void _ServerCommand();
66 bool usermsgs_extracted = false;
67 CVector<UsrMsgInfo> usermsgs_list;
69 ISmmAPI *metamod_api = NULL;
70 IVEngineServer *engine = NULL;
71 IServerGameClients *gameclients = NULL;
72 VSPListener g_VspListener;
73 BaseProvider g_Ep1Provider;
74 IMetamodSourceProvider *provider = &g_Ep1Provider;
75 List<ConCommandBase *> conbases_unreg;
76 IFileSystem *baseFs = NULL;
77 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
79 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
81 bool AssumeUserMessages()
88 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
90 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
97 void BaseProvider::ConsolePrint(const char *str)
102 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
103 CreateInterfaceFn serverFactory)
105 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
108 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
111 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
114 DisplayError("Could not find ICvar! Metamod cannot load.");
119 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
122 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
125 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
128 ::LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
132 RegisterConCommandBase(&meta_local_cmd);
133 conbases_unreg.push_back(&meta_local_cmd);
135 if ((usermsgs_extracted = CacheUserMessages()) == false)
137 usermsgs_extracted = AssumeUserMessages();
142 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
146 void BaseProvider::Notify_DLLShutdown_Pre()
148 List<ConCommandBase *>::iterator iter;
150 for (iter = conbases_unreg.begin();
151 iter != conbases_unreg.end();
154 UnregisterConCommandBase((*iter));
158 bool BaseProvider::IsRemotePrintingAvailable()
163 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
165 engine->ClientPrintf(client, message);
168 void BaseProvider::ServerCommand(const char *cmd)
170 engine->ServerCommand(cmd);
173 const char *BaseProvider::GetConVarString(ConVar *convar)
180 return convar->GetString();
183 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
185 convar->SetValue(str);
188 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
190 return pCommand->IsCommand();
194 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
196 return (build == SOURCE_ENGINE_ORIGINAL
197 || build == SOURCE_ENGINE_EPISODEONE);
200 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
202 if (key[0] == '-' || key[0] == '+')
204 return CommandLine_Tier0()->ParmValue(key, defval);
209 if ((val = icvar->GetCommandLineValue(key)) == NULL)
220 int BaseProvider::TryServerGameDLL(const char *iface)
222 if (strncmp(iface, "ServerGameDLL", 13) != 0)
227 return atoi(&iface[13]);
230 bool BaseProvider::LogMessage(const char *buffer)
237 engine->LogPrint(buffer);
242 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
244 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
246 if (hook == ProvidedHook_LevelInit)
248 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
250 else if (hook == ProvidedHook_LevelShutdown)
252 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
254 else if (hook == ProvidedHook_GameInit)
256 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
258 else if (hook == ProvidedHook_DLLShutdown)
260 SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
262 else if (hook == ProvidedHook_DLLInit)
264 SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
269 return (mfi.thisptroffs >= 0);
272 void BaseProvider::DisplayError(const char *fmt, ...)
278 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
284 void BaseProvider::DisplayWarning(const char *fmt, ...)
290 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
296 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
298 return &g_SMConVarAccessor;
301 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
303 return g_SMConVarAccessor.Register(pCommand);
306 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
308 return g_SMConVarAccessor.Unregister(pCommand);
311 int BaseProvider::GetUserMessageCount()
313 if (!usermsgs_extracted)
318 return (int)usermsgs_list.size();
321 int BaseProvider::FindUserMessage(const char *name, int *size)
323 for (size_t i = 0; i < usermsgs_list.size(); i++)
325 if (usermsgs_list[i].name.compare(name) == 0)
329 *size = usermsgs_list[i].size;
338 const char *BaseProvider::GetUserMessage(int index, int *size)
340 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
347 *size = usermsgs_list[index].size;
350 return usermsgs_list[index].name.c_str();
353 const char *BaseProvider::GetGameDescription()
355 return server->GetGameDescription();
358 int BaseProvider::DetermineSourceEngine(const char *game)
360 return SOURCE_ENGINE_ORANGEBOX;
363 ConVar *BaseProvider::CreateConVar(const char *name,
369 if (flags & ConVarFlag_Notify)
371 newflags |= FCVAR_NOTIFY;
373 if (flags & ConVarFlag_SpOnly)
375 newflags |= FCVAR_SPONLY;
378 ConVar *pVar = new ConVar(name, defval, newflags, help);
380 RegisterConCommandBase(pVar);
381 conbases_unreg.push_back(pVar);
386 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
388 g_VspListener.SetLoadable(true);
389 return &g_VspListener;
392 bool BaseProvider::IsAlternatelyLoaded()
394 return g_VspListener.IsRootLoadMethod();
397 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
405 const char *plugin_file, *p_alias;
407 pValues = new KeyValues("Metamod Plugin");
409 if (!pValues->LoadFromFile(baseFs, file))
411 pValues->deleteThis();
415 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
417 pValues->deleteThis();
421 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
423 UTIL_Format(alias, alias_len, "%s", p_alias);
427 UTIL_Format(alias, alias_len, "");
430 /* Attempt to find a file extension */
431 if (UTIL_GetExtension(plugin_file) == NULL)
433 g_pMetamod->PathFormat(path,
436 g_pMetamod->GetBaseDir(),
438 #if defined WIN32 || defined _WIN32
447 g_pMetamod->PathFormat(path,
450 g_pMetamod->GetBaseDir(),
454 pValues->deleteThis();
459 class GlobCommand : public IMetamodSourceCommandInfo
462 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
466 unsigned int GetArgCount()
468 return m_cmd->ArgC() - 1;
471 const char *GetArg(unsigned int num)
473 return m_cmd->Arg(num);
476 const char *GetArgString()
478 return m_cmd->ArgS();
481 const CCommand *m_cmd;
484 void LocalCommand_Meta(const CCommand &args)
486 GlobCommand cmd(&args);
490 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
492 GlobCommand cmd(&_cmd);
494 if (strcmp(cmd.GetArg(0), "meta") == 0)
496 Command_ClientMeta(pEdict, &cmd);
497 RETURN_META(MRES_SUPERCEDE);
500 RETURN_META(MRES_IGNORED);
503 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
505 unsigned char *addr1 = (unsigned char *)_addr1;
506 unsigned char *addr2 = (unsigned char *)_addr2;
508 for (size_t i=0; i<len; i++)
514 if (addr1[i] != addr2[i])
523 //////////////////////////////////////////////////////////////////////
524 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
525 // Signatures necessary in finding the pointer to the CUtlDict that //
526 // stores user message information. //
527 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
528 // message indices. This is our answer to it. Yuck! <:-( //
529 //////////////////////////////////////////////////////////////////////
531 /* General Windows sig */
532 #define MSGCLASS_SIGLEN 7
533 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
534 #define MSGCLASS_OFFS 2
536 /* Dystopia Wimdows hack */
537 #define MSGCLASS2_SIGLEN 16
538 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
539 #define MSGCLASS2_OFFS 11
541 /* Windows frame pointer sig */
542 #define MSGCLASS3_SIGLEN 18
543 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
544 #define MSGCLASS3_OFFS 13
545 #elif defined OS_LINUX
546 /* No frame pointer sig */
547 #define MSGCLASS_SIGLEN 14
548 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
549 #define MSGCLASS_OFFS 9
551 /* Frame pointer sig */
552 #define MSGCLASS2_SIGLEN 16
553 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
554 #define MSGCLASS2_OFFS 11
563 typedef CUtlDict<UserMessage *, int> UserMsgDict;
565 /* This is the ugliest function in all of SourceMM */
566 bool CacheUserMessages()
568 /* Get address of original GetUserMessageInfo() */
569 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
571 /* Oh dear, we have a relative jump on our hands
572 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
574 if (*vfunc == '\xE9')
576 /* Get address from displacement...
578 * Add 5 because it's relative to next instruction:
579 * Opcode <1 byte> + 32-bit displacement <4 bytes>
581 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
584 CUtlDict<UserMessage *, int> *dict = NULL;
586 if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
588 /* Get address of CUserMessages instance */
589 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
591 /* Get address of CUserMessages::m_UserMessages */
592 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
594 else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
597 /* If we get here, the code is possibly inlined like in Dystopia */
599 /* Get the address of the CUtlRBTree */
600 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
602 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
603 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
604 #elif defined OS_LINUX
605 /* Get address of CUserMessages instance */
606 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
608 /* Get address of CUserMessages::m_UserMessages */
609 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
613 else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
615 /* Get address of CUserMessages instance */
616 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
618 /* Get address of CUserMessages::m_UserMessages */
619 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
623 #if !defined OS_WIN32
627 if (GetFileOfAddress(vfunc, path, sizeof(path)))
629 void *handle = dlopen(path, RTLD_NOW);
632 void *addr = dlsym(handle, "usermessages");
637 dict = (UserMsgDict *)*(void **)addr;
646 int msg_count = dict->Count();
648 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
649 if (msg_count < 0 || msg_count > 255)
657 /* Cache messages in our CUtlDict */
658 for (int i = 0; i < msg_count; i++)
660 msg = dict->Element(i);
661 u_msg.name = msg->name;
662 u_msg.size = msg->size;
663 usermsgs_list.push_back(u_msg);