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