1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2006 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 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
33 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
34 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
35 void DLLShutdown_handler();
36 void LevelShutdown_handler();
37 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
39 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
41 SourceHook::CSourceHookImpl g_SourceHook;
42 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
43 SourceHook::String g_ModPath;
44 SourceHook::String g_BinPath;
45 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
46 bool bInFirstLevel = true;
47 bool gParsedGameInfo = false;
48 SourceHook::List<GameDllInfo *> gamedll_list;
49 SourceHook::CallClass<IServerGameDLL> *dllExec;
51 void ClearGamedllList();
54 #define IFACE_MACRO(orig,nam) \
55 CPluginManager::CPlugin *pl; \
56 SourceHook::List<IMetamodListener *>::iterator event; \
57 IMetamodListener *api; \
60 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
62 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
64 mret = IFACE_FAILED; \
65 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
66 if (ret) *ret = mret; \
71 return (orig)(iface, ret);
73 #define ITER_EVENT(evn, args) \
74 CPluginManager::CPlugin *pl; \
75 SourceHook::List<IMetamodListener *>::iterator event; \
76 IMetamodListener *api; \
77 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
79 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
85 ///////////////////////////////////
86 // Main code for HL2 Interaction //
87 ///////////////////////////////////
89 //Initialize everything here
92 char full_path[260] = {0};
93 GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
94 g_BinPath.assign(full_path);
96 //Like metamod, reload plugins at the end of the map.
97 //This is so plugins can hook everything on load, BUT, new plugins will be reloaded
98 // if the server is shut down (silly, but rare case).
101 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
102 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
105 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
107 if (g_GameDll.pGameClients)
108 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
111 // If IServerGameClients isn't found, this really isn't a fatal error so...
112 LogMessage("[META] Warning: Could not find IServerGameClients!");
113 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
117 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
119 g_Engine.engineFactory = engineFactory;
120 g_Engine.fileSystemFactory = filesystemFactory;
121 g_Engine.physicsFactory = physicsFactory;
122 g_Engine.pGlobals = pGlobals;
124 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
125 if (!g_Engine.engine)
127 Error("Could not find IVEngineServer! Metamod cannot load.");
130 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
133 Error("Could not find ICvar! Metamod cannot load.");
137 g_Engine.loaded = true;
139 //Initialize our console hooks
140 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
142 if (!g_SmmAPI.CacheCmds())
144 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
145 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
149 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
151 pluginFile = GetPluginsFile();
154 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
156 LoadPluginsFromFile(full_path);
158 bInFirstLevel = true;
160 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
162 RETURN_META_VALUE(MRES_IGNORED, true);
165 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
167 g_PluginMngr.SetAllLoaded();
168 RETURN_META_VALUE(MRES_IGNORED, true);
171 //This is where the magic happens
172 SMM_API void *CreateInterface(const char *iface, int *ret)
174 if (!gParsedGameInfo)
176 gParsedGameInfo = true;
177 char curpath[260] = {0};
178 char dllpath[260] = {0};
179 getcwd(curpath, sizeof(curpath)-1);
180 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
182 Error("GetFileOfAddress() failed! Metamod cannot load.");
185 SourceHook::String s_dllpath(dllpath);
186 //begin the heuristics for searching for the mod path (these are quite ugly).
187 //for OS compatibility purposes, we're going to do case insensitivity on windows.
188 size_t path_len = strlen(curpath);
189 size_t dll_len = strlen(dllpath);
191 //strip the dll path off
192 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
193 for (size_t i=dll_len-1; i>0; i--)
195 if (dllpath[i] == '\\' || dllpath[i] == '/')
199 //save path by stripping off file name and ending terminator
206 //strip absolute path terminators if any!
207 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
208 curpath[--path_len] = '\0';
210 //if the base path doesn't fit into the module path, something is wrong!
211 // ex: c:\games\srcds
213 if (path_len > dll_len)
215 Error("Could not detect GameDLL path! Metamod cannot load[1].");
219 //we are now in such a position that the two dir names SHOULD MATCH!
220 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
228 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
230 //:TODO: In this case, we should read /proc/self/maps and find srcds!
231 Error("Could not detect GameDLL path! Metamod cannot load[2].");
234 //this will skip past the dir and its separator char
235 char *ptr = &(dllpath[path_len+1]);
236 path_len = strlen(ptr);
237 for (size_t i=0; i<path_len; i++)
239 if (ptr[i] == '/' || ptr[i] == '\\')
243 Error("Could not detect GameDLL path! Metamod cannot load[3].");
252 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
254 snprintf(temp_path, sizeof(temp_path)-1,
260 g_ModPath.assign(temp_path);
262 snprintf(temp_path, sizeof(temp_path)-1,
268 FILE *fp = fopen(temp_path, "rt");
271 Error("Unable to open gameinfo.txt! Metamod cannot load.");
275 char key[128], val[128];
277 const char *gameinfo = "|gameinfo_path|";
278 size_t gameinfo_len = strlen(gameinfo);
280 bool gamebin = false;
285 fgets(buffer, sizeof(buffer)-1, fp);
286 len = strlen(buffer);
287 if (buffer[len-1] == '\n')
288 buffer[--len] = '\0';
289 UTIL_TrimComments(buffer);
290 UTIL_TrimLeft(buffer);
291 UTIL_TrimRight(buffer);
292 if (stricmp(buffer, "SearchPaths") == 0)
296 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
297 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
299 if (stricmp(key, "Game") == 0)
304 if (strncmp(val, gameinfo, gameinfo_len) == 0)
306 ptr = &(val[gameinfo_len]);
309 lptr = g_ModPath.c_str();
314 size_t ptr_len = strlen(ptr);
315 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
316 ptr[--ptr_len] = '\0';
317 //no need to append "bin"
320 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
322 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
324 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
326 FILE *fp = fopen(temp_path, "rb");
329 //:TODO: Optimize this a bit!
330 SourceHook::List<GameDllInfo *>::iterator iter;
333 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
336 if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
338 if (UTIL_PathCmp(temp_path, buffer))
348 HINSTANCE gamedll = dlmount(temp_path);
351 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
357 GameDllInfo *pInfo = new GameDllInfo;
359 pInfo->lib = gamedll;
360 pInfo->loaded = true;
361 pInfo->pGameDLL = NULL;
362 pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
363 gamedll_list.push_back(pInfo);
370 if (!g_GameDll.loaded)
372 const char *str = "ServerGameDLL";
373 size_t len = strlen(str);
375 if (strncmp(iface, str, len) == 0)
377 //This is the interface we want! Right now we support versions 3 and 4.
378 int version = atoi(&(iface[len]));
379 int sizeTooBig = 0; //rename this to sizeWrong in the future!
380 if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
382 //maybe this will get used in the future
383 sizeTooBig = version;
387 SourceHook::List<GameDllInfo *>::iterator iter;
388 GameDllInfo *pInfo = NULL;
390 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
393 ptr = (pInfo->factory)(iface, ret);
396 //this is our gamedll. unload the others.
397 gamedll_list.erase(iter);
399 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
405 if (g_GameDll.loaded)
409 Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!", sizeTooBig);
424 //:TODO: .. something a bit more intelligent?
425 Error("Engine requested unknown interface before GameDLL was known!");
430 //if we got here, there's definitely a gamedll.
431 IFACE_MACRO(g_GameDll.factory, GameDLL);
434 void ClearGamedllList()
436 SourceHook::List<GameDllInfo *>::iterator iter;
439 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
446 gamedll_list.clear();
449 void DLLShutdown_handler()
452 g_PluginMngr.UnloadAll();
454 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
455 g_SMConVarAccessor.MarkCommandsAsGameDLL();
456 g_SMConVarAccessor.UnregisterGameDLLCommands();
458 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
460 SH_RELEASE_CALLCLASS(dllExec);
463 g_SourceHook.CompleteShutdown();
465 if (g_GameDll.lib && g_GameDll.loaded)
466 dlclose(g_GameDll.lib);
467 memset(&g_GameDll, 0, sizeof(GameDllInfo));
469 RETURN_META(MRES_SUPERCEDE);
472 int LoadPluginsFromFile(const char *_file)
475 int total = 0, skipped=0;
479 fp = fopen(_file, "rt");
482 LogMessage("[META] Could not open plugins file %s\n", _file);
486 char buffer[255], error[255], full_path[128];
487 const char *ptr, *ext, *file;
492 fgets(buffer, sizeof(buffer)-1, fp);
493 length = strlen(buffer);
496 if (buffer[length-1] == '\n')
497 buffer[--length] = '\0';
499 UTIL_TrimLeft(buffer);
500 UTIL_TrimRight(buffer);
502 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
505 if (buffer[0] == '"')
526 while (*cptr && isspace(*cptr))
529 UTIL_TrimRight(cptr);
530 if (*cptr && isalpha(*cptr))
532 g_PluginMngr.SetAlias(buffer, cptr);
544 //First find if it's an absolute path or not...
545 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
547 //If we're in an absolute path, ignore our normal heuristics
548 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error)-1);
549 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
551 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
559 //Attempt to find a file extension
560 ptr = UTIL_GetExtension(file);
561 //Add an extension if there's none there
564 #if defined WIN32 || defined _WIN32
572 //Format the new path
573 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), file, ext);
574 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
575 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
577 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
590 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
592 LogMessage("[META] Loaded %d plugins from file.", total);
598 //Wrapper function. This is called when the GameDLL thinks it's using
599 // the engine's real engineFactory.
600 void *EngineFactory(const char *iface, int *ret)
602 IFACE_MACRO(g_Engine.engineFactory, Engine);
605 //Wrapper function. This is called when the GameDLL thinks it's using
606 // the engine's real physicsFactory.
607 void *PhysicsFactory(const char *iface, int *ret)
609 IFACE_MACRO(g_Engine.physicsFactory, Physics);
612 //Wrapper function. This is called when the GameDLL thinks it's using
613 // the engine's real fileSystemFactory.
614 void *FileSystemFactory(const char *iface, int *ret)
616 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
619 void LogMessage(const char *msg, ...)
622 static char buffer[2048];
627 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
628 strcat(buffer, "\n");
631 if (!g_Engine.engine)
633 fprintf(stdout, "%s", buffer);
635 g_Engine.engine->LogPrint(buffer);
639 void LevelShutdown_handler(void)
644 g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
646 LoadPluginsFromFile(full_path);
648 bInFirstLevel = false;
651 ITER_EVENT(OnLevelShutdown, ());
653 RETURN_META(MRES_IGNORED);
656 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
658 if (!g_SmmAPI.CacheSuccessful())
660 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
661 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
664 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
665 SetUnhandledExceptionFilter(NULL);
668 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
670 RETURN_META_VALUE(MRES_IGNORED, false);
673 #if defined __GNUC__ && (__GNUC__ == 3)
674 void * ::operator new(size_t size) {
675 return(calloc(1, size));
678 void * ::operator new[](size_t size) {
679 return(calloc(1, size));
682 void ::operator delete(void * ptr) {
687 void ::operator delete[](void * ptr) {