core/provider/provider_ep2.cpp
author Scott Ehlert <ds@alliedmods.net>
Sat May 22 00:45:44 2010 -0500 (2010-05-22)
changeset 716 6925fbd2b9fa
parent 689 4065ba5e9155
child 725 9eec529c3caa
permissions -rw-r--r--
Added Mac OS X build support to stub/sample plugin makefiles (bug 4391, r=dvander).
     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 		return;
   135 	}
   136 
   137 #if SOURCE_ENGINE >= SE_ORANGEBOX
   138 	g_pCVar = icvar;
   139 #endif
   140 
   141 	g_SMConVarAccessor.RegisterConCommandBase(&meta_local_cmd);
   142 
   143 	CacheUserMessages();
   144 
   145 #if SOURCE_ENGINE == SE_DARKMESSIAH
   146 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   147 	{
   148 		/* This is very unlikely considering it's old engine */
   149 		mm_LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   150 		mm_LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   151 	}
   152 #endif
   153 
   154 	if (gameclients)
   155 	{
   156 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, gameclients, ClientCommand, false);
   157 	}
   158 }
   159 
   160 void BaseProvider::Notify_DLLShutdown_Pre()
   161 {
   162 	g_SMConVarAccessor.RemoveMetamodCommands();
   163 
   164 #if SOURCE_ENGINE == SE_DARKMESSIAH
   165 	if (g_Metamod.IsLoadedAsGameDLL())
   166 	{
   167 		icvar->UnlinkVariables(FCVAR_GAMEDLL);
   168 	}
   169 #endif
   170 }
   171 
   172 bool BaseProvider::IsRemotePrintingAvailable()
   173 {
   174 	return true;
   175 }
   176 
   177 void BaseProvider::ClientConsolePrint(edict_t *client, const char *message)
   178 {
   179 	engine->ClientPrintf(client, message);
   180 }
   181 
   182 void BaseProvider::ServerCommand(const char *cmd)
   183 {
   184 	engine->ServerCommand(cmd);
   185 }
   186 
   187 const char *BaseProvider::GetConVarString(ConVar *convar)
   188 {
   189 	if (convar == NULL)
   190 	{
   191 		return NULL;
   192 	}
   193 
   194 	return convar->GetString();
   195 }
   196 
   197 void BaseProvider::SetConVarString(ConVar *convar, const char *str)
   198 {
   199 	convar->SetValue(str);
   200 }
   201 
   202 bool BaseProvider::IsConCommandBaseACommand(ConCommandBase *pCommand)
   203 {
   204 	return pCommand->IsCommand();
   205 }
   206 
   207 
   208 bool BaseProvider::IsSourceEngineBuildCompatible(int build)
   209 {
   210 	return (build == SOURCE_ENGINE_ORIGINAL
   211 			|| build == SOURCE_ENGINE_EPISODEONE);
   212 }
   213 
   214 const char *BaseProvider::GetCommandLineValue(const char *key, const char *defval)
   215 {
   216 	if (key[0] == '-' || key[0] == '+')
   217 	{
   218 		return CommandLine()->ParmValue(key, defval);
   219 	}
   220 	else if (icvar)
   221 	{
   222 		const char *val;
   223 		if ((val = icvar->GetCommandLineValue(key)) == NULL)
   224 		{
   225 			return defval;
   226 		}
   227 
   228 		return val;
   229 	}
   230 
   231 	return NULL;
   232 }
   233 
   234 int BaseProvider::TryServerGameDLL(const char *iface)
   235 {
   236 	if (strncmp(iface, "ServerGameDLL", 13) != 0)
   237 	{
   238 		return 0;
   239 	}
   240 
   241 	return atoi(&iface[13]);
   242 }
   243 
   244 bool BaseProvider::LogMessage(const char *buffer)
   245 {
   246 	if (!engine)
   247 	{
   248 		return false;
   249 	}
   250 
   251 	engine->LogPrint(buffer);
   252 
   253 	return true;
   254 }
   255 
   256 bool BaseProvider::GetHookInfo(ProvidedHooks hook, SourceHook::MemFuncInfo *pInfo)
   257 {
   258 	SourceHook::MemFuncInfo mfi = {true, -1, 0, 0};
   259 
   260 	if (hook == ProvidedHook_LevelInit)
   261 	{
   262 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelInit, mfi);
   263 	}
   264 	else if (hook == ProvidedHook_LevelShutdown)
   265 	{
   266 		SourceHook::GetFuncInfo(&IServerGameDLL::LevelShutdown, mfi);
   267 	}
   268 	else if (hook == ProvidedHook_GameInit)
   269 	{
   270 		SourceHook::GetFuncInfo(&IServerGameDLL::GameInit, mfi);
   271 	}
   272 
   273 	*pInfo = mfi;
   274 
   275 	return (mfi.thisptroffs >= 0);
   276 }
   277 
   278 void BaseProvider::DisplayError(const char *fmt, ...)
   279 {
   280 	va_list ap;
   281 	char buffer[2048];
   282 
   283 	va_start(ap, fmt);
   284 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   285 	va_end(ap);
   286 
   287 	Error(buffer);
   288 }
   289 
   290 void BaseProvider::DisplayWarning(const char *fmt, ...)
   291 {
   292 	va_list ap;
   293 	char buffer[2048];
   294 
   295 	va_start(ap, fmt);
   296 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   297 	va_end(ap);
   298 
   299 	Warning(buffer);
   300 }
   301 
   302 IConCommandBaseAccessor *BaseProvider::GetConCommandBaseAccessor()
   303 {
   304 	return &g_SMConVarAccessor;
   305 }
   306 
   307 bool BaseProvider::RegisterConCommandBase(ConCommandBase *pCommand)
   308 {
   309 	return g_SMConVarAccessor.Register(pCommand);
   310 }
   311 
   312 void BaseProvider::UnregisterConCommandBase(ConCommandBase *pCommand)
   313 {
   314 	return g_SMConVarAccessor.Unregister(pCommand);
   315 }
   316 
   317 int BaseProvider::GetUserMessageCount()
   318 {
   319 	return (int)usermsgs_list.size();
   320 }
   321 
   322 int BaseProvider::FindUserMessage(const char *name, int *size)
   323 {
   324 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   325 	{
   326 		if (usermsgs_list[i].name.compare(name) == 0)
   327 		{
   328 			if (size)
   329 			{
   330 				*size = usermsgs_list[i].size;
   331 			}
   332 			return (int)i;
   333 		}
   334 	}
   335 	
   336 	return -1;
   337 }
   338 
   339 const char *BaseProvider::GetUserMessage(int index, int *size)
   340 {
   341 	if (index < 0 || index >= (int)usermsgs_list.size())
   342 	{
   343 		return NULL;
   344 	}
   345 
   346 	if (size)
   347 	{
   348 		*size = usermsgs_list[index].size;
   349 	}
   350 
   351 	return usermsgs_list[index].name.c_str();
   352 }
   353 
   354 const char *BaseProvider::GetGameDescription()
   355 {
   356 	return server->GetGameDescription();
   357 }
   358 
   359 int BaseProvider::DetermineSourceEngine(const char *game)
   360 {
   361 #if SOURCE_ENGINE == SE_LEFT4DEAD2
   362 	return SOURCE_ENGINE_LEFT4DEAD2;
   363 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   364 	return SOURCE_ENGINE_LEFT4DEAD;
   365 #elif SOURCE_ENGINE == SE_ORANGEBOX
   366 	return SOURCE_ENGINE_ORANGEBOX;
   367 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
   368 	return SOURCE_ENGINE_ORANGEBOXVALVE;
   369 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   370 	return SOURCE_ENGINE_DARKMESSIAH;
   371 #else
   372 #error "SOURCE_ENGINE not defined to a known value"
   373 #endif
   374 }
   375 
   376 ConVar *BaseProvider::CreateConVar(const char *name,
   377 								   const char *defval,
   378 								   const char *help,
   379 								   int flags)
   380 {
   381 	int newflags = 0;
   382 	if (flags & ConVarFlag_Notify)
   383 	{
   384 		newflags |= FCVAR_NOTIFY;
   385 	}
   386 	if (flags & ConVarFlag_SpOnly)
   387 	{
   388 		newflags |= FCVAR_SPONLY;
   389 	}
   390 
   391 	ConVar *pVar = new ConVar(name, defval, newflags, help);
   392 
   393 	g_SMConVarAccessor.RegisterConCommandBase(pVar);
   394 
   395 	return pVar;
   396 }
   397 
   398 bool BaseProvider::ProcessVDF(const char *file, char path[], size_t path_len, char alias[], size_t alias_len)
   399 {
   400 	if (baseFs == NULL)
   401 	{
   402 		return false;
   403 	}
   404 
   405 	KeyValues *pValues;
   406 	const char *plugin_file, *p_alias;
   407 
   408 	pValues = new KeyValues("Metamod Plugin");
   409 
   410 	if (!pValues->LoadFromFile(baseFs, file))
   411 	{
   412 		pValues->deleteThis();
   413 		return false;
   414 	}
   415 
   416 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   417 	{
   418 		pValues->deleteThis();
   419 		return false;
   420 	}
   421 
   422 	UTIL_Format(path, path_len, "%s", plugin_file);
   423 
   424 	if ((p_alias = pValues->GetString("alias", NULL)) != NULL)
   425 	{
   426 		UTIL_Format(alias, alias_len, "%s", p_alias);
   427 	}
   428 	else
   429 	{
   430 		UTIL_Format(alias, alias_len, "");
   431 	}
   432 
   433 	pValues->deleteThis();
   434 
   435 	return true;
   436 }
   437 
   438 #if SOURCE_ENGINE >= SE_ORANGEBOX
   439 class GlobCommand : public IMetamodSourceCommandInfo
   440 {
   441 public:
   442 	GlobCommand(const CCommand *cmd) : m_cmd(cmd)
   443 	{
   444 	}
   445 public:
   446 	unsigned int GetArgCount()
   447 	{
   448 		return m_cmd->ArgC() - 1;
   449 	}
   450 
   451 	const char *GetArg(unsigned int num)
   452 	{
   453 		return m_cmd->Arg(num);
   454 	}
   455 
   456 	const char *GetArgString()
   457 	{
   458 		return m_cmd->ArgS();
   459 	}
   460 private:
   461 	const CCommand *m_cmd;
   462 };
   463 #else
   464 class GlobCommand : public IMetamodSourceCommandInfo
   465 {
   466 public:
   467 	unsigned int GetArgCount()
   468 	{
   469 		return engine->Cmd_Argc() - 1;
   470 	}
   471 
   472 	const char *GetArg(unsigned int num)
   473 	{
   474 		return engine->Cmd_Argv(num);
   475 	}
   476 
   477 	const char *GetArgString()
   478 	{
   479 		return engine->Cmd_Args();
   480 	}
   481 };
   482 #endif
   483 
   484 #if SOURCE_ENGINE >= SE_ORANGEBOX
   485 void LocalCommand_Meta(const CCommand &args)
   486 {
   487 	GlobCommand cmd(&args);
   488 #else
   489 void LocalCommand_Meta()
   490 {
   491 	GlobCommand cmd;
   492 #endif
   493 	Command_Meta(&cmd);
   494 }
   495 
   496 #if SOURCE_ENGINE >= SE_ORANGEBOX
   497 void ClientCommand(edict_t *pEdict, const CCommand &_cmd)
   498 {
   499 	GlobCommand cmd(&_cmd);
   500 #else
   501 void ClientCommand(edict_t *pEdict)
   502 {
   503 	GlobCommand cmd;
   504 #endif
   505 	if (strcmp(cmd.GetArg(0), "meta") == 0)
   506 	{
   507 		Command_ClientMeta(pEdict, &cmd);
   508 		RETURN_META(MRES_SUPERCEDE);
   509 	}
   510 
   511 	RETURN_META(MRES_IGNORED);
   512 }
   513 
   514 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
   515 void Detour_Error(const tchar *pMsg, ...)
   516 {
   517 	/* Jump back to setjmp() in CacheUserMessages() */
   518 	longjmp(usermsg_end, 1);
   519 }
   520 
   521 #define IA32_JMP_IMM32 0xE9
   522 
   523 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
   524  * early Orange Box. This is because Error() from tier0 gets called when a bad index is
   525  * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
   526  *
   527  * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
   528  * to a point before GetUserMessageInfo() is called. The detour is then removed and we
   529  * exit.
   530  */
   531 void CacheUserMessages()
   532 {
   533 	int q, size;
   534 	char buffer[256];
   535 	unsigned char *target, *detour;
   536 	unsigned char orig_bytes[5];
   537 
   538 	target = (unsigned char *)&Error;
   539 	detour = (unsigned char *)&Detour_Error;
   540 
   541 	/* Save bytes from target function */
   542 	memcpy(orig_bytes, target, sizeof(orig_bytes));
   543 
   544 	/* Patch in relative jump to our Error() detour */
   545 	SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   546 	target[0] = IA32_JMP_IMM32;
   547 	*(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
   548 
   549 	/* This is where longjmp() will end up */
   550 	if (setjmp(usermsg_end))
   551 	{
   552 		/* Restore bytes and memory protection */
   553 		memcpy(target, orig_bytes, sizeof(orig_bytes));
   554 		SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
   555 		return;
   556 	}
   557 
   558 	q = 0;
   559 
   560 	/* If GetUserMessageInfo() calls Error(), we should end up in our detour */
   561 	while (server->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
   562 	{
   563 		usermsgs_list.push_back(UsrMsgInfo(size, buffer));
   564 		q++;
   565 	}
   566 
   567 	/* Jump back to setjmp() */
   568 	longjmp(usermsg_end, 1);
   569 }