sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Wed May 04 13:59:57 2005 +0000 (2005-05-04)
changeset 57 90056ffa9784
parent 52 948ae76c45b5
child 63 ee7abd0da4dd
permissions -rw-r--r--
bugfix
     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 "CServerGameDLL.h"
    16 #include "CServerGameEnts.h"
    17 #include "CServerGameClients.h"
    18 #include "CHLTVDirector.h"
    19 #include "sourcemm.h"
    20 #include "concommands.h"
    21 #include "CSmmAPI.h"
    22 #include "util.h"
    23 
    24 /**
    25  * @brief Implementation of main SourceMM GameDLL functionality
    26  * @file sourcemm.cpp
    27  */
    28 
    29 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, 0);
    30 
    31 CServerGameDLL g_TempGameDLL;
    32 CServerGameEnts g_TempGameEnts;
    33 CServerGameClients g_TempGameClients;
    34 CHLTVDirector g_TempDirector;
    35 GameDllInfo g_GameDll = {false, NULL, NULL};
    36 EngineInfo g_Engine = {NULL, NULL, NULL, NULL};
    37 SourceHook::CSourceHookImpl g_SourceHook;
    38 SourceHook::ISourceHook *g_SHPtr;
    39 std::string g_ModPath;
    40 std::string g_BinPath;
    41 PluginId g_PLID = Pl_Console;		//Technically, SourceMM is the "Console" plugin... :p
    42 bool bInShutdown = false;
    43 bool bInFirstLevel = true;
    44 
    45 ///////////////////////////////////
    46 // Main code for HL2 Interaction //
    47 ///////////////////////////////////
    48 
    49 //This is where the magic happens
    50 SMM_API void *CreateInterface(const char *name, int *ret)
    51 {
    52 	if (!g_GameDll.loaded)
    53 	{
    54 		//State of the Mod:
    55 		// Currently, HL2 Engine has loaded Metamod:Source
    56 		// It is now asking it to get an interface.  We don't have one,
    57 		//  so we're gonna try to give it a fake one to get the information we need.
    58 		//  Then, the the interface will forward the calls to the original interface
    59 
    60 		if (strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0)
    61 		{
    62 			//We're in.  Give the server our fake class as bait.
    63 			if (ret)
    64 				*ret = IFACE_OK;
    65 			return static_cast<void *>(&g_TempGameDLL);
    66 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMEENTS) == 0) {
    67 			if (ret)
    68 				*ret = IFACE_OK;
    69 
    70 			return static_cast<void *>(&g_TempGameEnts);
    71 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMECLIENTS) == 0) {
    72 			if (ret)
    73 				*ret = IFACE_OK;
    74 
    75 			return static_cast<void *>(&g_TempGameClients);
    76 		} else if (strcmp(name, INTERFACEVERSION_HLTVDIRECTOR) == 0) {
    77 			if (ret)
    78 				*ret = IFACE_OK;
    79 
    80 			return static_cast<void *>(&g_TempDirector);
    81 		} else {
    82 			if (ret)
    83 				*ret = IFACE_FAILED;
    84 
    85 			return NULL;
    86 		}
    87 	} else {
    88 		META_INTERFACE_MACRO(server, g_GameDll.factory);
    89 	}
    90 }
    91 
    92 bool CServerGameDLL::DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals)
    93 {
    94 	if (m_pOrig)
    95 		return m_pOrig->DLLInit(engineFactory, physicsFactory, fileSystemFactory, pGlobals);
    96 
    97 	if (!g_GameDll.loaded)
    98 	{
    99 		//Initialize SourceHook
   100 		g_SHPtr = static_cast<SourceHook::ISourceHook *>(&g_SourceHook);
   101 
   102 		//The gamedll isn't loaded yet.  We need to find out where it's hiding.
   103 		IVEngineServer *ive = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   104 		if (!ive)
   105 		{
   106 			Error("Metamod:Source could not load %s", INTERFACEVERSION_VENGINESERVER);
   107 			return false;
   108 		}
   109 		
   110 		//Guess the file name
   111 		//We'll have better heurestics[sp?] later on
   112 		char mod_path[128], full_path[255];
   113 		ive->GetGameDir(mod_path, sizeof(mod_path)-1);
   114 		g_ModPath.assign(mod_path);
   115 #if defined WIN32 || defined _WIN32
   116 		snprintf(full_path, sizeof(full_path)-1, "%s\\bin\\server.dll", mod_path);
   117 #else
   118 		snprintf(full_path, sizeof(full_path)-1, "%s/bin/server_i486.so", mod_path);
   119 #endif
   120 
   121 		g_BinPath.assign(full_path);
   122 
   123 		//See if the file even exists
   124 		FILE *fp = fopen(g_BinPath.c_str(), "r");
   125 		if (!fp)
   126 		{
   127 			Error("Metamod:Source could not read %s", g_BinPath.c_str());
   128 			return false;
   129 		}
   130 		fclose(fp);
   131 		fp = NULL;
   132 
   133 		//Load the DLL
   134 		g_GameDll.lib = dlmount(g_BinPath.c_str());
   135 		if (!g_GameDll.lib)
   136 		{
   137 			Error("Metamod:Source could not load GameDLL: %s", dlerror());
   138 			return false;
   139 		} else {
   140 			//Find its factory
   141 			g_GameDll.factory = (CreateInterfaceFn)(dlsym(g_GameDll.lib, "CreateInterface"));
   142 			if (!g_GameDll.factory)
   143 			{
   144 				Error("Metamod:Source could not find an entry point in GameDLL: %s", g_BinPath.c_str());
   145 				dlclose(g_GameDll.lib);
   146 				return false;
   147 			}
   148 
   149 			//Find the new IServerGameDLL pointer
   150 			IServerGameDLL *serverDll;
   151 			serverDll = (IServerGameDLL *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEDLL, NULL));
   152 			if (!serverDll)
   153 			{
   154 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEDLL, g_BinPath.c_str());
   155 				dlclose(g_GameDll.lib);
   156 				return false;
   157 			}
   158 
   159 			//Set this information early in case our wrappers are called somehow
   160 			g_Engine.engineFactory = engineFactory;
   161 			g_Engine.icvar = (ICvar *)(g_Engine.engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL);
   162 			if (!g_Engine.icvar)
   163 			{
   164 				Error("Metamod:Source could not find %s in engine!", VENGINE_CVAR_INTERFACE_VERSION);
   165 				dlclose(g_GameDll.lib);
   166 				return false;
   167 			}
   168 			g_Engine.fileSystemFactory = fileSystemFactory;
   169 			g_Engine.pGlobals = pGlobals;
   170 			g_Engine.physicsFactory = physicsFactory;
   171 			g_Engine.engine = ive;
   172 			
   173 			//Attempt to load the GameDLL
   174 			// Note that nothing will be intercepting yet.
   175 			// This is the one and only call that plugins have no chance of seeing.
   176 			// Likewise, you won't be able to trick the Server DLL into loading random things.
   177 			// Luckily, because of SourceHook, this really isn't a problem - you can change
   178 			//  the virtual interfaces in anything it requests.
   179 			if (!serverDll->DLLInit(EngineFactory, PhysicsFactory, FileSystemFactory, pGlobals))
   180 			{
   181 				//For some reason, the GameDLL failed to load. 
   182 				Error("Metamod:Source: GameDLL %s refused to load.", g_BinPath.c_str());
   183 				dlclose(g_GameDll.lib);
   184 				return false;
   185 			}
   186 
   187 			//Retrieve the pointers we'll need from the GameDLL
   188 			IServerGameEnts *serverEnts;
   189 			IServerGameClients *serverClients;
   190 			IHLTVDirector *serverHLTV;
   191 
   192 			serverEnts = (IServerGameEnts *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEENTS, NULL));
   193 			if (!serverEnts)
   194 			{
   195 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEENTS, g_BinPath.c_str());
   196 				dlclose(g_GameDll.lib);
   197 				return false;
   198 			}
   199 
   200 			serverClients = (IServerGameClients *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   201 			if (!serverClients)
   202 			{
   203 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMECLIENTS, g_BinPath.c_str());
   204 				dlclose(g_GameDll.lib);
   205 				return false;
   206 			}
   207 
   208             serverHLTV = (IHLTVDirector *)((g_GameDll.factory)(INTERFACEVERSION_HLTVDIRECTOR, NULL));
   209 			if (!serverHLTV)
   210 			{
   211 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_HLTVDIRECTOR, g_BinPath.c_str());
   212 				dlclose(g_GameDll.lib);
   213 				return false;
   214 			}
   215 			
   216 			// Now tell the global temp classes that they can call the original functions
   217 			g_TempDirector.SetOrig(serverHLTV);
   218 			g_TempGameClients.SetOrig(serverClients);
   219 			g_TempGameEnts.SetOrig(serverEnts);
   220 			g_TempGameDLL.SetOrig(serverDll);
   221 
   222 			//Everything's done.
   223 			g_GameDll.loaded = true;
   224 
   225 			//Initialize our console hooks
   226 			ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   227             
   228 			//Now it's safe to load plugins.
   229 #if defined WIN32 || defined _WIN32
   230 			snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
   231 #else
   232 			snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
   233 #endif
   234 
   235 			LoadPluginsFromFile(full_path);
   236 
   237 			//All plugins are now loaded.
   238 			g_PluginMngr.SetAllLoaded();
   239 
   240 			//Like metamod, reload plugins at the end of the map.
   241 			//This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   242 			// if the server is shut down (silly, but rare case).
   243 			bInFirstLevel = true;
   244 			SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, serverDll, LevelShutdown_handler, false);
   245 
   246 			return true;
   247 		}
   248 	}
   249 
   250 	//Somehow, the function got here.  This should be impossible.
   251 	Error("Metamod:Source fatal error - IServerGameDLL::DLLInit() called inappropriately");
   252 
   253 	return false;
   254 }
   255 
   256 // The engine uses the DLL even after it has call DLLShutdown, so we unload it
   257 // when it unloads us
   258 #if defined _WIN32
   259 	BOOL WINAPI DllMain(
   260 						HINSTANCE hinstDLL,
   261 						DWORD fdwReason,
   262 						LPVOID lpvReserved
   263 						)
   264 	{
   265 		if (fdwReason == DLL_PROCESS_DETACH)
   266 		{
   267 			if (g_GameDll.lib && g_GameDll.loaded)
   268 				dlclose(g_GameDll.lib);
   269 			memset(&g_GameDll, 0, sizeof(GameDllInfo));
   270 		}
   271 		return TRUE;
   272 	}
   273 #elif defined __linux__
   274 	void __attribute__ ((destructor)) app_fini(void)
   275 	{
   276 		if (g_GameDll.lib && g_GameDll.loaded)
   277 			dlclose(g_GameDll.lib);
   278 		memset(&g_GameDll, 0, sizeof(GameDllInfo));
   279 	}
   280 #endif
   281 
   282 void CServerGameDLL::DLLShutdown()
   283 {
   284     //Call the original function
   285 	m_pOrig->DLLShutdown();
   286 
   287 	//Unload plugins
   288 	g_PluginMngr.UnloadAll();
   289 
   290 	// Shutdown sourcehook now
   291 	g_SourceHook.CompleteShutdown();
   292 }
   293 
   294 int LoadPluginsFromFile(const char *file)
   295 {
   296 	FILE *fp;
   297 	int total = 0, skipped=0;
   298 	PluginId id;
   299 	bool already;
   300 
   301 	fp = fopen(file, "rt");
   302 	if (!fp)
   303 	{
   304 		LogMessage("[META] Could not open plugins file %s\n", file);
   305 		return -1;
   306 	}
   307 
   308 	char buffer[255], error[255], full_path[128];
   309 	const char *ptr, *ext;
   310 	size_t length;
   311 	while (!feof(fp))
   312 	{
   313 		buffer[0] = '\0';
   314 		fgets(buffer, sizeof(buffer)-1, fp);
   315 		length = strlen(buffer);
   316 		if (!length)
   317 			continue;
   318 		if (buffer[length-1] == '\n')
   319 			buffer[length-1] = '\0';
   320 		if (buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   321 			continue;
   322 		//First find if it's an absolute path or not...
   323 		if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
   324 		{
   325 			//If we're in an absolute path, ignore our normal heuristics
   326 			id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
   327 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   328 			{
   329 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   330 			} else {
   331 				if (already)
   332 					skipped++;
   333 				else
   334 					total++;
   335 			}
   336 		} else {
   337 			//Attempt to find a file extension
   338 			ptr = UTIL_GetExtension(buffer);
   339 			//Add an extension if there's none there
   340 			if (!ptr)
   341 			{
   342 #if defined WIN32 || defined _WIN32
   343 				ext = ".dll";
   344 #else
   345 				ext = "_i486.so";
   346 #endif
   347 			} else {
   348 				ext = "";
   349 			}
   350 			//Format the new path
   351 #if defined WIN32 || defined _WIN32
   352 			snprintf(full_path, sizeof(full_path)-1, "%s\\%s%s", g_ModPath.c_str(), buffer, ext);
   353 #else
   354 			snprintf(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
   355 #endif
   356 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   357 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   358 			{
   359 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   360 			} else {
   361 				if (already)
   362 					skipped++;
   363 				else
   364 					total++;
   365 			}
   366 		}
   367 	}
   368 	fclose(fp);
   369 
   370 	if (skipped)
   371 	{
   372 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   373 	} else {
   374 		LogMessage("[META] Loaded %d plugins from file.", total);
   375 	}
   376 	
   377 	return total;
   378 }
   379 
   380 //Wrapper function.  This is called when the GameDLL thinks it's using
   381 // the engine's real engineFactory.
   382 void *EngineFactory(const char *name, int *ret)
   383 {
   384 	META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
   385 }
   386 
   387 //Wrapper function.  This is called when the GameDLL thinks it's using
   388 // the engine's real physicsFactory.
   389 void *PhysicsFactory(const char *name, int *ret)
   390 {
   391 	META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
   392 }
   393 
   394 //Wrapper function.  This is called when the GameDLL thinks it's using
   395 // the engine's real fileSystemFactory.
   396 void *FileSystemFactory(const char *name, int *ret)
   397 {
   398 	META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
   399 }
   400 
   401 void LogMessage(const char *msg, ...)
   402 {
   403 	va_list ap;
   404 	static char buffer[2048];
   405 
   406 	buffer[0] = '\0';
   407 
   408 	va_start(ap, msg);
   409 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   410 	strcat(buffer, "\n");
   411 	va_end(ap);
   412 
   413 	g_Engine.engine->LogPrint(buffer);
   414 }
   415 
   416 void LevelShutdown_handler(void)
   417 {
   418 	if (!bInFirstLevel)
   419 	{
   420 		char full_path[255];
   421 #if defined WIN32 || defined _WIN32
   422 		snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
   423 #else
   424 		snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
   425 #endif
   426 		LoadPluginsFromFile(full_path);
   427 	} else {
   428 		bInFirstLevel = false;
   429 	}
   430 
   431 	RETURN_META(MRES_IGNORED);
   432 }