core/metamod.cpp
author Scott Ehlert <ds@alliedmods.net>
Fri May 14 00:34:56 2010 -0500 (2010-05-14)
changeset 705 a1001281dcb1
parent 683 b507295429f9
child 714 966f819588a2
permissions -rw-r--r--
Mac OS X build fixes (bug 4391, r=dvander).
     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 #elif defined __APPLE__
   318 				ext = ".dylib";
   319 #else
   320 				ext = "_i486.so";
   321 #endif
   322 			}
   323 			else
   324 			{
   325 				ext = "";
   326 			}
   327 			/* Format the new path */
   328 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   329 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   330 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   331 			{
   332 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   333 			}
   334 			else
   335 			{
   336 				if (already)
   337 					skipped++;
   338 				else
   339 					total++;
   340 			}
   341 		}
   342 	}
   343 	fclose(fp);
   344 	
   345 	return total;
   346 }
   347 
   348 void InitializeVSP()
   349 {
   350 	if (g_bIsVspBridged)
   351 		return;
   352 
   353 	size_t len;
   354 	char engine_file[PATH_SIZE];
   355 	char engine_path[PATH_SIZE];
   356 	char rel_path[PATH_SIZE * 2];
   357 
   358 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   359 
   360 	/* Chop off the "engine" file part */
   361 	len = strlen(engine_file);
   362 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   363 	{
   364 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   365 		{
   366 			engine_file[i] = '\0';
   367 			break;
   368 		}
   369 	}
   370 	abspath(engine_path, engine_file);
   371 
   372 	const char *usepath = metamod_path.c_str();
   373 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   374 	{
   375 		usepath = rel_path;
   376 	}
   377 
   378 	char command[PATH_SIZE * 2];
   379 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   380 	provider->ServerCommand(command);
   381 }
   382 
   383 /* Wrapper function.  This is called when the GameDLL thinks it's using
   384  * the engine's real engineFactory.
   385  */
   386 static void *
   387 EngineFactory(const char *iface, int *ret)
   388 {
   389 	IFACE_MACRO(engine_factory, Engine);
   390 }
   391 
   392 /* Wrapper function.  This is called when the GameDLL thinks it's using
   393  * the engine's real physicsFactory.
   394  */
   395 static void *
   396 PhysicsFactory(const char *iface, int *ret)
   397 {
   398 	IFACE_MACRO(physics_factory, Physics);
   399 }
   400 
   401 /* Wrapper function.  This is called when the GameDLL thinks it's using
   402  * the engine's real fileSystemFactory.
   403  */
   404 static void *
   405 FileSystemFactory(const char *iface, int *ret)
   406 {
   407 	IFACE_MACRO(filesystem_factory, FileSystem);
   408 }
   409 
   410 void
   411 mm_LogMessage(const char *msg, ...)
   412 {
   413 	va_list ap;
   414 	static char buffer[2048];
   415 
   416 	va_start(ap, msg);
   417 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   418 	va_end(ap);
   419 
   420 	buffer[len++] = '\n';
   421 	buffer[len] = '\0';
   422 
   423 	if (!provider->LogMessage(buffer))
   424 	{
   425 		fprintf(stdout, "%s", buffer);
   426 	}
   427 }
   428 
   429 static void
   430 DoInitialPluginLoads()
   431 {
   432 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   433 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   434 	if (!pluginFile) 
   435 	{
   436 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   437 		if (pluginFile == NULL)
   438 		{
   439 			pluginFile = "addons/metamod/metaplugins.ini";
   440 		}
   441 	}
   442 	if (!mmBaseDir)
   443 	{
   444 		mmBaseDir = provider->GetConVarString(mm_basedir);
   445 		if (mmBaseDir == NULL)
   446 		{
   447 			mmBaseDir = "addons/metamod";
   448 		}
   449 	}
   450 
   451 	char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   452 
   453 	g_Metamod.PathFormat(filepath, sizeof(filepath), "%s/%s", mod_path.c_str(), pluginFile);
   454 	g_Metamod.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", mod_path.c_str(), mmBaseDir);
   455 	mm_LoadPlugins(filepath, vdfpath);
   456 }
   457 
   458 void
   459 mm_StartupMetamod(bool is_vsp_load)
   460 {
   461 	char buffer[255];
   462 
   463 	UTIL_Format(buffer,
   464 		sizeof(buffer),
   465 		"%s%s",
   466 		MMS_FULL_VERSION,
   467 		is_vsp_load ? "V" : "");
   468 
   469 	metamod_version = provider->CreateConVar("metamod_version", 
   470 		MMS_FULL_VERSION, 
   471 		"Metamod:Source Version",
   472 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   473 
   474 	provider->SetConVarString(metamod_version, buffer);
   475 
   476 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   477 #if defined WIN32 || defined _WIN32
   478 		"addons\\metamod\\metaplugins.ini", 
   479 #else
   480 		"addons/metamod/metaplugins.ini",
   481 #endif
   482 		"Metamod:Source Plugins File",
   483 		ConVarFlag_SpOnly);
   484 
   485 	mm_basedir = provider->CreateConVar("mm_basedir",
   486 #if defined __linux__ || defined __APPLE__
   487 		"addons/metamod",
   488 #else
   489 		"addons\\metamod",
   490 #endif
   491 		"Metamod:Source Base Folder",
   492 		ConVarFlag_SpOnly);
   493 	
   494 	g_bIsVspBridged = is_vsp_load;
   495 
   496 	if (!is_vsp_load)
   497 	{
   498 		DoInitialPluginLoads();
   499 		in_first_level = true;
   500 	}
   501 }
   502 
   503 void
   504 mm_InitializeGlobals(CreateInterfaceFn engineFactory, 
   505 					 CreateInterfaceFn physicsFactory,
   506 					 CreateInterfaceFn filesystemFactory,
   507 					 CGlobalVars *pGlobals)
   508 {
   509 	engine_factory = engineFactory;
   510 	physics_factory = physicsFactory;
   511 	filesystem_factory = filesystemFactory;
   512 	gpGlobals = pGlobals;
   513 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   514 }
   515 
   516 static bool
   517 Handler_GameInit()
   518 {
   519 	if (is_game_init)
   520 		return true;
   521 
   522 	if (vsp_load_requested)
   523 		InitializeVSP();
   524 
   525 	if (g_bIsVspBridged && !were_plugins_loaded)
   526 	{
   527 		DoInitialPluginLoads();
   528 		g_PluginMngr.SetAllLoaded();
   529 		were_plugins_loaded = true;
   530 	}
   531 
   532 	is_game_init = true;
   533 
   534 	RETURN_META_VALUE(MRES_IGNORED, true);
   535 }
   536 
   537 void
   538 mm_UnloadMetamod()
   539 {
   540 	/* Unload plugins */
   541 	g_PluginMngr.UnloadAll();
   542 
   543 	provider->Notify_DLLShutdown_Pre();
   544 
   545 	g_SourceHook.CompleteShutdown();
   546 }
   547 
   548 static void
   549 Handler_LevelShutdown(void)
   550 {
   551 	if (g_bIsVspBridged && !were_plugins_loaded)
   552 	{
   553 		DoInitialPluginLoads();
   554 		g_PluginMngr.SetAllLoaded();
   555 		were_plugins_loaded = true;
   556 		in_first_level = true;
   557 	}
   558 
   559 	if (!in_first_level)
   560 	{
   561 		char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   562 
   563 		g_Metamod.PathFormat(filepath, 
   564 			sizeof(filepath), 
   565 			"%s/%s", 
   566 			mod_path.c_str(),
   567 			provider->GetConVarString(mm_pluginsfile));
   568 		g_Metamod.PathFormat(vdfpath,
   569 			sizeof(vdfpath),
   570 			"%s/%s",
   571 			mod_path.c_str(),
   572 			provider->GetConVarString(mm_basedir));
   573 		mm_LoadPlugins(filepath, vdfpath);
   574 	}
   575 	else
   576 	{
   577 		in_first_level = false;
   578 	}
   579 
   580 	ITER_EVENT(OnLevelShutdown, ());
   581 
   582 	RETURN_META(MRES_IGNORED);
   583 }
   584 
   585 static bool
   586 Handler_LevelInit(char const *pMapName,
   587 				  char const *pMapEntities,
   588 				  char const *pOldLevel,
   589 				  char const *pLandmarkName,
   590 				  bool loadGame,
   591 				  bool background)
   592 {
   593 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   594 
   595 	RETURN_META_VALUE(MRES_IGNORED, false);
   596 }
   597 
   598 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   599 {
   600 	va_list ap;
   601 	char buffer[2048];
   602 	
   603 	va_start(ap, msg);
   604 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   605 	va_end(ap);
   606 
   607 	mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   608 }
   609 
   610 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   611 {
   612 	if (syn)
   613 		return EngineFactory;
   614 	return engine_factory;
   615 }
   616 
   617 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   618 {
   619 	if (syn)
   620 		return PhysicsFactory;
   621 	return physics_factory;
   622 }
   623 
   624 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   625 {
   626 	if (syn)
   627 		return FileSystemFactory;
   628 	return filesystem_factory;
   629 }
   630 
   631 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   632 {
   633 	if (syn)
   634 		return ServerFactory;
   635 	return gamedll_info.factory;
   636 }
   637 
   638 CGlobalVars *MetamodSource::GetCGlobals()
   639 {
   640 	return gpGlobals;
   641 }
   642 
   643 void MetamodSource::SetLastMetaReturn(META_RES res)
   644 {
   645 	last_meta_res = res;
   646 }
   647 
   648 META_RES MetamodSource::GetLastMetaReturn()
   649 {
   650 	return last_meta_res;
   651 }
   652 
   653 void MetamodSource::ConPrint(const char *str)
   654 {
   655 	provider->ConsolePrint(str);
   656 }
   657 
   658 void MetamodSource::ConPrintf(const char *fmt, ...)
   659 {
   660 	va_list ap;
   661 	char buffer[2048];
   662 
   663 	va_start(ap, fmt);
   664 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   665 	va_end(ap);
   666 
   667 	provider->ConsolePrint(buffer);
   668 }
   669 
   670 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   671 {
   672 	major = METAMOD_API_MAJOR;
   673 	minor = METAMOD_API_MINOR;
   674 	plvers = METAMOD_PLAPI_VERSION;
   675 	plmin = PLAPI_MIN_VERSION;
   676 }
   677 
   678 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
   679 {
   680 	shvers = SH_IFACE_VERSION;
   681 	shimpl = SH_IMPL_VERSION;
   682 }
   683 
   684 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
   685 {
   686 	int length = (int)strlen(iface);
   687 	int i;
   688 	int num = 0;
   689 
   690 	for (i = length - 1; i >= 0; i--)
   691 	{
   692 		if (!isdigit(iface[i]))
   693 		{
   694 			if (i != length - 1)
   695 			{
   696 				num = 1;
   697 			}
   698 			break;
   699 		}
   700 	}
   701 
   702 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   703 	{
   704 		return -1;
   705 	}
   706 
   707 	if (i != length - 1)
   708 	{
   709 		num = atoi(&(iface[++i]));
   710 	}
   711 
   712 	num++;
   713 
   714 	snprintf(&(iface[i]), 4, "%03d", num);
   715 
   716 	return num;
   717 }
   718 
   719 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   720 {
   721 	char _if[256];	/* assume no interface goes beyond this */
   722 	size_t len = strlen(iface);
   723 	int num = 0;
   724 	void *pf = NULL;
   725 
   726 	if (max > 999)
   727 	{
   728 		max = 999;
   729 	}
   730 
   731 	if (len + 4 > sizeof(_if))
   732 	{
   733 		if (ret)
   734 		{
   735 			*ret = IFACE_FAILED;
   736 		}
   737 		return NULL;
   738 	}
   739 
   740 	strcpy(_if, iface);
   741 
   742 	do
   743 	{
   744 		if ((pf = (fn)(_if, ret)) != NULL)
   745 		{
   746 			break;
   747 		}
   748 		if (num > max)
   749 		{
   750 			break;
   751 		}
   752 	} while ((num = FormatIface(_if, len+1)));
   753 
   754 	return pf;
   755 }
   756 
   757 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   758 {
   759 	char buffer[256];	/* assume no interface will go beyond this */
   760 	size_t len = strlen(iface);
   761 	int ret;			/* just in case something doesn't handle NULL properly */
   762 
   763 	if (len > sizeof(buffer) - 4)
   764 	{
   765 		return NULL;
   766 	}
   767 
   768 	strcpy(buffer, iface);
   769 
   770 	if (min != -1)
   771 	{
   772 		char *ptr = &buffer[len - 1];
   773 		int digits = 0;
   774 		while (isdigit(*ptr) && digits <=3)
   775 		{
   776 			*ptr = '\0';
   777 			digits++;
   778 			ptr--;
   779 		}
   780 		if (digits != 3)
   781 		{
   782 			/* for now, assume this is an error */
   783 			strcpy(buffer, iface);
   784 		}
   785 		else
   786 		{
   787 			char num[4];
   788 			min = (min == 0) ? 1 : min;
   789 			snprintf(num, sizeof(num), "%03d", min);
   790 			strcat(buffer, num);
   791 		}
   792 	}
   793 
   794 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   795 }
   796 
   797 const char *MetamodSource::GetBaseDir()
   798 {
   799 	return mod_path.c_str();
   800 }
   801 
   802 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   803 {
   804 	va_list ap;
   805 	va_start(ap, fmt);
   806 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   807 	va_end(ap);
   808 
   809 	for (size_t i = 0; i < mylen; i++)
   810 	{
   811 		if (buffer[i] == ALT_SEP_CHAR)
   812 		{
   813 			buffer[i] = PATH_SEP_CHAR;
   814 		}
   815 	}
   816 
   817 	return mylen;
   818 }
   819 
   820 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
   821 {
   822 	va_list ap;
   823 	char buffer[2048];
   824 
   825 	va_start(ap, fmt);
   826 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   827 	va_end(ap);
   828 
   829 	provider->ClientConsolePrint(client, buffer);
   830 }
   831 
   832 void MetamodSource::EnableVSPListener()
   833 {
   834 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
   835 	{
   836 		InitializeVSP();
   837 	}
   838 
   839 	vsp_load_requested = true;
   840 }
   841 
   842 int MetamodSource::GetVSPVersion()
   843 {
   844 	return vsp_version;
   845 }
   846 
   847 int MetamodSource::GetGameDLLVersion()
   848 {
   849 	return gamedll_version;
   850 }
   851 
   852 bool MetamodSource::RemotePrintingAvailable()
   853 {
   854 	return provider->IsRemotePrintingAvailable();
   855 }
   856 
   857 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
   858 {
   859 	if (id)
   860 	{
   861 		*id = 0;
   862 	}
   863 
   864 	if (!iface)
   865 	{
   866 		return NULL;
   867 	}
   868 
   869 	/* First check ours... we get first chance! */
   870 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   871 	{
   872 		if (ret)
   873 		{
   874 			*ret = IFACE_OK;
   875 		}
   876 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   877 	}
   878 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
   879 	{
   880 		if (ret)
   881 		{
   882 			*ret = IFACE_OK;
   883 		}
   884 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   885 	}
   886 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
   887 	{
   888 		if (ret)
   889 		{
   890 			*ret = IFACE_OK;
   891 		}
   892 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
   893 	}
   894 
   895 	CPluginManager::CPlugin *pl;
   896 	List<IMetamodListener *>::iterator event;
   897 	IMetamodListener *api;
   898 	void *value;
   899 	
   900 	int subret = 0;
   901 	for (PluginIter iter = g_PluginMngr._begin();
   902 		 iter != g_PluginMngr._end();
   903 		 iter++)
   904 	{
   905 		pl = (*iter);
   906 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
   907 		{
   908 			api = (*event);
   909 			subret = IFACE_FAILED;
   910 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
   911 			{
   912 				if (ret)
   913 				{
   914 					*ret = subret;
   915 				}
   916 				if (id)
   917 				{
   918 					*id = pl->m_Id;
   919 				}
   920 				return value;
   921 			}
   922 		}
   923 	}
   924 
   925 	if (ret)
   926 	{
   927 		*ret = IFACE_FAILED;
   928 	}
   929 
   930 	return NULL;
   931 }
   932 
   933 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   934 {
   935 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   936 
   937 	pl->m_Events.push_back(pListener);
   938 }
   939 
   940 const char *MetamodSource::GetGameBinaryPath()
   941 {
   942 	return full_bin_path.c_str();
   943 }
   944 
   945 const char *MetamodSource::GetPluginsFile()
   946 {
   947 	return provider->GetConVarString(mm_pluginsfile);
   948 }
   949 
   950 const char *MetamodSource::GetVDFDir()
   951 {
   952 	return provider->GetConVarString(mm_basedir);
   953 }
   954 
   955 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
   956 {
   957 	return provider->GetConCommandBaseAccessor();
   958 }
   959 
   960 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   961 {
   962 	if (provider->IsConCommandBaseACommand(pCommand))
   963 	{
   964 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   965 	}
   966 	else
   967 	{
   968 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   969 	}
   970 
   971 	return provider->RegisterConCommandBase(pCommand);
   972 }
   973 
   974 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   975 {
   976 	if (provider->IsConCommandBaseACommand(pCommand))
   977 	{
   978 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   979 	}
   980 	else
   981 	{
   982 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   983 	}
   984 
   985 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
   986 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
   987 }
   988 
   989 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
   990 {
   991 	PluginIter iter;
   992 	CPluginManager::CPlugin *pPlugin;
   993 	List<IMetamodListener *>::iterator event;
   994 	IMetamodListener *pML;
   995 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
   996 	{
   997 		pPlugin = (*iter);
   998 		if (pPlugin->m_Status < Pl_Paused)
   999 		{
  1000 			continue;
  1001 		}
  1002 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
  1003 		if (pPlugin->m_API->GetApiVersion() < 12)
  1004 		{
  1005 			continue;
  1006 		}
  1007 		for (event=pPlugin->m_Events.begin();
  1008 			event!=pPlugin->m_Events.end();
  1009 			event++)
  1010 		{
  1011 			pML = (*event);
  1012 			pML->OnUnlinkConCommandBase(id, pCommand);
  1013 		}
  1014 	}
  1015 
  1016 	return provider->UnregisterConCommandBase(pCommand);
  1017 }
  1018 
  1019 int MetamodSource::GetUserMessageCount()
  1020 {
  1021 	return provider->GetUserMessageCount();
  1022 }
  1023 
  1024 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
  1025 {
  1026 	return provider->FindUserMessage(name, size);
  1027 }
  1028 
  1029 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
  1030 {
  1031 	return provider->GetUserMessage(index, size);
  1032 }
  1033 
  1034 int MetamodSource::GetSourceEngineBuild()
  1035 {
  1036 	return engine_build;
  1037 }
  1038 
  1039 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks, int version)
  1040 {
  1041 	if (version != -1)
  1042 		vsp_version = version;
  1043 	
  1044 	vsp_callbacks = callbacks;
  1045 	ITER_EVENT(OnVSPListening, (callbacks));
  1046 
  1047 	if (is_gamedll_loaded)
  1048 	{
  1049 		/*
  1050 		 * MM:S is loaded as a game DLL so we need to set these for mm_IsVspBridged() and
  1051 		 * mm_IsVspLoadComplete()
  1052 		 */
  1053 		g_bIsVspBridged = true;
  1054 		were_plugins_loaded = true;
  1055 	}
  1056 }
  1057 
  1058 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1059 {
  1060 	if (pVersion)
  1061 	{
  1062 		*pVersion = vsp_version;
  1063 	}
  1064 
  1065 	return vsp_callbacks;
  1066 }
  1067 
  1068 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1069 {
  1070 	va_list ap;
  1071 	size_t result;
  1072 
  1073 	va_start(ap, format);
  1074 	result = FormatArgs(buffer, maxlength, format, ap);
  1075 	va_end(ap);
  1076 
  1077 	return result;
  1078 }
  1079 
  1080 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1081 {
  1082 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1083 }
  1084 
  1085 bool MetamodSource::IsLoadedAsGameDLL()
  1086 {
  1087 	return is_gamedll_loaded;
  1088 }
  1089 
  1090 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version, bool loaded)
  1091 {
  1092 	gamedll_info.factory = serverFactory;
  1093 	gamedll_version = version;
  1094 	is_gamedll_loaded = loaded;
  1095 }
  1096 
  1097 void MetamodSource::SetVSPListener(const char *path)
  1098 {
  1099 	metamod_path.assign(path);
  1100 }
  1101 
  1102 static bool
  1103 ProcessVDF(const char *path, bool &skipped)
  1104 {
  1105 	PluginId id;
  1106 	bool already;
  1107 	char alias[24], file[255], full_path[255], error[255];
  1108 
  1109 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1110 	{
  1111 		skipped = false;
  1112 		return false;
  1113 	}
  1114 
  1115 	if (alias[0] != '\0')
  1116 		g_PluginMngr.SetAlias(alias, file);
  1117 
  1118 	/* Attempt to find a file extension */
  1119 	if (UTIL_GetExtension(file) == NULL)
  1120 	{
  1121 		g_pMetamod->PathFormat(full_path, 
  1122 			sizeof(full_path), 
  1123 			"%s/%s%s", 
  1124 			g_pMetamod->GetBaseDir(), 
  1125 			file, 
  1126 #if defined WIN32 || defined _WIN32
  1127 			".dll"
  1128 #elif defined __APPLE__
  1129 			".dylib"
  1130 #else
  1131 			"_i486.so"
  1132 #endif
  1133 			);
  1134 	}
  1135 	else
  1136 	{
  1137 		g_pMetamod->PathFormat(full_path,
  1138 			sizeof(full_path),
  1139 			"%s/%s", 
  1140 			g_pMetamod->GetBaseDir(),
  1141 			file);
  1142 	}
  1143 
  1144 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
  1145 	skipped = already;
  1146 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1147 	{
  1148 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1149 		return false;
  1150 	}
  1151 
  1152 	return true;
  1153 }
  1154 
  1155 static int
  1156 LoadVDFPluginsFromDir(const char *dir, int &skipped)
  1157 {
  1158 	bool success, skip;
  1159 	int total = 0;
  1160 	char path[MAX_PATH];
  1161 	char relpath[MAX_PATH * 2];
  1162 
  1163 	skipped = 0;
  1164 
  1165 #if defined _MSC_VER
  1166 	HANDLE hFind;
  1167 	WIN32_FIND_DATA fd;
  1168 	char error[255];
  1169 
  1170 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
  1171 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1172 	{
  1173 		DWORD dw = GetLastError();
  1174 		if (dw == ERROR_FILE_NOT_FOUND)
  1175 			return 0;
  1176 
  1177 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1178 			NULL,
  1179 			dw,
  1180 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1181 			error,
  1182 			sizeof(error),
  1183 			NULL);
  1184 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1185 		return 0;
  1186 	}
  1187 
  1188 	do
  1189 	{
  1190 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1191 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1192 		success = ProcessVDF(relpath, skip);
  1193 		if (skip)
  1194 			skipped++;
  1195 		else if (success)
  1196 			total++;
  1197 	} while (FindNextFile(hFind, &fd));
  1198 
  1199 	FindClose(hFind);
  1200 #else
  1201 	DIR *pDir;
  1202 	struct dirent *pEnt;
  1203 	int extidx;
  1204 
  1205 	if ((pDir = opendir(dir)) == NULL)
  1206 	{
  1207 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1208 		return 0;
  1209 	}
  1210 
  1211 	while ((pEnt = readdir(pDir)) != NULL)
  1212 	{
  1213 		if (strcmp(pEnt->d_name, ".") == 0
  1214 			|| strcmp(pEnt->d_name, "..") == 0)
  1215 		{
  1216 			continue;
  1217 		}
  1218 		extidx = strlen(pEnt->d_name) - 4;
  1219 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1220 		{
  1221 			continue;
  1222 		}
  1223 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1224 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1225 		success = ProcessVDF(relpath, skip);
  1226 		if (skip)
  1227 			skipped++;
  1228 		else if (success)
  1229 			total++;
  1230 	}
  1231 
  1232 	closedir(pDir);
  1233 #endif
  1234 
  1235 	return total;
  1236 }
  1237 
  1238 int
  1239 mm_LoadPlugins(const char *filepath, const char *vdfpath)
  1240 {
  1241 	int total, skipped, fskipped, vskipped;
  1242 	const char *s = "";
  1243 
  1244 	total = LoadPluginsFromFile(filepath, fskipped);
  1245 	total += LoadVDFPluginsFromDir(vdfpath, vskipped);
  1246 	skipped = fskipped + vskipped;
  1247 
  1248 	if (total == 0 || total > 1)
  1249 		s = "s";
  1250 
  1251 	if (skipped)
  1252 		mm_LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
  1253 	else
  1254 		mm_LogMessage("[META] Loaded %d plugin%s.", total, s);
  1255 
  1256 	return total;
  1257 }
  1258 
  1259 bool
  1260 mm_IsVspBridged()
  1261 {
  1262 	return g_bIsVspBridged;
  1263 }
  1264 
  1265 bool
  1266 mm_IsVspLoadComplete()
  1267 {
  1268 	return were_plugins_loaded;
  1269 }
  1270