sourcemm/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Sat Apr 16 23:33:39 2005 +0000 (2005-04-16)
changeset 9 01b8b7435e67
parent 7 8ef11f6189e4
child 12 9fd53562f68c
permissions -rw-r--r--
Implemented factory hooks
Added commands: clear, load, pause, unload, unpause
Rewrote headers
     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 "sourcemm.h"
    14 #include "CServerGameDLL.h"
    15 #include "CServerGameEnts.h"
    16 #include "CServerGameClients.h"
    17 #include "CHLTVDirector.h"
    18 #include "concommands.h"
    19 #include "CSmmAPI.h"
    20 #include "util.h"
    21 
    22 /**
    23  * @brief Implementation of main SourceMM GameDLL functionality
    24  * @file sourcemm.cpp
    25  */
    26 
    27 CServerGameDLL *g_TempGameDLL = NULL;
    28 CServerGameEnts *g_TempGameEnts = NULL;
    29 CServerGameClients *g_TempGameClients = NULL;
    30 CHLTVDirector *g_TempDirector = NULL;
    31 GameDllInfo g_GameDll = {false, NULL, NULL};
    32 EngineInfo g_Engine = {NULL, NULL, NULL, NULL};
    33 SourceHook::CSourceHookImpl g_SourceHook;
    34 std::string g_ModPath;
    35 std::string g_BinPath;
    36 
    37 ///////////////////////////////////
    38 // Main code for HL2 Interaction //
    39 ///////////////////////////////////
    40 
    41 //This is where the magic happens
    42 SMM_API void *CreateInterface(const char *name, int *ret)
    43 {
    44 	if (!g_GameDll.loaded)
    45 	{
    46 		//State of the Mod:
    47 		// Currently, HL2 Engine has loaded Metamod:Source
    48 		// It is now asking it to get an interface.  We don't have one,
    49 		//  so we're gonna try to give it a fake one to get the information we need.
    50 		//  Then we'll swap the vtables with the real one from the real gamedll.
    51 
    52 		if (strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0)
    53 		{
    54 			//We're in.  Give the server our fake class as bait.
    55 			if (ret)
    56 				*ret = IFACE_OK;
    57 
    58 			g_TempGameDLL = new CServerGameDLL;
    59 
    60 			return static_cast<void *>(g_TempGameDLL);
    61 		} else if (strcmp(name, INTERFACEVERSION_SERVERGAMEENTS) == 0) {
    62 			if (ret)
    63 				*ret = IFACE_OK;
    64 
    65 			g_TempGameEnts = new CServerGameEnts;
    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 			g_TempGameClients = new CServerGameClients;
    73 
    74 			return static_cast<void *>(g_TempGameClients);
    75 		} else if (strcmp(name, INTERFACEVERSION_HLTVDIRECTOR) == 0) {
    76 			if (ret)
    77 				*ret = IFACE_OK;
    78 
    79 			g_TempDirector = new CHLTVDirector;
    80 
    81 			return static_cast<void *>(g_TempDirector);
    82 		} else {
    83 			if (ret)
    84 				*ret = IFACE_FAILED;
    85 
    86 			return NULL;
    87 		}
    88 	} else {
    89 		META_INTERFACE_MACRO(server, g_GameDll.factory);
    90 	}
    91 }
    92 
    93 bool CServerGameDLL::DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals)
    94 {
    95 	if (!g_GameDll.loaded)
    96 	{
    97 		//The gamedll isn't loaded yet.  We need to find out where it's hiding.
    98 		IVEngineServer *ive = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
    99 		if (!ive)
   100 		{
   101 			Error("Metamod:Source could not load %s", INTERFACEVERSION_VENGINESERVER);
   102 			return false;
   103 		}
   104 		
   105 		//Guess the file name
   106 		//We'll have better heurestics[sp?] later on
   107 		char mod_path[128], full_path[255];
   108 		ive->GetGameDir(mod_path, sizeof(mod_path)-1);
   109 		g_ModPath.assign(mod_path);
   110 #if defined WIN32 || defined _WIN32
   111 		snprintf(full_path, sizeof(full_path)-1, "%s\\bin\\server.dll", mod_path);
   112 #else
   113 		snprintf(full_path, sizeof(full_path)-1, "%s/bin/server_i486.so", mod_path);
   114 #endif
   115 
   116 		g_BinPath.assign(full_path);
   117 
   118 		//See if the file even exists
   119 		FILE *fp = fopen(g_BinPath.c_str(), "r");
   120 		if (!fp)
   121 		{
   122 			Error("Metamod:Source could not read %s", g_BinPath.c_str());
   123 			return false;
   124 		}
   125 		fclose(fp);
   126 		fp = NULL;
   127 
   128 		//Load the DLL
   129 		g_GameDll.lib = dlmount(g_BinPath.c_str());
   130 		if (!g_GameDll.lib)
   131 		{
   132 			Error("Metamod:Source could not load GameDLL: %s", dlerror());
   133 			return false;
   134 		} else {
   135 			//Find its factory
   136 			g_GameDll.factory = (CreateInterfaceFn)(dlsym(g_GameDll.lib, "CreateInterface"));
   137 			if (!g_GameDll.factory)
   138 			{
   139 				Error("Metamod:Source could not find an entry point in GameDLL: %s", g_BinPath.c_str());
   140 				dlclose(g_GameDll.lib);
   141 				return false;
   142 			}
   143 
   144 			//Find the new IServerGameDLL pointer
   145 			IServerGameDLL *serverDll;
   146 			serverDll = (IServerGameDLL *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEDLL, NULL));
   147 			if (!serverDll)
   148 			{
   149 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEDLL, g_BinPath.c_str());
   150 				dlclose(g_GameDll.lib);
   151 				return false;
   152 			}
   153 
   154 			//Set this information early in case our wrappers are called somehow
   155 			g_Engine.engineFactory = engineFactory;
   156 			g_Engine.icvar = (ICvar *)(g_Engine.engineFactory)(VENGINE_CVAR_INTERFACE_VERSION, NULL);
   157 			if (!g_Engine.icvar)
   158 			{
   159 				Error("Metamod:Source could not find %s in engine!", VENGINE_CVAR_INTERFACE_VERSION);
   160 				dlclose(g_GameDll.lib);
   161 				return false;
   162 			}
   163 			g_Engine.fileSystemFactory = fileSystemFactory;
   164 			g_Engine.pGlobals = pGlobals;
   165 			g_Engine.physicsFactory = physicsFactory;
   166 			g_Engine.engine = ive;
   167 			
   168 			//Attempt to load the GameDLL
   169 			// Note that nothing will be intercepting yet.
   170 			// This is the one and only call that plugins have no chance of seeing.
   171 			// Likewise, you won't be able to trick the Server DLL into loading random things.
   172 			// Luckily, because of SourceHook, this really isn't a problem - you can change
   173 			//  the virtual interfaces in anything it requests.
   174 			if (!serverDll->DLLInit(EngineFactory, PhysicsFactory, FileSystemFactory, pGlobals))
   175 			{
   176 				//For some reason, the GameDLL failed to load. 
   177 				Error("Metamod:Source: GameDLL %s refused to load.", g_BinPath.c_str());
   178 				dlclose(g_GameDll.lib);
   179 				return false;
   180 			}
   181 
   182 			//Retrieve the pointers we'll need from the GameDLL
   183 			IServerGameEnts *serverEnts;
   184 			IServerGameClients *serverClients;
   185 			IHLTVDirector *serverHLTV;
   186 
   187 			serverEnts = (IServerGameEnts *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEENTS, NULL));
   188 			if (!serverEnts)
   189 			{
   190 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEENTS, g_BinPath.c_str());
   191 				dlclose(g_GameDll.lib);
   192 				return false;
   193 			}
   194 
   195 			serverClients = (IServerGameClients *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   196 			if (!serverClients)
   197 			{
   198 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMECLIENTS, g_BinPath.c_str());
   199 				dlclose(g_GameDll.lib);
   200 				return false;
   201 			}
   202 
   203             serverHLTV = (IHLTVDirector *)((g_GameDll.factory)(INTERFACEVERSION_HLTVDIRECTOR, NULL));
   204 			if (!serverHLTV)
   205 			{
   206 				Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_HLTVDIRECTOR, g_BinPath.c_str());
   207 				dlclose(g_GameDll.lib);
   208 				return false;
   209 			}
   210 
   211 			//The GameDLL has given the go - now we'll swap the vtables ( eww! )
   212 			//This ugly hack will patch the pointer we've given the engine
   213 			// so it will just be calling the real GameDLL instead.
   214 			// Unlike Metamod:HL1, this is the effect we want, rather than duplicating
   215 			//  the entire class (because SourceHook doesn't do that).
   216 			void *vtableDst = ((void *)(g_TempGameDLL));
   217 			void *vtableSrc = ((void *)(serverDll));
   218 
   219 			SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameDLL), SH_MEM_READ|SH_MEM_WRITE);
   220 			memcpy(vtableDst, vtableSrc, sizeof(IServerGameDLL));
   221 
   222 			//Now patch IServerGameEnts
   223 			vtableDst = ((void *)(g_TempGameEnts));
   224 			vtableSrc = ((void *)(serverEnts));
   225 			SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameEnts), SH_MEM_READ|SH_MEM_WRITE);
   226 			memcpy(vtableDst, vtableSrc, sizeof(IServerGameEnts));
   227 
   228 			//Now patch IServerGameClients
   229 			vtableDst = ((void *)(g_TempGameClients));
   230 			vtableSrc = ((void *)(serverClients));
   231 			SourceHook::SetMemAccess(vtableDst, sizeof(IServerGameClients), SH_MEM_READ|SH_MEM_WRITE);
   232 			memcpy(vtableDst, vtableSrc, sizeof(IServerGameClients));
   233 
   234 			//Now patch IHLTVDirector
   235 			vtableDst = ((void *)(g_TempDirector));
   236 			vtableSrc = ((void *)(serverHLTV));
   237 			SourceHook::SetMemAccess(vtableDst, sizeof(IHLTVDirector), SH_MEM_READ|SH_MEM_WRITE);
   238 			memcpy(vtableDst, vtableSrc, sizeof(IHLTVDirector));
   239 
   240 			//Everything's done.
   241 			g_GameDll.loaded = true;
   242 
   243 			//Initialize our console hooks
   244 			ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   245             
   246 			//Now it's safe to load plugins.
   247 #if defined WIN32 || defined _WIN32
   248 			snprintf(full_path, sizeof(full_path)-1, "%s\\%s", g_ModPath.c_str(), "metaplugins.ini");
   249 #else
   250 			snprintf(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), "metaplugins.ini");
   251 #endif
   252 
   253 			LoadPluginsFromFile(full_path);
   254 
   255 			return true;
   256 		}
   257 	}
   258 
   259 	//Somehow, the function got here.  This should be impossible, as not only is it 
   260 	// only called once, but the vtables should be overridden.
   261 	Error("Metamod:Source fatal error - IServerGameDLL::DLLInit() called inappropriately");
   262 
   263 	return false;
   264 }
   265 
   266 int LoadPluginsFromFile(const char *file)
   267 {
   268 	FILE *fp;
   269 	int total = 0, skipped=0;
   270 	PluginId id;
   271 	bool already;
   272 
   273 	fp = fopen(file, "rt");
   274 	if (!fp)
   275 	{
   276 		LogMessage("[META] Could not open plugins file %s\n", file);
   277 		return -1;
   278 	}
   279 
   280 	char buffer[255], error[255], full_path[128];
   281 	const char *ptr, *ext;
   282 	while (!feof(fp))
   283 	{
   284 		buffer[0] = '\0';
   285 		fgets(buffer, sizeof(buffer)-1, fp);
   286 		if (buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   287 			continue;
   288 		//First find if it's an absolute path or not...
   289 		if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
   290 		{
   291 			//If we're in an absolute path, ignore our normal heuristics
   292 			id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
   293 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   294 			{
   295 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   296 			} else {
   297 				if (already)
   298 					skipped++;
   299 				else
   300 					total++;
   301 			}
   302 		} else {
   303 			//Attempt to find a file extension
   304 			ptr = UTIL_GetExtension(buffer);
   305 			//Add an extension if there's none there
   306 			if (!ptr)
   307 			{
   308 #if defined WIN32 || defined _WIN32
   309 				ext = ".dll";
   310 #else
   311 				ext = "_i486.so";
   312 #endif
   313 			} else {
   314 				ext = "";
   315 			}
   316 			//Format the new path
   317 #if defined WIN32 || defined _WIN32
   318 			snprintf(full_path, sizeof(full_path)-1, "%s\\%s%s", g_ModPath.c_str(), buffer, ext);
   319 #else
   320 			snprintf(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
   321 #endif
   322 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   323 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   324 			{
   325 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   326 			} else {
   327 				if (already)
   328 					skipped++;
   329 				else
   330 					total++;
   331 			}
   332 		}
   333 	}
   334 	fclose(fp);
   335 
   336 	if (skipped)
   337 	{
   338 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   339 	} else {
   340 		LogMessage("[META] Loaded %d plugins from file.", total);
   341 	}
   342 	
   343 	return total;
   344 }
   345 
   346 //Wrapper function.  This is called when the GameDLL thinks it's using
   347 // the engine's real engineFactory.
   348 void *EngineFactory(const char *name, int *ret)
   349 {
   350 	META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
   351 }
   352 
   353 //Wrapper function.  This is called when the GameDLL thinks it's using
   354 // the engine's real physicsFactory.
   355 void *PhysicsFactory(const char *name, int *ret)
   356 {
   357 	META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
   358 }
   359 
   360 //Wrapper function.  This is called when the GameDLL thinks it's using
   361 // the engine's real fileSystemFactory.
   362 void *FileSystemFactory(const char *name, int *ret)
   363 {
   364 	META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
   365 }
   366 
   367 void LogMessage(const char *msg, ...)
   368 {
   369 	va_list ap;
   370 	static char buffer[2048];
   371 
   372 	buffer[0] = '\0';
   373 
   374 	va_start(ap, msg);
   375 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   376 	strcat(buffer, "\n");
   377 	va_end(ap);
   378 
   379 	g_Engine.engine->LogPrint(buffer);
   380 }