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