sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Thu Oct 06 22:30:29 2005 +0000 (2005-10-06)
changeset 125 5cccffcd65a6
parent 124 b04971393ee4
child 138 dfa3b31cc042
permissions -rw-r--r--
Removed debug code
     1 /* ======== SourceMM ========
     2 * Copyright (C) 2004-2005 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 "util.h"
    19 
    20 /**
    21  * @brief Implementation of main SourceMM GameDLL functionality
    22  * @file sourcemm.cpp
    23  */
    24 
    25 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    26 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
    27 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    28 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    29 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    30 void DLLShutdown_handler();
    31 void LevelShutdown_handler();
    32 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
    33 
    34 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
    35 EngineInfo g_Engine;
    36 SourceHook::CSourceHookImpl g_SourceHook;
    37 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    38 SourceHook::String g_ModPath;
    39 SourceHook::String g_BinPath;
    40 PluginId g_PLID = Pl_Console;		//Technically, SourceMM is the "Console" plugin... :p
    41 bool bInFirstLevel = true;
    42 bool gParsedGameInfo = false;
    43 SourceHook::List<GameDllInfo *> gamedll_list;
    44 SourceHook::CallClass<IServerGameDLL> *dllExec;
    45 
    46 void ClearGamedllList();
    47 
    48 ///////////////////////////////////
    49 // Main code for HL2 Interaction //
    50 ///////////////////////////////////
    51 
    52 //Initialize everything here
    53 void InitMainStates()
    54 {
    55 	char full_path[260] = {0};
    56 	GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
    57 	g_BinPath.assign(full_path);
    58 
    59 	UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
    60 
    61 	//Like metamod, reload plugins at the end of the map.
    62 	//This is so plugins can hook everything on load, BUT, new plugins will be reloaded
    63 	// if the server is shut down (silly, but rare case).
    64 	bInFirstLevel = true;
    65 
    66 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
    67 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
    68 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
    69 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
    70 }
    71 
    72 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
    73 {
    74 	g_Engine.engineFactory = engineFactory;
    75 	g_Engine.fileSystemFactory = filesystemFactory;
    76 	g_Engine.physicsFactory = physicsFactory;
    77 	g_Engine.pGlobals = pGlobals;
    78 
    79 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
    80 	if (!g_Engine.engine)
    81 	{
    82 		Error("Could not find IVEngineServer! Metamod cannot load.");
    83 		return false;
    84 	}
    85 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
    86 	if (!g_Engine.icvar)
    87 	{
    88 		Error("Could not find ICvar! Metamod cannot load.");
    89 		return false;
    90 	}
    91 
    92 	g_Engine.loaded = true;
    93 
    94 	//Initialize our console hooks
    95 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
    96 
    97 	if (!g_SmmAPI.CacheCmds())
    98 	{
    99 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   100 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   101 	}
   102 
   103 	char full_path[260];
   104 	UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   105 
   106 	LoadPluginsFromFile(full_path);
   107 
   108 	g_PluginMngr.SetAllLoaded();
   109 
   110 	bInFirstLevel = true;
   111 
   112 	dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
   113 
   114 	RETURN_META_VALUE(MRES_IGNORED, true);
   115 }
   116 
   117 //This is where the magic happens
   118 SMM_API void *CreateInterface(const char *name, int *ret)
   119 {
   120 	if (!gParsedGameInfo)
   121 	{
   122 		gParsedGameInfo = true;
   123 		char curpath[260] = {0};
   124 		char dllpath[260] = {0};
   125 		getcwd(curpath, sizeof(curpath)-1);
   126 		if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
   127 		{
   128 			Error("GetFileOfAddress() failed! Metamod cannot load.");
   129 			return NULL;
   130 		}
   131 		SourceHook::String s_dllpath(dllpath);
   132 		//begin the heuristics for searching for the mod path (these are quite ugly).
   133 		//for OS compatibility purposes, we're going to do case insensitivity on windows.
   134 		size_t path_len = strlen(curpath);
   135 		size_t dll_len = strlen(dllpath);
   136 
   137 		//strip the dll path off
   138 		//:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
   139 		for (size_t i=dll_len-1; i>0; i--)
   140 		{
   141 			if (dllpath[i] == '\\' || dllpath[i] == '/')
   142 			{
   143 				if (i == dll_len-1)
   144 					break;
   145 				//save path by stripping off file name and ending terminator
   146 				dllpath[i] = '\0';
   147 				dll_len = i;
   148 				break;
   149 			}
   150 		}
   151 
   152 		//strip absolute path terminators if any!
   153 		if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
   154 			curpath[--path_len] = '\0';
   155 
   156 		//if the base path doesn't fit into the module path, something is wrong!
   157 		// ex: c:\games\srcds
   158 		//     c:\gaben.dll
   159 		if (path_len > dll_len)
   160 		{
   161 			Error("Could not detect GameDLL path! Metamod cannot load[1].");
   162 			return NULL;
   163 		}
   164 
   165 		//we are now in such a position that the two dir names SHOULD MATCH!
   166 		typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
   167 		STRNCMP cmp = 
   168 #ifdef WIN32
   169 			strnicmp;
   170 #else
   171 			strncmp;
   172 #endif
   173 		//are they equal?
   174 		if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
   175 		{
   176 			//:TODO: In this case, we should read /proc/self/maps and find srcds!
   177 			Error("Could not detect GameDLL path! Metamod cannot load[2].");
   178 			return NULL;
   179 		}
   180 		//this will skip past the dir and its separator char
   181 		char *ptr = &(dllpath[path_len+1]);
   182 		path_len = strlen(ptr);
   183 		for (size_t i=0; i<path_len; i++)
   184 		{
   185 			if (ptr[i] == '/' || ptr[i] == '\\')
   186 			{
   187 				if (i == 0)
   188 				{
   189 					Error("Could not detect GameDLL path! Metamod cannot load[3].");
   190 					return NULL;
   191 				} else {
   192 					ptr[i] = '\0';
   193 					path_len = i+1;
   194 					break;
   195 				}
   196 			}
   197 		}
   198 		//WE NOW HAVE A GUESS AT THE MOD DIR.  OH MY GOD.
   199 		char temp_path[260];
   200 		snprintf(temp_path, sizeof(temp_path)-1, 
   201 			"%s%s%s", 
   202 			curpath, 
   203 			PATH_SEP_STR, 
   204 			ptr);
   205 
   206 		g_ModPath.assign(temp_path);
   207 
   208 		snprintf(temp_path, sizeof(temp_path)-1, 
   209 			"%s%s%s", 
   210 			g_ModPath.c_str(),
   211 			PATH_SEP_STR,
   212 			"gameinfo.txt");
   213 
   214 		FILE *fp = fopen(temp_path, "rt");
   215 		if (!fp)
   216 		{
   217 			Error("Unable to open gameinfo.txt!  Metamod cannot load.");
   218 			return NULL;
   219 		}
   220 		char buffer[255];
   221 		char key[128], val[128];
   222 		size_t len = 0;
   223 		const char *gameinfo = "|gameinfo_path|";
   224 		size_t gameinfo_len = strlen(gameinfo);
   225 		bool search = false;
   226 		bool gamebin = false;
   227 		const char *lptr;
   228 		while (!feof(fp))
   229 		{
   230 			buffer[0] = '\0';
   231 			fgets(buffer, sizeof(buffer)-1, fp);
   232 			len = strlen(buffer);
   233 			if (buffer[len-1] == '\n')
   234 				buffer[--len] = '\0';
   235 			UTIL_TrimComments(buffer);
   236 			UTIL_TrimLeft(buffer);
   237 			UTIL_TrimRight(buffer);
   238 			if (stricmp(buffer, "SearchPaths") == 0)
   239 				search = true;
   240 			if (!search)
   241 				continue;
   242 			UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
   243 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   244 			{
   245 				if (stricmp(key, "Game") == 0)
   246 					gamebin = false;
   247 				else
   248 					gamebin = true;
   249 
   250 				if (strncmp(val, gameinfo, gameinfo_len) == 0)
   251 				{
   252 					ptr = &(val[gameinfo_len]);
   253 					if (ptr[0] == '.')
   254 						ptr++;
   255 					lptr = g_ModPath.c_str();
   256 				} else {
   257 					lptr = curpath;
   258 					ptr = val;
   259 				}
   260 				size_t ptr_len = strlen(ptr);
   261 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   262 					ptr[--ptr_len] = '\0';
   263 				//no need to append "bin"
   264 				if (gamebin)
   265 				{
   266 					UTIL_PathFmt(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   267 				} else {
   268 					UTIL_PathFmt(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   269 				}
   270 				if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
   271 				{
   272 					FILE *fp = fopen(temp_path, "rb");
   273 					if (!fp)
   274 						continue;
   275 					//:TODO: Optimize this a bit!
   276 					SourceHook::List<GameDllInfo *>::iterator iter;
   277 					GameDllInfo *pCheck;
   278 					bool found = false;
   279 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   280 					{
   281 						pCheck = (*iter);
   282 						if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
   283 						{
   284 							if (UTIL_PathCmp(temp_path, buffer))
   285 							{
   286 								found = true;
   287 								break;
   288 							}
   289 						}
   290 					}
   291 					if (found)
   292 						continue;
   293 					fclose(fp);
   294 					HINSTANCE gamedll = dlmount(temp_path);
   295 					if (gamedll == NULL)
   296 						continue;
   297 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   298 					if (fn == NULL)
   299 					{
   300 						dlclose(gamedll);
   301 						continue;
   302 					}
   303 					GameDllInfo *pInfo = new GameDllInfo;
   304 					pInfo->factory = fn;
   305 					pInfo->lib = gamedll;
   306 					pInfo->loaded = true;
   307 					pInfo->pGameDLL = NULL;
   308 					gamedll_list.push_back(pInfo);
   309 				}
   310 			}
   311 		}
   312 		fclose(fp);
   313 	}
   314 
   315 	if (!g_GameDll.loaded)
   316 	{
   317 		const char *str = "ServerGameDLL";
   318 		size_t len = strlen(str);
   319 
   320 		if (strncmp(name, str, len) == 0)
   321 		{
   322 			//This is the interface we want!  Right now we support versions 3 and 4.
   323 			int version = atoi(&(name[len]));
   324 			if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
   325 			{
   326 				Error("GameDLL version %d is not supported by Metamod!", version);
   327 				return NULL;
   328 			}
   329 			SourceHook::List<GameDllInfo *>::iterator iter;
   330 			GameDllInfo *pInfo = NULL;
   331 			void *ptr;
   332 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   333 			{
   334 				pInfo = (*iter);
   335 				ptr = (pInfo->factory)(name, ret);
   336 				if (ptr)
   337 				{
   338 					//this is our gamedll.  unload the others.
   339 					gamedll_list.erase(iter);
   340 					ClearGamedllList();
   341 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   342 					g_GameDll = *pInfo;
   343 					delete pInfo;
   344 					break;
   345 				}
   346 			}
   347 			if (g_GameDll.loaded)
   348 			{
   349 				InitMainStates();
   350 			} else {
   351 				if (ret)
   352 					*ret = IFACE_FAILED;
   353 				return NULL;
   354 			}
   355 		} else {
   356 			//wtf do we do...
   357 			//:TODO: .. something a bit more intelligent?
   358 			Error("Engine requested unknown interface before GameDLL was known!");
   359 			return NULL;
   360 		}
   361 	}
   362 
   363 	//if we got here, there's definitely a gamedll.
   364 	//META_INTERFACE_MACRO(server, g_GameDll.factory);
   365 	return (g_GameDll.factory)(name, ret);
   366 }
   367 
   368 void ClearGamedllList()
   369 {
   370 	SourceHook::List<GameDllInfo *>::iterator iter;
   371 
   372 	GameDllInfo *pInfo;
   373 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   374 	{
   375 		pInfo = (*iter);
   376 		dlclose(pInfo->lib);
   377 		delete pInfo;
   378 	}
   379 
   380 	gamedll_list.clear();
   381 }
   382 
   383 void DLLShutdown_handler()
   384 {
   385 	//Unload plugins
   386 	g_PluginMngr.UnloadAll();
   387 
   388 	// Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
   389 	g_SMConVarAccessor.MarkCommandsAsGameDLL();
   390 	g_SMConVarAccessor.UnregisterGameDLLCommands();
   391 
   392 	SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
   393 
   394 	SH_RELEASE_CALLCLASS(dllExec);
   395 	dllExec = NULL;
   396 
   397 	g_SourceHook.CompleteShutdown();
   398 
   399 	if (g_GameDll.lib && g_GameDll.loaded)
   400 		dlclose(g_GameDll.lib);
   401 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   402 
   403 	RETURN_META(MRES_SUPERCEDE);
   404 }
   405 
   406 int LoadPluginsFromFile(const char *file)
   407 {
   408 	FILE *fp;
   409 	int total = 0, skipped=0;
   410 	PluginId id;
   411 	bool already;
   412 
   413 	fp = fopen(file, "rt");
   414 	if (!fp)
   415 	{
   416 		LogMessage("[META] Could not open plugins file %s\n", file);
   417 		return -1;
   418 	}
   419 
   420 	char buffer[255], error[255], full_path[128];
   421 	const char *ptr, *ext;
   422 	size_t length;
   423 	while (!feof(fp))
   424 	{
   425 		buffer[0] = '\0';
   426 		fgets(buffer, sizeof(buffer)-1, fp);
   427 		length = strlen(buffer);
   428 		if (!length)
   429 			continue;
   430 		if (buffer[length-1] == '\n')
   431 			buffer[length-1] = '\0';
   432 
   433 		UTIL_TrimLeft(buffer);
   434 		UTIL_TrimRight(buffer);
   435 
   436 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   437 			continue;
   438 		//First find if it's an absolute path or not...
   439 		if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
   440 		{
   441 			//If we're in an absolute path, ignore our normal heuristics
   442 			id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
   443 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   444 			{
   445 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   446 			} else {
   447 				if (already)
   448 					skipped++;
   449 				else
   450 					total++;
   451 			}
   452 		} else {
   453 			//Attempt to find a file extension
   454 			ptr = UTIL_GetExtension(buffer);
   455 			//Add an extension if there's none there
   456 			if (!ptr)
   457 			{
   458 #if defined WIN32 || defined _WIN32
   459 				ext = ".dll";
   460 #else
   461 				ext = "_i486.so";
   462 #endif
   463 			} else {
   464 				ext = "";
   465 			}
   466 			//Format the new path
   467 			UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
   468 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   469 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   470 			{
   471 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   472 			} else {
   473 				if (already)
   474 					skipped++;
   475 				else
   476 					total++;
   477 			}
   478 		}
   479 	}
   480 	fclose(fp);
   481 
   482 	if (skipped)
   483 	{
   484 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   485 	} else {
   486 		LogMessage("[META] Loaded %d plugins from file.", total);
   487 	}
   488 	
   489 	return total;
   490 }
   491 
   492 //Wrapper function.  This is called when the GameDLL thinks it's using
   493 // the engine's real engineFactory.
   494 void *EngineFactory(const char *name, int *ret)
   495 {
   496 	META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
   497 }
   498 
   499 //Wrapper function.  This is called when the GameDLL thinks it's using
   500 // the engine's real physicsFactory.
   501 void *PhysicsFactory(const char *name, int *ret)
   502 {
   503 	META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
   504 }
   505 
   506 //Wrapper function.  This is called when the GameDLL thinks it's using
   507 // the engine's real fileSystemFactory.
   508 void *FileSystemFactory(const char *name, int *ret)
   509 {
   510 	META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
   511 }
   512 
   513 void LogMessage(const char *msg, ...)
   514 {
   515 	va_list ap;
   516 	static char buffer[2048];
   517 
   518 	buffer[0] = '\0';
   519 
   520 	va_start(ap, msg);
   521 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   522 	strcat(buffer, "\n");
   523 	va_end(ap);
   524 
   525 	if (!g_Engine.engine)
   526 	{
   527 		fprintf(stdout, "%s", buffer);
   528 	} else {
   529 		g_Engine.engine->LogPrint(buffer);
   530 	}
   531 }
   532 
   533 void LevelShutdown_handler(void)
   534 {
   535 	if (!bInFirstLevel)
   536 	{
   537 		char full_path[255];
   538 #if defined WIN32 || defined _WIN32
   539 		snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
   540 #else
   541 		snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
   542 #endif
   543 		LoadPluginsFromFile(full_path);
   544 	} else {
   545 		bInFirstLevel = false;
   546 	}
   547 }
   548 
   549 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   550 { 
   551 	if (!g_SmmAPI.CacheSuccessful())
   552 	{
   553 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   554 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   555 	}
   556 
   557 	RETURN_META_VALUE(MRES_IGNORED, false);
   558 }
   559 
   560 #if defined __GNUC__ && (__GNUC__ == 3)
   561 void * ::operator new(size_t size) {
   562 	return(calloc(1, size)); 
   563 }
   564 
   565 void * ::operator new[](size_t size) {
   566 	return(calloc(1, size)); 
   567 }
   568 
   569 void ::operator delete(void * ptr) {
   570 	if(ptr)
   571 		free(ptr);
   572 }
   573 
   574 void ::operator delete[](void * ptr) {
   575 	if(ptr)
   576 		free(ptr);
   577 }
   578 #endif