core/provider/provider_ep2.cpp
author Scott Ehlert <ds@alliedmods.net>
Mon Nov 17 00:57:17 2008 -0600 (2008-11-17)
changeset 557 0a8ad2b12708
parent 553 8fc4ad22c73d
child 589 8e97a1e960a5
permissions -rw-r--r--
Added Windows support for loader, core, and core-legacy
     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 #if SOURCE_ENGINE == SE_LEFT4DEAD
   364 	return SOURCE_ENGINE_LEFT4DEAD;
   365 #else
   366 	return SOURCE_ENGINE_ORANGEBOX;
   367 #endif
   368 }
   369 
   370 ConVar *BaseProvider::CreateConVar(const char *name,
   371 								   const char *defval,
   372 								   const char *help,
   373 								   int flags)
   374 {
   375 	int newflags = 0;
   376 	if (flags & ConVarFlag_Notify)
   377 	{
   378 		newflags |= FCVAR_NOTIFY;
   379 	}
   380 	if (flags & ConVarFlag_SpOnly)
   381 	{
   382 		newflags |= FCVAR_SPONLY;
   383 	}
   384 
   385 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   386 
   387 	RegisterConCommandBase(pVar);
   388 	conbases_unreg.push_back(pVar);
   389 
   390 	return pVar;
   391 }
   392 
   393 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
   394 {
   395 	if (version > 2)
   396 	{
   397 		return NULL;
   398 	}
   399 
   400 	g_VspListener.SetLoadable(true);
   401 	return &g_VspListener;
   402 }
   403 
   404 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   405 {
   406 	if (baseFs == NULL)
   407 	{
   408 		return false;
   409 	}
   410 
   411 	KeyValues *pValues;
   412 	const char *plugin_file, *p_alias;
   413 
   414 	pValues = new KeyValues("Metamod Plugin");
   415 
   416 	if (!pValues->LoadFromFile(baseFs, file))
   417 	{
   418 		pValues->deleteThis();
   419 		return false;
   420 	}
   421 
   422 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   423 	{
   424 		pValues->deleteThis();
   425 		return false;
   426 	}
   427 
   428 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   429 	{
   430 		UTIL_Format(alias, alias_len, "%s", p_alias);
   431 	}
   432 	else
   433 	{
   434 		UTIL_Format(alias, alias_len, "");
   435 	}
   436 
   437 	/* Attempt to find a file extension */
   438 	if (UTIL_GetExtension(plugin_file) == NULL)
   439 	{
   440 		g_pMetamod->PathFormat(path, 
   441 			path_len, 
   442 			"%s/%s%s", 
   443 			g_pMetamod->GetBaseDir(), 
   444 			plugin_file, 
   445 #if defined WIN32 || defined _WIN32
   446 			".dll"
   447 #else
   448 			"_i486.so"
   449 #endif
   450 			);
   451 	}
   452 	else
   453 	{
   454 		g_pMetamod->PathFormat(path,
   455 			path_len,
   456 			"%s/%s", 
   457 			g_pMetamod->GetBaseDir(),
   458 			plugin_file);
   459 	}
   460 
   461 	pValues->deleteThis();
   462 
   463 	return true;
   464 }
   465 
   466 class GlobCommand : public IMetamodSourceCommandInfo
   467 {
   468 public:
   469 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   470 	{
   471 	}
   472 public:
   473 	unsigned int GetArgCount()
   474 	{
   475 		return m_cmd->ArgC() - 1;
   476 	}
   477 
   478 	const char *GetArg(unsigned int num)
   479 	{
   480 		return m_cmd->Arg(num);
   481 	}
   482 
   483 	const char *GetArgString()
   484 	{
   485 		return m_cmd->ArgS();
   486 	}
   487 private:
   488 	const CCommand *m_cmd;
   489 };
   490 
   491 void LocalCommand_Meta(const CCommand &args)
   492 {
   493 	GlobCommand cmd(&args);
   494 	Command_Meta(&cmd);
   495 }
   496 
   497 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   498 {
   499 	GlobCommand cmd(&_cmd);
   500 
   501 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   502 	{
   503 		Command_ClientMeta(pEdict, &cmd);
   504 		RETURN_META(MRES_SUPERCEDE);
   505 	}
   506 
   507 	RETURN_META(MRES_IGNORED);
   508 }
   509 
   510 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   511 {
   512 	unsigned char *addr1 = (unsigned char *)_addr1;
   513 	unsigned char *addr2 = (unsigned char *)_addr2;
   514 
   515 	for (size_t i=0; i<len; i++)
   516 	{
   517 		if (addr2[i] == '*')
   518 		{
   519 			continue;
   520 		}
   521 		if (addr1[i] != addr2[i])
   522 		{
   523 			return false;
   524 		}
   525 	}
   526 
   527 	return true;
   528 }
   529 
   530 //////////////////////////////////////////////////////////////////////
   531 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   532 // Signatures necessary in finding the pointer to the CUtlDict that //
   533 //   stores user message information.                               //
   534 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   535 //   message indices. This is our answer to it. Yuck! <:-(          //
   536 //////////////////////////////////////////////////////////////////////
   537 #ifdef OS_WIN32
   538 	/* General Windows sig */
   539 	#define MSGCLASS_SIGLEN		7
   540 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   541 	#define MSGCLASS_OFFS		2
   542 
   543 	/* Dystopia Wimdows hack */
   544 	#define MSGCLASS2_SIGLEN	16
   545 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   546 	#define MSGCLASS2_OFFS		11
   547 
   548 	/* Windows frame pointer sig */
   549 	#define MSGCLASS3_SIGLEN	18
   550 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   551 	#define MSGCLASS3_OFFS		13
   552 #elif defined OS_LINUX
   553 	/* No frame pointer sig */
   554 	#define MSGCLASS_SIGLEN		14
   555 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   556 	#define MSGCLASS_OFFS		9
   557 
   558 	/* Frame pointer sig */
   559 	#define MSGCLASS2_SIGLEN	16
   560 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   561 	#define MSGCLASS2_OFFS		11
   562 #endif
   563 
   564 struct UserMessage
   565 {
   566 	int size;
   567 	const char *name;
   568 };
   569 
   570 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   571 
   572 /* This is the ugliest function in all of SourceMM */
   573 bool CacheUserMessages()
   574 {
   575 	/* Get address of original GetUserMessageInfo() */
   576 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   577 
   578 	/* Oh dear, we have a relative jump on our hands
   579 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   580 	 */
   581 	if (*vfunc == '\xE9')
   582 	{
   583 		/* Get address from displacement...
   584 		 *
   585 		 * Add 5 because it's relative to next instruction:
   586 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   587 		 */
   588 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   589 	}
   590 
   591 	CUtlDict<UserMessage *, int> *dict = NULL;
   592 
   593 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   594 	{
   595 		/* Get address of CUserMessages instance */
   596 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   597 
   598 		/* Get address of CUserMessages::m_UserMessages */
   599 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   600 	} 
   601 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   602 	{
   603 	#ifdef OS_WIN32
   604 		/* If we get here, the code is possibly inlined like in Dystopia */
   605 
   606 		/* Get the address of the CUtlRBTree */
   607 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   608 
   609 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   610 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   611 	#elif defined OS_LINUX
   612 		/* Get address of CUserMessages instance */
   613 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   614 
   615 		/* Get address of CUserMessages::m_UserMessages */
   616 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   617 	#endif
   618 	#ifdef OS_WIN32
   619 	} 
   620 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   621 	{
   622 		/* Get address of CUserMessages instance */
   623 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   624 
   625 		/* Get address of CUserMessages::m_UserMessages */
   626 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   627 	#endif
   628 	}
   629 
   630 	#if !defined OS_WIN32
   631 	if (dict == NULL)
   632 	{
   633 		char path[255];
   634 		if (GetFileOfAddress(vfunc, path, sizeof(path)))
   635 		{
   636 			void *handle = dlopen(path, RTLD_NOW);
   637 			if (handle != NULL)
   638 			{
   639 				void *addr = dlsym(handle, "usermessages");
   640 				if (addr == NULL)
   641 				{
   642 					return false;
   643 				}
   644 				dict = (UserMsgDict *)*(void **)addr;
   645 				dlclose(handle);
   646 			}
   647 		}
   648 	}
   649 	#endif
   650 
   651 	if (dict != NULL)
   652 	{
   653 		int msg_count = dict->Count();
   654 
   655 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   656 		if (msg_count < 0 || msg_count > 255)
   657 		{
   658 			return false;
   659 		}
   660 
   661 		UserMessage *msg;
   662 		UsrMsgInfo u_msg;
   663 
   664 		/* Cache messages in our CUtlDict */
   665 		for (int i = 0; i < msg_count; i++)
   666 		{
   667 			msg = dict->Element(i);
   668 			u_msg.name = msg->name;
   669 			u_msg.size = msg->size;
   670 			usermsgs_list.push_back(u_msg);
   671 		}
   672 
   673 		return true;
   674 	}
   675 
   676 	return false;
   677 }
   678