core/provider/provider_ep2.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Tue Jan 22 21:38:16 2013 -0500 (2013-01-22)
changeset 815 4a9172605d0e
parent 791 a1b97ab6e0b1
child 818 1516c9026fd0
permissions -rw-r--r--
Removed usermessage api support for CS:GO (bug 5578, r=asherkin).
     1 /**
     2  * vim: set ts=4 sw=4 tw=99 noet :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2009 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     9  * This software is provided 'as-is', without any express or implied warranty.
    10  * In no event will the authors be held liable for any damages arising from 
    11  * the use of this software.
    12  * 
    13  * Permission is granted to anyone to use this software for any purpose, 
    14  * including commercial applications, and to alter it and redistribute it 
    15  * freely, subject to the following restrictions:
    16  *
    17  * 1. The origin of this software must not be misrepresented; you must not 
    18  * claim that you wrote the original software. If you use this software in a 
    19  * product, an acknowledgment in the product documentation would be 
    20  * appreciated but is not required.
    21  * 2. Altered source versions must be plainly marked as such, and must not be
    22  * misrepresented as being the original software.
    23  * 3. This notice may not be removed or altered from any source distribution.
    24  */
    25 
    26 #include <stdio.h>
    27 #include <setjmp.h>
    28 #include "../metamod_oslink.h"
    29 #include <sourcehook.h>
    30 #include <convar.h>
    31 #include <eiface.h>
    32 #include <tier0/icommandline.h>
    33 #include <sh_vector.h>
    34 #include <sh_string.h>
    35 #include "../metamod_util.h"
    36 #include "provider_ep2.h"
    37 #include "console.h"
    38 #include "metamod_console.h"
    39 #include <filesystem.h>
    40 #include "metamod.h"
    41 
    42 /* Types */
    43 typedef void (*CONPRINTF_FUNC)(const char *, ...);
    44 struct UsrMsgInfo
    45 {
    46 	UsrMsgInfo()
    47 	{
    48 	}
    49 	UsrMsgInfo(int s, const char *t) : size(s), name(t)
    50 	{
    51 	}
    52 	int size;
    53 	String name;
    54 };
    55 
    56 /* Imports */
    57 #if SOURCE_ENGINE == SE_DARKMESSIAH
    58 #undef CommandLine
    59 DLL_IMPORT ICommandLine *CommandLine();
    60 #endif
    61 
    62 /* Functions */
    63 void CacheUserMessages();
    64 void Detour_Error(const tchar *pMsg, ...);
    65 #if SOURCE_ENGINE >= SE_ORANGEBOX
    66 void ClientCommand(edict_t *pEdict, const CCommand &args);
    67 void LocalCommand_Meta(const CCommand &args);
    68 #else
    69 void ClientCommand(edict_t *pEdict);
    70 void LocalCommand_Meta();
    71 #endif
    72 
    73 void _ServerCommand();
    74 /* Variables */
    75 static BaseProvider g_Ep1Provider;
    76 static List<ConCommandBase *> conbases_unreg;
    77 static CVector<UsrMsgInfo> usermsgs_list;
    78 static jmp_buf usermsg_end;
    79 
    80 ICvar *icvar = NULL;
    81 IFileSystem *baseFs = NULL;
    82 IServerGameDLL *server = NULL;
    83 IVEngineServer *engine = NULL;
    84 IServerGameClients *gameclients = NULL;
    85 IMetamodSourceProvider *provider = &g_Ep1Provider;
    86 ConCommand meta_local_cmd("meta", LocalCommand_Meta, "Metamod:Source control options");
    87 
    88 #if SOURCE_ENGINE >= SE_ORANGEBOX
    89 SH_DECL_HOOK2_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *, const CCommand &);
    90 #else
    91 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    92 #endif
    93 
    94 void BaseProvider::ConsolePrint(const char *str)
    95 {
    96 #if SOURCE_ENGINE >= SE_ORANGEBOX
    97 	ConMsg("%s", str);
    98 #else
    99 	Msg("%s", str);
   100 #endif
   101 }
   102 
   103 void BaseProvider::Notify_DLLInit_Pre(CreateInterfaceFn engineFactory, 
   104 									  CreateInterfaceFn serverFactory)
   105 {
   106 	engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   107 	if (!engine)
   108 	{
   109 		DisplayError("Could not find IVEngineServer! Metamod cannot load.");
   110 		return;
   111 	}
   112 #if SOURCE_ENGINE >= SE_ORANGEBOX
   113 	icvar = (ICvar *)((engineFactory)(CVAR_INTERFACE_VERSION, NULL));
   114 #else
   115 	icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL));
   116 #endif
   117 	if (!icvar)
   118 	{
   119 		DisplayError("Could not find ICvar! Metamod cannot load.");
   120 		return;
   121 	}
   122 
   123 
   124 	if ((gameclients = (IServerGameClients *)(serverFactory("ServerGameClients003", NULL)))
   125 		== NULL)
   126 	{
   127 		gameclients = (IServerGameClients *)(serverFactory("ServerGameClients004", NULL));
   128 	}
   129 
   130 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   131 	if (baseFs == NULL)
   132 	{
   133 		mm_LogMessage("Unable to find \"%s\": .vdf files will not be parsed", FILESYSTEM_INTERFACE_VERSION);
   134 	}
   135 
   136 #if SOURCE_ENGINE >= SE_ORANGEBOX
   137 	g_pCVar = icvar;
   138 #endif
   139 
   140 	g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
   141 
   142 	CacheUserMessages();
   143 
   144 #if SOURCE_ENGINE == SE_DARKMESSIAH
   145 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   146 	{
   147 		/* This is very unlikely considering it's old engine */
   148 		mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   149 		mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   150 	}
   151 #endif
   152 
   153 	if (gameclients)
   154 	{
   155 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   156 	}
   157 }
   158 
   159 void BaseProvider::Notify_DLLShutdown_Pre()
   160 {
   161 	g_SMConVarAccessor.RemoveMetamodCommands();
   162 
   163 #if SOURCE_ENGINE == SE_DARKMESSIAH
   164 	if (g_Metamod.IsLoadedAsGameDLL())
   165 	{
   166 		icvar->UnlinkVariables(FCVAR_GAMEDLL);
   167 	}
   168 #endif
   169 }
   170 
   171 bool BaseProvider::IsRemotePrintingAvailable()
   172 {
   173 	return true;
   174 }
   175 
   176 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
   177 {
   178 	engine->ClientPrintf(client, message);
   179 }
   180 
   181 void BaseProvider::ServerCommand(const char *cmd)
   182 {
   183 	engine->ServerCommand(cmd);
   184 }
   185 
   186 const char *BaseProvider::GetConVarString(ConVar *convar)
   187 {
   188 	if (convar == NULL)
   189 	{
   190 		return NULL;
   191 	}
   192 
   193 	return convar->GetString();
   194 }
   195 
   196 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
   197 {
   198 	convar->SetValue(str);
   199 }
   200 
   201 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   202 {
   203 	return pCommand->IsCommand();
   204 }
   205 
   206 
   207 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   208 {
   209 	return (build == SOURCE_ENGINE_ORIGINAL
   210 			|| build == SOURCE_ENGINE_EPISODEONE);
   211 }
   212 
   213 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   214 {
   215 	if (key[0] == '-' || key[0] == '+')
   216 	{
   217 		return CommandLine()->ParmValue(key, defval);
   218 	}
   219 	else if (icvar)
   220 	{
   221 		const char *val;
   222 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   223 		{
   224 			return defval;
   225 		}
   226 
   227 		return val;
   228 	}
   229 
   230 	return NULL;
   231 }
   232 
   233 int BaseProvider::TryServerGameDLL(const char *iface)
   234 {
   235 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   236 	{
   237 		return 0;
   238 	}
   239 
   240 	return atoi(&iface[13]);
   241 }
   242 
   243 bool BaseProvider::LogMessage(const char *buffer)
   244 {
   245 	if (!engine)
   246 	{
   247 		return false;
   248 	}
   249 
   250 	engine->LogPrint(buffer);
   251 
   252 	return true;
   253 }
   254 
   255 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   256 {
   257 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   258 
   259 	if (hook == ProvidedHook_LevelInit)
   260 	{
   261 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   262 	}
   263 	else if (hook == ProvidedHook_LevelShutdown)
   264 	{
   265 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   266 	}
   267 	else if (hook == ProvidedHook_GameInit)
   268 	{
   269 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   270 	}
   271 
   272 	*pInfo = mfi;
   273 
   274 	return (mfi.thisptroffs >= 0);
   275 }
   276 
   277 void BaseProvider::DisplayError(const char *fmt, ...)
   278 {
   279 	va_list ap;
   280 	char buffer[2048];
   281 
   282 	va_start(ap, fmt);
   283 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   284 	va_end(ap);
   285 
   286 	Error("%s", buffer);
   287 }
   288 
   289 void BaseProvider::DisplayWarning(const char *fmt, ...)
   290 {
   291 	va_list ap;
   292 	char buffer[2048];
   293 
   294 	va_start(ap, fmt);
   295 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   296 	va_end(ap);
   297 
   298 	Warning("%s", buffer);
   299 }
   300 
   301 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   302 {
   303 	return &g_SMConVarAccessor;
   304 }
   305 
   306 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   307 {
   308 	return g_SMConVarAccessor.Register(pCommand);
   309 }
   310 
   311 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   312 {
   313 	return g_SMConVarAccessor.Unregister(pCommand);
   314 }
   315 
   316 int BaseProvider::GetUserMessageCount()
   317 {
   318 #if SOURCE_ENGINE == SE_CSGO
   319 	return -1;
   320 #else
   321 	return (int)usermsgs_list.size();
   322 #endif
   323 }
   324 
   325 int BaseProvider::FindUserMessage(const char *name, int *size)
   326 {
   327 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   328 	{
   329 		if (usermsgs_list[i].name.compare(name) == 0)
   330 		{
   331 			if (size)
   332 			{
   333 				*size = usermsgs_list[i].size;
   334 			}
   335 			return (int)i;
   336 		}
   337 	}
   338 	
   339 	return -1;
   340 }
   341 
   342 const char *BaseProvider::GetUserMessage(int index, int *size)
   343 {
   344 	if (index < 0 || index >= (int)usermsgs_list.size())
   345 	{
   346 		return NULL;
   347 	}
   348 
   349 	if (size)
   350 	{
   351 		*size = usermsgs_list[index].size;
   352 	}
   353 
   354 	return usermsgs_list[index].name.c_str();
   355 }
   356 
   357 const char *BaseProvider::GetGameDescription()
   358 {
   359 	return server->GetGameDescription();
   360 }
   361 
   362 int BaseProvider::DetermineSourceEngine(const char *game)
   363 {
   364 #if SOURCE_ENGINE == SE_BLOODYGOODTIME
   365 	return SOURCE_ENGINE_BLOODYGOODTIME;
   366 #elif SOURCE_ENGINE == SE_ALIENSWARM
   367 	return SOURCE_ENGINE_ALIENSWARM;
   368 #elif SOURCE_ENGINE == SE_LEFT4DEAD2
   369 	return SOURCE_ENGINE_LEFT4DEAD2;
   370 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   371 	return SOURCE_ENGINE_LEFT4DEAD;
   372 #elif SOURCE_ENGINE == SE_ORANGEBOX
   373 	return SOURCE_ENGINE_ORANGEBOX;
   374 #elif SOURCE_ENGINE == SE_CSS
   375 	return SOURCE_ENGINE_CSS;
   376 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
   377 	return SOURCE_ENGINE_ORANGEBOXVALVE;
   378 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   379 	return SOURCE_ENGINE_DARKMESSIAH;
   380 #elif SOURCE_ENGINE == SE_EYE
   381 	return SOURCE_ENGINE_EYE;
   382 #elif SOURCE_ENGINE == SE_PORTAL2
   383 	return SOURCE_ENGINE_PORTAL2;
   384 #elif SOURCE_ENGINE == SE_CSGO
   385 	return SOURCE_ENGINE_CSGO;
   386 #else
   387 #error "SOURCE_ENGINE not defined to a known value"
   388 #endif
   389 }
   390 
   391 ConVar *BaseProvider::CreateConVar(const char *name,
   392 								   const char *defval,
   393 								   const char *help,
   394 								   int flags)
   395 {
   396 	int newflags = 0;
   397 	if (flags & ConVarFlag_Notify)
   398 	{
   399 		newflags |= FCVAR_NOTIFY;
   400 	}
   401 	if (flags & ConVarFlag_SpOnly)
   402 	{
   403 		newflags |= FCVAR_SPONLY;
   404 	}
   405 
   406 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   407 
   408 	g_SMConVarAccessor.RegisterConCommandBase(pVar);
   409 
   410 	return pVar;
   411 }
   412 
   413 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   414 {
   415 	if (baseFs == NULL)
   416 	{
   417 		return false;
   418 	}
   419 
   420 	KeyValues *pValues;
   421 	const char *plugin_file, *p_alias;
   422 
   423 	pValues = new KeyValues("Metamod Plugin");
   424 
   425 	if (!pValues->LoadFromFile(baseFs, file))
   426 	{
   427 		pValues->deleteThis();
   428 		return false;
   429 	}
   430 
   431 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   432 	{
   433 		pValues->deleteThis();
   434 		return false;
   435 	}
   436 
   437 	UTIL_Format(path, path_len, "%s", plugin_file);
   438 
   439 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   440 	{
   441 		UTIL_Format(alias, alias_len, "%s", p_alias);
   442 	}
   443 	else
   444 	{
   445 		UTIL_Format(alias, alias_len, "");
   446 	}
   447 
   448 	pValues->deleteThis();
   449 
   450 	return true;
   451 }
   452 
   453 #if SOURCE_ENGINE >= SE_ORANGEBOX
   454 class GlobCommand : public IMetamodSourceCommandInfo
   455 {
   456 public:
   457 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   458 	{
   459 	}
   460 public:
   461 	unsigned int GetArgCount()
   462 	{
   463 		return m_cmd->ArgC() - 1;
   464 	}
   465 
   466 	const char *GetArg(unsigned int num)
   467 	{
   468 		return m_cmd->Arg(num);
   469 	}
   470 
   471 	const char *GetArgString()
   472 	{
   473 		return m_cmd->ArgS();
   474 	}
   475 private:
   476 	const CCommand *m_cmd;
   477 };
   478 #else
   479 class GlobCommand : public IMetamodSourceCommandInfo
   480 {
   481 public:
   482 	unsigned int GetArgCount()
   483 	{
   484 		return engine->Cmd_Argc() - 1;
   485 	}
   486 
   487 	const char *GetArg(unsigned int num)
   488 	{
   489 		return engine->Cmd_Argv(num);
   490 	}
   491 
   492 	const char *GetArgString()
   493 	{
   494 		return engine->Cmd_Args();
   495 	}
   496 };
   497 #endif
   498 
   499 #if SOURCE_ENGINE >= SE_ORANGEBOX
   500 void LocalCommand_Meta(const CCommand &args)
   501 {
   502 	GlobCommand cmd(&args);
   503 #else
   504 void LocalCommand_Meta()
   505 {
   506 	GlobCommand cmd;
   507 #endif
   508 	Command_Meta(&cmd);
   509 }
   510 
   511 #if SOURCE_ENGINE >= SE_ORANGEBOX
   512 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   513 {
   514 	GlobCommand cmd(&_cmd);
   515 #else
   516 void ClientCommand(edict_t *pEdict)
   517 {
   518 	GlobCommand cmd;
   519 #endif
   520 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   521 	{
   522 		Command_ClientMeta(pEdict, &cmd);
   523 		RETURN_META(MRES_SUPERCEDE);
   524 	}
   525 
   526 	RETURN_META(MRES_IGNORED);
   527 }
   528 
   529 #if SOURCE_ENGINE == SE_CSGO
   530 
   531 void CacheUserMessages()
   532 {
   533 }
   534 
   535 #else
   536 
   537 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
   538 void Detour_Error(const tchar *pMsg, ...)
   539 {
   540 	/* Jump back to setjmp() in CacheUserMessages() */
   541 	longjmp(usermsg_end, 1);
   542 }
   543 
   544 #define IA32_JMP_IMM32 0xE9
   545 
   546 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
   547  * early Orange Box. This is because Error() from tier0 gets called when a bad index is
   548  * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
   549  *
   550  * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
   551  * to a point before GetUserMessageInfo() is called. The detour is then removed and we
   552  * exit.
   553  */
   554 void CacheUserMessages()
   555 {
   556 	int q, size;
   557 	char buffer[256];
   558 	unsigned char *target, *detour;
   559 	unsigned char orig_bytes[5];
   560 
   561 	target = (unsigned char *)&Error;
   562 	detour = (unsigned char *)&Detour_Error;
   563 
   564 	/* Save bytes from target function */
   565 	memcpy(orig_bytes, target, sizeof(orig_bytes));
   566 
   567 	/* Patch in relative jump to our Error() detour */
   568 	SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   569 	target[0] = IA32_JMP_IMM32;
   570 	*(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
   571 
   572 	/* This is where longjmp() will end up */
   573 	if (setjmp(usermsg_end))
   574 	{
   575 		/* Restore bytes and memory protection */
   576 		memcpy(target, orig_bytes, sizeof(orig_bytes));
   577 		SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
   578 		return;
   579 	}
   580 
   581 	q = 0;
   582 
   583 	/* If GetUserMessageInfo() calls Error(), we should end up in our detour */
   584 	while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
   585 	{
   586 		usermsgs_list.push_back(UsrMsgInfo(size, buffer));
   587 		q++;
   588 	}
   589 
   590 	/* Jump back to setjmp() */
   591 	longjmp(usermsg_end, 1);
   592 }
   593 
   594 #endif