core/provider/provider_ep2.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Tue Oct 08 21:01:53 2013 -0400 (2013-10-08)
changeset 856 4bf3ed73bba4
parent 850 3d9258ef9a30
child 857 d8cc9c7087b0
permissions -rw-r--r--
Add support for Source SDK Base 2013 (bug 5916, r=asherkin).
     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_NUCLEARDAWN
   381 	return SOURCE_ENGINE_NUCLEARDAWN;
   382 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   383 	return SOURCE_ENGINE_LEFT4DEAD;
   384 #elif SOURCE_ENGINE == SE_ORANGEBOX
   385 	return SOURCE_ENGINE_ORANGEBOX;
   386 #elif SOURCE_ENGINE == SE_CSS
   387 	return SOURCE_ENGINE_CSS;
   388 #elif SOURCE_ENGINE == SE_HL2DM
   389 	return SOURCE_ENGINE_HL2DM;
   390 #elif SOURCE_ENGINE == SE_DODS
   391 	return SOURCE_ENGINE_DODS;
   392 #elif SOURCE_ENGINE == SE_SDK2013
   393 	return SOURCE_ENGINE_SDK2013;
   394 #elif SOURCE_ENGINE == SE_TF2
   395 	return SOURCE_ENGINE_TF2;
   396 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   397 	return SOURCE_ENGINE_DARKMESSIAH;
   398 #elif SOURCE_ENGINE == SE_EYE
   399 	return SOURCE_ENGINE_EYE;
   400 #elif SOURCE_ENGINE == SE_PORTAL2
   401 	return SOURCE_ENGINE_PORTAL2;
   402 #elif SOURCE_ENGINE == SE_CSGO
   403 	return SOURCE_ENGINE_CSGO;
   404 #elif SOURCE_ENGINE == SE_DOTA
   405 	return SOURCE_ENGINE_DOTA;
   406 #else
   407 #error "SOURCE_ENGINE not defined to a known value"
   408 #endif
   409 }
   410 
   411 ConVar *BaseProvider::CreateConVar(const char *name,
   412 								   const char *defval,
   413 								   const char *help,
   414 								   int flags)
   415 {
   416 	int newflags = 0;
   417 	if (flags & ConVarFlag_Notify)
   418 	{
   419 		newflags |= FCVAR_NOTIFY;
   420 	}
   421 	if (flags & ConVarFlag_SpOnly)
   422 	{
   423 		newflags |= FCVAR_SPONLY;
   424 	}
   425 
   426 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   427 
   428 	g_SMConVarAccessor.RegisterConCommandBase(pVar);
   429 
   430 	return pVar;
   431 }
   432 
   433 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   434 {
   435 	if (baseFs == NULL)
   436 	{
   437 		return false;
   438 	}
   439 
   440 	KeyValues *pValues;
   441 	const char *plugin_file, *p_alias;
   442 
   443 	pValues = new KeyValues("Metamod Plugin");
   444 
   445 	if (!pValues->LoadFromFile(baseFs, file))
   446 	{
   447 		pValues->deleteThis();
   448 		return false;
   449 	}
   450 
   451 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   452 	{
   453 		pValues->deleteThis();
   454 		return false;
   455 	}
   456 
   457 	UTIL_Format(path, path_len, "%s", plugin_file);
   458 
   459 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   460 	{
   461 		UTIL_Format(alias, alias_len, "%s", p_alias);
   462 	}
   463 	else
   464 	{
   465 		UTIL_Format(alias, alias_len, "");
   466 	}
   467 
   468 	pValues->deleteThis();
   469 
   470 	return true;
   471 }
   472 
   473 #if SOURCE_ENGINE >= SE_ORANGEBOX
   474 class GlobCommand : public IMetamodSourceCommandInfo
   475 {
   476 public:
   477 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   478 	{
   479 	}
   480 public:
   481 	unsigned int GetArgCount()
   482 	{
   483 		return m_cmd->ArgC() - 1;
   484 	}
   485 
   486 	const char *GetArg(unsigned int num)
   487 	{
   488 		return m_cmd->Arg(num);
   489 	}
   490 
   491 	const char *GetArgString()
   492 	{
   493 		return m_cmd->ArgS();
   494 	}
   495 private:
   496 	const CCommand *m_cmd;
   497 };
   498 #else
   499 class GlobCommand : public IMetamodSourceCommandInfo
   500 {
   501 public:
   502 	unsigned int GetArgCount()
   503 	{
   504 		return engine->Cmd_Argc() - 1;
   505 	}
   506 
   507 	const char *GetArg(unsigned int num)
   508 	{
   509 		return engine->Cmd_Argv(num);
   510 	}
   511 
   512 	const char *GetArgString()
   513 	{
   514 		return engine->Cmd_Args();
   515 	}
   516 };
   517 #endif
   518 
   519 #if SOURCE_ENGINE == SE_DOTA
   520 void LocalCommand_Meta(const CCommandContext &context, const CCommand &args)
   521 {
   522 	GlobCommand cmd(&args);
   523 #elif SOURCE_ENGINE >= SE_ORANGEBOX
   524 void LocalCommand_Meta(const CCommand &args)
   525 {
   526 	GlobCommand cmd(&args);
   527 #else
   528 void LocalCommand_Meta()
   529 {
   530 	GlobCommand cmd;
   531 #endif
   532 	Command_Meta(&cmd);
   533 }
   534 
   535 #if SOURCE_ENGINE == SE_DOTA
   536 void ClientCommand(CEntityIndex index, const CCommand &_cmd)
   537 {
   538 	int client = index.Get();
   539 	GlobCommand cmd(&_cmd);
   540 #elif SOURCE_ENGINE >= SE_ORANGEBOX
   541 void ClientCommand(edict_t *client, const CCommand &_cmd)
   542 {
   543 	GlobCommand cmd(&_cmd);
   544 #else
   545 void ClientCommand(edict_t *client)
   546 {
   547 	GlobCommand cmd;
   548 #endif
   549 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   550 	{
   551 		Command_ClientMeta(client, &cmd);
   552 		RETURN_META(MRES_SUPERCEDE);
   553 	}
   554 
   555 	RETURN_META(MRES_IGNORED);
   556 }
   557 
   558 #if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_DOTA
   559 
   560 void CacheUserMessages()
   561 {
   562 }
   563 
   564 #else
   565 
   566 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
   567 void Detour_Error(const tchar *pMsg, ...)
   568 {
   569 	/* Jump back to setjmp() in CacheUserMessages() */
   570 	longjmp(usermsg_end, 1);
   571 }
   572 
   573 #define IA32_JMP_IMM32 0xE9
   574 
   575 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
   576  * early Orange Box. This is because Error() from tier0 gets called when a bad index is
   577  * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
   578  *
   579  * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
   580  * to a point before GetUserMessageInfo() is called. The detour is then removed and we
   581  * exit.
   582  */
   583 void CacheUserMessages()
   584 {
   585 	int q, size;
   586 	char buffer[256];
   587 	unsigned char *target, *detour;
   588 	unsigned char orig_bytes[5];
   589 
   590 	target = (unsigned char *)&Error;
   591 	detour = (unsigned char *)&Detour_Error;
   592 
   593 	/* Save bytes from target function */
   594 	memcpy(orig_bytes, target, sizeof(orig_bytes));
   595 
   596 	/* Patch in relative jump to our Error() detour */
   597 	SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   598 	target[0] = IA32_JMP_IMM32;
   599 	*(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
   600 
   601 	/* This is where longjmp() will end up */
   602 	if (setjmp(usermsg_end))
   603 	{
   604 		/* Restore bytes and memory protection */
   605 		memcpy(target, orig_bytes, sizeof(orig_bytes));
   606 		SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
   607 		return;
   608 	}
   609 
   610 	q = 0;
   611 
   612 	/* If GetUserMessageInfo() calls Error(), we should end up in our detour */
   613 	while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
   614 	{
   615 		usermsgs_list.push_back(UsrMsgInfo(size, buffer));
   616 		q++;
   617 	}
   618 
   619 	/* Jump back to setjmp() */
   620 	longjmp(usermsg_end, 1);
   621 }
   622 
   623 #endif