core/metamod.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Dec 10 00:59:50 2009 -0600 (2009-12-10)
changeset 689 4065ba5e9155
parent 683 b507295429f9
child 705 a1001281dcb1
permissions -rw-r--r--
Rewrote user message caching code to always use IServerGameDLL::GetUserMessageInfo (bug 4117, r=dvander).

Games where the above function can crash are handled by detouring tier0's Error() function and jumping back to our own code. So in theory this should work on all games now.
     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 "metamod_oslink.h"
    28 #include "metamod.h"
    29 #include <interface.h>
    30 #include <eiface.h>
    31 #include "metamod_provider.h"
    32 #include "metamod_plugins.h"
    33 #include "metamod_util.h"
    34 #include "metamod_console.h"
    35 #include "provider/provider_ep2.h"
    36 
    37 using namespace SourceMM;
    38 using namespace SourceHook;
    39 using namespace SourceHook::Impl;
    40 
    41 /**
    42  * @brief Implementation of main SourceMM GameDLL functionality
    43  * @file sourcemm.cpp
    44  */
    45 
    46 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
    47 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
    48 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
    49 
    50 static void
    51 Handler_LevelShutdown();
    52 
    53 static bool
    54 Handler_LevelInit(char const *pMapName,
    55 				  char const *pMapEntities,
    56 				  char const *pOldLevel,
    57 				  char const *pLandmarkName,
    58 				  bool loadGame,
    59 				  bool background);
    60 
    61 static bool
    62 Handler_GameInit();
    63 
    64 static void
    65 InitializeVSP();
    66 
    67 static int
    68 LoadPluginsFromFile(const char *filepath, int &skipped);
    69 
    70 static int
    71 LoadVDFPluginsFromDir(const char *dir, int &skipped);
    72 
    73 struct game_dll_t
    74 {
    75 	CreateInterfaceFn factory;
    76 };
    77 
    78 static String mod_path;
    79 static String metamod_path;
    80 static String full_bin_path;
    81 static int vsp_version = 0;
    82 static int gamedll_version = 0;
    83 static int engine_build = SOURCE_ENGINE_UNKNOWN;
    84 static List<game_dll_t *> gamedll_list;
    85 static bool is_gamedll_loaded = false;
    86 static bool in_first_level = true;
    87 static bool is_game_init = false;
    88 static bool vsp_load_requested = false;
    89 static bool vsp_loaded = false;
    90 static game_dll_t gamedll_info;
    91 static ConVar *metamod_version = NULL;
    92 static ConVar *mm_pluginsfile = NULL;
    93 static ConVar *mm_basedir = NULL;
    94 static CreateInterfaceFn engine_factory = NULL;
    95 static CreateInterfaceFn physics_factory = NULL;
    96 static CreateInterfaceFn filesystem_factory = NULL;
    97 static CGlobalVars *gpGlobals = NULL;
    98 static CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
    99 static META_RES last_meta_res;
   100 static IServerPluginCallbacks *vsp_callbacks = NULL;
   101 static bool were_plugins_loaded = false;
   102 static bool g_bIsVspBridged = false;
   103 
   104 MetamodSource g_Metamod;
   105 PluginId g_PLID = Pl_Console;
   106 CSourceHookImpl g_SourceHook;
   107 ISourceHook *g_SHPtr = &g_SourceHook;
   108 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
   109 
   110 /* Helper Macro */
   111 #define	IFACE_MACRO(orig,nam) \
   112 	CPluginManager::CPlugin *pl; \
   113 	SourceHook::List<IMetamodListener *>::iterator event; \
   114 	IMetamodListener *api; \
   115 	int mret = 0; \
   116 	void *val = NULL; \
   117 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   118 		pl = (*iter); \
   119 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   120 			api = (*event); \
   121 			mret = IFACE_FAILED; \
   122 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
   123 				if (ret) *ret = mret; \
   124 				return val; \
   125 			} \
   126 		} \
   127 	} \
   128 	return (orig)(iface, ret);
   129 
   130 #define ITER_EVENT(evn, args) \
   131 	CPluginManager::CPlugin *pl; \
   132 	SourceHook::List<IMetamodListener *>::iterator event; \
   133 	IMetamodListener *api; \
   134 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   135 		pl = (*iter); \
   136 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   137 			api = (*event); \
   138 			api->evn args; \
   139 		} \
   140 	}
   141 
   142 /* Initialize everything here */
   143 void
   144 mm_InitializeForLoad()
   145 {
   146 	char full_path[PATH_SIZE] = {0};
   147 	GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
   148 	full_bin_path.assign(full_path);
   149 
   150 	/* Like Metamod, reload plugins at the end of the map.
   151 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   152 	 * if the server is shut down (silly, but rare case).
   153 	 */
   154 	in_first_level = true;
   155 
   156 	SourceHook::MemFuncInfo info;
   157 
   158 	if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
   159 	{
   160 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
   161 	}
   162 	SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   163 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
   164 
   165 	if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
   166 	{
   167 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
   168 	}
   169 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   170 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
   171 
   172 	if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
   173 	{
   174 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
   175 	}
   176 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   177 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
   178 }
   179 
   180 bool
   181 mm_DetectGameInformation()
   182 {
   183 	char game_path[PATH_SIZE];
   184 
   185 	/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   186 	const char *game_dir = provider->GetCommandLineValue("-game");
   187 
   188 	if (game_dir)
   189 	{
   190 		/* Get absolute path */
   191 		abspath(game_path, game_dir);
   192 	}
   193 	else
   194 	{
   195 		/* Get absolute path for current directory */
   196 		abspath(game_path, ".");
   197 	}
   198 
   199 	mod_path.assign(game_path);
   200 
   201 	engine_build = provider->DetermineSourceEngine(game_dir);
   202 
   203 	return true;
   204 }
   205 
   206 void *
   207 ServerFactory(const char *iface, int *ret)
   208 {
   209 	IFACE_MACRO(gamedll_info.factory, GameDLL);
   210 }
   211 
   212 static int
   213 LoadPluginsFromFile(const char *filepath, int &skipped)
   214 {
   215 	FILE *fp;
   216 	int total = 0;
   217 	PluginId id;
   218 	bool already;
   219 
   220 	skipped = 0;
   221 
   222 	fp = fopen(filepath, "rt");
   223 	if (!fp)
   224 	{
   225 		return 0;
   226 	}
   227 
   228 	char buffer[255], error[255], full_path[PATH_SIZE];
   229 	const char *ptr, *ext, *file;
   230 	size_t length;
   231 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   232 	{
   233 		UTIL_TrimLeft(buffer);
   234 		UTIL_TrimRight(buffer);
   235 
   236 		length = strlen(buffer);
   237 		if (!length)
   238 		{
   239 			continue;
   240 		}
   241 
   242 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   243 		{
   244 			continue;
   245 		}
   246 
   247 		file = buffer;
   248 		if (buffer[0] == '"')
   249 		{
   250 			char *cptr = buffer;
   251 			file = ++cptr;
   252 
   253 			while (*cptr)
   254 			{
   255 				if (*cptr == '"')
   256 				{
   257 					*cptr = '\0';
   258 					break;
   259 				}
   260 				cptr++;
   261 			}
   262 		}
   263 		else
   264 		{
   265 			char *cptr = buffer;
   266 			while (*cptr)
   267 			{
   268 				if (isspace(*cptr))
   269 				{
   270 					char *optr = cptr;
   271 					while (*cptr && isspace(*cptr))
   272 					{
   273 						cptr++;
   274 					}
   275 					*optr = '\0';
   276 					UTIL_TrimRight(cptr);
   277 					if (*cptr && isalpha(*cptr))
   278 					{
   279 						g_PluginMngr.SetAlias(buffer, cptr);
   280 						file = cptr;
   281 					}
   282 					break;
   283 				}
   284 				cptr++;
   285 			}
   286 		}
   287 		if (!file[0])
   288 		{
   289 			continue;
   290 		}
   291 		/* First find if it's an absolute path or not... */
   292 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   293 		{
   294 			/* If we're in an absolute path, ignore our normal heuristics */
   295 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   296 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   297 			{
   298 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   299 			}
   300 			else
   301 			{
   302 				if (already)
   303 					skipped++;
   304 				else
   305 					total++;
   306 			}
   307 		}
   308 		else
   309 		{
   310 			/* Attempt to find a file extension */
   311 			ptr = UTIL_GetExtension(file);
   312 			/* Add an extension if there's none there */
   313 			if (!ptr)
   314 			{
   315 #if defined WIN32 || defined _WIN32
   316 				ext = ".dll";
   317 #else
   318 				ext = "_i486.so";
   319 #endif
   320 			}
   321 			else
   322 			{
   323 				ext = "";
   324 			}
   325 			/* Format the new path */
   326 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   327 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   328 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   329 			{
   330 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   331 			}
   332 			else
   333 			{
   334 				if (already)
   335 					skipped++;
   336 				else
   337 					total++;
   338 			}
   339 		}
   340 	}
   341 	fclose(fp);
   342 	
   343 	return total;
   344 }
   345 
   346 void InitializeVSP()
   347 {
   348 	if (g_bIsVspBridged)
   349 		return;
   350 
   351 	size_t len;
   352 	char engine_file[PATH_SIZE];
   353 	char engine_path[PATH_SIZE];
   354 	char rel_path[PATH_SIZE * 2];
   355 
   356 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   357 
   358 	/* Chop off the "engine" file part */
   359 	len = strlen(engine_file);
   360 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   361 	{
   362 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   363 		{
   364 			engine_file[i] = '\0';
   365 			break;
   366 		}
   367 	}
   368 	abspath(engine_path, engine_file);
   369 
   370 	const char *usepath = metamod_path.c_str();
   371 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   372 	{
   373 		usepath = rel_path;
   374 	}
   375 
   376 	char command[PATH_SIZE * 2];
   377 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   378 	provider->ServerCommand(command);
   379 }
   380 
   381 /* Wrapper function.  This is called when the GameDLL thinks it's using
   382  * the engine's real engineFactory.
   383  */
   384 static void *
   385 EngineFactory(const char *iface, int *ret)
   386 {
   387 	IFACE_MACRO(engine_factory, Engine);
   388 }
   389 
   390 /* Wrapper function.  This is called when the GameDLL thinks it's using
   391  * the engine's real physicsFactory.
   392  */
   393 static void *
   394 PhysicsFactory(const char *iface, int *ret)
   395 {
   396 	IFACE_MACRO(physics_factory, Physics);
   397 }
   398 
   399 /* Wrapper function.  This is called when the GameDLL thinks it's using
   400  * the engine's real fileSystemFactory.
   401  */
   402 static void *
   403 FileSystemFactory(const char *iface, int *ret)
   404 {
   405 	IFACE_MACRO(filesystem_factory, FileSystem);
   406 }
   407 
   408 void
   409 mm_LogMessage(const char *msg, ...)
   410 {
   411 	va_list ap;
   412 	static char buffer[2048];
   413 
   414 	va_start(ap, msg);
   415 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   416 	va_end(ap);
   417 
   418 	buffer[len++] = '\n';
   419 	buffer[len] = '\0';
   420 
   421 	if (!provider->LogMessage(buffer))
   422 	{
   423 		fprintf(stdout, "%s", buffer);
   424 	}
   425 }
   426 
   427 static void
   428 DoInitialPluginLoads()
   429 {
   430 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   431 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   432 	if (!pluginFile) 
   433 	{
   434 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   435 		if (pluginFile == NULL)
   436 		{
   437 			pluginFile = "addons/metamod/metaplugins.ini";
   438 		}
   439 	}
   440 	if (!mmBaseDir)
   441 	{
   442 		mmBaseDir = provider->GetConVarString(mm_basedir);
   443 		if (mmBaseDir == NULL)
   444 		{
   445 			mmBaseDir = "addons/metamod";
   446 		}
   447 	}
   448 
   449 	char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   450 
   451 	g_Metamod.PathFormat(filepath, sizeof(filepath), "%s/%s", mod_path.c_str(), pluginFile);
   452 	g_Metamod.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", mod_path.c_str(), mmBaseDir);
   453 	mm_LoadPlugins(filepath, vdfpath);
   454 }
   455 
   456 void
   457 mm_StartupMetamod(bool is_vsp_load)
   458 {
   459 	char buffer[255];
   460 
   461 	UTIL_Format(buffer,
   462 		sizeof(buffer),
   463 		"%s%s",
   464 		MMS_FULL_VERSION,
   465 		is_vsp_load ? "V" : "");
   466 
   467 	metamod_version = provider->CreateConVar("metamod_version", 
   468 		MMS_FULL_VERSION, 
   469 		"Metamod:Source Version",
   470 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   471 
   472 	provider->SetConVarString(metamod_version, buffer);
   473 
   474 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   475 #if defined WIN32 || defined _WIN32
   476 		"addons\\metamod\\metaplugins.ini", 
   477 #else
   478 		"addons/metamod/metaplugins.ini",
   479 #endif
   480 		"Metamod:Source Plugins File",
   481 		ConVarFlag_SpOnly);
   482 
   483 	mm_basedir = provider->CreateConVar("mm_basedir",
   484 #if defined __linux__
   485 		"addons/metamod",
   486 #else
   487 		"addons\\metamod",
   488 #endif
   489 		"Metamod:Source Base Folder",
   490 		ConVarFlag_SpOnly);
   491 	
   492 	g_bIsVspBridged = is_vsp_load;
   493 
   494 	if (!is_vsp_load)
   495 	{
   496 		DoInitialPluginLoads();
   497 		in_first_level = true;
   498 	}
   499 }
   500 
   501 void
   502 mm_InitializeGlobals(CreateInterfaceFn engineFactory, 
   503 					 CreateInterfaceFn physicsFactory,
   504 					 CreateInterfaceFn filesystemFactory,
   505 					 CGlobalVars *pGlobals)
   506 {
   507 	engine_factory = engineFactory;
   508 	physics_factory = physicsFactory;
   509 	filesystem_factory = filesystemFactory;
   510 	gpGlobals = pGlobals;
   511 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   512 }
   513 
   514 static bool
   515 Handler_GameInit()
   516 {
   517 	if (is_game_init)
   518 		return true;
   519 
   520 	if (vsp_load_requested)
   521 		InitializeVSP();
   522 
   523 	if (g_bIsVspBridged && !were_plugins_loaded)
   524 	{
   525 		DoInitialPluginLoads();
   526 		g_PluginMngr.SetAllLoaded();
   527 		were_plugins_loaded = true;
   528 	}
   529 
   530 	is_game_init = true;
   531 
   532 	RETURN_META_VALUE(MRES_IGNORED, true);
   533 }
   534 
   535 void
   536 mm_UnloadMetamod()
   537 {
   538 	/* Unload plugins */
   539 	g_PluginMngr.UnloadAll();
   540 
   541 	provider->Notify_DLLShutdown_Pre();
   542 
   543 	g_SourceHook.CompleteShutdown();
   544 }
   545 
   546 static void
   547 Handler_LevelShutdown(void)
   548 {
   549 	if (g_bIsVspBridged && !were_plugins_loaded)
   550 	{
   551 		DoInitialPluginLoads();
   552 		g_PluginMngr.SetAllLoaded();
   553 		were_plugins_loaded = true;
   554 		in_first_level = true;
   555 	}
   556 
   557 	if (!in_first_level)
   558 	{
   559 		char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   560 
   561 		g_Metamod.PathFormat(filepath, 
   562 			sizeof(filepath), 
   563 			"%s/%s", 
   564 			mod_path.c_str(),
   565 			provider->GetConVarString(mm_pluginsfile));
   566 		g_Metamod.PathFormat(vdfpath,
   567 			sizeof(vdfpath),
   568 			"%s/%s",
   569 			mod_path.c_str(),
   570 			provider->GetConVarString(mm_basedir));
   571 		mm_LoadPlugins(filepath, vdfpath);
   572 	}
   573 	else
   574 	{
   575 		in_first_level = false;
   576 	}
   577 
   578 	ITER_EVENT(OnLevelShutdown, ());
   579 
   580 	RETURN_META(MRES_IGNORED);
   581 }
   582 
   583 static bool
   584 Handler_LevelInit(char const *pMapName,
   585 				  char const *pMapEntities,
   586 				  char const *pOldLevel,
   587 				  char const *pLandmarkName,
   588 				  bool loadGame,
   589 				  bool background)
   590 {
   591 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   592 
   593 	RETURN_META_VALUE(MRES_IGNORED, false);
   594 }
   595 
   596 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   597 {
   598 	va_list ap;
   599 	char buffer[2048];
   600 	
   601 	va_start(ap, msg);
   602 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   603 	va_end(ap);
   604 
   605 	mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   606 }
   607 
   608 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   609 {
   610 	if (syn)
   611 		return EngineFactory;
   612 	return engine_factory;
   613 }
   614 
   615 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   616 {
   617 	if (syn)
   618 		return PhysicsFactory;
   619 	return physics_factory;
   620 }
   621 
   622 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   623 {
   624 	if (syn)
   625 		return FileSystemFactory;
   626 	return filesystem_factory;
   627 }
   628 
   629 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   630 {
   631 	if (syn)
   632 		return ServerFactory;
   633 	return gamedll_info.factory;
   634 }
   635 
   636 CGlobalVars *MetamodSource::GetCGlobals()
   637 {
   638 	return gpGlobals;
   639 }
   640 
   641 void MetamodSource::SetLastMetaReturn(META_RES res)
   642 {
   643 	last_meta_res = res;
   644 }
   645 
   646 META_RES MetamodSource::GetLastMetaReturn()
   647 {
   648 	return last_meta_res;
   649 }
   650 
   651 void MetamodSource::ConPrint(const char *str)
   652 {
   653 	provider->ConsolePrint(str);
   654 }
   655 
   656 void MetamodSource::ConPrintf(const char *fmt, ...)
   657 {
   658 	va_list ap;
   659 	char buffer[2048];
   660 
   661 	va_start(ap, fmt);
   662 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   663 	va_end(ap);
   664 
   665 	provider->ConsolePrint(buffer);
   666 }
   667 
   668 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   669 {
   670 	major = METAMOD_API_MAJOR;
   671 	minor = METAMOD_API_MINOR;
   672 	plvers = METAMOD_PLAPI_VERSION;
   673 	plmin = PLAPI_MIN_VERSION;
   674 }
   675 
   676 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
   677 {
   678 	shvers = SH_IFACE_VERSION;
   679 	shimpl = SH_IMPL_VERSION;
   680 }
   681 
   682 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
   683 {
   684 	int length = (int)strlen(iface);
   685 	int i;
   686 	int num = 0;
   687 
   688 	for (i = length - 1; i >= 0; i--)
   689 	{
   690 		if (!isdigit(iface[i]))
   691 		{
   692 			if (i != length - 1)
   693 			{
   694 				num = 1;
   695 			}
   696 			break;
   697 		}
   698 	}
   699 
   700 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   701 	{
   702 		return -1;
   703 	}
   704 
   705 	if (i != length - 1)
   706 	{
   707 		num = atoi(&(iface[++i]));
   708 	}
   709 
   710 	num++;
   711 
   712 	snprintf(&(iface[i]), 4, "%03d", num);
   713 
   714 	return num;
   715 }
   716 
   717 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   718 {
   719 	char _if[256];	/* assume no interface goes beyond this */
   720 	size_t len = strlen(iface);
   721 	int num = 0;
   722 	void *pf = NULL;
   723 
   724 	if (max > 999)
   725 	{
   726 		max = 999;
   727 	}
   728 
   729 	if (len + 4 > sizeof(_if))
   730 	{
   731 		if (ret)
   732 		{
   733 			*ret = IFACE_FAILED;
   734 		}
   735 		return NULL;
   736 	}
   737 
   738 	strcpy(_if, iface);
   739 
   740 	do
   741 	{
   742 		if ((pf = (fn)(_if, ret)) != NULL)
   743 		{
   744 			break;
   745 		}
   746 		if (num > max)
   747 		{
   748 			break;
   749 		}
   750 	} while ((num = FormatIface(_if, len+1)));
   751 
   752 	return pf;
   753 }
   754 
   755 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   756 {
   757 	char buffer[256];	/* assume no interface will go beyond this */
   758 	size_t len = strlen(iface);
   759 	int ret;			/* just in case something doesn't handle NULL properly */
   760 
   761 	if (len > sizeof(buffer) - 4)
   762 	{
   763 		return NULL;
   764 	}
   765 
   766 	strcpy(buffer, iface);
   767 
   768 	if (min != -1)
   769 	{
   770 		char *ptr = &buffer[len - 1];
   771 		int digits = 0;
   772 		while (isdigit(*ptr) && digits <=3)
   773 		{
   774 			*ptr = '\0';
   775 			digits++;
   776 			ptr--;
   777 		}
   778 		if (digits != 3)
   779 		{
   780 			/* for now, assume this is an error */
   781 			strcpy(buffer, iface);
   782 		}
   783 		else
   784 		{
   785 			char num[4];
   786 			min = (min == 0) ? 1 : min;
   787 			snprintf(num, sizeof(num), "%03d", min);
   788 			strcat(buffer, num);
   789 		}
   790 	}
   791 
   792 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   793 }
   794 
   795 const char *MetamodSource::GetBaseDir()
   796 {
   797 	return mod_path.c_str();
   798 }
   799 
   800 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   801 {
   802 	va_list ap;
   803 	va_start(ap, fmt);
   804 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   805 	va_end(ap);
   806 
   807 	for (size_t i = 0; i < mylen; i++)
   808 	{
   809 		if (buffer[i] == ALT_SEP_CHAR)
   810 		{
   811 			buffer[i] = PATH_SEP_CHAR;
   812 		}
   813 	}
   814 
   815 	return mylen;
   816 }
   817 
   818 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
   819 {
   820 	va_list ap;
   821 	char buffer[2048];
   822 
   823 	va_start(ap, fmt);
   824 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   825 	va_end(ap);
   826 
   827 	provider->ClientConsolePrint(client, buffer);
   828 }
   829 
   830 void MetamodSource::EnableVSPListener()
   831 {
   832 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
   833 	{
   834 		InitializeVSP();
   835 	}
   836 
   837 	vsp_load_requested = true;
   838 }
   839 
   840 int MetamodSource::GetVSPVersion()
   841 {
   842 	return vsp_version;
   843 }
   844 
   845 int MetamodSource::GetGameDLLVersion()
   846 {
   847 	return gamedll_version;
   848 }
   849 
   850 bool MetamodSource::RemotePrintingAvailable()
   851 {
   852 	return provider->IsRemotePrintingAvailable();
   853 }
   854 
   855 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
   856 {
   857 	if (id)
   858 	{
   859 		*id = 0;
   860 	}
   861 
   862 	if (!iface)
   863 	{
   864 		return NULL;
   865 	}
   866 
   867 	/* First check ours... we get first chance! */
   868 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   869 	{
   870 		if (ret)
   871 		{
   872 			*ret = IFACE_OK;
   873 		}
   874 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   875 	}
   876 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
   877 	{
   878 		if (ret)
   879 		{
   880 			*ret = IFACE_OK;
   881 		}
   882 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   883 	}
   884 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
   885 	{
   886 		if (ret)
   887 		{
   888 			*ret = IFACE_OK;
   889 		}
   890 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
   891 	}
   892 
   893 	CPluginManager::CPlugin *pl;
   894 	List<IMetamodListener *>::iterator event;
   895 	IMetamodListener *api;
   896 	void *value;
   897 	
   898 	int subret = 0;
   899 	for (PluginIter iter = g_PluginMngr._begin();
   900 		 iter != g_PluginMngr._end();
   901 		 iter++)
   902 	{
   903 		pl = (*iter);
   904 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
   905 		{
   906 			api = (*event);
   907 			subret = IFACE_FAILED;
   908 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
   909 			{
   910 				if (ret)
   911 				{
   912 					*ret = subret;
   913 				}
   914 				if (id)
   915 				{
   916 					*id = pl->m_Id;
   917 				}
   918 				return value;
   919 			}
   920 		}
   921 	}
   922 
   923 	if (ret)
   924 	{
   925 		*ret = IFACE_FAILED;
   926 	}
   927 
   928 	return NULL;
   929 }
   930 
   931 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   932 {
   933 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   934 
   935 	pl->m_Events.push_back(pListener);
   936 }
   937 
   938 const char *MetamodSource::GetGameBinaryPath()
   939 {
   940 	return full_bin_path.c_str();
   941 }
   942 
   943 const char *MetamodSource::GetPluginsFile()
   944 {
   945 	return provider->GetConVarString(mm_pluginsfile);
   946 }
   947 
   948 const char *MetamodSource::GetVDFDir()
   949 {
   950 	return provider->GetConVarString(mm_basedir);
   951 }
   952 
   953 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
   954 {
   955 	return provider->GetConCommandBaseAccessor();
   956 }
   957 
   958 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   959 {
   960 	if (provider->IsConCommandBaseACommand(pCommand))
   961 	{
   962 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   963 	}
   964 	else
   965 	{
   966 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   967 	}
   968 
   969 	return provider->RegisterConCommandBase(pCommand);
   970 }
   971 
   972 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   973 {
   974 	if (provider->IsConCommandBaseACommand(pCommand))
   975 	{
   976 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   977 	}
   978 	else
   979 	{
   980 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   981 	}
   982 
   983 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
   984 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
   985 }
   986 
   987 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
   988 {
   989 	PluginIter iter;
   990 	CPluginManager::CPlugin *pPlugin;
   991 	List<IMetamodListener *>::iterator event;
   992 	IMetamodListener *pML;
   993 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
   994 	{
   995 		pPlugin = (*iter);
   996 		if (pPlugin->m_Status < Pl_Paused)
   997 		{
   998 			continue;
   999 		}
  1000 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
  1001 		if (pPlugin->m_API->GetApiVersion() < 12)
  1002 		{
  1003 			continue;
  1004 		}
  1005 		for (event=pPlugin->m_Events.begin();
  1006 			event!=pPlugin->m_Events.end();
  1007 			event++)
  1008 		{
  1009 			pML = (*event);
  1010 			pML->OnUnlinkConCommandBase(id, pCommand);
  1011 		}
  1012 	}
  1013 
  1014 	return provider->UnregisterConCommandBase(pCommand);
  1015 }
  1016 
  1017 int MetamodSource::GetUserMessageCount()
  1018 {
  1019 	return provider->GetUserMessageCount();
  1020 }
  1021 
  1022 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
  1023 {
  1024 	return provider->FindUserMessage(name, size);
  1025 }
  1026 
  1027 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
  1028 {
  1029 	return provider->GetUserMessage(index, size);
  1030 }
  1031 
  1032 int MetamodSource::GetSourceEngineBuild()
  1033 {
  1034 	return engine_build;
  1035 }
  1036 
  1037 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks, int version)
  1038 {
  1039 	if (version != -1)
  1040 		vsp_version = version;
  1041 	
  1042 	vsp_callbacks = callbacks;
  1043 	ITER_EVENT(OnVSPListening, (callbacks));
  1044 
  1045 	if (is_gamedll_loaded)
  1046 	{
  1047 		/*
  1048 		 * MM:S is loaded as a game DLL so we need to set these for mm_IsVspBridged() and
  1049 		 * mm_IsVspLoadComplete()
  1050 		 */
  1051 		g_bIsVspBridged = true;
  1052 		were_plugins_loaded = true;
  1053 	}
  1054 }
  1055 
  1056 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1057 {
  1058 	if (pVersion)
  1059 	{
  1060 		*pVersion = vsp_version;
  1061 	}
  1062 
  1063 	return vsp_callbacks;
  1064 }
  1065 
  1066 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1067 {
  1068 	va_list ap;
  1069 	size_t result;
  1070 
  1071 	va_start(ap, format);
  1072 	result = FormatArgs(buffer, maxlength, format, ap);
  1073 	va_end(ap);
  1074 
  1075 	return result;
  1076 }
  1077 
  1078 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1079 {
  1080 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1081 }
  1082 
  1083 bool MetamodSource::IsLoadedAsGameDLL()
  1084 {
  1085 	return is_gamedll_loaded;
  1086 }
  1087 
  1088 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version, bool loaded)
  1089 {
  1090 	gamedll_info.factory = serverFactory;
  1091 	gamedll_version = version;
  1092 	is_gamedll_loaded = loaded;
  1093 }
  1094 
  1095 void MetamodSource::SetVSPListener(const char *path)
  1096 {
  1097 	metamod_path.assign(path);
  1098 }
  1099 
  1100 static bool
  1101 ProcessVDF(const char *path, bool &skipped)
  1102 {
  1103 	PluginId id;
  1104 	bool already;
  1105 	char alias[24], file[255], full_path[255], error[255];
  1106 
  1107 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1108 	{
  1109 		skipped = false;
  1110 		return false;
  1111 	}
  1112 
  1113 	if (alias[0] != '\0')
  1114 		g_PluginMngr.SetAlias(alias, file);
  1115 
  1116 	/* Attempt to find a file extension */
  1117 	if (UTIL_GetExtension(file) == NULL)
  1118 	{
  1119 		g_pMetamod->PathFormat(full_path, 
  1120 			sizeof(full_path), 
  1121 			"%s/%s%s", 
  1122 			g_pMetamod->GetBaseDir(), 
  1123 			file, 
  1124 #if defined WIN32 || defined _WIN32
  1125 			".dll"
  1126 #else
  1127 			"_i486.so"
  1128 #endif
  1129 			);
  1130 	}
  1131 	else
  1132 	{
  1133 		g_pMetamod->PathFormat(full_path,
  1134 			sizeof(full_path),
  1135 			"%s/%s", 
  1136 			g_pMetamod->GetBaseDir(),
  1137 			file);
  1138 	}
  1139 
  1140 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
  1141 	skipped = already;
  1142 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1143 	{
  1144 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1145 		return false;
  1146 	}
  1147 
  1148 	return true;
  1149 }
  1150 
  1151 static int
  1152 LoadVDFPluginsFromDir(const char *dir, int &skipped)
  1153 {
  1154 	bool success, skip;
  1155 	int total = 0;
  1156 	char path[MAX_PATH];
  1157 	char relpath[MAX_PATH * 2];
  1158 
  1159 	skipped = 0;
  1160 
  1161 #if defined _MSC_VER
  1162 	HANDLE hFind;
  1163 	WIN32_FIND_DATA fd;
  1164 	char error[255];
  1165 
  1166 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
  1167 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1168 	{
  1169 		DWORD dw = GetLastError();
  1170 		if (dw == ERROR_FILE_NOT_FOUND)
  1171 			return 0;
  1172 
  1173 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1174 			NULL,
  1175 			dw,
  1176 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1177 			error,
  1178 			sizeof(error),
  1179 			NULL);
  1180 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1181 		return 0;
  1182 	}
  1183 
  1184 	do
  1185 	{
  1186 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1187 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1188 		success = ProcessVDF(relpath, skip);
  1189 		if (skip)
  1190 			skipped++;
  1191 		else if (success)
  1192 			total++;
  1193 	} while (FindNextFile(hFind, &fd));
  1194 
  1195 	FindClose(hFind);
  1196 #else
  1197 	DIR *pDir;
  1198 	struct dirent *pEnt;
  1199 	int extidx;
  1200 
  1201 	if ((pDir = opendir(dir)) == NULL)
  1202 	{
  1203 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1204 		return 0;
  1205 	}
  1206 
  1207 	while ((pEnt = readdir(pDir)) != NULL)
  1208 	{
  1209 		if (strcmp(pEnt->d_name, ".") == 0
  1210 			|| strcmp(pEnt->d_name, "..") == 0)
  1211 		{
  1212 			continue;
  1213 		}
  1214 		extidx = strlen(pEnt->d_name) - 4;
  1215 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1216 		{
  1217 			continue;
  1218 		}
  1219 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1220 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1221 		success = ProcessVDF(relpath, skip);
  1222 		if (skip)
  1223 			skipped++;
  1224 		else if (success)
  1225 			total++;
  1226 	}
  1227 
  1228 	closedir(pDir);
  1229 #endif
  1230 
  1231 	return total;
  1232 }
  1233 
  1234 int
  1235 mm_LoadPlugins(const char *filepath, const char *vdfpath)
  1236 {
  1237 	int total, skipped, fskipped, vskipped;
  1238 	const char *s = "";
  1239 
  1240 	total = LoadPluginsFromFile(filepath, fskipped);
  1241 	total += LoadVDFPluginsFromDir(vdfpath, vskipped);
  1242 	skipped = fskipped + vskipped;
  1243 
  1244 	if (total == 0 || total > 1)
  1245 		s = "s";
  1246 
  1247 	if (skipped)
  1248 		mm_LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
  1249 	else
  1250 		mm_LogMessage("[META] Loaded %d plugin%s.", total, s);
  1251 
  1252 	return total;
  1253 }
  1254 
  1255 bool
  1256 mm_IsVspBridged()
  1257 {
  1258 	return g_bIsVspBridged;
  1259 }
  1260 
  1261 bool
  1262 mm_IsVspLoadComplete()
  1263 {
  1264 	return were_plugins_loaded;
  1265 }
  1266