sourcemm/episode2/provider_ep2.cpp
author David Anderson <dvander@alliedmods.net>
Thu Oct 04 19:18:19 2007 +0000 (2007-10-04)
branchsourcemm-1.6.0
changeset 369 2b8c2ea08b6d
parent 368 4a937e6e6f11
permissions -rw-r--r--
fixed usermessages not printing
removed old ConMsg extraction code
     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 
   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 ConVar *BaseProvider::CreateConVar(const char *name,
   328 								   const char *defval,
   329 								   const char *help,
   330 								   int flags)
   331 {
   332 	int newflags = 0;
   333 	if (flags & ConVarFlag_Notify)
   334 	{
   335 		newflags |= FCVAR_NOTIFY;
   336 	}
   337 	if (flags & ConVarFlag_Replicated)
   338 	{
   339 		newflags |= FCVAR_REPLICATED;
   340 	}
   341 	if (flags & ConVarFlag_SpOnly)
   342 	{
   343 		newflags |= FCVAR_SPONLY;
   344 	}
   345 
   346 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   347 
   348 	RegisterConCommandBase(pVar);
   349 	conbases_unreg.push_back(pVar);
   350 
   351 	return pVar;
   352 }
   353 
   354 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
   355 {
   356 	g_VspListener.SetLoadable(true);
   357 	return &g_VspListener;
   358 }
   359 
   360 class GlobCommand : public IMetamodSourceCommandInfo
   361 {
   362 public:
   363 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   364 	{
   365 	}
   366 public:
   367 	unsigned int GetArgCount()
   368 	{
   369 		return m_cmd->ArgC();
   370 	}
   371 
   372 	const char *GetArg(unsigned int num)
   373 	{
   374 		return m_cmd->Arg(num);
   375 	}
   376 
   377 	const char *GetArgString()
   378 	{
   379 		return m_cmd->ArgS();
   380 	}
   381 private:
   382 	const CCommand *m_cmd;
   383 };
   384 
   385 void LocalCommand_Meta(const CCommand &args)
   386 {
   387 	GlobCommand cmd(&args);
   388 	Command_Meta(&cmd);
   389 }
   390 
   391 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   392 {
   393 	GlobCommand cmd(&_cmd);
   394 
   395 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   396 	{
   397 		Command_ClientMeta(pEdict, &cmd);
   398 	}
   399 }
   400 
   401 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   402 {
   403 	unsigned char *addr1 = (unsigned char *)_addr1;
   404 	unsigned char *addr2 = (unsigned char *)_addr2;
   405 
   406 	for (size_t i=0; i<len; i++)
   407 	{
   408 		if (addr2[i] == '*')
   409 		{
   410 			continue;
   411 		}
   412 		if (addr1[i] != addr2[i])
   413 		{
   414 			return false;
   415 		}
   416 	}
   417 
   418 	return true;
   419 }
   420 
   421 //////////////////////////////////////////////////////////////////////
   422 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   423 // Signatures necessary in finding the pointer to the CUtlDict that //
   424 //   stores user message information.                               //
   425 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   426 //   message indices. This is our answer to it. Yuck! <:-(          //
   427 //////////////////////////////////////////////////////////////////////
   428 #ifdef OS_WIN32
   429 	/* General Windows sig */
   430 	#define MSGCLASS_SIGLEN		7
   431 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   432 	#define MSGCLASS_OFFS		2
   433 
   434 	/* Dystopia Wimdows hack */
   435 	#define MSGCLASS2_SIGLEN	16
   436 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   437 	#define MSGCLASS2_OFFS		11
   438 
   439 	/* Windows frame pointer sig */
   440 	#define MSGCLASS3_SIGLEN	18
   441 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   442 	#define MSGCLASS3_OFFS		13
   443 #elif defined OS_LINUX
   444 	/* No frame pointer sig */
   445 	#define MSGCLASS_SIGLEN		14
   446 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   447 	#define MSGCLASS_OFFS		9
   448 
   449 	/* Frame pointer sig */
   450 	#define MSGCLASS2_SIGLEN	16
   451 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   452 	#define MSGCLASS2_OFFS		11
   453 #endif
   454 
   455 struct UserMessage
   456 {
   457 	int size;
   458 	const char *name;
   459 };
   460 
   461 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   462 
   463 /* This is the ugliest function in all of SourceMM */
   464 bool CacheUserMessages()
   465 {
   466 	/* Get address of original GetUserMessageInfo() */
   467 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   468 
   469 	/* Oh dear, we have a relative jump on our hands
   470 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   471 	 */
   472 	if (*vfunc == '\xE9')
   473 	{
   474 		/* Get address from displacement...
   475 		 *
   476 		 * Add 5 because it's relative to next instruction:
   477 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   478 		 */
   479 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   480 	}
   481 
   482 	CUtlDict<UserMessage *, int> *dict = NULL;
   483 
   484 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   485 	{
   486 		/* Get address of CUserMessages instance */
   487 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   488 
   489 		/* Get address of CUserMessages::m_UserMessages */
   490 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   491 	} 
   492 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   493 	{
   494 	#ifdef OS_WIN32
   495 		/* If we get here, the code is possibly inlined like in Dystopia */
   496 
   497 		/* Get the address of the CUtlRBTree */
   498 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   499 
   500 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   501 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   502 	#elif defined OS_LINUX
   503 		/* Get address of CUserMessages instance */
   504 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   505 
   506 		/* Get address of CUserMessages::m_UserMessages */
   507 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   508 	#endif
   509 	#ifdef OS_WIN32
   510 	} 
   511 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   512 	{
   513 		/* Get address of CUserMessages instance */
   514 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   515 
   516 		/* Get address of CUserMessages::m_UserMessages */
   517 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   518 	#endif
   519 	}
   520 
   521 	if (dict)
   522 	{
   523 		int msg_count = dict->Count();
   524 
   525 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   526 		if (msg_count < 0 || msg_count > 255)
   527 		{
   528 			return false;
   529 		}
   530 
   531 		UserMessage *msg;
   532 		UsrMsgInfo u_msg;
   533 
   534 		/* Cache messages in our CUtlDict */
   535 		for (int i = 0; i < msg_count; i++)
   536 		{
   537 			msg = dict->Element(i);
   538 			u_msg.name = msg->name;
   539 			u_msg.size = msg->size;
   540 			usermsgs_list.push_back(u_msg);
   541 		}
   542 
   543 		return true;
   544 	}
   545 
   546 	return false;
   547 }
   548