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