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