sourcemm/episode2/provider_ep2.cpp
author David Anderson <dvander@alliedmods.net>
Wed Oct 10 02:43:25 2007 +0000 (2007-10-10)
changeset 408 a0f99231cf3b
parent 402 0434e5a5ab89
child 472 6b2d311e4c01
permissions -rw-r--r--
fixed a bug where engine version wasn't being passed right
     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 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 class GlobCommand : public IMetamodSourceCommandInfo
   366 {
   367 public:
   368 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   369 	{
   370 	}
   371 public:
   372 	unsigned int GetArgCount()
   373 	{
   374 		return m_cmd->ArgC();
   375 	}
   376 
   377 	const char *GetArg(unsigned int num)
   378 	{
   379 		return m_cmd->Arg(num);
   380 	}
   381 
   382 	const char *GetArgString()
   383 	{
   384 		return m_cmd->ArgS();
   385 	}
   386 private:
   387 	const CCommand *m_cmd;
   388 };
   389 
   390 void LocalCommand_Meta(const CCommand &args)
   391 {
   392 	GlobCommand cmd(&args);
   393 	Command_Meta(&cmd);
   394 }
   395 
   396 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   397 {
   398 	GlobCommand cmd(&_cmd);
   399 
   400 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   401 	{
   402 		Command_ClientMeta(pEdict, &cmd);
   403 	}
   404 }
   405 
   406 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   407 {
   408 	unsigned char *addr1 = (unsigned char *)_addr1;
   409 	unsigned char *addr2 = (unsigned char *)_addr2;
   410 
   411 	for (size_t i=0; i<len; i++)
   412 	{
   413 		if (addr2[i] == '*')
   414 		{
   415 			continue;
   416 		}
   417 		if (addr1[i] != addr2[i])
   418 		{
   419 			return false;
   420 		}
   421 	}
   422 
   423 	return true;
   424 }
   425 
   426 //////////////////////////////////////////////////////////////////////
   427 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   428 // Signatures necessary in finding the pointer to the CUtlDict that //
   429 //   stores user message information.                               //
   430 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   431 //   message indices. This is our answer to it. Yuck! <:-(          //
   432 //////////////////////////////////////////////////////////////////////
   433 #ifdef OS_WIN32
   434 	/* General Windows sig */
   435 	#define MSGCLASS_SIGLEN		7
   436 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   437 	#define MSGCLASS_OFFS		2
   438 
   439 	/* Dystopia Wimdows hack */
   440 	#define MSGCLASS2_SIGLEN	16
   441 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   442 	#define MSGCLASS2_OFFS		11
   443 
   444 	/* Windows frame pointer sig */
   445 	#define MSGCLASS3_SIGLEN	18
   446 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   447 	#define MSGCLASS3_OFFS		13
   448 #elif defined OS_LINUX
   449 	/* No frame pointer sig */
   450 	#define MSGCLASS_SIGLEN		14
   451 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   452 	#define MSGCLASS_OFFS		9
   453 
   454 	/* Frame pointer sig */
   455 	#define MSGCLASS2_SIGLEN	16
   456 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   457 	#define MSGCLASS2_OFFS		11
   458 #endif
   459 
   460 struct UserMessage
   461 {
   462 	int size;
   463 	const char *name;
   464 };
   465 
   466 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   467 
   468 /* This is the ugliest function in all of SourceMM */
   469 bool CacheUserMessages()
   470 {
   471 	/* Get address of original GetUserMessageInfo() */
   472 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   473 
   474 	/* Oh dear, we have a relative jump on our hands
   475 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   476 	 */
   477 	if (*vfunc == '\xE9')
   478 	{
   479 		/* Get address from displacement...
   480 		 *
   481 		 * Add 5 because it's relative to next instruction:
   482 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   483 		 */
   484 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   485 	}
   486 
   487 	CUtlDict<UserMessage *, int> *dict = NULL;
   488 
   489 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   490 	{
   491 		/* Get address of CUserMessages instance */
   492 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   493 
   494 		/* Get address of CUserMessages::m_UserMessages */
   495 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   496 	} 
   497 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   498 	{
   499 	#ifdef OS_WIN32
   500 		/* If we get here, the code is possibly inlined like in Dystopia */
   501 
   502 		/* Get the address of the CUtlRBTree */
   503 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   504 
   505 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   506 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   507 	#elif defined OS_LINUX
   508 		/* Get address of CUserMessages instance */
   509 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   510 
   511 		/* Get address of CUserMessages::m_UserMessages */
   512 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   513 	#endif
   514 	#ifdef OS_WIN32
   515 	} 
   516 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   517 	{
   518 		/* Get address of CUserMessages instance */
   519 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   520 
   521 		/* Get address of CUserMessages::m_UserMessages */
   522 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   523 	#endif
   524 	}
   525 
   526 	#if !defined OS_WIN32
   527 	if (dict == NULL)
   528 	{
   529 		char path[255];
   530 		if (GetFileOfAddress(vfunc, path, sizeof(path)))
   531 		{
   532 			void *handle = dlopen(path, RTLD_NOW);
   533 			if (handle != NULL)
   534 			{
   535 				void *addr = dlsym(handle, "usermessages");
   536 				dict = (UserMsgDict *)*(void **)addr;
   537 				dlclose(handle);
   538 			}
   539 		}
   540 	}
   541 	#endif
   542 
   543 	if (dict != NULL)
   544 	{
   545 		int msg_count = dict->Count();
   546 
   547 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   548 		if (msg_count < 0 || msg_count > 255)
   549 		{
   550 			return false;
   551 		}
   552 
   553 		UserMessage *msg;
   554 		UsrMsgInfo u_msg;
   555 
   556 		/* Cache messages in our CUtlDict */
   557 		for (int i = 0; i < msg_count; i++)
   558 		{
   559 			msg = dict->Element(i);
   560 			u_msg.name = msg->name;
   561 			u_msg.size = msg->size;
   562 			usermsgs_list.push_back(u_msg);
   563 		}
   564 
   565 		return true;
   566 	}
   567 
   568 	return false;
   569 }
   570