sourcemm/episode1/provider_ep1.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Mar 20 07:13:53 2008 +0000 (2008-03-20)
changeset 520 2eaf34b16fbe
parent 482 f881da6de3a5
child 523 6f1630519b81
permissions -rw-r--r--
amb1480 - Removed FCVAR_REPLICATED from MM:S convars
     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_SpOnly)
   335 	{
   336 		newflags |= FCVAR_SPONLY;
   337 	}
   338 
   339 	return new ConVar(name, defval, newflags, help);
   340 }
   341 
   342 IServerPluginCallbacks *BaseProvider::GetVSPCallbacks(const char *iface)
   343 {
   344 	g_VspListener.SetLoadable(true);
   345 	return &g_VspListener;
   346 }
   347 
   348 bool BaseProvider::IsAlternatelyLoaded(/* =0 */)
   349 {
   350 	return false;
   351 }
   352 
   353 class GlobCommand : public IMetamodSourceCommandInfo
   354 {
   355 public:
   356 	unsigned int GetArgCount()
   357 	{
   358 		return engine->Cmd_Argc() - 1;
   359 	}
   360 
   361 	const char *GetArg(unsigned int num)
   362 	{
   363 		return engine->Cmd_Argv(num);
   364 	}
   365 
   366 	const char *GetArgString()
   367 	{
   368 		return engine->Cmd_Args();
   369 	}
   370 };
   371 
   372 CON_COMMAND(meta, "Metamod:Source control commands")
   373 {
   374 	GlobCommand cmd;
   375 	Command_Meta(&cmd);
   376 }
   377 
   378 void ClientCommand(edict_t *pEdict)
   379 {
   380 	GlobCommand cmd;
   381 
   382 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   383 	{
   384 		Command_ClientMeta(pEdict, &cmd);
   385 	}
   386 }
   387 
   388 //////////////////////////////////////////////////////////////////////////
   389 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
   390 // (note: you can find the offset by looking for the text               //
   391 //   "Echo text to console", you'll find the callback cmd pushed on the //
   392 //   stack.)                                                            //
   393 //////////////////////////////////////////////////////////////////////////
   394 
   395 #define SIGLEN			8
   396 #define ENGINE486_SIG	"\x55\x89\xE5\x53\x83\xEC\x14\xBB"
   397 #define ENGINE486_OFFS	40
   398 #define ENGINE686_SIG	"\x53\x83\xEC\x08\xBB\x01\x00\x00"
   399 #define ENGINE686_OFFS	50
   400 #define	ENGINEAMD_SIG	"\x53\x51\xBB\x01\x00\x00\x00\x51"
   401 #define	ENGINEAMD_OFFS	47
   402 #define ENGINEW32_SIG	"\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
   403 #define ENGINEW32_OFFS	38
   404 #define IA32_CALL		0xE8
   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 //Thanks to fysh for the idea of extracting info from "echo" and for
   427 // having the original offsets at hand!
   428 CONPRINTF_FUNC ExtractRemotePrinter()
   429 {
   430 	ConCommandBase *pBase = icvar->GetCommands();
   431 	unsigned char *ptr = NULL;
   432 	FnCommandCallback callback = NULL;
   433 	int offs = 0;
   434 
   435 	while (pBase)
   436 	{
   437 		if (strcmp(pBase->GetName(), "echo") == 0)
   438 		{
   439 			callback = ((ConCommand *)pBase)->GetCallback();
   440 			ptr = (unsigned char *)callback;
   441 #ifdef OS_LINUX
   442 			if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
   443 			{
   444 				offs = ENGINE486_OFFS;
   445 			}
   446 			else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
   447 			{
   448 				offs = ENGINE686_OFFS;
   449 			}
   450 			else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
   451 			{
   452 				offs = ENGINEAMD_OFFS;
   453 			}
   454 #elif defined OS_WIN32 // Only one Windows engine binary so far...
   455 			if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
   456 			{
   457 				offs = ENGINEW32_OFFS;
   458 			}
   459 #endif
   460 
   461 			if (!offs || ptr[offs - 1] != IA32_CALL)
   462 			{
   463 				return NULL;
   464 			}
   465 			//get the relative offset
   466 			void *addr = *((void **)(ptr + offs));
   467 			//add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
   468 			return (CONPRINTF_FUNC)((unsigned long)addr + (unsigned long)(ptr + offs) + 4);
   469 		}
   470 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   471 	}
   472 
   473 	return NULL;
   474 }
   475 
   476 //////////////////////////////////////////////////////////////////////
   477 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   478 // Signatures necessary in finding the pointer to the CUtlDict that //
   479 //   stores user message information.                               //
   480 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   481 //   message indices. This is our answer to it. Yuck! <:-(          //
   482 //////////////////////////////////////////////////////////////////////
   483 #ifdef OS_WIN32
   484 	/* General Windows sig */
   485 	#define MSGCLASS_SIGLEN		7
   486 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   487 	#define MSGCLASS_OFFS		2
   488 
   489 	/* Dystopia Wimdows hack */
   490 	#define MSGCLASS2_SIGLEN	16
   491 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   492 	#define MSGCLASS2_OFFS		11
   493 
   494 	/* Windows frame pointer sig */
   495 	#define MSGCLASS3_SIGLEN	18
   496 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   497 	#define MSGCLASS3_OFFS		13
   498 #elif defined OS_LINUX
   499 	/* No frame pointer sig */
   500 	#define MSGCLASS_SIGLEN		14
   501 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   502 	#define MSGCLASS_OFFS		9
   503 
   504 	/* Frame pointer sig */
   505 	#define MSGCLASS2_SIGLEN	16
   506 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   507 	#define MSGCLASS2_OFFS		11
   508 #endif
   509 
   510 struct UserMessage
   511 {
   512 	int size;
   513 	const char *name;
   514 };
   515 
   516 typedef CUtlDict<UserMessage *, int> UserMsgDict;
   517 
   518 /* This is the ugliest function in all of SourceMM */
   519 bool CacheUserMessages()
   520 {
   521 	/* Get address of original GetUserMessageInfo() */
   522 	char *vfunc = (char *)SH_GET_ORIG_VFNPTR_ENTRY(server, &IServerGameDLL::GetUserMessageInfo);
   523 
   524 	/* Oh dear, we have a relative jump on our hands
   525 	 * PVK II on Windows made me do this, but I suppose it doesn't hurt to check this on Linux too...
   526 	 */
   527 	if (*vfunc == '\xE9')
   528 	{
   529 		/* Get address from displacement...
   530 		 *
   531 		 * Add 5 because it's relative to next instruction:
   532 		 * Opcode <1 byte> + 32-bit displacement <4 bytes> 
   533 		 */
   534 		vfunc += *reinterpret_cast<int *>(vfunc + 1) + 5;
   535 	}
   536 
   537 	CUtlDict<UserMessage *, int> *dict = NULL;
   538 
   539 	if (vcmp(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   540 	{
   541 		/* Get address of CUserMessages instance */
   542 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   543 
   544 		/* Get address of CUserMessages::m_UserMessages */
   545 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   546 	} 
   547 	else if (vcmp(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) 
   548 	{
   549 	#ifdef OS_WIN32
   550 		/* If we get here, the code is possibly inlined like in Dystopia */
   551 
   552 		/* Get the address of the CUtlRBTree */
   553 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   554 
   555 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   556 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   557 	#elif defined OS_LINUX
   558 		/* Get address of CUserMessages instance */
   559 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   560 
   561 		/* Get address of CUserMessages::m_UserMessages */
   562 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   563 	#endif
   564 	#ifdef OS_WIN32
   565 	} 
   566 	else if (vcmp(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) 
   567 	{
   568 		/* Get address of CUserMessages instance */
   569 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   570 
   571 		/* Get address of CUserMessages::m_UserMessages */
   572 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   573 	#endif
   574 	}
   575 
   576 	if (dict)
   577 	{
   578 		int msg_count = dict->Count();
   579 
   580 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   581 		if (msg_count < 0 || msg_count > 255)
   582 		{
   583 			return false;
   584 		}
   585 
   586 		UserMessage *msg;
   587 		UsrMsgInfo u_msg;
   588 
   589 		/* Cache messages in our CUtlDict */
   590 		for (int i = 0; i < msg_count; i++)
   591 		{
   592 			msg = dict->Element(i);
   593 			u_msg.name = msg->name;
   594 			u_msg.size = msg->size;
   595 			usermsgs_list.push_back(u_msg);
   596 		}
   597 
   598 		return true;
   599 	}
   600 
   601 	return false;
   602 }
   603