sourcemm/episode2/provider_ep2.cpp
author David Anderson <dvander@alliedmods.net>
Sat Nov 24 06:11:23 2007 +0000 (2007-11-24)
changeset 472 6b2d311e4c01
parent 408 a0f99231cf3b
child 481 5a2e34651450
permissions -rw-r--r--
fixed amb1113 - mm_pluginsfile crashed on MM:S 1.6
     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 #if defined _DEBUG
    30 #define DEBUG2
    31 #undef _DEBUG
    32 #endif
    33 #include <sourcehook.h>
    34 #include <convar.h>
    35 #include <eiface.h>
    36 #include <tier0/icommandline.h>
    37 #include <tier1/utldict.h>
    38 #include <sh_vector.h>
    39 #include <sh_string.h>
    40 #include "../metamod_util.h"
    41 #include "provider_ep2.h"
    42 #include "console.h"
    43 #include "metamod_console.h"
    44 #include "vsp_listener.h"
    45 #if defined DEBUG2
    46 #undef DEBUG2
    47 #define _DEBUG
    48 #endif
    49 
    50 /* Types */
    51 typedef void (*CONPRINTF_FUNC)(const char *, ...);
    52 struct UsrMsgInfo
    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 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
    77 
    78 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    79 
    80 void BaseProvider::ConsolePrint(const char *str)
    81 {
    82 	ConMsg("%s", str);
    83 }
    84 
    85 void BaseProvider::Notify_DLLInit_Pre(void *gamedll,
    86 									  CreateInterfaceFn engineFactory, 
    87 									  CreateInterfaceFn serverFactory)
    88 {
    89 	server = (IServerGameDLL *)gamedll;
    90 	engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
    91 	if (!engine)
    92 	{
    93 		DisplayError("Could not find IVEngineServer! Metamod cannot load.");
    94 		return;
    95 	}
    96 	icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
    97 	if (!icvar)
    98 	{
    99 		DisplayError("Could not find ICvar! Metamod cannot load.");
   100 		return;
   101 	}
   102 	g_pCVar = icvar;
   103 
   104 	if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
   105 		== NULL)
   106 	{
   107 		gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
   108 	}
   109 
   110 	RegisterConCommandBase(&meta_local_cmd);
   111 	conbases_unreg.push_back(&meta_local_cmd);
   112 
   113 	usermsgs_extracted = CacheUserMessages();
   114 
   115 	if (gameclients)
   116 	{
   117 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   118 	}
   119 }
   120 
   121 void BaseProvider::Notify_DLLShutdown_Pre()
   122 {
   123 	List<ConCommandBase *>::iterator iter;
   124 
   125 	for (iter = conbases_unreg.begin();
   126 		 iter != conbases_unreg.end();
   127 		 iter++)
   128 	{
   129 		UnregisterConCommandBase((*iter));
   130 	}
   131 }
   132 
   133 bool BaseProvider::IsRemotePrintingAvailable()
   134 {
   135 	return true;
   136 }
   137 
   138 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
   139 {
   140 	engine->ClientPrintf(client, message);
   141 }
   142 
   143 void BaseProvider::ServerCommand(const char *cmd)
   144 {
   145 	engine->ServerCommand(cmd);
   146 }
   147 
   148 const char *BaseProvider::GetConVarString(ConVar *convar)
   149 {
   150 	if (convar == NULL)
   151 	{
   152 		return NULL;
   153 	}
   154 
   155 	return convar->GetString();
   156 }
   157 
   158 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   159 {
   160 	return pCommand->IsCommand();
   161 }
   162 
   163 
   164 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   165 {
   166 	return (build == SOURCE_ENGINE_ORIGINAL
   167 			|| build == SOURCE_ENGINE_EPISODEONE);
   168 }
   169 
   170 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   171 {
   172 	if (key[0] == '-' || key[0] == '+')
   173 	{
   174 		return CommandLine_Tier0()->ParmValue(key, defval);
   175 	}
   176 	else if (icvar)
   177 	{
   178 		const char *val;
   179 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   180 		{
   181 			return defval;
   182 		}
   183 
   184 		return val;
   185 	}
   186 
   187 	return NULL;
   188 }
   189 
   190 int BaseProvider::TryServerGameDLL(const char *iface)
   191 {
   192 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   193 	{
   194 		return 0;
   195 	}
   196 
   197 	return atoi(&iface[13]);
   198 }
   199 
   200 bool BaseProvider::LogMessage(const char *buffer)
   201 {
   202 	if (!engine)
   203 	{
   204 		return false;
   205 	}
   206 
   207 	engine->LogPrint(buffer);
   208 
   209 	return true;
   210 }
   211 
   212 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   213 {
   214 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   215 
   216 	if (hook == ProvidedHook_LevelInit)
   217 	{
   218 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   219 	}
   220 	else if (hook == ProvidedHook_LevelShutdown)
   221 	{
   222 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   223 	}
   224 	else if (hook == ProvidedHook_GameInit)
   225 	{
   226 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   227 	}
   228 	else if (hook == ProvidedHook_DLLShutdown)
   229 	{
   230 		SourceHook::GetFuncInfo(&IServerGameDLL::DLLShutdown, mfi);
   231 	}
   232 	else if (hook == ProvidedHook_DLLInit)
   233 	{
   234 		SourceHook::GetFuncInfo(&IServerGameDLL::DLLInit, mfi);
   235 	}
   236 
   237 	*pInfo = mfi;
   238 
   239 	return (mfi.thisptroffs >= 0);
   240 }
   241 
   242 void BaseProvider::DisplayError(const char *fmt, ...)
   243 {
   244 	va_list ap;
   245 	char buffer[2048];
   246 
   247 	va_start(ap, fmt);
   248 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   249 	va_end(ap);
   250 
   251 	Error(buffer);
   252 }
   253 
   254 void BaseProvider::DisplayWarning(const char *fmt, ...)
   255 {
   256 	va_list ap;
   257 	char buffer[2048];
   258 
   259 	va_start(ap, fmt);
   260 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   261 	va_end(ap);
   262 
   263 	Warning(buffer);
   264 }
   265 
   266 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   267 {
   268 	return &g_SMConVarAccessor;
   269 }
   270 
   271 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   272 {
   273 	return g_SMConVarAccessor.Register(pCommand);
   274 }
   275 
   276 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   277 {
   278 	return g_SMConVarAccessor.Unregister(pCommand);
   279 }
   280 
   281 int BaseProvider::GetUserMessageCount()
   282 {
   283 	if (!usermsgs_extracted)
   284 	{
   285 		return -1;
   286 	}
   287 
   288 	return (int)usermsgs_list.size();
   289 }
   290 
   291 int BaseProvider::FindUserMessage(const char *name, int *size)
   292 {
   293 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   294 	{
   295 		if (usermsgs_list[i].name.compare(name) == 0)
   296 		{
   297 			if (size)
   298 			{
   299 				*size = usermsgs_list[i].size;
   300 			}
   301 			return (int)i;
   302 		}
   303 	}
   304 	
   305 	return -1;
   306 }
   307 
   308 const char *BaseProvider::GetUserMessage(int index, int *size)
   309 {
   310 	if (!usermsgs_extracted || index < 0 || index >= (int)usermsgs_list.size())
   311 	{
   312 		return NULL;
   313 	}
   314 
   315 	if (size)
   316 	{
   317 		*size = usermsgs_list[index].size;
   318 	}
   319 
   320 	return usermsgs_list[index].name.c_str();
   321 }
   322 
   323 const char *BaseProvider::GetGameDescription()
   324 {
   325 	return server->GetGameDescription();
   326 }
   327 
   328 int BaseProvider::DetermineSourceEngine(const char *game)
   329 {
   330 	return SOURCE_ENGINE_ORANGEBOX;
   331 }
   332 
   333 ConVar *BaseProvider::CreateConVar(const char *name,
   334 								   const char *defval,
   335 								   const char *help,
   336 								   int flags)
   337 {
   338 	int newflags = 0;
   339 	if (flags & ConVarFlag_Notify)
   340 	{
   341 		newflags |= FCVAR_NOTIFY;
   342 	}
   343 	if (flags & ConVarFlag_Replicated)
   344 	{
   345 		newflags |= FCVAR_REPLICATED;
   346 	}
   347 	if (flags & ConVarFlag_SpOnly)
   348 	{
   349 		newflags |= FCVAR_SPONLY;
   350 	}
   351 
   352 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   353 
   354 	RegisterConCommandBase(pVar);
   355 	conbases_unreg.push_back(pVar);
   356 
   357 	return pVar;
   358 }
   359 
   360 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
   361 {
   362 	g_VspListener.SetLoadable(true);
   363 	return &g_VspListener;
   364 }
   365 
   366 class GlobCommand : public IMetamodSourceCommandInfo
   367 {
   368 public:
   369 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   370 	{
   371 	}
   372 public:
   373 	unsigned int GetArgCount()
   374 	{
   375 		return m_cmd->ArgC();
   376 	}
   377 
   378 	const char *GetArg(unsigned int num)
   379 	{
   380 		return m_cmd->Arg(num);
   381 	}
   382 
   383 	const char *GetArgString()
   384 	{
   385 		return m_cmd->ArgS();
   386 	}
   387 private:
   388 	const CCommand *m_cmd;
   389 };
   390 
   391 void LocalCommand_Meta(const CCommand &args)
   392 {
   393 	GlobCommand cmd(&args);
   394 	Command_Meta(&cmd);
   395 }
   396 
   397 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   398 {
   399 	GlobCommand cmd(&_cmd);
   400 
   401 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   402 	{
   403 		Command_ClientMeta(pEdict, &cmd);
   404 	}
   405 }
   406 
   407 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   408 {
   409 	unsigned char *addr1 = (unsigned char *)_addr1;
   410 	unsigned char *addr2 = (unsigned char *)_addr2;
   411 
   412 	for (size_t i=0; i<len; i++)
   413 	{
   414 		if (addr2[i] == '*')
   415 		{
   416 			continue;
   417 		}
   418 		if (addr1[i] != addr2[i])
   419 		{
   420 			return false;
   421 		}
   422 	}
   423 
   424 	return true;
   425 }
   426 
   427 //////////////////////////////////////////////////////////////////////
   428 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   429 // Signatures necessary in finding the pointer to the CUtlDict that //
   430 //   stores user message information.                               //
   431 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   432 //   message indices. This is our answer to it. Yuck! <:-(          //
   433 //////////////////////////////////////////////////////////////////////
   434 #ifdef OS_WIN32
   435 	/* General Windows sig */
   436 	#define MSGCLASS_SIGLEN		7
   437 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   438 	#define MSGCLASS_OFFS		2
   439 
   440 	/* Dystopia Wimdows hack */
   441 	#define MSGCLASS2_SIGLEN	16
   442 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   443 	#define MSGCLASS2_OFFS		11
   444 
   445 	/* Windows frame pointer sig */
   446 	#define MSGCLASS3_SIGLEN	18
   447 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   448 	#define MSGCLASS3_OFFS		13
   449 #elif defined OS_LINUX
   450 	/* No frame pointer sig */
   451 	#define MSGCLASS_SIGLEN		14
   452 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   453 	#define MSGCLASS_OFFS		9
   454 
   455 	/* Frame pointer sig */
   456 	#define MSGCLASS2_SIGLEN	16
   457 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   458 	#define MSGCLASS2_OFFS		11
   459 #endif
   460 
   461 struct UserMessage
   462 {
   463 	int size;
   464 	const char *name;
   465 };
   466 
   467 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   468 
   469 /* This is the ugliest function in all of SourceMM */
   470 bool CacheUserMessages()
   471 {
   472 	/* Get address of original GetUserMessageInfo() */
   473 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   474 
   475 	/* Oh dear, we have a relative jump on our hands
   476 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   477 	 */
   478 	if (*vfunc == '\xE9')
   479 	{
   480 		/* Get address from displacement...
   481 		 *
   482 		 * Add 5 because it's relative to next instruction:
   483 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   484 		 */
   485 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   486 	}
   487 
   488 	CUtlDict<UserMessage *, int> *dict = NULL;
   489 
   490 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   491 	{
   492 		/* Get address of CUserMessages instance */
   493 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   494 
   495 		/* Get address of CUserMessages::m_UserMessages */
   496 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   497 	} 
   498 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   499 	{
   500 	#ifdef OS_WIN32
   501 		/* If we get here, the code is possibly inlined like in Dystopia */
   502 
   503 		/* Get the address of the CUtlRBTree */
   504 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   505 
   506 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   507 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   508 	#elif defined OS_LINUX
   509 		/* Get address of CUserMessages instance */
   510 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   511 
   512 		/* Get address of CUserMessages::m_UserMessages */
   513 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   514 	#endif
   515 	#ifdef OS_WIN32
   516 	} 
   517 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   518 	{
   519 		/* Get address of CUserMessages instance */
   520 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   521 
   522 		/* Get address of CUserMessages::m_UserMessages */
   523 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   524 	#endif
   525 	}
   526 
   527 	#if !defined OS_WIN32
   528 	if (dict == NULL)
   529 	{
   530 		char path[255];
   531 		if (GetFileOfAddress(vfunc, path, sizeof(path)))
   532 		{
   533 			void *handle = dlopen(path, RTLD_NOW);
   534 			if (handle != NULL)
   535 			{
   536 				void *addr = dlsym(handle, "usermessages");
   537 				dict = (UserMsgDict *)*(void **)addr;
   538 				dlclose(handle);
   539 			}
   540 		}
   541 	}
   542 	#endif
   543 
   544 	if (dict != NULL)
   545 	{
   546 		int msg_count = dict->Count();
   547 
   548 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   549 		if (msg_count < 0 || msg_count > 255)
   550 		{
   551 			return false;
   552 		}
   553 
   554 		UserMessage *msg;
   555 		UsrMsgInfo u_msg;
   556 
   557 		/* Cache messages in our CUtlDict */
   558 		for (int i = 0; i < msg_count; i++)
   559 		{
   560 			msg = dict->Element(i);
   561 			u_msg.name = msg->name;
   562 			u_msg.size = msg->size;
   563 			usermsgs_list.push_back(u_msg);
   564 		}
   565 
   566 		return true;
   567 	}
   568 
   569 	return false;
   570 }
   571