2 * vim: set ts=4 sw=4 tw=99 noet :
3 * ======================================================
5 * Copyright (C) 2004-2009 AlliedModders LLC and authors.
7 * ======================================================
9 * This software is provided 'as-is', without any express or implied warranty.
10 * In no event will the authors be held liable for any damages arising from
11 * the use of this software.
13 * Permission is granted to anyone to use this software for any purpose,
14 * including commercial applications, and to alter it and redistribute it
15 * freely, subject to the following restrictions:
17 * 1. The origin of this software must not be misrepresented; you must not
18 * claim that you wrote the original software. If you use this software in a
19 * product, an acknowledgment in the product documentation would be
20 * appreciated but is not required.
21 * 2. Altered source versions must be plainly marked as such, and must not be
22 * misrepresented as being the original software.
23 * 3. This notice may not be removed or altered from any source distribution.
27 #include "../metamod_oslink.h"
28 #include <sourcehook.h>
31 #include <tier0/icommandline.h>
32 #include <tier1/utldict.h>
33 #include <sh_vector.h>
34 #include <sh_string.h>
35 #include "../metamod_util.h"
36 #include "provider_ep2.h"
38 #include "metamod_console.h"
39 #include "vsp_listener.h"
40 #include <filesystem.h>
44 typedef void (*CONPRINTF_FUNC)(const char *, ...);
50 UsrMsgInfo(int s, const char *t) : size(s), name(t)
58 #if SOURCE_ENGINE == SE_DARKMESSIAH
60 DLL_IMPORT ICommandLine *CommandLine();
64 bool CacheUserMessages();
65 #if SOURCE_ENGINE >= SE_ORANGEBOX
66 void ClientCommand(edict_t *pEdict, const CCommand &args);
67 void LocalCommand_Meta(const CCommand &args);
69 void ClientCommand(edict_t *pEdict);
70 void LocalCommand_Meta();
73 void _ServerCommand();
75 static bool usermsgs_extracted = false;
76 static CVector<UsrMsgInfo> usermsgs_list;
77 static VSPListener g_VspListener;
78 static BaseProvider g_Ep1Provider;
79 static List<ConCommandBase *> conbases_unreg;
82 IFileSystem *baseFs = NULL;
83 IServerGameDLL *server = NULL;
84 IVEngineServer *engine = NULL;
85 IServerGameClients *gameclients = NULL;
86 IMetamodSourceProvider *provider = &g_Ep1Provider;
87 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
89 #if SOURCE_ENGINE >= SE_ORANGEBOX
90 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
92 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
95 bool AssumeUserMessages()
102 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
104 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
111 void BaseProvider::ConsolePrint(const char *str)
113 #if SOURCE_ENGINE >= SE_ORANGEBOX
120 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory,
121 CreateInterfaceFn serverFactory)
123 engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
126 DisplayError("Could not find IVEngineServer! Metamod cannot load.");
129 #if SOURCE_ENGINE >= SE_ORANGEBOX
130 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
132 icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
136 DisplayError("Could not find ICvar! Metamod cannot load.");
141 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
144 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
147 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
150 mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
154 #if SOURCE_ENGINE >= SE_ORANGEBOX
158 g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
160 if ((usermsgs_extracted = CacheUserMessages()) == false)
162 usermsgs_extracted = AssumeUserMessages();
165 #if SOURCE_ENGINE == SE_DARKMESSIAH
166 if (!g_SMConVarAccessor.InitConCommandBaseList())
168 /* This is very unlikely considering it's old engine */
169 mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
170 mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
176 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
180 void BaseProvider::Notify_DLLShutdown_Pre()
182 g_SMConVarAccessor.RemoveMetamodCommands();
184 #if SOURCE_ENGINE == SE_DARKMESSIAH
185 if (g_Metamod.IsLoadedAsGameDLL())
187 icvar->UnlinkVariables(FCVAR_GAMEDLL);
192 bool BaseProvider::IsRemotePrintingAvailable()
197 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
199 engine->ClientPrintf(client, message);
202 void BaseProvider::ServerCommand(const char *cmd)
204 engine->ServerCommand(cmd);
207 const char *BaseProvider::GetConVarString(ConVar *convar)
214 return convar->GetString();
217 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
219 convar->SetValue(str);
222 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
224 return pCommand->IsCommand();
228 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
230 return (build == SOURCE_ENGINE_ORIGINAL
231 || build == SOURCE_ENGINE_EPISODEONE);
234 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
236 if (key[0] == '-' || key[0] == '+')
238 return CommandLine()->ParmValue(key, defval);
243 if ((val = icvar->GetCommandLineValue(key)) == NULL)
254 int BaseProvider::TryServerGameDLL(const char *iface)
256 if (strncmp(iface, "ServerGameDLL", 13) != 0)
261 return atoi(&iface[13]);
264 bool BaseProvider::LogMessage(const char *buffer)
271 engine->LogPrint(buffer);
276 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
278 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
280 if (hook == ProvidedHook_LevelInit)
282 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
284 else if (hook == ProvidedHook_LevelShutdown)
286 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
288 else if (hook == ProvidedHook_GameInit)
290 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
295 return (mfi.thisptroffs >= 0);
298 void BaseProvider::DisplayError(const char *fmt, ...)
304 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
310 void BaseProvider::DisplayWarning(const char *fmt, ...)
316 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
322 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
324 return &g_SMConVarAccessor;
327 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
329 return g_SMConVarAccessor.Register(pCommand);
332 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
334 return g_SMConVarAccessor.Unregister(pCommand);
337 int BaseProvider::GetUserMessageCount()
339 if (!usermsgs_extracted)
344 return (int)usermsgs_list.size();
347 int BaseProvider::FindUserMessage(const char *name, int *size)
349 for (size_t i = 0; i < usermsgs_list.size(); i++)
351 if (usermsgs_list[i].name.compare(name) == 0)
355 *size = usermsgs_list[i].size;
364 const char *BaseProvider::GetUserMessage(int index, int *size)
366 if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
373 *size = usermsgs_list[index].size;
376 return usermsgs_list[index].name.c_str();
379 const char *BaseProvider::GetGameDescription()
381 return server->GetGameDescription();
384 int BaseProvider::DetermineSourceEngine(const char *game)
386 #if SOURCE_ENGINE == SE_LEFT4DEAD2
387 return SOURCE_ENGINE_LEFT4DEAD2;
388 #elif SOURCE_ENGINE == SE_LEFT4DEAD
389 return SOURCE_ENGINE_LEFT4DEAD;
390 #elif SOURCE_ENGINE == SE_ORANGEBOX
391 return SOURCE_ENGINE_ORANGEBOX;
392 #elif SOURCE_ENGINE == SE_DARKMESSIAH
393 return SOURCE_ENGINE_DARKMESSIAH;
395 #error "SOURCE_ENGINE not defined to a known value"
399 ConVar *BaseProvider::CreateConVar(const char *name,
405 if (flags & ConVarFlag_Notify)
407 newflags |= FCVAR_NOTIFY;
409 if (flags & ConVarFlag_SpOnly)
411 newflags |= FCVAR_SPONLY;
414 ConVar *pVar = new ConVar(name, defval, newflags, help);
416 g_SMConVarAccessor.RegisterConCommandBase(pVar);
421 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
428 g_VspListener.SetLoadable(true);
429 return &g_VspListener;
432 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
440 const char *plugin_file, *p_alias;
442 pValues = new KeyValues("Metamod Plugin");
444 if (!pValues->LoadFromFile(baseFs, file))
446 pValues->deleteThis();
450 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
452 pValues->deleteThis();
456 UTIL_Format(path, path_len, "%s", plugin_file);
458 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
460 UTIL_Format(alias, alias_len, "%s", p_alias);
464 UTIL_Format(alias, alias_len, "");
467 pValues->deleteThis();
472 #if SOURCE_ENGINE >= SE_ORANGEBOX
473 class GlobCommand : public IMetamodSourceCommandInfo
476 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
480 unsigned int GetArgCount()
482 return m_cmd->ArgC() - 1;
485 const char *GetArg(unsigned int num)
487 return m_cmd->Arg(num);
490 const char *GetArgString()
492 return m_cmd->ArgS();
495 const CCommand *m_cmd;
498 class GlobCommand : public IMetamodSourceCommandInfo
501 unsigned int GetArgCount()
503 return engine->Cmd_Argc() - 1;
506 const char *GetArg(unsigned int num)
508 return engine->Cmd_Argv(num);
511 const char *GetArgString()
513 return engine->Cmd_Args();
518 #if SOURCE_ENGINE >= SE_ORANGEBOX
519 void LocalCommand_Meta(const CCommand &args)
521 GlobCommand cmd(&args);
523 void LocalCommand_Meta()
530 #if SOURCE_ENGINE >= SE_ORANGEBOX
531 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
533 GlobCommand cmd(&_cmd);
535 void ClientCommand(edict_t *pEdict)
539 if (strcmp(cmd.GetArg(0), "meta") == 0)
541 Command_ClientMeta(pEdict, &cmd);
542 RETURN_META(MRES_SUPERCEDE);
545 RETURN_META(MRES_IGNORED);
548 //////////////////////////////////////////////////////////////////////
549 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
550 // Signatures necessary in finding the pointer to the CUtlDict that //
551 // stores user message information. //
552 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
553 // message indices. This is our answer to it. Yuck! <:-( //
554 //////////////////////////////////////////////////////////////////////
556 /* General Windows sig */
557 #define MSGCLASS_SIGLEN 7
558 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
559 #define MSGCLASS_OFFS 2
561 /* Dystopia Windows hack */
562 #define MSGCLASS2_SIGLEN 16
563 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
564 #define MSGCLASS2_OFFS 11
566 /* Windows frame pointer sig */
567 #define MSGCLASS3_SIGLEN 18
568 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
569 #define MSGCLASS3_OFFS 13
570 #elif defined OS_LINUX
571 /* No frame pointer sig */
572 #define MSGCLASS_SIGLEN 14
573 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
574 #define MSGCLASS_OFFS 9
576 /* Frame pointer sig */
577 #define MSGCLASS2_SIGLEN 16
578 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
579 #define MSGCLASS2_OFFS 11
588 typedef CUtlDict<UserMessage *, int> UserMsgDict;
590 /* This is the ugliest function in all of MM:S */
591 bool CacheUserMessages()
593 UserMsgDict *dict = NULL;
595 /* Get address of original GetUserMessageInfo() */
596 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
598 /* Oh dear, we have a relative jump on our hands
599 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
601 if (*vfunc == '\xE9')
603 /* Get address from displacement...
605 * Add 5 because it's relative to next instruction:
606 * Opcode <1 byte> + 32-bit displacement <4 bytes>
608 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
611 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
613 /* Get address of CUserMessages instance */
614 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
616 /* Get address of CUserMessages::m_UserMessages */
617 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
619 else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
622 /* If we get here, the code is possibly inlined like in Dystopia */
624 /* Get the address of the CUtlRBTree */
625 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
627 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
628 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
629 #elif defined OS_LINUX
630 /* Get address of CUserMessages instance */
631 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
633 /* Get address of CUserMessages::m_UserMessages */
634 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
638 else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
640 /* Get address of CUserMessages instance */
641 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
643 /* Get address of CUserMessages::m_UserMessages */
644 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
648 #if !defined OS_WIN32
652 if (GetFileOfAddress(vfunc, path, sizeof(path)))
654 void *handle = dlopen(path, RTLD_NOW);
657 void *addr = dlsym(handle, "usermessages");
662 dict = (UserMsgDict *)*(void **)addr;
671 int msg_count = dict->Count();
673 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
674 if (msg_count < 0 || msg_count > 255)
682 /* Cache messages in our CUtlDict */
683 for (int i = 0; i < msg_count; i++)
685 msg = dict->Element(i);
686 u_msg.name = msg->name;
687 u_msg.size = msg->size;
688 usermsgs_list.push_back(u_msg);