core-legacy/CSmmAPI.cpp
author David Anderson <dvander@alliedmods.net>
Fri Nov 14 05:02:00 2008 -0600 (2008-11-14)
changeset 545 07e5df11f9fc
parent 541 core-1.4/CSmmAPI.cpp@35a8cda28485
child 548 dd85920ecaaf
permissions -rw-r--r--
Renamed core-1.4 to core-legacy.
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2008 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 "vsp_listener.h"
    17 
    18 /**
    19  * @brief Implementation of main API interface
    20  * @file CSmmAPI.cpp
    21  */
    22 
    23 using namespace SourceMM;
    24 
    25 CSmmAPI g_SmmAPI;
    26 
    27 CSmmAPI::CSmmAPI()
    28 {
    29 	m_ConPrintf = NULL;
    30 	m_CmdCache = false;
    31 	m_MsgCount = -1;
    32 	m_VSP = false;
    33 }
    34 
    35 CSmmAPI::~CSmmAPI()
    36 {
    37 	m_UserMessages.RemoveAll();
    38 }
    39 
    40 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
    41 {
    42 	va_list ap;
    43 	static char buffer[2048];
    44 
    45 	va_start(ap, msg);
    46 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
    47 	va_end(ap);
    48 
    49 	LogMessage("[%s] %s", pl->GetLogTag(), buffer);
    50 }
    51 
    52 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
    53 {
    54 	if (syn)
    55 		return EngineFactory;
    56 	return g_Engine.engineFactory;
    57 }
    58 
    59 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
    60 {
    61 	if (syn)
    62 		return PhysicsFactory;
    63 	return g_Engine.physicsFactory;
    64 }
    65 
    66 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
    67 {
    68 	if (syn)
    69 		return FileSystemFactory;
    70 	return g_Engine.fileSystemFactory;
    71 }
    72 
    73 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
    74 {
    75 	if (syn)
    76 		return CreateInterface;
    77 	return g_GameDll.factory;
    78 }
    79 
    80 CGlobalVars *CSmmAPI::pGlobals()
    81 {
    82 	return g_Engine.pGlobals;
    83 }
    84 
    85 void CSmmAPI::SetLastMetaReturn(META_RES res)
    86 {
    87 	m_Res = res;
    88 }
    89 
    90 META_RES CSmmAPI::GetLastMetaReturn()
    91 {
    92 	return m_Res;
    93 }
    94 
    95 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
    96 {
    97 	return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
    98 }
    99 
   100 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   101 {
   102 	if (pCommand->IsCommand())
   103 	{
   104 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   105 	} else {
   106 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   107 	}
   108 
   109 	return g_SMConVarAccessor.Register(pCommand);
   110 }
   111 
   112 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   113 {
   114 	if (pCommand->IsCommand())
   115 	{
   116 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   117 	} else {
   118 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   119 	}
   120 
   121 	g_SMConVarAccessor.Unregister(pCommand);
   122 }
   123 
   124 void CSmmAPI::ConPrint(const char *fmt)
   125 {
   126 	(m_ConPrintf)("%s", fmt);
   127 }
   128 
   129 void CSmmAPI::ConPrintf(const char *fmt, ...)
   130 {
   131 	va_list ap;
   132 	static char buffer[4096];
   133 
   134 	va_start(ap, fmt);
   135 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   136 	va_end(ap);
   137 
   138 	(m_ConPrintf)("%s", buffer);
   139 }
   140 
   141 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   142 {
   143 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   144 	CPluginEventHandler cpeh;
   145 
   146 	cpeh.event = pListener;
   147 	cpeh.got_vsp = false;
   148 
   149 	pl->m_Events.push_back(cpeh);
   150 }
   151 
   152 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
   153 {
   154 	if (id)
   155 	{
   156 		*id = 0;
   157 	}
   158 
   159 	if (!iface)
   160 	{
   161 		return NULL;
   162 	}
   163 
   164 	//first check ours... we get first chance!
   165 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   166 	{
   167 		if (_ret)
   168 		{
   169 			*_ret = IFACE_OK;
   170 		}
   171 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   172 	} else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
   173 		if (_ret)
   174 		{
   175 			*_ret = IFACE_OK;
   176 		}
   177 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   178 	}
   179 
   180 	CPluginManager::CPlugin *pl;
   181 	SourceHook::List<CPluginEventHandler>::iterator event;
   182 	IMetamodListener *api;
   183 	int ret = 0;
   184 	void *val = NULL;
   185 
   186 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
   187 	{
   188 		pl = (*iter);
   189 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
   190 		{
   191 			api = (*event).event;
   192 			ret = IFACE_FAILED;
   193 			if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
   194 			{
   195 				if (_ret)
   196 					*_ret = ret;
   197 				if (id)
   198 					*id = pl->m_Id;
   199 				return val;
   200 			}
   201 		}
   202 	}
   203 
   204 	if (_ret)
   205 		*_ret = IFACE_FAILED;
   206 
   207 	return NULL;
   208 }
   209 
   210 //////////////////////////////////////////////////////////////////////////
   211 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
   212 // (note: you can find the offset by looking for the text               //
   213 //   "Echo text to console", you'll find the callback cmd pushed on the //
   214 //   stack.)                                                            //
   215 //////////////////////////////////////////////////////////////////////////
   216 
   217 #define SIGLEN			8
   218 #define ENGINE486_SIG	"\x55\x89\xE5\x53\x83\xEC\x14\xBB"
   219 #define ENGINE486_OFFS	40
   220 #define ENGINE686_SIG	"\x53\x83\xEC\x08\xBB\x01\x00\x00"
   221 #define ENGINE686_OFFS	50
   222 #define	ENGINEAMD_SIG	"\x53\x51\xBB\x01\x00\x00\x00\x51"
   223 #define	ENGINEAMD_OFFS	47
   224 #define ENGINEW32_SIG	"\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
   225 #define ENGINEW32_OFFS	38
   226 #define IA32_CALL		0xE8
   227 
   228 //Thanks to fysh for the idea of extracting info from "echo" and for
   229 // having the original offsets at hand!
   230 bool CSmmAPI::CacheCmds()
   231 {
   232 	ICvar *pCvar = g_Engine.icvar;
   233 
   234 	ConCommandBase *pBase = pCvar->GetCommands();
   235 	unsigned char *ptr = NULL;
   236 	FnCommandCallback callback = NULL;
   237 	int offs = 0;
   238 
   239 	while (pBase)
   240 	{
   241 		if ( strcmp(pBase->GetName(), "echo") == 0 )
   242 		{
   243 			//callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
   244 			callback = ((ConCommand *)pBase)->GetCallback();
   245 			ptr = (unsigned char *)callback;
   246 		#ifdef OS_LINUX
   247 			if (UTIL_VerifySignature(ptr, ENGINE486_SIG, SIGLEN))
   248 			{
   249 				offs = ENGINE486_OFFS;
   250 			}
   251 			else if (UTIL_VerifySignature(ptr, ENGINE686_SIG, SIGLEN))
   252 			{
   253 				offs = ENGINE686_OFFS;
   254 			}
   255 			else if (UTIL_VerifySignature(ptr, ENGINEAMD_SIG, SIGLEN))
   256 			{
   257 				offs = ENGINEAMD_OFFS;
   258 			}
   259 		#elif defined OS_WIN32 // Only one Windows engine binary so far...
   260 			if (UTIL_VerifySignature(ptr, ENGINEW32_SIG, SIGLEN))
   261 			{
   262 				offs = ENGINEW32_OFFS;
   263 			}
   264 		#endif
   265 
   266 			if (!offs || ptr[offs - 1] != IA32_CALL)
   267 			{
   268 				m_ConPrintf = (CONPRINTF_FUNC)Msg;
   269 				return false;
   270 			}
   271 			//get the relative offset
   272 			m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
   273 			//add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
   274 			m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
   275 
   276 			m_CmdCache = true;
   277 
   278 			return true;
   279 		}
   280 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   281 	}
   282 
   283 	m_ConPrintf = (CONPRINTF_FUNC)Msg;
   284 
   285 	return false;
   286 }
   287 
   288 bool CSmmAPI::CmdCacheSuccessful()
   289 {
   290 	return m_CmdCache;
   291 }
   292 
   293 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   294 {
   295 	major = SM_VERS_API_MAJOR;
   296 	minor = SM_VERS_API_MINOR;
   297 	plvers = PLAPI_VERSION;
   298 	plmin = PLAPI_MIN_VERSION;
   299 }
   300 
   301 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
   302 {
   303 	shvers = SH_IFACE_VERSION;
   304 	shimpl = SH_IMPL_VERSION;
   305 }
   306 
   307 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
   308 {
   309 	int length = (int)strlen(iface);
   310 	int i;
   311 	int num = 0;
   312 
   313 	for (i = length - 1; i >= 0; i--)
   314 	{
   315 		if (!isdigit(iface[i]))
   316 		{
   317 			if (i != length - 1)
   318 			{
   319 				num = 1;
   320 			}
   321 			break;
   322 		}
   323 	}
   324 
   325 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   326 	{
   327 		return -1;
   328 	}
   329 
   330 	if (i != length - 1)
   331 		num = atoi(&(iface[++i]));
   332 
   333 	num++;
   334 
   335 	snprintf(&(iface[i]), 4, "%03d", num);
   336 
   337 	return num;
   338 }
   339 
   340 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   341 {
   342 	char _if[256];	/* assume no interface goes beyond this */
   343 	size_t len = strlen(iface);
   344 	int num = 0;
   345 	void *pf = NULL;
   346 
   347 	if (max > 999)
   348 		max = 999;
   349 
   350 	if (len + 4 > sizeof(_if))
   351 	{
   352 		if (ret)
   353 		{
   354 			*ret = IFACE_FAILED;
   355 		}
   356 		return NULL;
   357 	}
   358 
   359 	strcpy(_if, iface);
   360 
   361 	do
   362 	{
   363 		if ( (pf = (fn)(_if, ret)) != NULL )
   364 			break;
   365 		if (num > max)
   366 			break;
   367 	} while (( num = FormatIface(_if, len+1) ));
   368 
   369 	return pf;
   370 }
   371 
   372 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   373 {
   374 	char buffer[256];	/* assume no interface will go beyond this */
   375 	size_t len = strlen(iface);
   376 	int ret;			/* just in case something doesn't handle NULL properly */
   377 
   378 	if (len > sizeof(buffer) - 4)
   379 	{
   380 		return NULL;
   381 	}
   382 
   383 	strcpy(buffer, iface);
   384 
   385 	if (min != -1)
   386 	{
   387 		char *ptr = &buffer[len - 1];
   388 		int digits = 0;
   389 		while (isdigit(*ptr) && digits <=3)
   390 		{
   391 			*ptr = '\0';
   392 			digits++;
   393 			ptr--;
   394 		}
   395 		if (digits != 3)
   396 		{
   397 			/* for now, assume this is an error */
   398 			strcpy(buffer, iface);
   399 		} else {
   400 			char num[4];
   401 			min = (min == 0) ? 1 : min;
   402 			snprintf(num, sizeof(num), "%03d", min);
   403 			strcat(buffer, num);
   404 		}
   405 	}
   406 
   407 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   408 }
   409 
   410 const char *CSmmAPI::GetBaseDir()
   411 {
   412 	return g_ModPath.c_str();
   413 }
   414 
   415 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   416 {
   417 	va_list ap;
   418 	va_start(ap, fmt);
   419 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   420 	va_end(ap);
   421 
   422 	for (size_t i = 0; i < mylen; i++)
   423 	{
   424 		if (buffer[i] == ALT_SEP_CHAR)
   425 		{
   426 			buffer[i] = PATH_SEP_CHAR;
   427 		}
   428 	}
   429 }
   430 
   431 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
   432 {
   433 	va_list ap;
   434 	static char buffer[4096];
   435 
   436 	va_start(ap, fmt);
   437 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   438 	va_end(ap);
   439 
   440 	g_Engine.engine->ClientPrintf(client, buffer);
   441 }
   442 
   443 void CSmmAPI::LoadAsVSP()
   444 {
   445 	size_t len;
   446 	char engine_file[PATH_SIZE];
   447 	char rel_path[PATH_SIZE * 2];
   448 
   449 	GetFileOfAddress(g_Engine.engine, engine_file, sizeof(engine_file));
   450 
   451 	/* Chop off the "engine" file part */
   452 	len = strlen(engine_file);
   453 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   454 	{
   455 		if (engine_file[i] == '/'
   456 			|| engine_file[i] == '\\')
   457 		{
   458 			engine_file[i] = '\0';
   459 			break;
   460 		}
   461 	}
   462 
   463 	const char *usepath = g_SmmPath.c_str();
   464 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_file, g_SmmPath.c_str()))
   465 	{
   466 		usepath = rel_path;
   467 	}
   468 	
   469 	char command[PATH_SIZE * 2];
   470 	g_VspListener.SetLoadable(true);
   471 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   472 	g_Engine.engine->ServerCommand(command);
   473 }
   474 
   475 void CSmmAPI::EnableVSPListener()
   476 {
   477 	/* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
   478 	if (bGameInit && !m_VSP && !g_VspListener.IsLoaded() && !g_VspListener.IsRootLoadMethod())
   479 	{
   480 		LoadAsVSP();
   481 	}
   482 	m_VSP = true;
   483 }
   484 
   485 int CSmmAPI::GetGameDLLVersion()
   486 {
   487 	return g_GameDllVersion;
   488 }
   489 
   490 //////////////////////////////////////////////////////////////////////
   491 // EVEN MORE HACKS HERE! YOU HAVE BEEN WARNED!                      //
   492 // Signatures necessary in finding the pointer to the CUtlDict that //
   493 //   stores user message information.                               //
   494 // IServerGameDLL::GetUserMessageInfo() normally crashes with bad   //
   495 //   message indices. This is our answer to it. Yuck! <:-(          //
   496 //////////////////////////////////////////////////////////////////////
   497 #ifdef OS_WIN32
   498 	/* General Windows sig */
   499 	#define MSGCLASS_SIGLEN		7
   500 	#define MSGCLASS_SIG		"\x8B\x0D\x2A\x2A\x2A\x2A\x56"
   501 	#define MSGCLASS_OFFS		2
   502 
   503 	/* Dystopia Wimdows hack */
   504 	#define MSGCLASS2_SIGLEN	16
   505 	#define MSGCLASS2_SIG		"\x56\x8B\x74\x24\x2A\x85\xF6\x7C\x2A\x3B\x35\x2A\x2A\x2A\x2A\x7D"
   506 	#define MSGCLASS2_OFFS		11
   507 
   508 	/* Windows frame pointer sig */
   509 	#define MSGCLASS3_SIGLEN	18
   510 	#define MSGCLASS3_SIG		"\x55\x8B\xEC\x51\x89\x2A\x2A\x8B\x2A\x2A\x50\x8B\x0D\x2A\x2A\x2A\x2A\xE8"
   511 	#define MSGCLASS3_OFFS		13
   512 #elif defined OS_LINUX
   513 	/* No frame pointer sig */
   514 	#define MSGCLASS_SIGLEN		14
   515 	#define MSGCLASS_SIG		"\x53\x83\xEC\x2A\x8B\x2A\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   516 	#define MSGCLASS_OFFS		9
   517 
   518 	/* Frame pointer sig */
   519 	#define MSGCLASS2_SIGLEN	16
   520 	#define MSGCLASS2_SIG		"\x55\x89\xE5\x53\x83\xEC\x2A\x8B\x2A\x2A\xA1\x2A\x2A\x2A\x2A\x89"
   521 	#define MSGCLASS2_OFFS		11
   522 #endif
   523 
   524 /* This is the ugliest function in all of SourceMM */
   525 /* :TODO: Make this prettier */
   526 bool CSmmAPI::CacheUserMessages()
   527 {
   528 	UserMsgDict *dict = NULL;
   529 	char *vfunc = UTIL_GetOrigFunction(&IServerGameDLL::GetUserMessageInfo, g_GameDll.pGameDLL, g_GameDllPatch);
   530 
   531 	if (!vfunc)
   532 	{
   533 		return false;
   534 	}
   535 
   536 	if (UTIL_VerifySignature(vfunc, MSGCLASS_SIG, MSGCLASS_SIGLEN))
   537 	{
   538 		/* Get address of CUserMessages instance */
   539 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS_OFFS);
   540 
   541 		/* Get address of CUserMessages::m_UserMessages */
   542 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   543 	} else if (UTIL_VerifySignature(vfunc, MSGCLASS2_SIG, MSGCLASS2_SIGLEN)) {
   544 	#ifdef OS_WIN32
   545 		/* If we get here, the code is possibly inlined like in Dystopia */
   546 
   547 		/* Get the address of the CUtlRBTree */
   548 		char *rbtree = *reinterpret_cast<char **>(vfunc + MSGCLASS2_OFFS);
   549 
   550 		/* CUtlDict should be 8 bytes before the CUtlRBTree (hacktacular!) */
   551 		dict = reinterpret_cast<UserMsgDict *>(rbtree - 8);
   552 	#elif defined OS_LINUX
   553 		/* Get address of CUserMessages instance */
   554 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS2_OFFS);
   555 
   556 		/* Get address of CUserMessages::m_UserMessages */
   557 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   558 	#endif
   559 	#ifdef OS_WIN32
   560 	} else if (UTIL_VerifySignature(vfunc, MSGCLASS3_SIG, MSGCLASS3_SIGLEN)) {
   561 		/* Get address of CUserMessages instance */
   562 		char **userMsgClass = *reinterpret_cast<char ***>(vfunc + MSGCLASS3_OFFS);
   563 
   564 		/* Get address of CUserMessages::m_UserMessages */
   565 		dict = reinterpret_cast<UserMsgDict *>(*userMsgClass);
   566 	#endif
   567 	}
   568 
   569 	if (dict)
   570 	{
   571 		m_MsgCount = dict->Count();
   572 
   573 		/* Ensure that count is within bounds of an unsigned byte, because that's what engine supports */
   574 		if (m_MsgCount < 0 || m_MsgCount > 255)
   575 		{
   576 			m_MsgCount = -1;
   577 			return false;
   578 		}
   579 
   580 		UserMessage *msg;
   581 
   582 		/* Cache messages in our CUtlDict */
   583 		for (int i = 0; i < m_MsgCount; i++)
   584 		{
   585 			msg = dict->Element(i);
   586 			m_UserMessages.Insert(msg->name, msg);
   587 		}
   588 
   589 		return true;
   590 	}
   591 
   592 	return false;
   593 }
   594 
   595 bool CSmmAPI::MsgCacheSuccessful()
   596 {
   597 	return m_MsgCount > -1;
   598 }
   599 
   600 int CSmmAPI::GetUserMessageCount()
   601 {
   602 	return m_MsgCount;
   603 }
   604 
   605 int CSmmAPI::FindUserMessage(const char *name, int *size)
   606 {
   607 	int index = m_UserMessages.Find(name);
   608 
   609 	if (size && index > -1)
   610 	{
   611 		UserMessage *msg = m_UserMessages.Element(index);
   612 		*size = msg->size;
   613 	}
   614 
   615 	return index;
   616 }
   617 
   618 const char *CSmmAPI::GetUserMessage(int index, int *size)
   619 {
   620 	if (m_MsgCount <= 0 || index < 0 || index >= m_MsgCount)
   621 	{
   622 		return NULL;
   623 	}
   624 
   625 	UserMessage *msg = m_UserMessages.Element(index);
   626 
   627 	if (size)
   628 	{
   629 		*size = msg->size;
   630 	}
   631 
   632 	return msg->name;
   633 }