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