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