core/metamod.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Jul 01 02:43:22 2010 -0500 (2010-07-01)
changeset 722 78f730f91439
parent 714 966f819588a2
child 747 9563de0165f7
permissions -rw-r--r--
Fixed problem on OBV where alternately loaded plugins (CreateInterface_MMS) could be incorrectly told they were on the OB engine (bug 4491, r=dvander).

This only happened when there was more than one plugin that loaded this way. And the first plugin to load had to fail on OBV first so that OB could be tried. It was being permanently set to OB for future plugin loads and this caused problems.
     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 *ptr, *ext, *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 >= 0 && 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 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
   788 {
   789 	va_list ap;
   790 	char buffer[2048];
   791 
   792 	va_start(ap, fmt);
   793 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   794 	va_end(ap);
   795 
   796 	provider->ClientConsolePrint(client, buffer);
   797 }
   798 
   799 void MetamodSource::EnableVSPListener()
   800 {
   801 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
   802 	{
   803 		InitializeVSP();
   804 	}
   805 
   806 	vsp_load_requested = true;
   807 }
   808 
   809 int MetamodSource::GetVSPVersion()
   810 {
   811 	return vsp_version;
   812 }
   813 
   814 int MetamodSource::GetGameDLLVersion()
   815 {
   816 	return gamedll_version;
   817 }
   818 
   819 bool MetamodSource::RemotePrintingAvailable()
   820 {
   821 	return provider->IsRemotePrintingAvailable();
   822 }
   823 
   824 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
   825 {
   826 	if (id)
   827 	{
   828 		*id = 0;
   829 	}
   830 
   831 	if (!iface)
   832 	{
   833 		return NULL;
   834 	}
   835 
   836 	/* First check ours... we get first chance! */
   837 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   838 	{
   839 		if (ret)
   840 		{
   841 			*ret = IFACE_OK;
   842 		}
   843 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   844 	}
   845 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
   846 	{
   847 		if (ret)
   848 		{
   849 			*ret = IFACE_OK;
   850 		}
   851 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   852 	}
   853 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
   854 	{
   855 		if (ret)
   856 		{
   857 			*ret = IFACE_OK;
   858 		}
   859 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
   860 	}
   861 
   862 	CPluginManager::CPlugin *pl;
   863 	List<IMetamodListener *>::iterator event;
   864 	IMetamodListener *api;
   865 	void *value;
   866 	
   867 	int subret = 0;
   868 	for (PluginIter iter = g_PluginMngr._begin();
   869 		 iter != g_PluginMngr._end();
   870 		 iter++)
   871 	{
   872 		pl = (*iter);
   873 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
   874 		{
   875 			api = (*event);
   876 			subret = IFACE_FAILED;
   877 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
   878 			{
   879 				if (ret)
   880 				{
   881 					*ret = subret;
   882 				}
   883 				if (id)
   884 				{
   885 					*id = pl->m_Id;
   886 				}
   887 				return value;
   888 			}
   889 		}
   890 	}
   891 
   892 	if (ret)
   893 	{
   894 		*ret = IFACE_FAILED;
   895 	}
   896 
   897 	return NULL;
   898 }
   899 
   900 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   901 {
   902 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   903 
   904 	pl->m_Events.push_back(pListener);
   905 }
   906 
   907 const char *MetamodSource::GetGameBinaryPath()
   908 {
   909 	return full_bin_path.c_str();
   910 }
   911 
   912 const char *MetamodSource::GetPluginsFile()
   913 {
   914 	return provider->GetConVarString(mm_pluginsfile);
   915 }
   916 
   917 const char *MetamodSource::GetVDFDir()
   918 {
   919 	return provider->GetConVarString(mm_basedir);
   920 }
   921 
   922 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
   923 {
   924 	return provider->GetConCommandBaseAccessor();
   925 }
   926 
   927 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   928 {
   929 	if (provider->IsConCommandBaseACommand(pCommand))
   930 	{
   931 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   932 	}
   933 	else
   934 	{
   935 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
   936 	}
   937 
   938 	return provider->RegisterConCommandBase(pCommand);
   939 }
   940 
   941 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   942 {
   943 	if (provider->IsConCommandBaseACommand(pCommand))
   944 	{
   945 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
   946 	}
   947 	else
   948 	{
   949 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
   950 	}
   951 
   952 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
   953 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
   954 }
   955 
   956 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
   957 {
   958 	PluginIter iter;
   959 	CPluginManager::CPlugin *pPlugin;
   960 	List<IMetamodListener *>::iterator event;
   961 	IMetamodListener *pML;
   962 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
   963 	{
   964 		pPlugin = (*iter);
   965 		if (pPlugin->m_Status < Pl_Paused)
   966 		{
   967 			continue;
   968 		}
   969 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
   970 		if (pPlugin->m_API->GetApiVersion() < 12)
   971 		{
   972 			continue;
   973 		}
   974 		for (event=pPlugin->m_Events.begin();
   975 			event!=pPlugin->m_Events.end();
   976 			event++)
   977 		{
   978 			pML = (*event);
   979 			pML->OnUnlinkConCommandBase(id, pCommand);
   980 		}
   981 	}
   982 
   983 	return provider->UnregisterConCommandBase(pCommand);
   984 }
   985 
   986 int MetamodSource::GetUserMessageCount()
   987 {
   988 	return provider->GetUserMessageCount();
   989 }
   990 
   991 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
   992 {
   993 	return provider->FindUserMessage(name, size);
   994 }
   995 
   996 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
   997 {
   998 	return provider->GetUserMessage(index, size);
   999 }
  1000 
  1001 int MetamodSource::GetSourceEngineBuild()
  1002 {
  1003 	return engine_build;
  1004 }
  1005 
  1006 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks, int version)
  1007 {
  1008 	if (version != -1)
  1009 		vsp_version = version;
  1010 	
  1011 	vsp_callbacks = callbacks;
  1012 	ITER_EVENT(OnVSPListening, (callbacks));
  1013 
  1014 	if (is_gamedll_loaded)
  1015 	{
  1016 		/*
  1017 		 * MM:S is loaded as a game DLL so we need to set these for mm_IsVspBridged() and
  1018 		 * mm_IsVspLoadComplete()
  1019 		 */
  1020 		g_bIsVspBridged = true;
  1021 		were_plugins_loaded = true;
  1022 	}
  1023 }
  1024 
  1025 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1026 {
  1027 	if (pVersion)
  1028 	{
  1029 		*pVersion = vsp_version;
  1030 	}
  1031 
  1032 	return vsp_callbacks;
  1033 }
  1034 
  1035 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1036 {
  1037 	va_list ap;
  1038 	size_t result;
  1039 
  1040 	va_start(ap, format);
  1041 	result = FormatArgs(buffer, maxlength, format, ap);
  1042 	va_end(ap);
  1043 
  1044 	return result;
  1045 }
  1046 
  1047 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1048 {
  1049 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1050 }
  1051 
  1052 bool MetamodSource::IsLoadedAsGameDLL()
  1053 {
  1054 	return is_gamedll_loaded;
  1055 }
  1056 
  1057 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version, bool loaded)
  1058 {
  1059 	gamedll_info.factory = serverFactory;
  1060 	gamedll_version = version;
  1061 	is_gamedll_loaded = loaded;
  1062 }
  1063 
  1064 void MetamodSource::SetVSPListener(const char *path)
  1065 {
  1066 	metamod_path.assign(path);
  1067 }
  1068 
  1069 size_t MetamodSource::GetFullPluginPath(const char *plugin, char *buffer, size_t len)
  1070 {
  1071 	const char *pext, *ext;
  1072 	size_t num;
  1073 
  1074 	/* First find if it's an absolute path or not... */
  1075 	if (plugin[0] == '/' || strncmp(&(plugin[1]), ":\\", 2) == 0)
  1076 	{
  1077 		return UTIL_Format(buffer, len, plugin);
  1078 	}
  1079 
  1080 	/* Attempt to find a file extension */
  1081 	pext = UTIL_GetExtension(plugin);
  1082 	/* Add an extension if there's none there */
  1083 	if (!pext)
  1084 	{
  1085 #if defined WIN32 || defined _WIN32
  1086 		ext = ".dll";
  1087 #elif defined __APPLE__
  1088 		ext = ".dylib";
  1089 #else
  1090 		ext = "_i486.so";
  1091 #endif
  1092 	}
  1093 	else
  1094 	{
  1095 		ext = "";
  1096 	}
  1097 
  1098 	/* Format the new path */
  1099 	num = PathFormat(buffer, len, "%s/%s%s", mod_path.c_str(), plugin, ext);
  1100 
  1101 #if defined __linux__
  1102 	/* If path was passed without extension and it doesn't exist with "_i486.so" try ".so" */
  1103 	struct stat s;
  1104 	if (!pext && stat(buffer, &s) != 0)
  1105 	{
  1106 		num = PathFormat(buffer, len, "%s/%s.so", mod_path.c_str(), plugin);
  1107 	}
  1108 #endif
  1109 
  1110 	return num;
  1111 }
  1112 
  1113 static bool
  1114 ProcessVDF(const char *path, bool &skipped)
  1115 {
  1116 	PluginId id;
  1117 	bool already;
  1118 	char alias[24], file[255], full_path[255], error[255];
  1119 
  1120 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1121 	{
  1122 		skipped = false;
  1123 		return false;
  1124 	}
  1125 
  1126 	if (alias[0] != '\0')
  1127 		g_PluginMngr.SetAlias(alias, file);
  1128 
  1129 	g_Metamod.GetFullPluginPath(file, full_path, sizeof(full_path));
  1130 
  1131 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
  1132 	skipped = already;
  1133 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1134 	{
  1135 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1136 		return false;
  1137 	}
  1138 
  1139 	return true;
  1140 }
  1141 
  1142 static int
  1143 LoadVDFPluginsFromDir(const char *dir, int &skipped)
  1144 {
  1145 	bool success, skip;
  1146 	int total = 0;
  1147 	char path[MAX_PATH];
  1148 	char relpath[MAX_PATH * 2];
  1149 
  1150 	skipped = 0;
  1151 
  1152 #if defined _MSC_VER
  1153 	HANDLE hFind;
  1154 	WIN32_FIND_DATA fd;
  1155 	char error[255];
  1156 
  1157 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
  1158 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1159 	{
  1160 		DWORD dw = GetLastError();
  1161 		if (dw == ERROR_FILE_NOT_FOUND)
  1162 			return 0;
  1163 
  1164 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1165 			NULL,
  1166 			dw,
  1167 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1168 			error,
  1169 			sizeof(error),
  1170 			NULL);
  1171 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1172 		return 0;
  1173 	}
  1174 
  1175 	do
  1176 	{
  1177 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1178 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1179 		success = ProcessVDF(relpath, skip);
  1180 		if (skip)
  1181 			skipped++;
  1182 		else if (success)
  1183 			total++;
  1184 	} while (FindNextFile(hFind, &fd));
  1185 
  1186 	FindClose(hFind);
  1187 #else
  1188 	DIR *pDir;
  1189 	struct dirent *pEnt;
  1190 	int extidx;
  1191 
  1192 	if ((pDir = opendir(dir)) == NULL)
  1193 	{
  1194 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1195 		return 0;
  1196 	}
  1197 
  1198 	while ((pEnt = readdir(pDir)) != NULL)
  1199 	{
  1200 		if (strcmp(pEnt->d_name, ".") == 0
  1201 			|| strcmp(pEnt->d_name, "..") == 0)
  1202 		{
  1203 			continue;
  1204 		}
  1205 		extidx = strlen(pEnt->d_name) - 4;
  1206 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1207 		{
  1208 			continue;
  1209 		}
  1210 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1211 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1212 		success = ProcessVDF(relpath, skip);
  1213 		if (skip)
  1214 			skipped++;
  1215 		else if (success)
  1216 			total++;
  1217 	}
  1218 
  1219 	closedir(pDir);
  1220 #endif
  1221 
  1222 	return total;
  1223 }
  1224 
  1225 int
  1226 mm_LoadPlugins(const char *filepath, const char *vdfpath)
  1227 {
  1228 	int total, skipped, fskipped, vskipped;
  1229 	const char *s = "";
  1230 
  1231 	total = LoadPluginsFromFile(filepath, fskipped);
  1232 	total += LoadVDFPluginsFromDir(vdfpath, vskipped);
  1233 	skipped = fskipped + vskipped;
  1234 
  1235 	if (total == 0 || total > 1)
  1236 		s = "s";
  1237 
  1238 	if (skipped)
  1239 		mm_LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
  1240 	else
  1241 		mm_LogMessage("[META] Loaded %d plugin%s.", total, s);
  1242 
  1243 	return total;
  1244 }
  1245 
  1246 bool
  1247 mm_IsVspBridged()
  1248 {
  1249 	return g_bIsVspBridged;
  1250 }
  1251 
  1252 bool
  1253 mm_IsVspLoadComplete()
  1254 {
  1255 	return were_plugins_loaded;
  1256 }
  1257