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 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
34 void DLLShutdown_handler();
35 void LevelShutdown_handler();
36 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
38 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
40 SourceHook::CSourceHookImpl g_SourceHook;
41 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
42 SourceHook::String g_ModPath;
43 SourceHook::String g_BinPath;
44 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
45 bool bInFirstLevel = true;
46 bool gParsedGameInfo = false;
47 SourceHook::List<GameDllInfo *> gamedll_list;
48 SourceHook::CallClass<IServerGameDLL> *dllExec;
50 void ClearGamedllList();
53 #define IFACE_MACRO(orig,nam) \
54 CPluginManager::CPlugin *pl; \
55 SourceHook::List<IMetamodListener *>::iterator event; \
56 IMetamodListener *api; \
59 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
61 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
63 mret = IFACE_FAILED; \
64 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
65 if (ret) *ret = mret; \
70 return (orig)(iface, ret);
72 #define ITER_EVENT(evn, args) \
73 CPluginManager::CPlugin *pl; \
74 SourceHook::List<IMetamodListener *>::iterator event; \
75 IMetamodListener *api; \
76 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
78 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
84 ///////////////////////////////////
85 // Main code for HL2 Interaction //
86 ///////////////////////////////////
88 //Initialize everything here
91 char full_path[260] = {0};
92 GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
93 g_BinPath.assign(full_path);
95 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
97 //Like metamod, reload plugins at the end of the map.
98 //This is so plugins can hook everything on load, BUT, new plugins will be reloaded
99 // if the server is shut down (silly, but rare case).
100 bInFirstLevel = true;
102 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
105 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
106 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
109 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
111 g_Engine.engineFactory = engineFactory;
112 g_Engine.fileSystemFactory = filesystemFactory;
113 g_Engine.physicsFactory = physicsFactory;
114 g_Engine.pGlobals = pGlobals;
116 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
117 if (!g_Engine.engine)
119 Error("Could not find IVEngineServer! Metamod cannot load.");
122 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
125 Error("Could not find ICvar! Metamod cannot load.");
129 g_Engine.loaded = true;
131 //Initialize our console hooks
132 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
134 if (!g_SmmAPI.CacheCmds())
136 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
137 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
141 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
143 LoadPluginsFromFile(full_path);
145 bInFirstLevel = true;
147 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
149 RETURN_META_VALUE(MRES_IGNORED, true);
152 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
154 g_PluginMngr.SetAllLoaded();
155 RETURN_META_VALUE(MRES_IGNORED, true);
158 //This is where the magic happens
159 SMM_API void *CreateInterface(const char *iface, int *ret)
161 if (!gParsedGameInfo)
163 gParsedGameInfo = true;
164 char curpath[260] = {0};
165 char dllpath[260] = {0};
166 getcwd(curpath, sizeof(curpath)-1);
167 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
169 Error("GetFileOfAddress() failed! Metamod cannot load.");
172 SourceHook::String s_dllpath(dllpath);
173 //begin the heuristics for searching for the mod path (these are quite ugly).
174 //for OS compatibility purposes, we're going to do case insensitivity on windows.
175 size_t path_len = strlen(curpath);
176 size_t dll_len = strlen(dllpath);
178 //strip the dll path off
179 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
180 for (size_t i=dll_len-1; i>0; i--)
182 if (dllpath[i] == '\\' || dllpath[i] == '/')
186 //save path by stripping off file name and ending terminator
193 //strip absolute path terminators if any!
194 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
195 curpath[--path_len] = '\0';
197 //if the base path doesn't fit into the module path, something is wrong!
198 // ex: c:\games\srcds
200 if (path_len > dll_len)
202 Error("Could not detect GameDLL path! Metamod cannot load[1].");
206 //we are now in such a position that the two dir names SHOULD MATCH!
207 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
215 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
217 //:TODO: In this case, we should read /proc/self/maps and find srcds!
218 Error("Could not detect GameDLL path! Metamod cannot load[2].");
221 //this will skip past the dir and its separator char
222 char *ptr = &(dllpath[path_len+1]);
223 path_len = strlen(ptr);
224 for (size_t i=0; i<path_len; i++)
226 if (ptr[i] == '/' || ptr[i] == '\\')
230 Error("Could not detect GameDLL path! Metamod cannot load[3].");
239 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
241 snprintf(temp_path, sizeof(temp_path)-1,
247 g_ModPath.assign(temp_path);
249 snprintf(temp_path, sizeof(temp_path)-1,
255 FILE *fp = fopen(temp_path, "rt");
258 Error("Unable to open gameinfo.txt! Metamod cannot load.");
262 char key[128], val[128];
264 const char *gameinfo = "|gameinfo_path|";
265 size_t gameinfo_len = strlen(gameinfo);
267 bool gamebin = false;
272 fgets(buffer, sizeof(buffer)-1, fp);
273 len = strlen(buffer);
274 if (buffer[len-1] == '\n')
275 buffer[--len] = '\0';
276 UTIL_TrimComments(buffer);
277 UTIL_TrimLeft(buffer);
278 UTIL_TrimRight(buffer);
279 if (stricmp(buffer, "SearchPaths") == 0)
283 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
284 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
286 if (stricmp(key, "Game") == 0)
291 if (strncmp(val, gameinfo, gameinfo_len) == 0)
293 ptr = &(val[gameinfo_len]);
296 lptr = g_ModPath.c_str();
301 size_t ptr_len = strlen(ptr);
302 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
303 ptr[--ptr_len] = '\0';
304 //no need to append "bin"
307 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
309 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
311 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
313 FILE *fp = fopen(temp_path, "rb");
316 //:TODO: Optimize this a bit!
317 SourceHook::List<GameDllInfo *>::iterator iter;
320 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
323 if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
325 if (UTIL_PathCmp(temp_path, buffer))
335 HINSTANCE gamedll = dlmount(temp_path);
338 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
344 GameDllInfo *pInfo = new GameDllInfo;
346 pInfo->lib = gamedll;
347 pInfo->loaded = true;
348 pInfo->pGameDLL = NULL;
349 gamedll_list.push_back(pInfo);
356 if (!g_GameDll.loaded)
358 const char *str = "ServerGameDLL";
359 size_t len = strlen(str);
361 if (strncmp(iface, str, len) == 0)
363 //This is the interface we want! Right now we support versions 3 and 4.
364 int version = atoi(&(iface[len]));
365 if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
367 Error("GameDLL version %d is not supported by Metamod!", version);
370 SourceHook::List<GameDllInfo *>::iterator iter;
371 GameDllInfo *pInfo = NULL;
373 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
376 ptr = (pInfo->factory)(iface, ret);
379 //this is our gamedll. unload the others.
380 gamedll_list.erase(iter);
382 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
388 if (g_GameDll.loaded)
398 //:TODO: .. something a bit more intelligent?
399 Error("Engine requested unknown interface before GameDLL was known!");
404 //if we got here, there's definitely a gamedll.
405 IFACE_MACRO(g_GameDll.factory, GameDLL);
408 void ClearGamedllList()
410 SourceHook::List<GameDllInfo *>::iterator iter;
413 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
420 gamedll_list.clear();
423 void DLLShutdown_handler()
426 g_PluginMngr.UnloadAll();
428 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
429 g_SMConVarAccessor.MarkCommandsAsGameDLL();
430 g_SMConVarAccessor.UnregisterGameDLLCommands();
432 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
434 SH_RELEASE_CALLCLASS(dllExec);
437 g_SourceHook.CompleteShutdown();
439 if (g_GameDll.lib && g_GameDll.loaded)
440 dlclose(g_GameDll.lib);
441 memset(&g_GameDll, 0, sizeof(GameDllInfo));
443 RETURN_META(MRES_SUPERCEDE);
446 int LoadPluginsFromFile(const char *file)
449 int total = 0, skipped=0;
453 fp = fopen(file, "rt");
456 LogMessage("[META] Could not open plugins file %s\n", file);
460 char buffer[255], error[255], full_path[128];
461 const char *ptr, *ext;
466 fgets(buffer, sizeof(buffer)-1, fp);
467 length = strlen(buffer);
470 if (buffer[length-1] == '\n')
471 buffer[length-1] = '\0';
473 UTIL_TrimLeft(buffer);
474 UTIL_TrimRight(buffer);
476 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
478 //First find if it's an absolute path or not...
479 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
481 //If we're in an absolute path, ignore our normal heuristics
482 id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
483 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
485 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
493 //Attempt to find a file extension
494 ptr = UTIL_GetExtension(buffer);
495 //Add an extension if there's none there
498 #if defined WIN32 || defined _WIN32
506 //Format the new path
507 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
508 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
509 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
511 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
524 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
526 LogMessage("[META] Loaded %d plugins from file.", total);
532 //Wrapper function. This is called when the GameDLL thinks it's using
533 // the engine's real engineFactory.
534 void *EngineFactory(const char *iface, int *ret)
536 IFACE_MACRO(g_Engine.engineFactory, Engine);
539 //Wrapper function. This is called when the GameDLL thinks it's using
540 // the engine's real physicsFactory.
541 void *PhysicsFactory(const char *iface, int *ret)
543 IFACE_MACRO(g_Engine.physicsFactory, Physics);
546 //Wrapper function. This is called when the GameDLL thinks it's using
547 // the engine's real fileSystemFactory.
548 void *FileSystemFactory(const char *iface, int *ret)
550 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
553 void LogMessage(const char *msg, ...)
556 static char buffer[2048];
561 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
562 strcat(buffer, "\n");
565 if (!g_Engine.engine)
567 fprintf(stdout, "%s", buffer);
569 g_Engine.engine->LogPrint(buffer);
573 void LevelShutdown_handler(void)
578 #if defined WIN32 || defined _WIN32
579 snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
581 snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
583 LoadPluginsFromFile(full_path);
585 bInFirstLevel = false;
588 ITER_EVENT(OnLevelShutdown, ());
590 RETURN_META(MRES_IGNORED);
593 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
595 if (!g_SmmAPI.CacheSuccessful())
597 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
598 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
601 #if (defined _DEBUG || defined DEBUG) && (defined WIN32 || defined _WIN32)
602 SetUnhandledExceptionFilter(NULL);
605 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
607 RETURN_META_VALUE(MRES_IGNORED, false);
610 #if defined __GNUC__ && (__GNUC__ == 3)
611 void * ::operator new(size_t size) {
612 return(calloc(1, size));
615 void * ::operator new[](size_t size) {
616 return(calloc(1, size));
619 void ::operator delete(void * ptr) {
624 void ::operator delete[](void * ptr) {