sourcemm/CSmmAPI.cpp
author David Anderson <dvander@alliedmods.net>
Sat Feb 10 00:31:34 2007 +0000 (2007-02-10)
changeset 282 7a237e9ea5a1
parent 280 946485e00593
child 287 0492209c065f
permissions -rw-r--r--
added experimental API for hooking VSP interface calls
updated file license headers
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2007 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_Cache = false;
    31 	m_VSP = false;
    32 }
    33 
    34 void CSmmAPI::LogMsg(ISmmPlugin *pl, const char *msg, ...)
    35 {
    36 	va_list ap;
    37 	static char buffer[2048];
    38 
    39 	buffer[0] = '\0';
    40 
    41 	va_start(ap, msg);
    42 	vsnprintf(buffer, sizeof(buffer)-1, msg, ap);
    43 	va_end(ap);
    44 
    45 	LogMessage("[%s] %s", pl->GetLogTag(), buffer);
    46 }
    47 
    48 CreateInterfaceFn CSmmAPI::engineFactory(bool syn)
    49 {
    50 	if (syn)
    51 		return EngineFactory;
    52 	return g_Engine.engineFactory;
    53 }
    54 
    55 CreateInterfaceFn CSmmAPI::physicsFactory(bool syn)
    56 {
    57 	if (syn)
    58 		return PhysicsFactory;
    59 	return g_Engine.physicsFactory;
    60 }
    61 
    62 CreateInterfaceFn CSmmAPI::fileSystemFactory(bool syn)
    63 {
    64 	if (syn)
    65 		return FileSystemFactory;
    66 	return g_Engine.fileSystemFactory;
    67 }
    68 
    69 CreateInterfaceFn CSmmAPI::serverFactory(bool syn)
    70 {
    71 	if (syn)
    72 		return CreateInterface;
    73 	return g_GameDll.factory;
    74 }
    75 
    76 CGlobalVars *CSmmAPI::pGlobals()
    77 {
    78 	return g_Engine.pGlobals;
    79 }
    80 
    81 void CSmmAPI::SetLastMetaReturn(META_RES res)
    82 {
    83 	m_Res = res;
    84 }
    85 
    86 META_RES CSmmAPI::GetLastMetaReturn()
    87 {
    88 	return m_Res;
    89 }
    90 
    91 IConCommandBaseAccessor *CSmmAPI::GetCvarBaseAccessor()
    92 {
    93 	return static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor);
    94 }
    95 
    96 bool CSmmAPI::RegisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
    97 {
    98 	if (pCommand->IsCommand())
    99 	{
   100 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   101 	} else {
   102 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   103 	}
   104 
   105 	return g_SMConVarAccessor.Register(pCommand);
   106 }
   107 
   108 void CSmmAPI::UnregisterConCmdBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   109 {
   110 	if (pCommand->IsCommand())
   111 	{
   112 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   113 	} else {
   114 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   115 	}
   116 
   117 	g_SMConVarAccessor.Unregister(pCommand);
   118 }
   119 
   120 void CSmmAPI::ConPrint(const char *fmt)
   121 {
   122 	(m_ConPrintf)("%s", fmt);
   123 }
   124 
   125 void CSmmAPI::ConPrintf(const char *fmt, ...)
   126 {
   127 	va_list ap;
   128 	static char buf[4096];
   129 	va_start(ap, fmt);
   130 	vsnprintf(buf, sizeof(buf)-1, fmt, ap);
   131 	ConPrint(buf);
   132 	va_end(ap);
   133 }
   134 
   135 void CSmmAPI::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   136 {
   137 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   138 
   139 	pl->m_Events.push_back(pListener);
   140 }
   141 
   142 void *CSmmAPI::MetaFactory(const char *iface, int *_ret, PluginId *id)
   143 {
   144 	if (id)
   145 	{
   146 		*id = 0;
   147 	}
   148 
   149 	if (!iface)
   150 	{
   151 		return NULL;
   152 	}
   153 
   154 	//first check ours... we get first chance!
   155 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   156 	{
   157 		if (_ret)
   158 		{
   159 			*_ret = IFACE_OK;
   160 		}
   161 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   162 	} else if (strcmp(iface, MMIFACE_PLMANAGER) == 0) {
   163 		if (_ret)
   164 		{
   165 			*_ret = IFACE_OK;
   166 		}
   167 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   168 	}
   169 
   170 	CPluginManager::CPlugin *pl;
   171 	SourceHook::List<IMetamodListener *>::iterator event;
   172 	IMetamodListener *api;
   173 	int ret = 0;
   174 	void *val = NULL;
   175 
   176 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++)
   177 	{
   178 		pl = (*iter);
   179 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++)
   180 		{
   181 			api = (*event);
   182 			ret = IFACE_FAILED;
   183 			if ( (val=api->OnMetamodQuery(iface, &ret)) != NULL )
   184 			{
   185 				if (_ret)
   186 					*_ret = ret;
   187 				if (id)
   188 					*id = pl->m_Id;
   189 				return val;
   190 			}
   191 		}
   192 	}
   193 
   194 	if (_ret)
   195 		*_ret = IFACE_FAILED;
   196 
   197 	return NULL;
   198 }
   199 
   200 //////////////////////////////////////////////////////////////////////////
   201 //THERE BE HAX HERE!!!! DON'T TELL ALFRED, BUT GABE WANTED IT THAT WAY. //
   202 // (note: you can find the offset by looking for the text               //
   203 //   "Echo text to console", you'll find the callback cmd pushed on the //
   204 //   stack.)                                                            //
   205 //////////////////////////////////////////////////////////////////////////
   206 
   207 #define SIGLEN			8
   208 #define ENGINE486_SIG	"\x55\x89\xE5\x53\x83\xEC\x14\xBB"
   209 #define ENGINE486_OFFS	40
   210 #define ENGINE686_SIG	"\x53\x83\xEC\x08\xBB\x01\x00\x00"
   211 #define ENGINE686_OFFS	50
   212 #define	ENGINEAMD_SIG	"\x53\x51\xBB\x01\x00\x00\x00\x51"
   213 #define	ENGINEAMD_OFFS	47
   214 #define ENGINEW32_SIG	"\xA1\x2A\x2A\x2A\x2A\x56\xBE\x01"
   215 #define ENGINEW32_OFFS	38
   216 #define IA32_CALL		0xE8
   217 
   218 bool vcmp(const void *_addr1, const void *_addr2, size_t len)
   219 {
   220 	unsigned char *addr1 = (unsigned char *)_addr1;
   221 	unsigned char *addr2 = (unsigned char *)_addr2;
   222 
   223 	for (size_t i=0; i<len; i++)
   224 	{
   225 		if (addr2[i] == '*')
   226 			continue;
   227 		if (addr1[i] != addr2[i])
   228 			return false;
   229 	}
   230 
   231 	return true;
   232 }
   233 
   234 //Thanks to fysh for the idea of extracting info from "echo" and for
   235 // having the original offsets at hand!
   236 bool CSmmAPI::CacheCmds()
   237 {
   238 	ICvar *pCvar = g_Engine.icvar;
   239 
   240 	ConCommandBase *pBase = pCvar->GetCommands();
   241 	unsigned char *ptr = NULL;
   242 	FnCommandCallback callback = NULL;
   243 	int offs = 0;
   244 
   245 	while (pBase)
   246 	{
   247 		if ( strcmp(pBase->GetName(), "echo") == 0 )
   248 		{
   249 			//callback = //*((FnCommandCallback *)((char *)pBase + offsetof(ConCommand, m_fnCommandCallback)));
   250 			callback = ((ConCommand *)pBase)->GetCallback();
   251 			ptr = (unsigned char *)callback;
   252 		#ifdef OS_LINUX
   253 			if (vcmp(ptr, ENGINE486_SIG, SIGLEN))
   254 			{
   255 				offs = ENGINE486_OFFS;
   256 			}
   257 			else if (vcmp(ptr, ENGINE686_SIG, SIGLEN))
   258 			{
   259 				offs = ENGINE686_OFFS;
   260 			}
   261 			else if (vcmp(ptr, ENGINEAMD_SIG, SIGLEN))
   262 			{
   263 				offs = ENGINEAMD_OFFS;
   264 			}
   265 		#elif defined OS_WIN32 // Only one Windows engine binary so far...
   266 			if (vcmp(ptr, ENGINEW32_SIG, SIGLEN))
   267 			{
   268 				offs = ENGINEW32_OFFS;
   269 			}
   270 		#endif
   271 
   272 			if (!offs || ptr[offs-1] != IA32_CALL)
   273 			{
   274 				m_ConPrintf = (CONPRINTF_FUNC)Msg;
   275 				return false;
   276 			}
   277 			//get the relative offset
   278 			m_ConPrintf = *((CONPRINTF_FUNC *)(ptr + offs));
   279 			//add the base offset, to the ip (which is the address+offset + 4 bytes for next instruction)
   280 			m_ConPrintf = (CONPRINTF_FUNC)((unsigned long)m_ConPrintf + (unsigned long)(ptr + offs) + 4);
   281 
   282 			m_Cache = true;
   283 
   284 			return true;
   285 		}
   286 		pBase = const_cast<ConCommandBase *>(pBase->GetNext());
   287 	}
   288 
   289 	m_ConPrintf = (CONPRINTF_FUNC)Msg;
   290 
   291 	return false;
   292 }
   293 
   294 bool CSmmAPI::CacheSuccessful()
   295 {
   296 	return m_Cache;
   297 }
   298 
   299 void CSmmAPI::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   300 {
   301 	major = SM_VERS_API_MAJOR;
   302 	minor = SM_VERS_API_MINOR;
   303 	plvers = PLAPI_VERSION;
   304 	plmin = PLAPI_MIN_VERSION;
   305 }
   306 
   307 void CSmmAPI::GetShVersions(int &shvers, int &shimpl)
   308 {
   309 	shvers = SH_IFACE_VERSION;
   310 	shimpl = SH_IMPL_VERSION;
   311 }
   312 
   313 int CSmmAPI::FormatIface(char iface[], unsigned int maxlength)
   314 {
   315 	int length = (int)strlen(iface);
   316 	int i;
   317 	int num = 0;
   318 
   319 	for (i=length-1; i>=0; i--)
   320 	{
   321 		if (!isdigit(iface[i]))
   322 		{
   323 			if (i != length-1)
   324 			{
   325 				num = 1;
   326 			}
   327 			break;
   328 		}
   329 	}
   330 
   331 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length+3)) )
   332 	{
   333 		return -1;
   334 	}
   335 
   336 	if (i != length-1)
   337 		num = atoi(&(iface[++i]));
   338 
   339 	num++;
   340 
   341 	snprintf(&(iface[i]), 4, "%03d", num);
   342 
   343 	return num;
   344 }
   345 
   346 void *CSmmAPI::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   347 {
   348 	char _if[256];	/* assume no interface goes beyond this */
   349 	size_t len = strlen(iface);
   350 	int num = 0;
   351 	void *pf = NULL;
   352 
   353 	if (max > 999)
   354 		max = 999;
   355 
   356 	if (len + 4 > sizeof(_if))
   357 	{
   358 		if (ret)
   359 		{
   360 			*ret = IFACE_FAILED;
   361 		}
   362 		return NULL;
   363 	}
   364 
   365 	strcpy(_if, iface);
   366 
   367 	do
   368 	{
   369 		if ( (pf = (fn)(_if, ret)) != NULL )
   370 			break;
   371 		if (num > max)
   372 			break;
   373 	} while (( num = FormatIface(_if, len+1) ));
   374 
   375 	return pf;
   376 }
   377 
   378 void *CSmmAPI::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   379 {
   380 	char buffer[256];	/* assume no interface will go beyond this */
   381 	int len = static_cast<int>(strlen(iface));
   382 	int ret;			/* just in case something doesn't handle NULL properly */
   383 
   384 	if (len > static_cast<int>(sizeof(buffer) - 4))
   385 	{
   386 		return NULL;
   387 	}
   388 
   389 	strcpy(buffer, iface);
   390 
   391 	if (min != -1)
   392 	{
   393 		char *ptr = &buffer[len-1];
   394 		int digits = 0;
   395 		while (isdigit(*ptr) && digits <=3)
   396 		{
   397 			*ptr = '\0';
   398 			digits++;
   399 			ptr--;
   400 		}
   401 		if (digits != 3)
   402 		{
   403 			/* for now, assume this is an error */
   404 			strcpy(buffer, iface);
   405 		} else {
   406 			char num[4];
   407 			min = (min == 0) ? 1 : min;
   408 			snprintf(num, sizeof(num), "%03d", min);
   409 			strcat(buffer, num);
   410 		}
   411 	}
   412 
   413 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   414 }
   415 
   416 const char *CSmmAPI::GetBaseDir()
   417 {
   418 	return g_ModPath.c_str();
   419 }
   420 
   421 void CSmmAPI::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   422 {
   423 	va_list ap;
   424 	va_start(ap,fmt);
   425 	size_t mylen = vsnprintf(buffer, len, fmt, ap);
   426 	va_end(ap);
   427 
   428 	if (mylen == 0xFFFFFFFF || mylen >= len)
   429 	{
   430 		mylen = len - 1;
   431 	}
   432 
   433 	for (size_t i=0; i<mylen; i++)
   434 	{
   435 		if (buffer[i] == ALT_SEP_CHAR)
   436 			buffer[i] = PATH_SEP_CHAR;
   437 	}
   438 }
   439 
   440 void CSmmAPI::ClientConPrintf(edict_t *client, const char *fmt, ...)
   441 {
   442 	va_list ap;
   443 	static char buf[4096];
   444 	va_start(ap, fmt);
   445 	vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
   446 	g_Engine.engine->ClientPrintf(client, buf);
   447 	va_end(ap);
   448 }
   449 
   450 void CSmmAPI::LoadAsVSP()
   451 {
   452 	g_Engine.engine->ServerCommand("plugin_load \n");
   453 	g_Engine.engine->ServerExecute();
   454 
   455 	IServerPluginCallbacks *iface = NULL;
   456 	if (g_VspListener.IsLoaded())
   457 	{
   458 		iface = &g_VspListener;
   459 	}
   460 
   461 	PluginIter iter;
   462 	CPluginManager::CPlugin *pPlugin;
   463 	SourceHook::List<IMetamodListener *>::iterator event;
   464 	IMetamodListener *pML;
   465 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
   466 	{
   467 		pPlugin = (*iter);
   468 		if (pPlugin->m_Status < Pl_Paused)
   469 		{
   470 			continue;
   471 		}
   472 		/* Only valid for plugins >= 10 (v1:5, SourceMM 1.4) */
   473 		if (pPlugin->m_API->GetApiVersion() < 10)
   474 		{
   475 			continue;
   476 		}
   477 		for (event=pPlugin->m_Events.begin();
   478 			 event!=pPlugin->m_Events.end();
   479 			 event++)
   480 		{
   481 			pML = (*event);
   482 			pML->OnVSPListening(iface);
   483 		}
   484 	}
   485 }
   486 
   487 void CSmmAPI::EnableVSPListener()
   488 {
   489 	/* If GameInit already passed and we're not already enabled or loaded, go ahead and LoadAsVSP load */
   490 	if (bGameInit && !m_VSP && !g_VspListener.IsLoaded())
   491 	{
   492 		LoadAsVSP();
   493 	}
   494 	m_VSP = true;
   495 }
   496 
   497 int CSmmAPI::GetGameDLLVersion()
   498 {
   499 	return g_GameDllVersion;
   500 }