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