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