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;
50 int g_GameDllVersion = 0;
52 void ClearGamedllList();
55 #define IFACE_MACRO(orig,nam) \
56 CPluginManager::CPlugin *pl; \
57 SourceHook::List<IMetamodListener *>::iterator event; \
58 IMetamodListener *api; \
61 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
63 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
65 mret = IFACE_FAILED; \
66 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
67 if (ret) *ret = mret; \
72 return (orig)(iface, ret);
74 #define ITER_EVENT(evn, args) \
75 CPluginManager::CPlugin *pl; \
76 SourceHook::List<IMetamodListener *>::iterator event; \
77 IMetamodListener *api; \
78 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
80 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
86 ///////////////////////////////////
87 // Main code for HL2 Interaction //
88 ///////////////////////////////////
90 //Initialize everything here
93 char full_path[260] = {0};
94 GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
95 g_BinPath.assign(full_path);
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);
108 if (g_GameDll.pGameClients)
109 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
112 // If IServerGameClients isn't found, this really isn't a fatal error so...
113 LogMessage("[META] Warning: Could not find IServerGameClients!");
114 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
118 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
120 g_Engine.engineFactory = engineFactory;
121 g_Engine.fileSystemFactory = filesystemFactory;
122 g_Engine.physicsFactory = physicsFactory;
123 g_Engine.pGlobals = pGlobals;
125 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
126 if (!g_Engine.engine)
128 Error("Could not find IVEngineServer! Metamod cannot load.");
131 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
134 Error("Could not find ICvar! Metamod cannot load.");
138 g_Engine.loaded = true;
140 //Initialize our console hooks
141 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
143 if (!g_SmmAPI.CacheCmds())
145 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
146 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
150 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
152 pluginFile = GetPluginsFile();
155 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
157 LoadPluginsFromFile(full_path);
159 bInFirstLevel = true;
161 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
163 RETURN_META_VALUE(MRES_IGNORED, true);
166 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
168 g_PluginMngr.SetAllLoaded();
169 RETURN_META_VALUE(MRES_IGNORED, true);
172 //This is where the magic happens
173 SMM_API void *CreateInterface(const char *iface, int *ret)
175 // Prevent loading of self as a SourceMM plugin or Valve server plugin :x
176 const char *vspIface = "ISERVERPLUGINCALLBACKS";
177 if (strcmp(iface, PLAPI_NAME) == 0 || strnicmp(iface, vspIface, strlen(vspIface)) == 0)
179 Warning("Do not try loading Metamod:Source as a SourceMM or Valve server plugin.\n");
186 if (!gParsedGameInfo)
188 gParsedGameInfo = true;
189 char curpath[260] = {0};
190 char dllpath[260] = {0};
191 getcwd(curpath, sizeof(curpath)-1);
192 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
194 Error("GetFileOfAddress() failed! Metamod cannot load.\n");
197 SourceHook::String s_dllpath(dllpath);
198 //begin the heuristics for searching for the mod path (these are quite ugly).
199 //for OS compatibility purposes, we're going to do case insensitivity on windows.
200 size_t path_len = strlen(curpath);
201 size_t dll_len = strlen(dllpath);
203 //strip the dll path off
204 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
205 for (size_t i=dll_len-1; i>0; i--)
207 if (dllpath[i] == '\\' || dllpath[i] == '/')
211 //save path by stripping off file name and ending terminator
218 //strip absolute path terminators if any!
219 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
220 curpath[--path_len] = '\0';
222 //if the base path doesn't fit into the module path, something is wrong!
223 // ex: c:\games\srcds
225 if (path_len > dll_len)
227 Error("Could not detect GameDLL path! Metamod cannot load[1].\n");
231 //we are now in such a position that the two dir names SHOULD MATCH!
232 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
240 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
242 //:TODO: In this case, we should read /proc/self/maps and find srcds!
243 Error("Could not detect GameDLL path! Metamod cannot load[2].\n");
246 //this will skip past the dir and its separator char
247 char *ptr = &(dllpath[path_len+1]);
248 path_len = strlen(ptr);
249 for (size_t i=0; i<path_len; i++)
251 if (ptr[i] == '/' || ptr[i] == '\\')
255 Error("Could not detect GameDLL path! Metamod cannot load[3].\n");
264 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
266 snprintf(temp_path, sizeof(temp_path)-1,
272 g_ModPath.assign(temp_path);
274 snprintf(temp_path, sizeof(temp_path)-1,
280 FILE *fp = fopen(temp_path, "rt");
283 Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
287 char key[128], val[128];
289 const char *gameinfo = "|gameinfo_path|";
290 size_t gameinfo_len = strlen(gameinfo);
292 bool gamebin = false;
297 fgets(buffer, sizeof(buffer)-1, fp);
298 len = strlen(buffer);
299 if (buffer[len-1] == '\n')
300 buffer[--len] = '\0';
301 UTIL_TrimComments(buffer);
302 UTIL_TrimLeft(buffer);
303 UTIL_TrimRight(buffer);
304 if (stricmp(buffer, "SearchPaths") == 0)
308 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
309 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
311 if (stricmp(key, "Game") == 0)
316 if (strncmp(val, gameinfo, gameinfo_len) == 0)
318 ptr = &(val[gameinfo_len]);
321 lptr = g_ModPath.c_str();
326 size_t ptr_len = strlen(ptr);
327 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
328 ptr[--ptr_len] = '\0';
330 //no need to append "bin"
333 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
334 } else if (ptr[0] == NULL) {
335 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, "bin", SERVER_DLL);
337 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
339 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
341 FILE *fp = fopen(temp_path, "rb");
344 //:TODO: Optimize this a bit!
345 SourceHook::List<GameDllInfo *>::iterator iter;
348 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
351 if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
353 if (UTIL_PathCmp(temp_path, buffer))
363 HINSTANCE gamedll = dlmount(temp_path);
366 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
372 GameDllInfo *pInfo = new GameDllInfo;
374 pInfo->lib = gamedll;
375 pInfo->loaded = true;
376 pInfo->pGameDLL = NULL;
377 pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
378 gamedll_list.push_back(pInfo);
386 if (!g_GameDll.loaded)
388 const char *str = "ServerGameDLL";
389 size_t len = strlen(str);
391 if (strncmp(iface, str, len) == 0)
393 //This is the interface we want! Right now we support versions 3 through 5.
394 g_GameDllVersion = atoi(&(iface[len]));
395 int sizeTooBig = 0; //rename this to sizeWrong in the future!
396 if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
398 //maybe this will get used in the future
399 sizeTooBig = g_GameDllVersion;
403 SourceHook::List<GameDllInfo *>::iterator iter;
404 GameDllInfo *pInfo = NULL;
406 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
409 ptr = (pInfo->factory)(iface, ret);
412 //this is our gamedll. unload the others.
413 gamedll_list.erase(iter);
415 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
421 if (g_GameDll.loaded)
425 Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
440 //:TODO: .. something a bit more intelligent?
441 Error("Engine requested unknown interface before GameDLL was known!\n");
446 //if we got here, there's definitely a gamedll.
447 IFACE_MACRO(g_GameDll.factory, GameDLL);
450 void ClearGamedllList()
452 SourceHook::List<GameDllInfo *>::iterator iter;
455 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
462 gamedll_list.clear();
465 void DLLShutdown_handler()
468 g_PluginMngr.UnloadAll();
470 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
471 g_SMConVarAccessor.MarkCommandsAsGameDLL();
472 g_SMConVarAccessor.UnregisterGameDLLCommands();
474 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
476 SH_RELEASE_CALLCLASS(dllExec);
479 g_SourceHook.CompleteShutdown();
481 if (g_GameDll.lib && g_GameDll.loaded)
482 dlclose(g_GameDll.lib);
483 memset(&g_GameDll, 0, sizeof(GameDllInfo));
485 RETURN_META(MRES_SUPERCEDE);
488 int LoadPluginsFromFile(const char *_file)
491 int total = 0, skipped=0;
495 fp = fopen(_file, "rt");
498 LogMessage("[META] Could not open plugins file %s\n", _file);
502 char buffer[255], error[255], full_path[128];
503 const char *ptr, *ext, *file;
508 fgets(buffer, sizeof(buffer)-1, fp);
509 length = strlen(buffer);
512 if (buffer[length-1] == '\n')
513 buffer[--length] = '\0';
515 UTIL_TrimLeft(buffer);
516 UTIL_TrimRight(buffer);
518 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
521 if (buffer[0] == '"')
542 while (*cptr && isspace(*cptr))
545 UTIL_TrimRight(cptr);
546 if (*cptr && isalpha(*cptr))
548 g_PluginMngr.SetAlias(buffer, cptr);
560 //First find if it's an absolute path or not...
561 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
563 //If we're in an absolute path, ignore our normal heuristics
564 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error)-1);
565 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
567 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
575 //Attempt to find a file extension
576 ptr = UTIL_GetExtension(file);
577 //Add an extension if there's none there
580 #if defined WIN32 || defined _WIN32
588 //Format the new path
589 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), file, ext);
590 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
591 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
593 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
606 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
608 LogMessage("[META] Loaded %d plugins from file.", total);
614 //Wrapper function. This is called when the GameDLL thinks it's using
615 // the engine's real engineFactory.
616 void *EngineFactory(const char *iface, int *ret)
618 IFACE_MACRO(g_Engine.engineFactory, Engine);
621 //Wrapper function. This is called when the GameDLL thinks it's using
622 // the engine's real physicsFactory.
623 void *PhysicsFactory(const char *iface, int *ret)
625 IFACE_MACRO(g_Engine.physicsFactory, Physics);
628 //Wrapper function. This is called when the GameDLL thinks it's using
629 // the engine's real fileSystemFactory.
630 void *FileSystemFactory(const char *iface, int *ret)
632 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
635 void LogMessage(const char *msg, ...)
638 static char buffer[2048];
643 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
644 strcat(buffer, "\n");
647 if (!g_Engine.engine)
649 fprintf(stdout, "%s", buffer);
651 g_Engine.engine->LogPrint(buffer);
655 void LevelShutdown_handler(void)
660 g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
662 LoadPluginsFromFile(full_path);
664 bInFirstLevel = false;
667 ITER_EVENT(OnLevelShutdown, ());
669 RETURN_META(MRES_IGNORED);
672 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
674 if (!g_SmmAPI.CacheSuccessful())
676 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
677 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
680 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
681 SetUnhandledExceptionFilter(NULL);
684 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
686 RETURN_META_VALUE(MRES_IGNORED, false);
689 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
690 void * operator new(size_t size) {
691 return(calloc(1, size));
694 void * operator new[](size_t size) {
695 return(calloc(1, size));
698 void operator delete(void * ptr) {
703 void operator delete[](void * ptr) {