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_ORANGEBOXVALVE
393 return SOURCE_ENGINE_ORANGEBOXVALVE;
394 #elif SOURCE_ENGINE == SE_DARKMESSIAH
395 return SOURCE_ENGINE_DARKMESSIAH;
397 #error "SOURCE_ENGINE not defined to a known value"
401 ConVar *BaseProvider::CreateConVar(const char *name,
407 if (flags & ConVarFlag_Notify)
409 newflags |= FCVAR_NOTIFY;
411 if (flags & ConVarFlag_SpOnly)
413 newflags |= FCVAR_SPONLY;
416 ConVar *pVar = new ConVar(name, defval, newflags, help);
418 g_SMConVarAccessor.RegisterConCommandBase(pVar);
423 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
430 g_VspListener.SetLoadable(true);
431 return &g_VspListener;
434 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
442 const char *plugin_file, *p_alias;
444 pValues = new KeyValues("Metamod Plugin");
446 if (!pValues->LoadFromFile(baseFs, file))
448 pValues->deleteThis();
452 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
454 pValues->deleteThis();
458 UTIL_Format(path, path_len, "%s", plugin_file);
460 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
462 UTIL_Format(alias, alias_len, "%s", p_alias);
466 UTIL_Format(alias, alias_len, "");
469 pValues->deleteThis();
474 #if SOURCE_ENGINE >= SE_ORANGEBOX
475 class GlobCommand : public IMetamodSourceCommandInfo
478 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
482 unsigned int GetArgCount()
484 return m_cmd->ArgC() - 1;
487 const char *GetArg(unsigned int num)
489 return m_cmd->Arg(num);
492 const char *GetArgString()
494 return m_cmd->ArgS();
497 const CCommand *m_cmd;
500 class GlobCommand : public IMetamodSourceCommandInfo
503 unsigned int GetArgCount()
505 return engine->Cmd_Argc() - 1;
508 const char *GetArg(unsigned int num)
510 return engine->Cmd_Argv(num);
513 const char *GetArgString()
515 return engine->Cmd_Args();
520 #if SOURCE_ENGINE >= SE_ORANGEBOX
521 void LocalCommand_Meta(const CCommand &args)
523 GlobCommand cmd(&args);
525 void LocalCommand_Meta()
532 #if SOURCE_ENGINE >= SE_ORANGEBOX
533 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
535 GlobCommand cmd(&_cmd);
537 void ClientCommand(edict_t *pEdict)
541 if (strcmp(cmd.GetArg(0), "meta") == 0)
543 Command_ClientMeta(pEdict, &cmd);
544 RETURN_META(MRES_SUPERCEDE);
547 RETURN_META(MRES_IGNORED);
550 //////////////////////////////////////////////////////////////////////
551 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED! //
552 // Signatures necessary in finding the pointer to the CUtlDict that //
553 // stores user message information. //
554 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad //
555 // message indices. This is our answer to it. Yuck! <:-( //
556 //////////////////////////////////////////////////////////////////////
558 /* General Windows sig */
559 #define MSGCLASS_SIGLEN 7
560 #define MSGCLASS_SIG "\x8B\x0D\x2A\x2A\x2A\x2A\x56"
561 #define MSGCLASS_OFFS 2
563 /* Dystopia Windows hack */
564 #define MSGCLASS2_SIGLEN 16
565 #define MSGCLASS2_SIG "\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
566 #define MSGCLASS2_OFFS 11
568 /* Windows frame pointer sig */
569 #define MSGCLASS3_SIGLEN 18
570 #define MSGCLASS3_SIG "\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
571 #define MSGCLASS3_OFFS 13
572 #elif defined OS_LINUX
573 /* No frame pointer sig */
574 #define MSGCLASS_SIGLEN 14
575 #define MSGCLASS_SIG "\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
576 #define MSGCLASS_OFFS 9
578 /* Frame pointer sig */
579 #define MSGCLASS2_SIGLEN 16
580 #define MSGCLASS2_SIG "\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
581 #define MSGCLASS2_OFFS 11
590 typedef CUtlDict<UserMessage *, int> UserMsgDict;
592 /* This is the ugliest function in all of MM:S */
593 bool CacheUserMessages()
595 UserMsgDict *dict = NULL;
597 /* Get address of original GetUserMessageInfo() */
598 char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
600 /* Oh dear, we have a relative jump on our hands
601 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
603 if (*vfunc == '\xE9')
605 /* Get address from displacement...
607 * Add 5 because it's relative to next instruction:
608 * Opcode <1 byte> + 32-bit displacement <4 bytes>
610 vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
613 if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
615 /* Get address of CUserMessages instance */
616 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
618 /* Get address of CUserMessages::m_UserMessages */
619 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
621 else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN))
624 /* If we get here, the code is possibly inlined like in Dystopia */
626 /* Get the address of the CUtlRBTree */
627 char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
629 /* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
630 dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
631 #elif defined OS_LINUX
632 /* Get address of CUserMessages instance */
633 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
635 /* Get address of CUserMessages::m_UserMessages */
636 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
640 else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN))
642 /* Get address of CUserMessages instance */
643 char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
645 /* Get address of CUserMessages::m_UserMessages */
646 dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
650 #if !defined OS_WIN32
654 if (GetFileOfAddress(vfunc, path, sizeof(path)))
656 void *handle = dlopen(path, RTLD_NOW);
659 void *addr = dlsym(handle, "usermessages");
665 dict = (UserMsgDict *)*(void **)addr;
674 int msg_count = dict->Count();
676 /* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
677 if (msg_count < 0 || msg_count > 255)
685 /* Cache messages in our CUtlDict */
686 for (int i = 0; i < msg_count; i++)
688 msg = dict->Element(i);
689 u_msg.name = msg->name;
690 u_msg.size = msg->size;
691 usermsgs_list.push_back(u_msg);