core/provider/provider_ep2.cpp
author Scott Ehlert <ds@alliedmods.net>
Mon Dec 22 22:55:55 2008 -0600 (2008-12-22)
changeset 626 08879e2aa990
parent 589 8e97a1e960a5
child 637 b66489d8aedc
permissions -rw-r--r--
Fixed bug where plugin aliases defined in VDF files on core (Orange Box and L4D engines) didn't work.
     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 
   262 	*pInfo = mfi;
   263 
   264 	return (mfi.thisptroffs >= 0);
   265 }
   266 
   267 void BaseProvider::DisplayError(const char *fmt, ...)
   268 {
   269 	va_list ap;
   270 	char buffer[2048];
   271 
   272 	va_start(ap, fmt);
   273 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   274 	va_end(ap);
   275 
   276 	Error(buffer);
   277 }
   278 
   279 void BaseProvider::DisplayWarning(const char *fmt, ...)
   280 {
   281 	va_list ap;
   282 	char buffer[2048];
   283 
   284 	va_start(ap, fmt);
   285 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   286 	va_end(ap);
   287 
   288 	Warning(buffer);
   289 }
   290 
   291 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   292 {
   293 	return &g_SMConVarAccessor;
   294 }
   295 
   296 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   297 {
   298 	return g_SMConVarAccessor.Register(pCommand);
   299 }
   300 
   301 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   302 {
   303 	return g_SMConVarAccessor.Unregister(pCommand);
   304 }
   305 
   306 int BaseProvider::GetUserMessageCount()
   307 {
   308 	if (!usermsgs_extracted)
   309 	{
   310 		return -1;
   311 	}
   312 
   313 	return (int)usermsgs_list.size();
   314 }
   315 
   316 int BaseProvider::FindUserMessage(const char *name, int *size)
   317 {
   318 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   319 	{
   320 		if (usermsgs_list[i].name.compare(name) == 0)
   321 		{
   322 			if (size)
   323 			{
   324 				*size = usermsgs_list[i].size;
   325 			}
   326 			return (int)i;
   327 		}
   328 	}
   329 	
   330 	return -1;
   331 }
   332 
   333 const char *BaseProvider::GetUserMessage(int index, int *size)
   334 {
   335 	if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
   336 	{
   337 		return NULL;
   338 	}
   339 
   340 	if (size)
   341 	{
   342 		*size = usermsgs_list[index].size;
   343 	}
   344 
   345 	return usermsgs_list[index].name.c_str();
   346 }
   347 
   348 const char *BaseProvider::GetGameDescription()
   349 {
   350 	return server->GetGameDescription();
   351 }
   352 
   353 int BaseProvider::DetermineSourceEngine(const char *game)
   354 {
   355 #if SOURCE_ENGINE == SE_LEFT4DEAD
   356 	return SOURCE_ENGINE_LEFT4DEAD;
   357 #else
   358 	return SOURCE_ENGINE_ORANGEBOX;
   359 #endif
   360 }
   361 
   362 ConVar *BaseProvider::CreateConVar(const char *name,
   363 								   const char *defval,
   364 								   const char *help,
   365 								   int flags)
   366 {
   367 	int newflags = 0;
   368 	if (flags & ConVarFlag_Notify)
   369 	{
   370 		newflags |= FCVAR_NOTIFY;
   371 	}
   372 	if (flags & ConVarFlag_SpOnly)
   373 	{
   374 		newflags |= FCVAR_SPONLY;
   375 	}
   376 
   377 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   378 
   379 	RegisterConCommandBase(pVar);
   380 	conbases_unreg.push_back(pVar);
   381 
   382 	return pVar;
   383 }
   384 
   385 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(int version)
   386 {
   387 	if (version > 2)
   388 	{
   389 		return NULL;
   390 	}
   391 
   392 	g_VspListener.SetLoadable(true);
   393 	return &g_VspListener;
   394 }
   395 
   396 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   397 {
   398 	if (baseFs == NULL)
   399 	{
   400 		return false;
   401 	}
   402 
   403 	KeyValues *pValues;
   404 	const char *plugin_file, *p_alias;
   405 
   406 	pValues = new KeyValues("Metamod Plugin");
   407 
   408 	if (!pValues->LoadFromFile(baseFs, file))
   409 	{
   410 		pValues->deleteThis();
   411 		return false;
   412 	}
   413 
   414 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   415 	{
   416 		pValues->deleteThis();
   417 		return false;
   418 	}
   419 
   420 	UTIL_Format(path, path_len, "%s", plugin_file);
   421 
   422 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   423 	{
   424 		UTIL_Format(alias, alias_len, "%s", p_alias);
   425 	}
   426 	else
   427 	{
   428 		UTIL_Format(alias, alias_len, "");
   429 	}
   430 
   431 	pValues->deleteThis();
   432 
   433 	return true;
   434 }
   435 
   436 class GlobCommand : public IMetamodSourceCommandInfo
   437 {
   438 public:
   439 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   440 	{
   441 	}
   442 public:
   443 	unsigned int GetArgCount()
   444 	{
   445 		return m_cmd->ArgC() - 1;
   446 	}
   447 
   448 	const char *GetArg(unsigned int num)
   449 	{
   450 		return m_cmd->Arg(num);
   451 	}
   452 
   453 	const char *GetArgString()
   454 	{
   455 		return m_cmd->ArgS();
   456 	}
   457 private:
   458 	const CCommand *m_cmd;
   459 };
   460 
   461 void LocalCommand_Meta(const CCommand &args)
   462 {
   463 	GlobCommand cmd(&args);
   464 	Command_Meta(&cmd);
   465 }
   466 
   467 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   468 {
   469 	GlobCommand cmd(&_cmd);
   470 
   471 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   472 	{
   473 		Command_ClientMeta(pEdict, &cmd);
   474 		RETURN_META(MRES_SUPERCEDE);
   475 	}
   476 
   477 	RETURN_META(MRES_IGNORED);
   478 }
   479 
   480 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   481 {
   482 	unsigned char *addr1 = (unsigned char *)_addr1;
   483 	unsigned char *addr2 = (unsigned char *)_addr2;
   484 
   485 	for (size_t i=0; i<len; i++)
   486 	{
   487 		if (addr2[i] == '*')
   488 		{
   489 			continue;
   490 		}
   491 		if (addr1[i] != addr2[i])
   492 		{
   493 			return false;
   494 		}
   495 	}
   496 
   497 	return true;
   498 }
   499 
   500 //////////////////////////////////////////////////////////////////////
   501 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   502 // Signatures necessary in finding the pointer to the CUtlDict that //
   503 //   stores user message information.                               //
   504 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   505 //   message indices. This is our answer to it. Yuck! <:-(          //
   506 //////////////////////////////////////////////////////////////////////
   507 #ifdef OS_WIN32
   508 	/* General Windows sig */
   509 	#define MSGCLASS_SIGLEN		7
   510 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   511 	#define MSGCLASS_OFFS		2
   512 
   513 	/* Dystopia Wimdows hack */
   514 	#define MSGCLASS2_SIGLEN	16
   515 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   516 	#define MSGCLASS2_OFFS		11
   517 
   518 	/* Windows frame pointer sig */
   519 	#define MSGCLASS3_SIGLEN	18
   520 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   521 	#define MSGCLASS3_OFFS		13
   522 #elif defined OS_LINUX
   523 	/* No frame pointer sig */
   524 	#define MSGCLASS_SIGLEN		14
   525 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   526 	#define MSGCLASS_OFFS		9
   527 
   528 	/* Frame pointer sig */
   529 	#define MSGCLASS2_SIGLEN	16
   530 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   531 	#define MSGCLASS2_OFFS		11
   532 #endif
   533 
   534 struct UserMessage
   535 {
   536 	int size;
   537 	const char *name;
   538 };
   539 
   540 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   541 
   542 /* This is the ugliest function in all of SourceMM */
   543 bool CacheUserMessages()
   544 {
   545 	/* Get address of original GetUserMessageInfo() */
   546 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   547 
   548 	/* Oh dear, we have a relative jump on our hands
   549 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   550 	 */
   551 	if (*vfunc == '\xE9')
   552 	{
   553 		/* Get address from displacement...
   554 		 *
   555 		 * Add 5 because it's relative to next instruction:
   556 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   557 		 */
   558 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   559 	}
   560 
   561 	CUtlDict<UserMessage *, int> *dict = NULL;
   562 
   563 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   564 	{
   565 		/* Get address of CUserMessages instance */
   566 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   567 
   568 		/* Get address of CUserMessages::m_UserMessages */
   569 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   570 	} 
   571 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   572 	{
   573 	#ifdef OS_WIN32
   574 		/* If we get here, the code is possibly inlined like in Dystopia */
   575 
   576 		/* Get the address of the CUtlRBTree */
   577 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   578 
   579 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   580 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   581 	#elif defined OS_LINUX
   582 		/* Get address of CUserMessages instance */
   583 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   584 
   585 		/* Get address of CUserMessages::m_UserMessages */
   586 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   587 	#endif
   588 	#ifdef OS_WIN32
   589 	} 
   590 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   591 	{
   592 		/* Get address of CUserMessages instance */
   593 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   594 
   595 		/* Get address of CUserMessages::m_UserMessages */
   596 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   597 	#endif
   598 	}
   599 
   600 	#if !defined OS_WIN32
   601 	if (dict == NULL)
   602 	{
   603 		char path[255];
   604 		if (GetFileOfAddress(vfunc, path, sizeof(path)))
   605 		{
   606 			void *handle = dlopen(path, RTLD_NOW);
   607 			if (handle != NULL)
   608 			{
   609 				void *addr = dlsym(handle, "usermessages");
   610 				if (addr == NULL)
   611 				{
   612 					return false;
   613 				}
   614 				dict = (UserMsgDict *)*(void **)addr;
   615 				dlclose(handle);
   616 			}
   617 		}
   618 	}
   619 	#endif
   620 
   621 	if (dict != NULL)
   622 	{
   623 		int msg_count = dict->Count();
   624 
   625 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   626 		if (msg_count < 0 || msg_count > 255)
   627 		{
   628 			return false;
   629 		}
   630 
   631 		UserMessage *msg;
   632 		UsrMsgInfo u_msg;
   633 
   634 		/* Cache messages in our CUtlDict */
   635 		for (int i = 0; i < msg_count; i++)
   636 		{
   637 			msg = dict->Element(i);
   638 			u_msg.name = msg->name;
   639 			u_msg.size = msg->size;
   640 			usermsgs_list.push_back(u_msg);
   641 		}
   642 
   643 		return true;
   644 	}
   645 
   646 	return false;
   647 }
   648