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