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.
28 #include "../metamod_oslink.h"
29 #include <sourcehook.h>
32 #include <tier0/icommandline.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 <filesystem.h>
43 typedef void (*CONPRINTF_FUNC)(const char *, ...);
49 UsrMsgInfo(int s, const char *t) : size(s), name(t)
57 #if SOURCE_ENGINE == SE_DARKMESSIAH
59 DLL_IMPORT ICommandLine *CommandLine();
63 void CacheUserMessages();
64 void Detour_Error(const tchar *pMsg, ...);
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 BaseProvider g_Ep1Provider;
76 static List<ConCommandBase *> conbases_unreg;
77 static CVector<UsrMsgInfo> usermsgs_list;
78 static jmp_buf usermsg_end;
81 IFileSystem *baseFs = NULL;
82 IServerGameDLL *server = NULL;
83 IVEngineServer *engine = NULL;
84 IServerGameClients *gameclients = NULL;
85 IMetamodSourceProvider *provider = &g_Ep1Provider;
86 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
88 #if SOURCE_ENGINE >= SE_ORANGEBOX
89 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
91 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
94 void BaseProvider::ConsolePrint(const char *str)
96 #if SOURCE_ENGINE >= SE_ORANGEBOX
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 #if SOURCE_ENGINE >= SE_ORANGEBOX
113 icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
115 icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
119 DisplayError("Could not find ICvar! Metamod cannot load.");
124 if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
127 gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
130 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
133 mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
137 #if SOURCE_ENGINE >= SE_ORANGEBOX
141 g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
145 #if SOURCE_ENGINE == SE_DARKMESSIAH
146 if (!g_SMConVarAccessor.InitConCommandBaseList())
148 /* This is very unlikely considering it's old engine */
149 mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
150 mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
156 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
160 void BaseProvider::Notify_DLLShutdown_Pre()
162 g_SMConVarAccessor.RemoveMetamodCommands();
164 #if SOURCE_ENGINE == SE_DARKMESSIAH
165 if (g_Metamod.IsLoadedAsGameDLL())
167 icvar->UnlinkVariables(FCVAR_GAMEDLL);
172 bool BaseProvider::IsRemotePrintingAvailable()
177 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
179 engine->ClientPrintf(client, message);
182 void BaseProvider::ServerCommand(const char *cmd)
184 engine->ServerCommand(cmd);
187 const char *BaseProvider::GetConVarString(ConVar *convar)
194 return convar->GetString();
197 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
199 convar->SetValue(str);
202 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
204 return pCommand->IsCommand();
208 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
210 return (build == SOURCE_ENGINE_ORIGINAL
211 || build == SOURCE_ENGINE_EPISODEONE);
214 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
216 if (key[0] == '-' || key[0] == '+')
218 return CommandLine()->ParmValue(key, defval);
223 if ((val = icvar->GetCommandLineValue(key)) == NULL)
234 int BaseProvider::TryServerGameDLL(const char *iface)
236 if (strncmp(iface, "ServerGameDLL", 13) != 0)
241 return atoi(&iface[13]);
244 bool BaseProvider::LogMessage(const char *buffer)
251 engine->LogPrint(buffer);
256 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
258 SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
260 if (hook == ProvidedHook_LevelInit)
262 SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
264 else if (hook == ProvidedHook_LevelShutdown)
266 SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
268 else if (hook == ProvidedHook_GameInit)
270 SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
275 return (mfi.thisptroffs >= 0);
278 void BaseProvider::DisplayError(const char *fmt, ...)
284 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
290 void BaseProvider::DisplayWarning(const char *fmt, ...)
296 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
302 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
304 return &g_SMConVarAccessor;
307 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
309 return g_SMConVarAccessor.Register(pCommand);
312 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
314 return g_SMConVarAccessor.Unregister(pCommand);
317 int BaseProvider::GetUserMessageCount()
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 (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 #if SOURCE_ENGINE == SE_LEFT4DEAD2
362 return SOURCE_ENGINE_LEFT4DEAD2;
363 #elif SOURCE_ENGINE == SE_LEFT4DEAD
364 return SOURCE_ENGINE_LEFT4DEAD;
365 #elif SOURCE_ENGINE == SE_ORANGEBOX
366 return SOURCE_ENGINE_ORANGEBOX;
367 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
368 return SOURCE_ENGINE_ORANGEBOXVALVE;
369 #elif SOURCE_ENGINE == SE_DARKMESSIAH
370 return SOURCE_ENGINE_DARKMESSIAH;
372 #error "SOURCE_ENGINE not defined to a known value"
376 ConVar *BaseProvider::CreateConVar(const char *name,
382 if (flags & ConVarFlag_Notify)
384 newflags |= FCVAR_NOTIFY;
386 if (flags & ConVarFlag_SpOnly)
388 newflags |= FCVAR_SPONLY;
391 ConVar *pVar = new ConVar(name, defval, newflags, help);
393 g_SMConVarAccessor.RegisterConCommandBase(pVar);
398 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
406 const char *plugin_file, *p_alias;
408 pValues = new KeyValues("Metamod Plugin");
410 if (!pValues->LoadFromFile(baseFs, file))
412 pValues->deleteThis();
416 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
418 pValues->deleteThis();
422 UTIL_Format(path, path_len, "%s", plugin_file);
424 if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
426 UTIL_Format(alias, alias_len, "%s", p_alias);
430 UTIL_Format(alias, alias_len, "");
433 pValues->deleteThis();
438 #if SOURCE_ENGINE >= SE_ORANGEBOX
439 class GlobCommand : public IMetamodSourceCommandInfo
442 GlobCommand(const CCommand *cmd) : m_cmd(cmd)
446 unsigned int GetArgCount()
448 return m_cmd->ArgC() - 1;
451 const char *GetArg(unsigned int num)
453 return m_cmd->Arg(num);
456 const char *GetArgString()
458 return m_cmd->ArgS();
461 const CCommand *m_cmd;
464 class GlobCommand : public IMetamodSourceCommandInfo
467 unsigned int GetArgCount()
469 return engine->Cmd_Argc() - 1;
472 const char *GetArg(unsigned int num)
474 return engine->Cmd_Argv(num);
477 const char *GetArgString()
479 return engine->Cmd_Args();
484 #if SOURCE_ENGINE >= SE_ORANGEBOX
485 void LocalCommand_Meta(const CCommand &args)
487 GlobCommand cmd(&args);
489 void LocalCommand_Meta()
496 #if SOURCE_ENGINE >= SE_ORANGEBOX
497 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
499 GlobCommand cmd(&_cmd);
501 void ClientCommand(edict_t *pEdict)
505 if (strcmp(cmd.GetArg(0), "meta") == 0)
507 Command_ClientMeta(pEdict, &cmd);
508 RETURN_META(MRES_SUPERCEDE);
511 RETURN_META(MRES_IGNORED);
514 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
515 void Detour_Error(const tchar *pMsg, ...)
517 /* Jump back to setjmp() in CacheUserMessages() */
518 longjmp(usermsg_end, 1);
521 #define IA32_JMP_IMM32 0xE9
523 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
524 * early Orange Box. This is because Error() from tier0 gets called when a bad index is
525 * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
527 * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
528 * to a point before GetUserMessageInfo() is called. The detour is then removed and we
531 void CacheUserMessages()
535 unsigned char *target, *detour;
536 unsigned char orig_bytes[5];
538 target = (unsigned char *)&Error;
539 detour = (unsigned char *)&Detour_Error;
541 /* Save bytes from target function */
542 memcpy(orig_bytes, target, sizeof(orig_bytes));
544 /* Patch in relative jump to our Error() detour */
545 SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
546 target[0] = IA32_JMP_IMM32;
547 *(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
549 /* This is where longjmp() will end up */
550 if (setjmp(usermsg_end))
552 /* Restore bytes and memory protection */
553 memcpy(target, orig_bytes, sizeof(orig_bytes));
554 SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
560 /* If GetUserMessageInfo() calls Error(), we should end up in our detour */
561 while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
563 usermsgs_list.push_back(UsrMsgInfo(size, buffer));
567 /* Jump back to setjmp() */
568 longjmp(usermsg_end, 1);