core-legacy/CSmmAPI.cpp
author David Anderson <dvander@alliedmods.net>
Mon Nov 18 11:57:04 2013 -0800 (2013-11-18)
changeset 884 ae6d28eabea0
parent 747 9563de0165f7
permissions -rw-r--r--
Push build.
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2010 Metamod:Source Development Team
     3  * No warranties of any kind
     4  *
     5  * License: zlib/libpng
     6  *
     7  * Author(s): David "BAILOPAN" Anderson
     8  * ============================
     9  */
    10 
    11 #include "convar_smm.h"
    12 #include "CSmmAPI.h"
    13 #include "sourcemm.h"
    14 #include "concommands.h"
    15 #include "CPlugin.h"
    16 #include "util.h"
    17 #include "sh_memory.h"
    18 #include <setjmp.h>
    19 #if defined __linux__
    20 #include <sys/stat.h>
    21 #endif
    22 
    23 /**
    24  * @brief Implementation of main API interface
    25  * @file CSmmAPI.cpp
    26  */
    27 
    28 using namespace SourceMM;
    29 using namespace SourceHook;
    30 
    31 struct UsrMsgInfo
    32 {
    33 	UsrMsgInfo()
    34 	{
    35 	}
    36 	UsrMsgInfo(int s, const char *t) : size(s), name(t)
    37 	{
    38 	}
    39 	int size;
    40 	String name;
    41 };
    42 
    43 CSmmAPI g_SmmAPI;
    44 
    45 static CVector<UsrMsgInfo> usermsgs_list;
    46 static jmp_buf usermsg_end;
    47 
    48 CSmmAPI::CSmmAPI()
    49 {
    50 	m_ConPrintf = NULL;
    51 	m_CmdCache = false;
    52 	m_VSP = false;
    53 }
    54 
    55 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
    56 {
    57 	va_list ap;
    58 	static char buffer[2048];
    59 
    60 	va_start(ap, msg);
    61 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
    62 	va_end(ap);
    63 
    64 	LogMessage("[%s] %s", pl->GetLogTag(), buffer);
    65 }
    66 
    67 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
    68 {
    69 	if (syn)
    70 		return EngineFactory;
    71 	return g_Engine.engineFactory;
    72 }
    73 
    74 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
    75 {
    76 	if (syn)
    77 		return PhysicsFactory;
    78 	return g_Engine.physicsFactory;
    79 }
    80 
    81 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
    82 {
    83 	if (syn)
    84 		return FileSystemFactory;
    85 	return g_Engine.fileSystemFactory;
    86 }
    87 
    88 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
    89 {
    90 	if (syn)
    91 		return ServerFactory;
    92 	return g_GameDll.factory;
    93 }
    94 
    95 CGlobalVars *CSmmAPI::pGlobals()
    96 {
    97 	return g_Engine.pGlobals;
    98 }
    99 
   100 void CSmmAPI::SetLastMetaReturn(META_RES res)
   101 {
   102 	m_Res = res;
   103 }
   104 
   105 META_RES CSmmAPI::GetLastMetaReturn()
   106 {
   107 	return m_Res;
   108 }
   109 
   110 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
   111 {
   112 	return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
   113 }
   114 
   115 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   116 {
   117 	if (pCommand->IsCommand())
   118 	{
   119 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   120 	} else {
   121 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   122 	}
   123 
   124 	return g_SMConVarAccessor.Register(pCommand);
   125 }
   126 
   127 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   128 {
   129 	if (pCommand->IsCommand())
   130 	{
   131 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   132 	} else {
   133 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   134 	}
   135 
   136 	CPluginManager::CPlugin *pPlugin = g_PluginMngr.FindByAPI(plugin);
   137 	PluginId id = (pPlugin != NULL) ? pPlugin->m_Id : Pl_BadLoad;
   138 
   139 	NotifyConCommandBaseDrop(id, pCommand);
   140 
   141 	g_SMConVarAccessor.Unregister(pCommand);
   142 }
   143 
   144 void CSmmAPI::ConPrint(const char *fmt)
   145 {
   146 	(m_ConPrintf)("%s", fmt);
   147 }
   148 
   149 void CSmmAPI::ConPrintf(const char *fmt, ...)
   150 {
   151 	va_list ap;
   152 	static char buffer[4096];
   153 
   154 	va_start(ap, fmt);
   155 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   156 	va_end(ap);
   157 
   158 	(m_ConPrintf)("%s", buffer);
   159 }
   160 
   161 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   162 {
   163 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   164 	CPluginEventHandler cpeh;
   165 
   166 	cpeh.event = pListener;
   167 	cpeh.got_vsp = false;
   168 
   169 	pl->m_Events.push_back(cpeh);
   170 }
   171 
   172 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
   173 {
   174 	if (id)
   175 	{
   176 		*id = 0;
   177 	}
   178 
   179 	if (!iface)
   180 	{
   181 		return NULL;
   182 	}
   183 
   184 	//first check ours... we get first chance!
   185 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   186 	{
   187 		if (_ret)
   188 		{
   189 			*_ret = IFACE_OK;
   190 		}
   191 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   192 	} else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
   193 		if (_ret)
   194 		{
   195 			*_ret = IFACE_OK;
   196 		}
   197 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   198 	}
   199 
   200 	CPluginManager::CPlugin *pl;
   201 	SourceHook::List<CPluginEventHandler>::iterator event;
   202 	IMetamodListener *api;
   203 	int ret = 0;
   204 	void *val = NULL;
   205 
   206 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
   207 	{
   208 		pl = (*iter);
   209 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
   210 		{
   211 			api = (*event).event;
   212 			ret = IFACE_FAILED;
   213 			if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
   214 			{
   215 				if (_ret)
   216 					*_ret = ret;
   217 				if (id)
   218 					*id = pl->m_Id;
   219 				return val;
   220 			}
   221 		}
   222 	}
   223 
   224 	if (_ret)
   225 		*_ret = IFACE_FAILED;
   226 
   227 	return NULL;
   228 }
   229 
   230 //////////////////////////////////////////////////////////////////////////
   231 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
   232 // (note: you can find the offset by looking for the text               //
   233 //   "Echo text to console", you'll find the callback cmd pushed on the //
   234 //   stack.)                                                            //
   235 //////////////////////////////////////////////////////////////////////////
   236 
   237 #define SIGLEN			8
   238 #define ENGINE486_SIG	"\x55\x89\xE5\x53\x83\xEC\x14\xBB"
   239 #define ENGINE486_OFFS	40
   240 #define ENGINE686_SIG	"\x53\x83\xEC\x08\xBB\x01\x00\x00"
   241 #define ENGINE686_OFFS	50
   242 #define	ENGINEAMD_SIG	"\x53\x51\xBB\x01\x00\x00\x00\x51"
   243 #define	ENGINEAMD_OFFS	47
   244 #define ENGINEW32_SIG	"\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
   245 #define ENGINEW32_OFFS	38
   246 #define IA32_CALL		0xE8
   247 
   248 //Thanks to fysh for the idea of extracting info from "echo" and for
   249 // having the original offsets at hand!
   250 bool CSmmAPI::CacheCmds()
   251 {
   252 	ICvar *pCvar = g_Engine.icvar;
   253 
   254 	ConCommandBase *pBase = pCvar->GetCommands();
   255 	unsigned char *ptr = NULL;
   256 	FnCommandCallback callback = NULL;
   257 	int offs = 0;
   258 
   259 	while (pBase)
   260 	{
   261 		if ( strcmp(pBase->GetName(), "echo") == 0 )
   262 		{
   263 			//callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
   264 			callback = ((ConCommand *)pBase)->GetCallback();
   265 			ptr = (unsigned char *)callback;
   266 		#ifdef OS_LINUX
   267 			if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
   268 			{
   269 				offs = ENGINE486_OFFS;
   270 			}
   271 			else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
   272 			{
   273 				offs = ENGINE686_OFFS;
   274 			}
   275 			else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
   276 			{
   277 				offs = ENGINEAMD_OFFS;
   278 			}
   279 		#elif defined OS_WIN32 // Only one Windows engine binary so far...
   280 			if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
   281 			{
   282 				offs = ENGINEW32_OFFS;
   283 			}
   284 		#endif
   285 
   286 			if (!offs || ptr[offs - 1] != IA32_CALL)
   287 			{
   288 				m_ConPrintf = (CONPRINTF_FUNC)Msg;
   289 				return false;
   290 			}
   291 			//get the relative offset
   292 			m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
   293 			//add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
   294 			m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
   295 
   296 			m_CmdCache = true;
   297 
   298 			return true;
   299 		}
   300 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   301 	}
   302 
   303 	m_ConPrintf = (CONPRINTF_FUNC)Msg;
   304 
   305 	return false;
   306 }
   307 
   308 bool CSmmAPI::CmdCacheSuccessful()
   309 {
   310 	return m_CmdCache;
   311 }
   312 
   313 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   314 {
   315 	major = SM_VERS_API_MAJOR;
   316 	minor = SM_VERS_API_MINOR;
   317 	plvers = PLAPI_VERSION;
   318 	plmin = PLAPI_MIN_VERSION;
   319 }
   320 
   321 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
   322 {
   323 	shvers = SH_IFACE_VERSION;
   324 	shimpl = SH_IMPL_VERSION;
   325 }
   326 
   327 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
   328 {
   329 	int length = (int)strlen(iface);
   330 	int i;
   331 	int num = 0;
   332 
   333 	for (i = length - 1; i >= 0; i--)
   334 	{
   335 		if (!isdigit(iface[i]))
   336 		{
   337 			if (i != length - 1)
   338 			{
   339 				num = 1;
   340 			}
   341 			break;
   342 		}
   343 	}
   344 
   345 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   346 	{
   347 		return -1;
   348 	}
   349 
   350 	if (i != length - 1)
   351 		num = atoi(&(iface[++i]));
   352 
   353 	num++;
   354 
   355 	snprintf(&(iface[i]), 4, "%03d", num);
   356 
   357 	return num;
   358 }
   359 
   360 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   361 {
   362 	char _if[256];	/* assume no interface goes beyond this */
   363 	size_t len = strlen(iface);
   364 	int num = 0;
   365 	void *pf = NULL;
   366 
   367 	if (max > 999)
   368 		max = 999;
   369 
   370 	if (len + 4 > sizeof(_if))
   371 	{
   372 		if (ret)
   373 		{
   374 			*ret = IFACE_FAILED;
   375 		}
   376 		return NULL;
   377 	}
   378 
   379 	strcpy(_if, iface);
   380 
   381 	do
   382 	{
   383 		if ( (pf = (fn)(_if, ret)) != NULL )
   384 			break;
   385 		if (num > max)
   386 			break;
   387 	} while (( num = FormatIface(_if, len+1) ));
   388 
   389 	return pf;
   390 }
   391 
   392 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   393 {
   394 	char buffer[256];	/* assume no interface will go beyond this */
   395 	size_t len = strlen(iface);
   396 	int ret;			/* just in case something doesn't handle NULL properly */
   397 
   398 	if (len > sizeof(buffer) - 4)
   399 	{
   400 		return NULL;
   401 	}
   402 
   403 	strcpy(buffer, iface);
   404 
   405 	if (min != -1)
   406 	{
   407 		char *ptr = &buffer[len - 1];
   408 		int digits = 0;
   409 		while (isdigit(*ptr) && digits <=3)
   410 		{
   411 			*ptr = '\0';
   412 			digits++;
   413 			ptr--;
   414 		}
   415 		if (digits != 3)
   416 		{
   417 			/* for now, assume this is an error */
   418 			strcpy(buffer, iface);
   419 		} else {
   420 			char num[4];
   421 			min = (min == 0) ? 1 : min;
   422 			snprintf(num, sizeof(num), "%03d", min);
   423 			strcat(buffer, num);
   424 		}
   425 	}
   426 
   427 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   428 }
   429 
   430 const char *CSmmAPI::GetBaseDir()
   431 {
   432 	return g_ModPath.c_str();
   433 }
   434 
   435 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   436 {
   437 	va_list ap;
   438 	va_start(ap, fmt);
   439 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   440 	va_end(ap);
   441 
   442 	for (size_t i = 0; i < mylen; i++)
   443 	{
   444 		if (buffer[i] == ALT_SEP_CHAR)
   445 		{
   446 			buffer[i] = PATH_SEP_CHAR;
   447 		}
   448 	}
   449 }
   450 
   451 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
   452 {
   453 	va_list ap;
   454 	static char buffer[4096];
   455 
   456 	va_start(ap, fmt);
   457 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   458 	va_end(ap);
   459 
   460 	g_Engine.engine->ClientPrintf(client, buffer);
   461 }
   462 
   463 void CSmmAPI::LoadAsVSP()
   464 {
   465 	size_t len;
   466 	char engine_file[PATH_SIZE];
   467 	char rel_path[PATH_SIZE * 2];
   468 
   469 	GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
   470 
   471 	/* Chop off the "engine" file part */
   472 	len = strlen(engine_file);
   473 	for (size_t i = len - 1; i < len; i--)
   474 	{
   475 		if (engine_file[i] == '/'
   476 			|| engine_file[i] == '\\')
   477 		{
   478 			engine_file[i] = '\0';
   479 			break;
   480 		}
   481 	}
   482 
   483 	const char *usepath = g_MetamodPath.c_str();
   484 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, g_MetamodPath.c_str()))
   485 	{
   486 		usepath = rel_path;
   487 	}
   488 	
   489 	char command[PATH_SIZE * 2];
   490 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   491 	g_Engine.engine->ServerCommand(command);
   492 }
   493 
   494 void CSmmAPI::EnableVSPListener()
   495 {
   496 	/* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
   497 	if (g_bGameInit && !m_VSP && !g_bIsBridgedAsVsp)
   498 	{
   499 		LoadAsVSP();
   500 	}
   501 	m_VSP = true;
   502 }
   503 
   504 int CSmmAPI::GetGameDLLVersion()
   505 {
   506 	return g_GameDllVersion;
   507 }
   508 
   509 /* This only gets called if IServerGameDLL::GetUserMessageInfo() triggers it */
   510 void Detour_Error(const tchar *pMsg, ...)
   511 {
   512 	/* Jump back to setjmp() in CacheUserMessages() */
   513 	longjmp(usermsg_end, 1);
   514 }
   515 
   516 /* IServerGameDLL::GetUserMessageInfo() crashes on games based on the old engine and
   517  * early Orange Box. This is because Error() from tier0 gets called when a bad index is
   518  * passed. This is all due to a bug in CUtlRBTree::IsValidIndex().
   519  *
   520  * So we detour Error() to fix this. Our detour then jumps back into CacheUserMessages()
   521  * to a point before GetUserMessageInfo() is called. The detour is then removed and we
   522  * exit.
   523  */
   524 void CSmmAPI::CacheUserMessages()
   525 {
   526 	int q, size;
   527 	char buffer[256];
   528 	unsigned char *target, *detour;
   529 	unsigned char orig_bytes[5];
   530 
   531 	target = (unsigned char *)&Error;
   532 	detour = (unsigned char *)&Detour_Error;
   533 
   534 	/* Save bytes from target function */
   535 	memcpy(orig_bytes, target, sizeof(orig_bytes));
   536 
   537 	/* Patch in relative jump to our Error() detour */
   538 	SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_WRITE|SH_MEM_EXEC);
   539 	target[0] = IA32_JMP_IMM32;
   540 	*(int32_t *)&target[1] = (int32_t)(detour - (target + 5));
   541 
   542 	/* This is where longjmp() will end up */
   543 	if (setjmp(usermsg_end))
   544 	{
   545 		/* Restore bytes and memory protection */
   546 		memcpy(target, orig_bytes, sizeof(orig_bytes));
   547 		SetMemAccess(target, sizeof(orig_bytes), SH_MEM_READ|SH_MEM_EXEC);
   548 		return;
   549 	}
   550 
   551 	q = 0;
   552 
   553 	/* If GetUserMessageInfo() calls Error(), we should end up in our detour */
   554 	while (g_GameDll.pGameDLL->GetUserMessageInfo(q, buffer, sizeof(buffer), size))
   555 	{
   556 		usermsgs_list.push_back(UsrMsgInfo(size, buffer));
   557 		q++;
   558 	}
   559 
   560 	/* Jump back to setjmp() */
   561 	longjmp(usermsg_end, 1);
   562 }
   563 
   564 int CSmmAPI::GetUserMessageCount()
   565 {
   566 	return (int)usermsgs_list.size();
   567 }
   568 
   569 int CSmmAPI::FindUserMessage(const char *name, int *size)
   570 {
   571 	for (size_t i = 0; i < usermsgs_list.size(); i++)
   572 	{
   573 		if (usermsgs_list[i].name.compare(name) == 0)
   574 		{
   575 			if (size)
   576 			{
   577 				*size = usermsgs_list[i].size;
   578 			}
   579 			return (int)i;
   580 		}
   581 	}
   582 
   583 	return -1;
   584 }
   585 
   586 const char *CSmmAPI::GetUserMessage(int index, int *size)
   587 {
   588 	if (index < 0 || index >= (int)usermsgs_list.size())
   589 	{
   590 		return NULL;
   591 	}
   592 
   593 	if (size)
   594 	{
   595 		*size = usermsgs_list[index].size;
   596 	}
   597 
   598 	return usermsgs_list[index].name.c_str();
   599 }
   600 
   601 IServerPluginCallbacks *CSmmAPI::GetVSPInfo(int *pVersion)
   602 {
   603 	if (pVersion != NULL)
   604 		*pVersion = g_vsp_version;
   605 
   606 	return g_pRealVspCallbacks;
   607 }
   608 
   609 int CSmmAPI::GetSourceEngineBuild()
   610 {
   611 	return g_Engine.original ? SOURCE_ENGINE_ORIGINAL : SOURCE_ENGINE_EPISODEONE;
   612 }
   613 
   614 void CSmmAPI::GetFullPluginPath(const char *plugin, char *buffer, size_t len)
   615 {
   616 	const char *pext, *ext;
   617 
   618 	/* First find if it's an absolute path or not... */
   619 	if (plugin[0] == '/' || strncmp(&(plugin[1]), ":\\", 2) == 0)
   620 	{
   621 		UTIL_Format(buffer, len, plugin);
   622 		return;
   623 	}
   624 
   625 	/* Attempt to find a file extension */
   626 	pext = UTIL_GetExtension(plugin);
   627 	/* Add an extension if there's none there */
   628 	if (!pext)
   629 	{
   630 #if defined WIN32 || defined _WIN32
   631 		ext = ".dll";
   632 #else
   633 		ext = "_i486.so";
   634 #endif
   635 	}
   636 	else
   637 	{
   638 		ext = "";
   639 	}
   640 
   641 	/* Format the new path */
   642 	PathFormat(buffer, len, "%s/%s%s", g_ModPath.c_str(), plugin, ext);
   643 
   644 #if defined __linux__
   645 	/* If path was passed without extension and it doesn't exist with "_i486.so" try ".so" */
   646 	struct stat s;
   647 	if (!pext && stat(buffer, &s) != 0)
   648 	{
   649 		PathFormat(buffer, len, "%s/%s.so", g_ModPath.c_str(), plugin);
   650 	}
   651 #endif
   652 }
   653