core/provider/provider_ep2.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Fri Jul 12 02:31:24 2013 -0400 (2013-07-12)
changeset 849 43df9a463b6e
parent 839 eab123e5ee23
child 850 3d9258ef9a30
permissions -rw-r--r--
Updated for latest hl2sdk-dota changes.
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2009 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     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.
    12  * 
    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:
    16  *
    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.
    24  */
    25 
    26 #include <stdio.h>
    27 #include <setjmp.h>
    28 #include "../metamod_oslink.h"
    29 #include <sourcehook.h>
    30 #include <convar.h>
    31 #include <eiface.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"
    37 #include "console.h"
    38 #include "metamod_console.h"
    39 #include <filesystem.h>
    40 #include "metamod.h"
    41 
    42 /* Types */
    43 typedef void (*CONPRINTF_FUNC)(const char *, ...);
    44 struct UsrMsgInfo
    45 {
    46 	UsrMsgInfo()
    47 	{
    48 	}
    49 	UsrMsgInfo(int s, const char *t) : size(s), name(t)
    50 	{
    51 	}
    52 	int size;
    53 	String name;
    54 };
    55 
    56 /* Imports */
    57 #if SOURCE_ENGINE == SE_DARKMESSIAH
    58 #undef CommandLine
    59 DLL_IMPORT ICommandLine *CommandLine();
    60 #endif
    61 
    62 /* Functions */
    63 void CacheUserMessages();
    64 void Detour_Error(const tchar *pMsg, ...);
    65 #if SOURCE_ENGINE == SE_DOTA
    66 void ClientCommand(CEntityIndex index, const CCommand &args);
    67 void LocalCommand_Meta(const CCommandContext &context, const CCommand &args);
    68 #elif SOURCE_ENGINE >= SE_ORANGEBOX
    69 void ClientCommand(edict_t *pEdict, const CCommand &args);
    70 void LocalCommand_Meta(const CCommand &args);
    71 #else
    72 void ClientCommand(edict_t *pEdict);
    73 void LocalCommand_Meta();
    74 #endif
    75 
    76 void _ServerCommand();
    77 /* Variables */
    78 static BaseProvider g_Ep1Provider;
    79 static List<ConCommandBase *> conbases_unreg;
    80 static CVector<UsrMsgInfo> usermsgs_list;
    81 static jmp_buf usermsg_end;
    82 
    83 ICvar *icvar = NULL;
    84 IFileSystem *baseFs = NULL;
    85 IServerGameDLL *server = NULL;
    86 IVEngineServer *engine = NULL;
    87 IServerGameClients *gameclients = NULL;
    88 IMetamodSourceProvider *provider = &g_Ep1Provider;
    89 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
    90 
    91 #if SOURCE_ENGINE == SE_DOTA
    92 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, CEntityIndex, const CCommand &);
    93 #elif SOURCE_ENGINE >= SE_ORANGEBOX
    94 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    95 #else
    96 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    97 #endif
    98 
    99 void BaseProvider::ConsolePrint(const char *str)
   100 {
   101 #if SOURCE_ENGINE >= SE_ORANGEBOX
   102 	ConMsg("%s", str);
   103 #else
   104 	Msg("%s", str);
   105 #endif
   106 }
   107 
   108 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory, 
   109 									  CreateInterfaceFn serverFactory)
   110 {
   111 	engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   112 	if (!engine)
   113 	{
   114 		DisplayError("Could not find IVEngineServer! Metamod cannot load.");
   115 		return;
   116 	}
   117 #if SOURCE_ENGINE >= SE_ORANGEBOX
   118 	icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
   119 #else
   120 	icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
   121 #endif
   122 	if (!icvar)
   123 	{
   124 		DisplayError("Could not find ICvar! Metamod cannot load.");
   125 		return;
   126 	}
   127 
   128 
   129 	if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
   130 		== NULL)
   131 	{
   132 		gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
   133 	}
   134 
   135 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   136 	if (baseFs == NULL)
   137 	{
   138 		mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
   139 	}
   140 
   141 #if SOURCE_ENGINE >= SE_ORANGEBOX
   142 	g_pCVar = icvar;
   143 #endif
   144 
   145 	g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
   146 
   147 	CacheUserMessages();
   148 
   149 #if SOURCE_ENGINE == SE_DARKMESSIAH
   150 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   151 	{
   152 		/* This is very unlikely considering it's old engine */
   153 		mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   154 		mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   155 	}
   156 #endif
   157 
   158 	if (gameclients)
   159 	{
   160 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   161 	}
   162 }
   163 
   164 void BaseProvider::Notify_DLLShutdown_Pre()
   165 {
   166 	g_SMConVarAccessor.RemoveMetamodCommands();
   167 
   168 #if SOURCE_ENGINE == SE_DARKMESSIAH
   169 	if (g_Metamod.IsLoadedAsGameDLL())
   170 	{
   171 		icvar->UnlinkVariables(FCVAR_GAMEDLL);
   172 	}
   173 #endif
   174 }
   175 
   176 bool BaseProvider::IsRemotePrintingAvailable()
   177 {
   178 	return true;
   179 }
   180 
   181 void BaseProvider::ClientConsolePrint(edict_t *pEdict, const char *message)
   182 {
   183 #if SOURCE_ENGINE == SE_DOTA
   184 	int client = (int)(pEdict - g_Metamod.GetCGlobals()->pEdicts);
   185 	engine->ClientPrintf(client, message);
   186 #else
   187 	engine->ClientPrintf(pEdict, message);
   188 #endif
   189 }
   190 
   191 void BaseProvider::ServerCommand(const char *cmd)
   192 {
   193 	engine->ServerCommand(cmd);
   194 }
   195 
   196 const char *BaseProvider::GetConVarString(ConVar *convar)
   197 {
   198 	if (convar == NULL)
   199 	{
   200 		return NULL;
   201 	}
   202 
   203 	return convar->GetString();
   204 }
   205 
   206 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
   207 {
   208 	convar->SetValue(str);
   209 }
   210 
   211 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   212 {
   213 	return pCommand->IsCommand();
   214 }
   215 
   216 
   217 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   218 {
   219 	return (build == SOURCE_ENGINE_ORIGINAL
   220 			|| build == SOURCE_ENGINE_EPISODEONE);
   221 }
   222 
   223 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   224 {
   225 	if (key[0] == '-' || key[0] == '+')
   226 	{
   227 		return CommandLine()->ParmValue(key, defval);
   228 	}
   229 	else if (icvar)
   230 	{
   231 		const char *val;
   232 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   233 		{
   234 			return defval;
   235 		}
   236 
   237 		return val;
   238 	}
   239 
   240 	return NULL;
   241 }
   242 
   243 int BaseProvider::TryServerGameDLL(const char *iface)
   244 {
   245 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   246 	{
   247 		return 0;
   248 	}
   249 
   250 	return atoi(&iface[13]);
   251 }
   252 
   253 bool BaseProvider::LogMessage(const char *buffer)
   254 {
   255 	if (!engine)
   256 	{
   257 		return false;
   258 	}
   259 
   260 	engine->LogPrint(buffer);
   261 
   262 	return true;
   263 }
   264 
   265 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   266 {
   267 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   268 
   269 	if (hook == ProvidedHook_LevelInit)
   270 	{
   271 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   272 	}
   273 	else if (hook == ProvidedHook_LevelShutdown)
   274 	{
   275 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   276 	}
   277 	else if (hook == ProvidedHook_GameInit)
   278 	{
   279 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   280 	}
   281 
   282 	*pInfo = mfi;
   283 
   284 	return (mfi.thisptroffs >= 0);
   285 }
   286 
   287 void BaseProvider::DisplayError(const char *fmt, ...)
   288 {
   289 	va_list ap;
   290 	char buffer[2048];
   291 
   292 	va_start(ap, fmt);
   293 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   294 	va_end(ap);
   295 
   296 	Error("%s", buffer);
   297 }
   298 
   299 void BaseProvider::DisplayWarning(const char *fmt, ...)
   300 {
   301 	va_list ap;
   302 	char buffer[2048];
   303 
   304 	va_start(ap, fmt);
   305 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   306 	va_end(ap);
   307 
   308 	Warning("%s", buffer);
   309 }
   310 
   311 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   312 {
   313 	return &g_SMConVarAccessor;
   314 }
   315 
   316 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   317 {
   318 	return g_SMConVarAccessor.Register(pCommand);
   319 }
   320 
   321 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   322 {
   323 	return g_SMConVarAccessor.Unregister(pCommand);
   324 }
   325 
   326 int BaseProvider::GetUserMessageCount()
   327 {
   328 #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_DOTA
   329 	return -1;
   330 #else
   331 	return (int)usermsgs_list.size();
   332 #endif
   333 }
   334 
   335 int BaseProvider::FindUserMessage(const char *name, int *size)
   336 {
   337 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   338 	{
   339 		if (usermsgs_list[i].name.compare(name) == 0)
   340 		{
   341 			if (size)
   342 			{
   343 				*size = usermsgs_list[i].size;
   344 			}
   345 			return (int)i;
   346 		}
   347 	}
   348 	
   349 	return -1;
   350 }
   351 
   352 const char *BaseProvider::GetUserMessage(int index, int *size)
   353 {
   354 	if (index < 0 || index >= (int)usermsgs_list.size())
   355 	{
   356 		return NULL;
   357 	}
   358 
   359 	if (size)
   360 	{
   361 		*size = usermsgs_list[index].size;
   362 	}
   363 
   364 	return usermsgs_list[index].name.c_str();
   365 }
   366 
   367 const char *BaseProvider::GetGameDescription()
   368 {
   369 	return server->GetGameDescription();
   370 }
   371 
   372 int BaseProvider::DetermineSourceEngine(const char *game)
   373 {
   374 #if SOURCE_ENGINE == SE_BLOODYGOODTIME
   375 	return SOURCE_ENGINE_BLOODYGOODTIME;
   376 #elif SOURCE_ENGINE == SE_ALIENSWARM
   377 	return SOURCE_ENGINE_ALIENSWARM;
   378 #elif SOURCE_ENGINE == SE_LEFT4DEAD2
   379 	return SOURCE_ENGINE_LEFT4DEAD2;
   380 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   381 	return SOURCE_ENGINE_LEFT4DEAD;
   382 #elif SOURCE_ENGINE == SE_ORANGEBOX
   383 	return SOURCE_ENGINE_ORANGEBOX;
   384 #elif SOURCE_ENGINE == SE_CSS
   385 	return SOURCE_ENGINE_CSS;
   386 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
   387 	return SOURCE_ENGINE_ORANGEBOXVALVE;
   388 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   389 	return SOURCE_ENGINE_DARKMESSIAH;
   390 #elif SOURCE_ENGINE == SE_EYE
   391 	return SOURCE_ENGINE_EYE;
   392 #elif SOURCE_ENGINE == SE_PORTAL2
   393 	return SOURCE_ENGINE_PORTAL2;
   394 #elif SOURCE_ENGINE == SE_CSGO
   395 	return SOURCE_ENGINE_CSGO;
   396 #elif SOURCE_ENGINE == SE_DOTA
   397 	return SOURCE_ENGINE_DOTA;
   398 #else
   399 #error "SOURCE_ENGINE not defined to a known value"
   400 #endif
   401 }
   402 
   403 ConVar *BaseProvider::CreateConVar(const char *name,
   404 								   const char *defval,
   405 								   const char *help,
   406 								   int flags)
   407 {
   408 	int newflags = 0;
   409 	if (flags & ConVarFlag_Notify)
   410 	{
   411 		newflags |= FCVAR_NOTIFY;
   412 	}
   413 	if (flags & ConVarFlag_SpOnly)
   414 	{
   415 		newflags |= FCVAR_SPONLY;
   416 	}
   417 
   418 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   419 
   420 	g_SMConVarAccessor.RegisterConCommandBase(pVar);
   421 
   422 	return pVar;
   423 }
   424 
   425 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   426 {
   427 	if (baseFs == NULL)
   428 	{
   429 		return false;
   430 	}
   431 
   432 	KeyValues *pValues;
   433 	const char *plugin_file, *p_alias;
   434 
   435 	pValues = new KeyValues("Metamod Plugin");
   436 
   437 	if (!pValues->LoadFromFile(baseFs, file))
   438 	{
   439 		pValues->deleteThis();
   440 		return false;
   441 	}
   442 
   443 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   444 	{
   445 		pValues->deleteThis();
   446 		return false;
   447 	}
   448 
   449 	UTIL_Format(path, path_len, "%s", plugin_file);
   450 
   451 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   452 	{
   453 		UTIL_Format(alias, alias_len, "%s", p_alias);
   454 	}
   455 	else
   456 	{
   457 		UTIL_Format(alias, alias_len, "");
   458 	}
   459 
   460 	pValues->deleteThis();
   461 
   462 	return true;
   463 }
   464 
   465 #if SOURCE_ENGINE >= SE_ORANGEBOX
   466 class GlobCommand : public IMetamodSourceCommandInfo
   467 {
   468 public:
   469 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   470 	{
   471 	}
   472 public:
   473 	unsigned int GetArgCount()
   474 	{
   475 		return m_cmd->ArgC() - 1;
   476 	}
   477 
   478 	const char *GetArg(unsigned int num)
   479 	{
   480 		return m_cmd->Arg(num);
   481 	}
   482 
   483 	const char *GetArgString()
   484 	{
   485 		return m_cmd->ArgS();
   486 	}
   487 private:
   488 	const CCommand *m_cmd;
   489 };
   490 #else
   491 class GlobCommand : public IMetamodSourceCommandInfo
   492 {
   493 public:
   494 	unsigned int GetArgCount()
   495 	{
   496 		return engine->Cmd_Argc() - 1;
   497 	}
   498 
   499 	const char *GetArg(unsigned int num)
   500 	{
   501 		return engine->Cmd_Argv(num);
   502 	}
   503 
   504 	const char *GetArgString()
   505 	{
   506 		return engine->Cmd_Args();
   507 	}
   508 };
   509 #endif
   510 
   511 #if SOURCE_ENGINE == SE_DOTA
   512 void LocalCommand_Meta(const CCommandContext &context, const CCommand &args)
   513 {
   514 	GlobCommand cmd(&args);
   515 #elif SOURCE_ENGINE >= SE_ORANGEBOX
   516 void LocalCommand_Meta(const CCommand &args)
   517 {
   518 	GlobCommand cmd(&args);
   519 #else
   520 void LocalCommand_Meta()
   521 {
   522 	GlobCommand cmd;
   523 #endif
   524 	Command_Meta(&cmd);
   525 }
   526 
   527 #if SOURCE_ENGINE == SE_DOTA
   528 void ClientCommand(CEntityIndex index, const CCommand &_cmd)
   529 {
   530 	int client = index.Get();
   531 	GlobCommand cmd(&_cmd);
   532 #elif SOURCE_ENGINE >= SE_ORANGEBOX
   533 void ClientCommand(edict_t *client, const CCommand &_cmd)
   534 {
   535 	GlobCommand cmd(&_cmd);
   536 #else
   537 void ClientCommand(edict_t *client)
   538 {
   539 	GlobCommand cmd;
   540 #endif
   541 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   542 	{
   543 		Command_ClientMeta(client, &cmd);
   544 		RETURN_META(MRES_SUPERCEDE);
   545 	}
   546 
   547 	RETURN_META(MRES_IGNORED);
   548 }
   549 
   550 #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_DOTA
   551 
   552 void CacheUserMessages()
   553 {
   554 }
   555 
   556 #else
   557 
   558 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
   559 void Detour_Error(const tchar *pMsg, ...)
   560 {
   561 	/* Jump back to setjmp() in CacheUserMessages() */
   562 	longjmp(usermsg_end, 1);
   563 }
   564 
   565 #define IA32_JMP_IMM32 0xE9
   566 
   567 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
   568  * early Orange Box. This is because Error() from tier0 gets called when a bad index is
   569  * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
   570  *
   571  * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
   572  * to a point before GetUserMessageInfo() is called. The detour is then removed and we
   573  * exit.
   574  */
   575 void CacheUserMessages()
   576 {
   577 	int q, size;
   578 	char buffer[256];
   579 	unsigned char *target, *detour;
   580 	unsigned char orig_bytes[5];
   581 
   582 	target = (unsigned char *)&Error;
   583 	detour = (unsigned char *)&Detour_Error;
   584 
   585 	/* Save bytes from target function */
   586 	memcpy(orig_bytes, target, sizeof(orig_bytes));
   587 
   588 	/* Patch in relative jump to our Error() detour */
   589 	SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   590 	target[0] = IA32_JMP_IMM32;
   591 	*(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
   592 
   593 	/* This is where longjmp() will end up */
   594 	if (setjmp(usermsg_end))
   595 	{
   596 		/* Restore bytes and memory protection */
   597 		memcpy(target, orig_bytes, sizeof(orig_bytes));
   598 		SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
   599 		return;
   600 	}
   601 
   602 	q = 0;
   603 
   604 	/* If GetUserMessageInfo() calls Error(), we should end up in our detour */
   605 	while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
   606 	{
   607 		usermsgs_list.push_back(UsrMsgInfo(size, buffer));
   608 		q++;
   609 	}
   610 
   611 	/* Jump back to setjmp() */
   612 	longjmp(usermsg_end, 1);
   613 }
   614 
   615 #endif