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