sourcemm/episode2/provider_ep2.cpp
author Scott Ehlert <ds@alliedmods.net>
Sun Feb 17 09:19:52 2008 +0000 (2008-02-17)
changeset 495 e091f2b5e913
parent 485 d8f0a0416936
child 517 60d79cd53da2
permissions -rw-r--r--
Minor fixes so 1.6 builds with new Orange Box SDK
     1 
     2 /**
     3  * vim: set ts=4 :
     4  * ======================================================
     5  * Metamod:Source
     6  * Copyright (C) 2004-2007 AlliedModders LLC and authors.
     7  * All rights reserved.
     8  * ======================================================
     9  *
    10  * This software is provided 'as-is', without any express or implied warranty.
    11  * In no event will the authors be held liable for any damages arising from 
    12  * the use of this software.
    13  * 
    14  * Permission is granted to anyone to use this software for any purpose, 
    15  * including commercial applications, and to alter it and redistribute it 
    16  * freely, subject to the following restrictions:
    17  *
    18  * 1. The origin of this software must not be misrepresented; you must not 
    19  * claim that you wrote the original software. If you use this software in a 
    20  * product, an acknowledgment in the product documentation would be 
    21  * appreciated but is not required.
    22  * 2. Altered source versions must be plainly marked as such, and must not be
    23  * misrepresented as being the original software.
    24  * 3. This notice may not be removed or altered from any source distribution.
    25  *
    26  * Version: $Id$
    27  */
    28 
    29 #include "../metamod_oslink.h"
    30 #include <sourcehook.h>
    31 #include <convar.h>
    32 #include <eiface.h>
    33 #include <tier0/icommandline.h>
    34 #include <tier1/utldict.h>
    35 #include <sh_vector.h>
    36 #include <sh_string.h>
    37 #include "../metamod_util.h"
    38 #include "provider_ep2.h"
    39 #include "console.h"
    40 #include "metamod_console.h"
    41 #include "vsp_listener.h"
    42 #include <filesystem.h>
    43 
    44 /* Types */
    45 typedef void (*CONPRINTF_FUNC)(const char *, ...);
    46 struct UsrMsgInfo
    47 {
    48 	int size;
    49 	String name;
    50 };
    51 /* Imports */
    52 #undef CommandLine
    53 DLL_IMPORT ICommandLine *CommandLine();
    54 /* Functions */
    55 bool CacheUserMessages();
    56 void ClientCommand(edict_t *pEdict, const CCommand &args);
    57 void LocalCommand_Meta(const CCommand &args);
    58 void _ServerCommand();
    59 /* Variables */
    60 bool usermsgs_extracted = false;
    61 CVector<UsrMsgInfo> usermsgs_list;
    62 ICvar *icvar = NULL;
    63 ISmmAPI *metamod_api = NULL;
    64 IVEngineServer *engine = NULL;
    65 IServerGameClients *gameclients = NULL;
    66 VSPListener g_VspListener;
    67 BaseProvider g_Ep1Provider;
    68 IMetamodSourceProvider *provider = &g_Ep1Provider;
    69 List<ConCommandBase *> conbases_unreg;
    70 IFileSystem *baseFs = NULL;
    71 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
    72 
    73 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    74 
    75 void BaseProvider::ConsolePrint(const char *str)
    76 {
    77 	ConMsg("%s", str);
    78 }
    79 
    80 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory, 
    81 									  CreateInterfaceFn serverFactory)
    82 {
    83 	engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
    84 	if (!engine)
    85 	{
    86 		DisplayError("Could not find IVEngineServer! Metamod cannot load.");
    87 		return;
    88 	}
    89 	icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
    90 	if (!icvar)
    91 	{
    92 		DisplayError("Could not find ICvar! Metamod cannot load.");
    93 		return;
    94 	}
    95 	g_pCVar = icvar;
    96 
    97 	if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
    98 		== NULL)
    99 	{
   100 		gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
   101 	}
   102 
   103 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   104 	if (baseFs == NULL)
   105 	{
   106 		::LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
   107 		return;
   108 	}
   109 
   110 	RegisterConCommandBase(&meta_local_cmd);
   111 	conbases_unreg.push_back(&meta_local_cmd);
   112 
   113 	usermsgs_extracted = CacheUserMessages();
   114 
   115 	if (gameclients)
   116 	{
   117 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   118 	}
   119 }
   120 
   121 void BaseProvider::Notify_DLLShutdown_Pre()
   122 {
   123 	List<ConCommandBase *>::iterator iter;
   124 
   125 	for (iter = conbases_unreg.begin();
   126 		 iter != conbases_unreg.end();
   127 		 iter++)
   128 	{
   129 		UnregisterConCommandBase((*iter));
   130 	}
   131 }
   132 
   133 bool BaseProvider::IsRemotePrintingAvailable()
   134 {
   135 	return true;
   136 }
   137 
   138 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
   139 {
   140 	engine->ClientPrintf(client, message);
   141 }
   142 
   143 void BaseProvider::ServerCommand(const char *cmd)
   144 {
   145 	engine->ServerCommand(cmd);
   146 }
   147 
   148 const char *BaseProvider::GetConVarString(ConVar *convar)
   149 {
   150 	if (convar == NULL)
   151 	{
   152 		return NULL;
   153 	}
   154 
   155 	return convar->GetString();
   156 }
   157 
   158 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
   159 {
   160 	convar->SetValue(str);
   161 }
   162 
   163 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   164 {
   165 	return pCommand->IsCommand();
   166 }
   167 
   168 
   169 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   170 {
   171 	return (build == SOURCE_ENGINE_ORIGINAL
   172 			|| build == SOURCE_ENGINE_EPISODEONE);
   173 }
   174 
   175 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   176 {
   177 	if (key[0] == '-' || key[0] == '+')
   178 	{
   179 		return CommandLine_Tier0()->ParmValue(key, defval);
   180 	}
   181 	else if (icvar)
   182 	{
   183 		const char *val;
   184 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   185 		{
   186 			return defval;
   187 		}
   188 
   189 		return val;
   190 	}
   191 
   192 	return NULL;
   193 }
   194 
   195 int BaseProvider::TryServerGameDLL(const char *iface)
   196 {
   197 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   198 	{
   199 		return 0;
   200 	}
   201 
   202 	return atoi(&iface[13]);
   203 }
   204 
   205 bool BaseProvider::LogMessage(const char *buffer)
   206 {
   207 	if (!engine)
   208 	{
   209 		return false;
   210 	}
   211 
   212 	engine->LogPrint(buffer);
   213 
   214 	return true;
   215 }
   216 
   217 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   218 {
   219 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   220 
   221 	if (hook == ProvidedHook_LevelInit)
   222 	{
   223 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   224 	}
   225 	else if (hook == ProvidedHook_LevelShutdown)
   226 	{
   227 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   228 	}
   229 	else if (hook == ProvidedHook_GameInit)
   230 	{
   231 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   232 	}
   233 	else if (hook == ProvidedHook_DLLShutdown)
   234 	{
   235 		SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
   236 	}
   237 	else if (hook == ProvidedHook_DLLInit)
   238 	{
   239 		SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
   240 	}
   241 
   242 	*pInfo = mfi;
   243 
   244 	return (mfi.thisptroffs >= 0);
   245 }
   246 
   247 void BaseProvider::DisplayError(const char *fmt, ...)
   248 {
   249 	va_list ap;
   250 	char buffer[2048];
   251 
   252 	va_start(ap, fmt);
   253 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   254 	va_end(ap);
   255 
   256 	Error(buffer);
   257 }
   258 
   259 void BaseProvider::DisplayWarning(const char *fmt, ...)
   260 {
   261 	va_list ap;
   262 	char buffer[2048];
   263 
   264 	va_start(ap, fmt);
   265 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   266 	va_end(ap);
   267 
   268 	Warning(buffer);
   269 }
   270 
   271 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   272 {
   273 	return &g_SMConVarAccessor;
   274 }
   275 
   276 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   277 {
   278 	return g_SMConVarAccessor.Register(pCommand);
   279 }
   280 
   281 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   282 {
   283 	return g_SMConVarAccessor.Unregister(pCommand);
   284 }
   285 
   286 int BaseProvider::GetUserMessageCount()
   287 {
   288 	if (!usermsgs_extracted)
   289 	{
   290 		return -1;
   291 	}
   292 
   293 	return (int)usermsgs_list.size();
   294 }
   295 
   296 int BaseProvider::FindUserMessage(const char *name, int *size)
   297 {
   298 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   299 	{
   300 		if (usermsgs_list[i].name.compare(name) == 0)
   301 		{
   302 			if (size)
   303 			{
   304 				*size = usermsgs_list[i].size;
   305 			}
   306 			return (int)i;
   307 		}
   308 	}
   309 	
   310 	return -1;
   311 }
   312 
   313 const char *BaseProvider::GetUserMessage(int index, int *size)
   314 {
   315 	if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
   316 	{
   317 		return NULL;
   318 	}
   319 
   320 	if (size)
   321 	{
   322 		*size = usermsgs_list[index].size;
   323 	}
   324 
   325 	return usermsgs_list[index].name.c_str();
   326 }
   327 
   328 const char *BaseProvider::GetGameDescription()
   329 {
   330 	return server->GetGameDescription();
   331 }
   332 
   333 int BaseProvider::DetermineSourceEngine(const char *game)
   334 {
   335 	return SOURCE_ENGINE_ORANGEBOX;
   336 }
   337 
   338 ConVar *BaseProvider::CreateConVar(const char *name,
   339 								   const char *defval,
   340 								   const char *help,
   341 								   int flags)
   342 {
   343 	int newflags = 0;
   344 	if (flags & ConVarFlag_Notify)
   345 	{
   346 		newflags |= FCVAR_NOTIFY;
   347 	}
   348 	if (flags & ConVarFlag_Replicated)
   349 	{
   350 		newflags |= FCVAR_REPLICATED;
   351 	}
   352 	if (flags & ConVarFlag_SpOnly)
   353 	{
   354 		newflags |= FCVAR_SPONLY;
   355 	}
   356 
   357 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   358 
   359 	RegisterConCommandBase(pVar);
   360 	conbases_unreg.push_back(pVar);
   361 
   362 	return pVar;
   363 }
   364 
   365 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
   366 {
   367 	g_VspListener.SetLoadable(true);
   368 	return &g_VspListener;
   369 }
   370 
   371 bool BaseProvider::IsAlternatelyLoaded()
   372 {
   373 	return g_VspListener.IsRootLoadMethod();
   374 }
   375 
   376 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   377 {
   378 	if (baseFs == NULL)
   379 	{
   380 		return false;
   381 	}
   382 
   383 	KeyValues *pValues;
   384 	const char *plugin_file, *p_alias;
   385 
   386 	pValues = new KeyValues("Metamod Plugin");
   387 
   388 	if (!pValues->LoadFromFile(baseFs, file))
   389 	{
   390 		pValues->deleteThis();
   391 		return false;
   392 	}
   393 
   394 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   395 	{
   396 		pValues->deleteThis();
   397 		return false;
   398 	}
   399 
   400 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   401 	{
   402 		UTIL_Format(alias, alias_len, "%s", p_alias);
   403 	}
   404 	else
   405 	{
   406 		UTIL_Format(alias, alias_len, "");
   407 	}
   408 
   409 	/* Attempt to find a file extension */
   410 	if (UTIL_GetExtension(plugin_file) == NULL)
   411 	{
   412 		g_pMetamod->PathFormat(path, 
   413 			path_len, 
   414 			"%s/%s%s", 
   415 			g_pMetamod->GetBaseDir(), 
   416 			plugin_file, 
   417 #if defined WIN32 || defined _WIN32
   418 			".dll"
   419 #else
   420 			"_i486.so"
   421 #endif
   422 			);
   423 	}
   424 	else
   425 	{
   426 		g_pMetamod->PathFormat(path,
   427 			path_len,
   428 			"%s/%s", 
   429 			g_pMetamod->GetBaseDir(),
   430 			plugin_file);
   431 	}
   432 
   433 	pValues->deleteThis();
   434 
   435 	return true;
   436 }
   437 
   438 class GlobCommand : public IMetamodSourceCommandInfo
   439 {
   440 public:
   441 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   442 	{
   443 	}
   444 public:
   445 	unsigned int GetArgCount()
   446 	{
   447 		return m_cmd->ArgC() - 1;
   448 	}
   449 
   450 	const char *GetArg(unsigned int num)
   451 	{
   452 		return m_cmd->Arg(num);
   453 	}
   454 
   455 	const char *GetArgString()
   456 	{
   457 		return m_cmd->ArgS();
   458 	}
   459 private:
   460 	const CCommand *m_cmd;
   461 };
   462 
   463 void LocalCommand_Meta(const CCommand &args)
   464 {
   465 	GlobCommand cmd(&args);
   466 	Command_Meta(&cmd);
   467 }
   468 
   469 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   470 {
   471 	GlobCommand cmd(&_cmd);
   472 
   473 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   474 	{
   475 		Command_ClientMeta(pEdict, &cmd);
   476 		RETURN_META(MRES_SUPERCEDE);
   477 	}
   478 
   479 	RETURN_META(MRES_IGNORED);
   480 }
   481 
   482 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   483 {
   484 	unsigned char *addr1 = (unsigned char *)_addr1;
   485 	unsigned char *addr2 = (unsigned char *)_addr2;
   486 
   487 	for (size_t i=0; i<len; i++)
   488 	{
   489 		if (addr2[i] == '*')
   490 		{
   491 			continue;
   492 		}
   493 		if (addr1[i] != addr2[i])
   494 		{
   495 			return false;
   496 		}
   497 	}
   498 
   499 	return true;
   500 }
   501 
   502 //////////////////////////////////////////////////////////////////////
   503 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   504 // Signatures necessary in finding the pointer to the CUtlDict that //
   505 //   stores user message information.                               //
   506 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   507 //   message indices. This is our answer to it. Yuck! <:-(          //
   508 //////////////////////////////////////////////////////////////////////
   509 #ifdef OS_WIN32
   510 	/* General Windows sig */
   511 	#define MSGCLASS_SIGLEN		7
   512 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   513 	#define MSGCLASS_OFFS		2
   514 
   515 	/* Dystopia Wimdows hack */
   516 	#define MSGCLASS2_SIGLEN	16
   517 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   518 	#define MSGCLASS2_OFFS		11
   519 
   520 	/* Windows frame pointer sig */
   521 	#define MSGCLASS3_SIGLEN	18
   522 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   523 	#define MSGCLASS3_OFFS		13
   524 #elif defined OS_LINUX
   525 	/* No frame pointer sig */
   526 	#define MSGCLASS_SIGLEN		14
   527 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   528 	#define MSGCLASS_OFFS		9
   529 
   530 	/* Frame pointer sig */
   531 	#define MSGCLASS2_SIGLEN	16
   532 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   533 	#define MSGCLASS2_OFFS		11
   534 #endif
   535 
   536 struct UserMessage
   537 {
   538 	int size;
   539 	const char *name;
   540 };
   541 
   542 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   543 
   544 /* This is the ugliest function in all of SourceMM */
   545 bool CacheUserMessages()
   546 {
   547 	/* Get address of original GetUserMessageInfo() */
   548 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   549 
   550 	/* Oh dear, we have a relative jump on our hands
   551 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   552 	 */
   553 	if (*vfunc == '\xE9')
   554 	{
   555 		/* Get address from displacement...
   556 		 *
   557 		 * Add 5 because it's relative to next instruction:
   558 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   559 		 */
   560 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   561 	}
   562 
   563 	CUtlDict<UserMessage *, int> *dict = NULL;
   564 
   565 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   566 	{
   567 		/* Get address of CUserMessages instance */
   568 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   569 
   570 		/* Get address of CUserMessages::m_UserMessages */
   571 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   572 	} 
   573 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   574 	{
   575 	#ifdef OS_WIN32
   576 		/* If we get here, the code is possibly inlined like in Dystopia */
   577 
   578 		/* Get the address of the CUtlRBTree */
   579 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   580 
   581 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   582 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   583 	#elif defined OS_LINUX
   584 		/* Get address of CUserMessages instance */
   585 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   586 
   587 		/* Get address of CUserMessages::m_UserMessages */
   588 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   589 	#endif
   590 	#ifdef OS_WIN32
   591 	} 
   592 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   593 	{
   594 		/* Get address of CUserMessages instance */
   595 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   596 
   597 		/* Get address of CUserMessages::m_UserMessages */
   598 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   599 	#endif
   600 	}
   601 
   602 	#if !defined OS_WIN32
   603 	if (dict == NULL)
   604 	{
   605 		char path[255];
   606 		if (GetFileOfAddress(vfunc, path, sizeof(path)))
   607 		{
   608 			void *handle = dlopen(path, RTLD_NOW);
   609 			if (handle != NULL)
   610 			{
   611 				void *addr = dlsym(handle, "usermessages");
   612 				dict = (UserMsgDict *)*(void **)addr;
   613 				dlclose(handle);
   614 			}
   615 		}
   616 	}
   617 	#endif
   618 
   619 	if (dict != NULL)
   620 	{
   621 		int msg_count = dict->Count();
   622 
   623 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   624 		if (msg_count < 0 || msg_count > 255)
   625 		{
   626 			return false;
   627 		}
   628 
   629 		UserMessage *msg;
   630 		UsrMsgInfo u_msg;
   631 
   632 		/* Cache messages in our CUtlDict */
   633 		for (int i = 0; i < msg_count; i++)
   634 		{
   635 			msg = dict->Element(i);
   636 			u_msg.name = msg->name;
   637 			u_msg.size = msg->size;
   638 			usermsgs_list.push_back(u_msg);
   639 		}
   640 
   641 		return true;
   642 	}
   643 
   644 	return false;
   645 }
   646