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 if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
381 Error("GameDLL version %d is not supported by Metamod!", version);
384 SourceHook::List<GameDllInfo *>::iterator iter;
385 GameDllInfo *pInfo = NULL;
387 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
390 ptr = (pInfo->factory)(iface, ret);
393 //this is our gamedll. unload the others.
394 gamedll_list.erase(iter);
396 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
402 if (g_GameDll.loaded)
412 //:TODO: .. something a bit more intelligent?
413 Error("Engine requested unknown interface before GameDLL was known!");
418 //if we got here, there's definitely a gamedll.
419 IFACE_MACRO(g_GameDll.factory, GameDLL);
422 void ClearGamedllList()
424 SourceHook::List<GameDllInfo *>::iterator iter;
427 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
434 gamedll_list.clear();
437 void DLLShutdown_handler()
440 g_PluginMngr.UnloadAll();
442 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
443 g_SMConVarAccessor.MarkCommandsAsGameDLL();
444 g_SMConVarAccessor.UnregisterGameDLLCommands();
446 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
448 SH_RELEASE_CALLCLASS(dllExec);
451 g_SourceHook.CompleteShutdown();
453 if (g_GameDll.lib && g_GameDll.loaded)
454 dlclose(g_GameDll.lib);
455 memset(&g_GameDll, 0, sizeof(GameDllInfo));
457 RETURN_META(MRES_SUPERCEDE);
460 int LoadPluginsFromFile(const char *file)
463 int total = 0, skipped=0;
467 fp = fopen(file, "rt");
470 LogMessage("[META] Could not open plugins file %s\n", file);
474 char buffer[255], error[255], full_path[128];
475 const char *ptr, *ext;
480 fgets(buffer, sizeof(buffer)-1, fp);
481 length = strlen(buffer);
484 if (buffer[length-1] == '\n')
485 buffer[length-1] = '\0';
487 UTIL_TrimLeft(buffer);
488 UTIL_TrimRight(buffer);
490 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
492 //First find if it's an absolute path or not...
493 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
495 //If we're in an absolute path, ignore our normal heuristics
496 id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
497 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
499 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
507 //Attempt to find a file extension
508 ptr = UTIL_GetExtension(buffer);
509 //Add an extension if there's none there
512 #if defined WIN32 || defined _WIN32
520 //Format the new path
521 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
522 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
523 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
525 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
538 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
540 LogMessage("[META] Loaded %d plugins from file.", total);
546 //Wrapper function. This is called when the GameDLL thinks it's using
547 // the engine's real engineFactory.
548 void *EngineFactory(const char *iface, int *ret)
550 IFACE_MACRO(g_Engine.engineFactory, Engine);
553 //Wrapper function. This is called when the GameDLL thinks it's using
554 // the engine's real physicsFactory.
555 void *PhysicsFactory(const char *iface, int *ret)
557 IFACE_MACRO(g_Engine.physicsFactory, Physics);
560 //Wrapper function. This is called when the GameDLL thinks it's using
561 // the engine's real fileSystemFactory.
562 void *FileSystemFactory(const char *iface, int *ret)
564 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
567 void LogMessage(const char *msg, ...)
570 static char buffer[2048];
575 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
576 strcat(buffer, "\n");
579 if (!g_Engine.engine)
581 fprintf(stdout, "%s", buffer);
583 g_Engine.engine->LogPrint(buffer);
587 void LevelShutdown_handler(void)
592 g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
594 LoadPluginsFromFile(full_path);
596 bInFirstLevel = false;
599 ITER_EVENT(OnLevelShutdown, ());
601 RETURN_META(MRES_IGNORED);
604 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
606 if (!g_SmmAPI.CacheSuccessful())
608 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
609 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
612 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
613 SetUnhandledExceptionFilter(NULL);
616 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
618 RETURN_META_VALUE(MRES_IGNORED, false);
621 #if defined __GNUC__ && (__GNUC__ == 3)
622 void * ::operator new(size_t size) {
623 return(calloc(1, size));
626 void * ::operator new[](size_t size) {
627 return(calloc(1, size));
630 void ::operator delete(void * ptr) {
635 void ::operator delete[](void * ptr) {