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