1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2005 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): David "BAILOPAN" Anderson
8 * Contributor(s): Scott "Damaged Soul" Ehlert
9 * : Pavol "PM OnoTo" Marko
10 * ============================
13 #include <interface.h>
15 #include "CServerGameDLL.h"
16 #include "CServerGameEnts.h"
17 #include "CServerGameClients.h"
18 #include "CHLTVDirector.h"
20 #include "concommands.h"
25 * @brief Implementation of main SourceMM GameDLL functionality
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;
42 ///////////////////////////////////
43 // Main code for HL2 Interaction //
44 ///////////////////////////////////
46 //This is where the magic happens
47 SMM_API void *CreateInterface(const char *name, int *ret)
49 if (!g_GameDll.loaded)
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
57 if (strcmp(name, INTERFACEVERSION_SERVERGAMEDLL) == 0)
59 //We're in. Give the server our fake class as bait.
62 return static_cast<void *>(&g_TempGameDLL);
63 } else if (strcmp(name, INTERFACEVERSION_SERVERGAMEENTS) == 0) {
67 return static_cast<void *>(&g_TempGameEnts);
68 } else if (strcmp(name, INTERFACEVERSION_SERVERGAMECLIENTS) == 0) {
72 return static_cast<void *>(&g_TempGameClients);
73 } else if (strcmp(name, INTERFACEVERSION_HLTVDIRECTOR) == 0) {
77 return static_cast<void *>(&g_TempDirector);
85 META_INTERFACE_MACRO(server, g_GameDll.factory);
89 bool CServerGameDLL::DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals)
92 return m_pOrig->DLLInit(engineFactory, physicsFactory, fileSystemFactory, pGlobals);
94 if (!g_GameDll.loaded)
96 //Initialize SourceHook
97 g_SHPtr = static_cast<SourceHook::ISourceHook *>(&g_SourceHook);
99 //The gamedll isn't loaded yet. We need to find out where it's hiding.
100 IVEngineServer *ive = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
103 Error("Metamod:Source could not load %s", INTERFACEVERSION_VENGINESERVER);
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);
115 snprintf(full_path, sizeof(full_path)-1, "%s/bin/server_i486.so", mod_path);
118 g_BinPath.assign(full_path);
120 //See if the file even exists
121 FILE *fp = fopen(g_BinPath.c_str(), "r");
124 Error("Metamod:Source could not read %s", g_BinPath.c_str());
131 g_GameDll.lib = dlmount(g_BinPath.c_str());
134 Error("Metamod:Source could not load GameDLL: %s", dlerror());
138 g_GameDll.factory = (CreateInterfaceFn)(dlsym(g_GameDll.lib, "CreateInterface"));
139 if (!g_GameDll.factory)
141 Error("Metamod:Source could not find an entry point in GameDLL: %s", g_BinPath.c_str());
142 dlclose(g_GameDll.lib);
146 //Find the new IServerGameDLL pointer
147 IServerGameDLL *serverDll;
148 serverDll = (IServerGameDLL *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEDLL, NULL));
151 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEDLL, g_BinPath.c_str());
152 dlclose(g_GameDll.lib);
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);
161 Error("Metamod:Source could not find %s in engine!", VENGINE_CVAR_INTERFACE_VERSION);
162 dlclose(g_GameDll.lib);
165 g_Engine.fileSystemFactory = fileSystemFactory;
166 g_Engine.pGlobals = pGlobals;
167 g_Engine.physicsFactory = physicsFactory;
168 g_Engine.engine = ive;
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))
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);
184 //Retrieve the pointers we'll need from the GameDLL
185 IServerGameEnts *serverEnts;
186 IServerGameClients *serverClients;
187 IHLTVDirector *serverHLTV;
189 serverEnts = (IServerGameEnts *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMEENTS, NULL));
192 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMEENTS, g_BinPath.c_str());
193 dlclose(g_GameDll.lib);
197 serverClients = (IServerGameClients *)((g_GameDll.factory)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
200 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_SERVERGAMECLIENTS, g_BinPath.c_str());
201 dlclose(g_GameDll.lib);
205 serverHLTV = (IHLTVDirector *)((g_GameDll.factory)(INTERFACEVERSION_HLTVDIRECTOR, NULL));
208 Error("Metamod:Source could not find %s in GameDLL: %s", INTERFACEVERSION_HLTVDIRECTOR, g_BinPath.c_str());
209 dlclose(g_GameDll.lib);
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);
220 g_GameDll.loaded = true;
222 //Initialize our console hooks
223 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
225 if (!g_SmmAPI.CacheCmds())
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.");
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());
235 snprintf(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
238 LoadPluginsFromFile(full_path);
240 //All plugins are now loaded.
241 g_PluginMngr.SetAllLoaded();
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;
252 //Somehow, the function got here. This should be impossible.
253 Error("Metamod:Source fatal error - IServerGameDLL::DLLInit() called inappropriately");
261 g_PluginMngr.UnloadAll();
263 // Shutdown sourcehook now
264 g_SourceHook.CompleteShutdown();
266 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
267 g_SMConVarAccessor.MarkCommandsAsGameDLL();
270 void CServerGameDLL::DLLShutdown()
274 //Call the original function
275 m_pOrig->DLLShutdown();
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();
282 if (g_GameDll.lib && g_GameDll.loaded)
283 dlclose(g_GameDll.lib);
284 memset(&g_GameDll, 0, sizeof(GameDllInfo));
287 int LoadPluginsFromFile(const char *file)
290 int total = 0, skipped=0;
294 fp = fopen(file, "rt");
297 LogMessage("[META] Could not open plugins file %s\n", file);
301 char buffer[255], error[255], full_path[128];
302 const char *ptr, *ext;
307 fgets(buffer, sizeof(buffer)-1, fp);
308 length = strlen(buffer);
311 if (buffer[length-1] == '\n')
312 buffer[length-1] = '\0';
314 UTIL_TrimLeft(buffer);
315 UTIL_TrimRight(buffer);
317 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
319 //First find if it's an absolute path or not...
320 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
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)
326 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
334 //Attempt to find a file extension
335 ptr = UTIL_GetExtension(buffer);
336 //Add an extension if there's none there
339 #if defined WIN32 || defined _WIN32
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);
351 snprintf(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
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)
356 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
369 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
371 LogMessage("[META] Loaded %d plugins from file.", total);
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)
381 META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
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)
388 META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
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)
395 META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
398 void LogMessage(const char *msg, ...)
401 static char buffer[2048];
406 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
407 strcat(buffer, "\n");
410 g_Engine.engine->LogPrint(buffer);
413 void CServerGameDLL::LevelShutdown(void)
415 LevelShutdown_handler();
416 m_pOrig->LevelShutdown();
419 void LevelShutdown_handler(void)
424 #if defined WIN32 || defined _WIN32
425 snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
427 snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
429 LoadPluginsFromFile(full_path);
431 bInFirstLevel = false;
435 bool CServerGameDLL::LevelInit( char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background )
437 if (!g_SmmAPI.CacheSuccessful())
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.");
443 return m_pOrig->LevelInit(pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background);
446 const char *CServerGameDLL::GetGameDescription()
450 const char *game = m_pOrig->GetGameDescription();
452 strcpy(m_GameDescBuffer, game);
455 return m_GameDescBuffer;
458 #if defined __GNUC__ && (__GNUC__ == 3)
459 void * ::operator new(size_t size) {
460 return(calloc(1, size));
463 void * ::operator new[](size_t size) {
464 return(calloc(1, size));
467 void ::operator delete(void * ptr) {
472 void ::operator delete[](void * ptr) {