sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Sat Jan 27 09:18:17 2007 +0000 (2007-01-27)
changeset 278 614ea295cd25
parent 263 13c2809e96b8
child 282 7a237e9ea5a1
permissions -rw-r--r--
fixed SourceMM crashing on long paths (steam srcds)
     1 /* ======== SourceMM ========
     2 * Copyright (C) 2004-2006 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): David "BAILOPAN" Anderson
     8 * Contributor(s): Scott "Damaged Soul" Ehlert
     9 *				: Pavol "PM OnoTo" Marko
    10 * ============================
    11 */
    12 
    13 #include <interface.h>
    14 #include <eiface.h>
    15 #include "sourcemm.h"
    16 #include "concommands.h"
    17 #include "CSmmAPI.h"
    18 #include "CPlugin.h"
    19 #include "util.h"
    20 
    21 using namespace SourceMM;
    22 
    23 /**
    24  * @brief Implementation of main SourceMM GameDLL functionality
    25  * @file sourcemm.cpp
    26  */
    27 
    28 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    29 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
    30 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    31 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    32 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    33 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    34 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    35 void DLLShutdown_handler();
    36 void LevelShutdown_handler();
    37 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
    38 
    39 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
    40 EngineInfo g_Engine;
    41 SourceHook::CSourceHookImpl g_SourceHook;
    42 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    43 SourceHook::String g_ModPath;
    44 SourceHook::String g_BinPath;
    45 PluginId g_PLID = Pl_Console;		//Technically, SourceMM is the "Console" plugin... :p
    46 bool bInFirstLevel = true;
    47 bool gParsedGameInfo = false;
    48 SourceHook::List<GameDllInfo *> gamedll_list;
    49 SourceHook::CallClass<IServerGameDLL> *dllExec;
    50 int g_GameDllVersion = 0;
    51 
    52 void ClearGamedllList();
    53 
    54 //helper macro
    55 #define	IFACE_MACRO(orig,nam) \
    56 	CPluginManager::CPlugin *pl; \
    57 	SourceHook::List<IMetamodListener *>::iterator event; \
    58 	IMetamodListener *api; \
    59 	int mret = 0; \
    60 	void *val = NULL; \
    61 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    62 		pl = (*iter); \
    63 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    64 			api = (*event); \
    65 			mret = IFACE_FAILED; \
    66 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
    67 				if (ret) *ret = mret; \
    68 				return val; \
    69 			} \
    70 		} \
    71 	} \
    72 	return (orig)(iface, ret);
    73 
    74 #define ITER_EVENT(evn, args) \
    75 	CPluginManager::CPlugin *pl; \
    76 	SourceHook::List<IMetamodListener *>::iterator event; \
    77 	IMetamodListener *api; \
    78 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    79 		pl = (*iter); \
    80 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    81 			api = (*event); \
    82 			api->evn args; \
    83 		} \
    84 	}
    85 
    86 ///////////////////////////////////
    87 // Main code for HL2 Interaction //
    88 ///////////////////////////////////
    89 
    90 //Initialize everything here
    91 void InitMainStates()
    92 {
    93 	char full_path[260] = {0};
    94 	GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path)-1);
    95 	g_BinPath.assign(full_path);
    96 
    97 	//Like metamod, reload plugins at the end of the map.
    98 	//This is so plugins can hook everything on load, BUT, new plugins will be reloaded
    99 	// if the server is shut down (silly, but rare case).
   100 	bInFirstLevel = true;
   101 
   102 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
   103 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
   104 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
   105 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
   106 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
   107 
   108 	if (g_GameDll.pGameClients)
   109 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
   110 	else
   111 	{
   112 		// If IServerGameClients isn't found, this really isn't a fatal error so...
   113 		LogMessage("[META] Warning: Could not find IServerGameClients!");
   114 		LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
   115 	}
   116 }
   117 
   118 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   119 {
   120 	g_Engine.engineFactory = engineFactory;
   121 	g_Engine.fileSystemFactory = filesystemFactory;
   122 	g_Engine.physicsFactory = physicsFactory;
   123 	g_Engine.pGlobals = pGlobals;
   124 
   125 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   126 	if (!g_Engine.engine)
   127 	{
   128 		Error("Could not find IVEngineServer! Metamod cannot load.");
   129 		return false;
   130 	}
   131 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
   132 	if (!g_Engine.icvar)
   133 	{
   134 		Error("Could not find ICvar! Metamod cannot load.");
   135 		return false;
   136 	}
   137 
   138 	g_Engine.loaded = true;
   139 
   140 	//Initialize our console hooks
   141 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   142 
   143 	if (!g_SmmAPI.CacheCmds())
   144 	{
   145 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   146 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   147 	}
   148 
   149 
   150 	const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
   151 	if (!pluginFile) 
   152 		pluginFile = GetPluginsFile();
   153 
   154 	char full_path[260];
   155 	g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
   156 
   157 	LoadPluginsFromFile(full_path);
   158 
   159 	bInFirstLevel = true;
   160 
   161 	dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
   162 
   163 	RETURN_META_VALUE(MRES_IGNORED, true);
   164 }
   165 
   166 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   167 {
   168 	g_PluginMngr.SetAllLoaded();
   169 	RETURN_META_VALUE(MRES_IGNORED, true);
   170 }
   171 
   172 //This is where the magic happens
   173 SMM_API void *CreateInterface(const char *iface, int *ret)
   174 {
   175 	// Prevent loading of self as a SourceMM plugin or Valve server plugin :x
   176 	const char *vspIface = "ISERVERPLUGINCALLBACKS";
   177 	if (strcmp(iface, PLAPI_NAME) == 0 || strnicmp(iface, vspIface, strlen(vspIface)) == 0)
   178 	{
   179 		Warning("Do not try loading Metamod:Source as a SourceMM or Valve server plugin.\n");
   180 
   181 		if (ret)
   182 			*ret = IFACE_FAILED;
   183 		return NULL;
   184 	}
   185 
   186 	if (!gParsedGameInfo)
   187 	{
   188 		gParsedGameInfo = true;
   189 		char curpath[260] = {0};
   190 		char dllpath[260] = {0};
   191 		getcwd(curpath, sizeof(curpath)-1);
   192 		if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
   193 		{
   194 			Error("GetFileOfAddress() failed! Metamod cannot load.\n");
   195 			return NULL;
   196 		}
   197 		SourceHook::String s_dllpath(dllpath);
   198 		//begin the heuristics for searching for the mod path (these are quite ugly).
   199 		//for OS compatibility purposes, we're going to do case insensitivity on windows.
   200 		size_t path_len = strlen(curpath);
   201 		size_t dll_len = strlen(dllpath);
   202 
   203 		//strip the dll path off
   204 		//:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
   205 		for (size_t i=dll_len-1; i>0; i--)
   206 		{
   207 			if (dllpath[i] == '\\' || dllpath[i] == '/')
   208 			{
   209 				if (i == dll_len-1)
   210 					break;
   211 				//save path by stripping off file name and ending terminator
   212 				dllpath[i] = '\0';
   213 				dll_len = i;
   214 				break;
   215 			}
   216 		}
   217 
   218 		//strip absolute path terminators if any!
   219 		if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
   220 			curpath[--path_len] = '\0';
   221 
   222 		//if the base path doesn't fit into the module path, something is wrong!
   223 		// ex: c:\games\srcds
   224 		//     c:\gaben.dll
   225 		if (path_len > dll_len)
   226 		{
   227 			Error("Could not detect GameDLL path! Metamod cannot load[1].\n");
   228 			return NULL;
   229 		}
   230 
   231 		//we are now in such a position that the two dir names SHOULD MATCH!
   232 		typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
   233 		STRNCMP cmp = 
   234 #ifdef WIN32
   235 			strnicmp;
   236 #else
   237 			strncmp;
   238 #endif
   239 		//are they equal?
   240 		if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
   241 		{
   242 			//:TODO: In this case, we should read /proc/self/maps and find srcds!
   243 			Error("Could not detect GameDLL path! Metamod cannot load[2].\n");
   244 			return NULL;
   245 		}
   246 		//this will skip past the dir and its separator char
   247 		char *ptr = &(dllpath[path_len+1]);
   248 		path_len = strlen(ptr);
   249 		for (size_t i=0; i<path_len; i++)
   250 		{
   251 			if (ptr[i] == '/' || ptr[i] == '\\')
   252 			{
   253 				if (i == 0)
   254 				{
   255 					Error("Could not detect GameDLL path! Metamod cannot load[3].\n");
   256 					return NULL;
   257 				} else {
   258 					ptr[i] = '\0';
   259 					path_len = i+1;
   260 					break;
   261 				}
   262 			}
   263 		}
   264 		//WE NOW HAVE A GUESS AT THE MOD DIR.  OH MY GOD.
   265 		char temp_path[260];
   266 		snprintf(temp_path, sizeof(temp_path)-1, 
   267 			"%s%s%s", 
   268 			curpath, 
   269 			PATH_SEP_STR, 
   270 			ptr);
   271 
   272 		g_ModPath.assign(temp_path);
   273 
   274 		snprintf(temp_path, sizeof(temp_path)-1, 
   275 			"%s%s%s", 
   276 			g_ModPath.c_str(),
   277 			PATH_SEP_STR,
   278 			"gameinfo.txt");
   279 
   280 		FILE *fp = fopen(temp_path, "rt");
   281 		if (!fp)
   282 		{
   283 			/* Do not error out here! It's possible the mod exists in the root directory, i.e.
   284 			 * Dark Messiah.  Let's check that just in case!
   285 			 */
   286 			g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s", curpath);
   287 			g_ModPath.assign(temp_path);
   288 			g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
   289 
   290 			fp = fopen(temp_path, "rt");
   291 			if (!fp)
   292 			{
   293 				/* Okay, we have to concede here. */
   294 				Error("Unable to open gameinfo.txt!  Metamod cannot load.\n");
   295 				return NULL;
   296 			}
   297 		}
   298 		char buffer[255];
   299 		char key[128], val[128];
   300 		size_t len = 0;
   301 		const char *gameinfo = "|gameinfo_path|";
   302 		size_t gameinfo_len = strlen(gameinfo);
   303 		bool search = false;
   304 		bool gamebin = false;
   305 		const char *lptr;
   306 		while (!feof(fp))
   307 		{
   308 			buffer[0] = '\0';
   309 			fgets(buffer, sizeof(buffer)-1, fp);
   310 			len = strlen(buffer);
   311 			if (buffer[len-1] == '\n')
   312 				buffer[--len] = '\0';
   313 			UTIL_TrimComments(buffer);
   314 			UTIL_TrimLeft(buffer);
   315 			UTIL_TrimRight(buffer);
   316 			if (stricmp(buffer, "SearchPaths") == 0)
   317 				search = true;
   318 			if (!search)
   319 				continue;
   320 			UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
   321 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   322 			{
   323 				if (stricmp(key, "Game") == 0)
   324 					gamebin = false;
   325 				else
   326 					gamebin = true;
   327 
   328 				if (strncmp(val, gameinfo, gameinfo_len) == 0)
   329 				{
   330 					ptr = &(val[gameinfo_len]);
   331 					if (ptr[0] == '.')
   332 						ptr++;
   333 					lptr = g_ModPath.c_str();
   334 				} else {
   335 					lptr = curpath;
   336 					ptr = val;
   337 				}
   338 				size_t ptr_len = strlen(ptr);
   339 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   340 					ptr[--ptr_len] = '\0';
   341 
   342 				//no need to append "bin"
   343 				if (gamebin)
   344 				{
   345 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   346 				} else if (!ptr[0]) {
   347 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   348 				} else {
   349 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   350 				}
   351 				if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
   352 				{
   353 					FILE *fp = fopen(temp_path, "rb");
   354 					if (!fp)
   355 						continue;
   356 					//:TODO: Optimize this a bit!
   357 					SourceHook::List<GameDllInfo *>::iterator iter;
   358 					GameDllInfo *pCheck;
   359 					bool found = false;
   360 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   361 					{
   362 						pCheck = (*iter);
   363 						if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)-1))
   364 						{
   365 							if (UTIL_PathCmp(temp_path, buffer))
   366 							{
   367 								found = true;
   368 								break;
   369 							}
   370 						}
   371 					}
   372 					if (found)
   373 						continue;
   374 					fclose(fp);
   375 					HINSTANCE gamedll = dlmount(temp_path);
   376 					if (gamedll == NULL)
   377 						continue;
   378 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   379 					if (fn == NULL)
   380 					{
   381 						dlclose(gamedll);
   382 						continue;
   383 					}
   384 					GameDllInfo *pInfo = new GameDllInfo;
   385 					pInfo->factory = fn;
   386 					pInfo->lib = gamedll;
   387 					pInfo->loaded = true;
   388 					pInfo->pGameDLL = NULL;
   389 					pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   390 					gamedll_list.push_back(pInfo);
   391 					break;
   392 				}
   393 			}
   394 		}
   395 		fclose(fp);
   396 	}
   397 
   398 	if (!g_GameDll.loaded)
   399 	{
   400 		const char *str = "ServerGameDLL";
   401 		size_t len = strlen(str);
   402 
   403 		if (strncmp(iface, str, len) == 0)
   404 		{
   405 			//This is the interface we want!  Right now we support versions 3 through 5.
   406 			g_GameDllVersion = atoi(&(iface[len]));
   407 			int sizeTooBig = 0;	//rename this to sizeWrong in the future!
   408 			if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
   409 			{
   410 				//maybe this will get used in the future
   411 				sizeTooBig = g_GameDllVersion;
   412 				if (ret)
   413 					*ret = IFACE_FAILED;
   414 			}
   415 			SourceHook::List<GameDllInfo *>::iterator iter;
   416 			GameDllInfo *pInfo = NULL;
   417 			void *ptr;
   418 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   419 			{
   420 				pInfo = (*iter);
   421 				ptr = (pInfo->factory)(iface, ret);
   422 				if (ptr)
   423 				{
   424 					//this is our gamedll.  unload the others.
   425 					gamedll_list.erase(iter);
   426 					ClearGamedllList();
   427 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   428 					g_GameDll = *pInfo;
   429 					delete pInfo;
   430 					break;
   431 				}
   432 			}
   433 			if (g_GameDll.loaded)
   434 			{
   435 				if (sizeTooBig)
   436 				{
   437 					Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
   438 					if (ret)
   439 						*ret = IFACE_FAILED;
   440 					return NULL;
   441 				} else {
   442 					InitMainStates();
   443 				}
   444 			} else {
   445 				sizeTooBig = 0;
   446 				if (ret)
   447 					*ret = IFACE_FAILED;
   448 				return NULL;
   449 			}
   450 		} else {
   451 			//wtf do we do...
   452 			//:TODO: .. something a bit more intelligent?
   453 			Error("Engine requested unknown interface before GameDLL was known!\n");
   454 			return NULL;
   455 		}
   456 	}
   457 
   458 	//if we got here, there's definitely a gamedll.
   459 	IFACE_MACRO(g_GameDll.factory, GameDLL);
   460 }
   461 
   462 void ClearGamedllList()
   463 {
   464 	SourceHook::List<GameDllInfo *>::iterator iter;
   465 
   466 	GameDllInfo *pInfo;
   467 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   468 	{
   469 		pInfo = (*iter);
   470 		dlclose(pInfo->lib);
   471 		delete pInfo;
   472 	}
   473 
   474 	gamedll_list.clear();
   475 }
   476 
   477 void DLLShutdown_handler()
   478 {
   479 	//Unload plugins
   480 	g_PluginMngr.UnloadAll();
   481 
   482 	// Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
   483 	g_SMConVarAccessor.MarkCommandsAsGameDLL();
   484 	g_SMConVarAccessor.UnregisterGameDLLCommands();
   485 
   486 	SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
   487 
   488 	SH_RELEASE_CALLCLASS(dllExec);
   489 	dllExec = NULL;
   490 
   491 	g_SourceHook.CompleteShutdown();
   492 
   493 	if (g_GameDll.lib && g_GameDll.loaded)
   494 		dlclose(g_GameDll.lib);
   495 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   496 
   497 	RETURN_META(MRES_SUPERCEDE);
   498 }
   499 
   500 int LoadPluginsFromFile(const char *_file)
   501 {
   502 	FILE *fp;
   503 	int total = 0, skipped=0;
   504 	PluginId id;
   505 	bool already;
   506 
   507 	fp = fopen(_file, "rt");
   508 	if (!fp)
   509 	{
   510 		LogMessage("[META] Could not open plugins file %s\n", _file);
   511 		return -1;
   512 	}
   513 
   514 	char buffer[255], error[255], full_path[255];
   515 	const char *ptr, *ext, *file;
   516 	size_t length;
   517 	while (!feof(fp))
   518 	{
   519 		buffer[0] = '\0';
   520 		fgets(buffer, sizeof(buffer)-1, fp);
   521 		length = strlen(buffer);
   522 		if (!length)
   523 			continue;
   524 		if (buffer[length-1] == '\n')
   525 			buffer[--length] = '\0';
   526 
   527 		UTIL_TrimLeft(buffer);
   528 		UTIL_TrimRight(buffer);
   529 
   530 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   531 			continue;
   532 		file = buffer;
   533 		if (buffer[0] == '"')
   534 		{
   535 			char *cptr = buffer;
   536 			file = ++cptr;
   537 
   538 			while (*cptr)
   539 			{
   540 				if (*cptr == '"')
   541 				{
   542 					*cptr = '\0';
   543 					break;
   544 				}
   545 				cptr++;
   546 			}
   547 		} else {
   548 			char *cptr = buffer;
   549 			while (*cptr)
   550 			{
   551 				if (isspace(*cptr))
   552 				{
   553 					char *optr = cptr;
   554 					while (*cptr && isspace(*cptr))
   555 						cptr++;
   556 					*optr = '\0';
   557 					UTIL_TrimRight(cptr);
   558 					if (*cptr && isalpha(*cptr))
   559 					{
   560 						g_PluginMngr.SetAlias(buffer, cptr);
   561 						file = cptr;
   562 					}
   563 					break;
   564 				}
   565 				cptr++;
   566 			}
   567 		}
   568 		if (!file[0])
   569 		{
   570 			continue;
   571 		}
   572 		//First find if it's an absolute path or not...
   573 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   574 		{
   575 			//If we're in an absolute path, ignore our normal heuristics
   576 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error)-1);
   577 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   578 			{
   579 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   580 			} else {
   581 				if (already)
   582 					skipped++;
   583 				else
   584 					total++;
   585 			}
   586 		} else {
   587 			//Attempt to find a file extension
   588 			ptr = UTIL_GetExtension(file);
   589 			//Add an extension if there's none there
   590 			if (!ptr)
   591 			{
   592 #if defined WIN32 || defined _WIN32
   593 				ext = ".dll";
   594 #else
   595 				ext = "_i486.so";
   596 #endif
   597 			} else {
   598 				ext = "";
   599 			}
   600 			//Format the new path
   601 			g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), file, ext);
   602 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   603 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   604 			{
   605 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   606 			} else {
   607 				if (already)
   608 					skipped++;
   609 				else
   610 					total++;
   611 			}
   612 		}
   613 	}
   614 	fclose(fp);
   615 
   616 	if (skipped)
   617 	{
   618 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   619 	} else {
   620 		LogMessage("[META] Loaded %d plugins from file.", total);
   621 	}
   622 	
   623 	return total;
   624 }
   625 
   626 //Wrapper function.  This is called when the GameDLL thinks it's using
   627 // the engine's real engineFactory.
   628 void *EngineFactory(const char *iface, int *ret)
   629 {
   630 	IFACE_MACRO(g_Engine.engineFactory, Engine);
   631 }
   632 
   633 //Wrapper function.  This is called when the GameDLL thinks it's using
   634 // the engine's real physicsFactory.
   635 void *PhysicsFactory(const char *iface, int *ret)
   636 {
   637 	IFACE_MACRO(g_Engine.physicsFactory, Physics);
   638 }
   639 
   640 //Wrapper function.  This is called when the GameDLL thinks it's using
   641 // the engine's real fileSystemFactory.
   642 void *FileSystemFactory(const char *iface, int *ret)
   643 {
   644 	IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
   645 }
   646 
   647 void LogMessage(const char *msg, ...)
   648 {
   649 	va_list ap;
   650 	static char buffer[2048];
   651 
   652 	buffer[0] = '\0';
   653 
   654 	va_start(ap, msg);
   655 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   656 	strcat(buffer, "\n");
   657 	va_end(ap);
   658 
   659 	if (!g_Engine.engine)
   660 	{
   661 		fprintf(stdout, "%s", buffer);
   662 	} else {
   663 		g_Engine.engine->LogPrint(buffer);
   664 	}
   665 }
   666 
   667 void LevelShutdown_handler(void)
   668 {
   669 	if (!bInFirstLevel)
   670 	{
   671 		char full_path[255];
   672 		g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   673 
   674 		LoadPluginsFromFile(full_path);
   675 	} else {
   676 		bInFirstLevel = false;
   677 	}
   678 
   679 	ITER_EVENT(OnLevelShutdown, ());
   680 
   681 	RETURN_META(MRES_IGNORED);
   682 }
   683 
   684 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   685 {
   686 	if (!g_SmmAPI.CacheSuccessful())
   687 	{
   688 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   689 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   690 	}
   691 
   692 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
   693     SetUnhandledExceptionFilter(NULL);
   694 #endif
   695 
   696 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   697 
   698 	RETURN_META_VALUE(MRES_IGNORED, false);
   699 }
   700 
   701 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
   702 void * operator new(size_t size) {
   703 	return(calloc(1, size)); 
   704 }
   705 
   706 void * operator new[](size_t size) {
   707 	return(calloc(1, size)); 
   708 }
   709 
   710 void operator delete(void * ptr) {
   711 	if(ptr)
   712 		free(ptr);
   713 }
   714 
   715 void operator delete[](void * ptr) {
   716 	if(ptr)
   717 		free(ptr);
   718 }
   719 #endif