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>
16 #include "concommands.h"
21 using namespace SourceMM;
24 * @brief Implementation of main SourceMM GameDLL functionality
28 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
29 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
30 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
31 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
32 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
33 void DLLShutdown_handler();
34 void LevelShutdown_handler();
35 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
37 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
39 SourceHook::CSourceHookImpl g_SourceHook;
40 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
41 SourceHook::String g_ModPath;
42 SourceHook::String g_BinPath;
43 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
44 bool bInFirstLevel = true;
45 bool gParsedGameInfo = false;
46 SourceHook::List<GameDllInfo *> gamedll_list;
47 SourceHook::CallClass<IServerGameDLL> *dllExec;
49 void ClearGamedllList();
52 #define IFACE_MACRO(orig,nam) \
53 CPluginManager::CPlugin *pl; \
54 SourceHook::List<IMetamodListener *>::iterator event; \
55 IMetamodListener *api; \
58 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
60 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
62 mret = IFACE_FAILED; \
63 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
64 if (ret) *ret = mret; \
69 return (orig)(iface, ret);
71 ///////////////////////////////////
72 // Main code for HL2 Interaction //
73 ///////////////////////////////////
75 //Initialize everything here
78 char full_path[260] = {0};
79 GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
80 g_BinPath.assign(full_path);
82 UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
84 //Like metamod, reload plugins at the end of the map.
85 //This is so plugins can hook everything on load, BUT, new plugins will be reloaded
86 // if the server is shut down (silly, but rare case).
89 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
90 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
91 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
92 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
95 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
97 g_Engine.engineFactory = engineFactory;
98 g_Engine.fileSystemFactory = filesystemFactory;
99 g_Engine.physicsFactory = physicsFactory;
100 g_Engine.pGlobals = pGlobals;
102 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
103 if (!g_Engine.engine)
105 Error("Could not find IVEngineServer! Metamod cannot load.");
108 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
111 Error("Could not find ICvar! Metamod cannot load.");
115 g_Engine.loaded = true;
117 //Initialize our console hooks
118 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
120 if (!g_SmmAPI.CacheCmds())
122 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
123 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
127 UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
129 LoadPluginsFromFile(full_path);
131 g_PluginMngr.SetAllLoaded();
133 bInFirstLevel = true;
135 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
137 RETURN_META_VALUE(MRES_IGNORED, true);
140 //This is where the magic happens
141 SMM_API void *CreateInterface(const char *iface, int *ret)
143 if (!gParsedGameInfo)
145 gParsedGameInfo = true;
146 char curpath[260] = {0};
147 char dllpath[260] = {0};
148 getcwd(curpath, sizeof(curpath)-1);
149 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
151 Error("GetFileOfAddress() failed! Metamod cannot load.");
154 SourceHook::String s_dllpath(dllpath);
155 //begin the heuristics for searching for the mod path (these are quite ugly).
156 //for OS compatibility purposes, we're going to do case insensitivity on windows.
157 size_t path_len = strlen(curpath);
158 size_t dll_len = strlen(dllpath);
160 //strip the dll path off
161 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
162 for (size_t i=dll_len-1; i>0; i--)
164 if (dllpath[i] == '\\' || dllpath[i] == '/')
168 //save path by stripping off file name and ending terminator
175 //strip absolute path terminators if any!
176 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
177 curpath[--path_len] = '\0';
179 //if the base path doesn't fit into the module path, something is wrong!
180 // ex: c:\games\srcds
182 if (path_len > dll_len)
184 Error("Could not detect GameDLL path! Metamod cannot load[1].");
188 //we are now in such a position that the two dir names SHOULD MATCH!
189 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
197 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
199 //:TODO: In this case, we should read /proc/self/maps and find srcds!
200 Error("Could not detect GameDLL path! Metamod cannot load[2].");
203 //this will skip past the dir and its separator char
204 char *ptr = &(dllpath[path_len+1]);
205 path_len = strlen(ptr);
206 for (size_t i=0; i<path_len; i++)
208 if (ptr[i] == '/' || ptr[i] == '\\')
212 Error("Could not detect GameDLL path! Metamod cannot load[3].");
221 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
223 snprintf(temp_path, sizeof(temp_path)-1,
229 g_ModPath.assign(temp_path);
231 snprintf(temp_path, sizeof(temp_path)-1,
237 FILE *fp = fopen(temp_path, "rt");
240 Error("Unable to open gameinfo.txt! Metamod cannot load.");
244 char key[128], val[128];
246 const char *gameinfo = "|gameinfo_path|";
247 size_t gameinfo_len = strlen(gameinfo);
249 bool gamebin = false;
254 fgets(buffer, sizeof(buffer)-1, fp);
255 len = strlen(buffer);
256 if (buffer[len-1] == '\n')
257 buffer[--len] = '\0';
258 UTIL_TrimComments(buffer);
259 UTIL_TrimLeft(buffer);
260 UTIL_TrimRight(buffer);
261 if (stricmp(buffer, "SearchPaths") == 0)
265 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
266 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
268 if (stricmp(key, "Game") == 0)
273 if (strncmp(val, gameinfo, gameinfo_len) == 0)
275 ptr = &(val[gameinfo_len]);
278 lptr = g_ModPath.c_str();
283 size_t ptr_len = strlen(ptr);
284 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
285 ptr[--ptr_len] = '\0';
286 //no need to append "bin"
289 UTIL_PathFmt(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
291 UTIL_PathFmt(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
293 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
295 FILE *fp = fopen(temp_path, "rb");
298 //:TODO: Optimize this a bit!
299 SourceHook::List<GameDllInfo *>::iterator iter;
302 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
305 if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
307 if (UTIL_PathCmp(temp_path, buffer))
317 HINSTANCE gamedll = dlmount(temp_path);
320 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
326 GameDllInfo *pInfo = new GameDllInfo;
328 pInfo->lib = gamedll;
329 pInfo->loaded = true;
330 pInfo->pGameDLL = NULL;
331 gamedll_list.push_back(pInfo);
338 if (!g_GameDll.loaded)
340 const char *str = "ServerGameDLL";
341 size_t len = strlen(str);
343 if (strncmp(iface, str, len) == 0)
345 //This is the interface we want! Right now we support versions 3 and 4.
346 int version = atoi(&(iface[len]));
347 if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
349 Error("GameDLL version %d is not supported by Metamod!", version);
352 SourceHook::List<GameDllInfo *>::iterator iter;
353 GameDllInfo *pInfo = NULL;
355 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
358 ptr = (pInfo->factory)(iface, ret);
361 //this is our gamedll. unload the others.
362 gamedll_list.erase(iter);
364 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
370 if (g_GameDll.loaded)
380 //:TODO: .. something a bit more intelligent?
381 Error("Engine requested unknown interface before GameDLL was known!");
386 //if we got here, there's definitely a gamedll.
387 IFACE_MACRO(g_GameDll.factory, GameDLL);
390 void ClearGamedllList()
392 SourceHook::List<GameDllInfo *>::iterator iter;
395 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
402 gamedll_list.clear();
405 void DLLShutdown_handler()
408 g_PluginMngr.UnloadAll();
410 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
411 g_SMConVarAccessor.MarkCommandsAsGameDLL();
412 g_SMConVarAccessor.UnregisterGameDLLCommands();
414 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
416 SH_RELEASE_CALLCLASS(dllExec);
419 g_SourceHook.CompleteShutdown();
421 if (g_GameDll.lib && g_GameDll.loaded)
422 dlclose(g_GameDll.lib);
423 memset(&g_GameDll, 0, sizeof(GameDllInfo));
425 RETURN_META(MRES_SUPERCEDE);
428 int LoadPluginsFromFile(const char *file)
431 int total = 0, skipped=0;
435 fp = fopen(file, "rt");
438 LogMessage("[META] Could not open plugins file %s\n", file);
442 char buffer[255], error[255], full_path[128];
443 const char *ptr, *ext;
448 fgets(buffer, sizeof(buffer)-1, fp);
449 length = strlen(buffer);
452 if (buffer[length-1] == '\n')
453 buffer[length-1] = '\0';
455 UTIL_TrimLeft(buffer);
456 UTIL_TrimRight(buffer);
458 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
460 //First find if it's an absolute path or not...
461 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
463 //If we're in an absolute path, ignore our normal heuristics
464 id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
465 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
467 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
475 //Attempt to find a file extension
476 ptr = UTIL_GetExtension(buffer);
477 //Add an extension if there's none there
480 #if defined WIN32 || defined _WIN32
488 //Format the new path
489 UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
490 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
491 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
493 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
506 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
508 LogMessage("[META] Loaded %d plugins from file.", total);
514 //Wrapper function. This is called when the GameDLL thinks it's using
515 // the engine's real engineFactory.
516 void *EngineFactory(const char *iface, int *ret)
518 IFACE_MACRO(g_Engine.engineFactory, Engine);
521 //Wrapper function. This is called when the GameDLL thinks it's using
522 // the engine's real physicsFactory.
523 void *PhysicsFactory(const char *iface, int *ret)
525 IFACE_MACRO(g_Engine.physicsFactory, Physics);
528 //Wrapper function. This is called when the GameDLL thinks it's using
529 // the engine's real fileSystemFactory.
530 void *FileSystemFactory(const char *iface, int *ret)
532 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
535 void LogMessage(const char *msg, ...)
538 static char buffer[2048];
543 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
544 strcat(buffer, "\n");
547 if (!g_Engine.engine)
549 fprintf(stdout, "%s", buffer);
551 g_Engine.engine->LogPrint(buffer);
555 void LevelShutdown_handler(void)
560 #if defined WIN32 || defined _WIN32
561 snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
563 snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
565 LoadPluginsFromFile(full_path);
567 bInFirstLevel = false;
571 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
573 if (!g_SmmAPI.CacheSuccessful())
575 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
576 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
579 RETURN_META_VALUE(MRES_IGNORED, false);
582 #if defined __GNUC__ && (__GNUC__ == 3)
583 void * ::operator new(size_t size) {
584 return(calloc(1, size));
587 void * ::operator new[](size_t size) {
588 return(calloc(1, size));
591 void ::operator delete(void * ptr) {
596 void ::operator delete[](void * ptr) {