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