1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2007 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"
20 #include "vsp_listener.h"
22 using namespace SourceMM;
25 * @brief Implementation of main SourceMM GameDLL functionality
29 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
30 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
31 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
32 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
33 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
34 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
35 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
36 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
37 void DLLShutdown_handler();
38 void LevelShutdown_handler();
39 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
40 bool GameInit_handler();
42 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
44 SourceHook::CSourceHookImpl g_SourceHook;
45 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
46 SourceHook::String g_ModPath;
47 SourceHook::String g_BinPath;
48 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
49 bool bInFirstLevel = true;
50 bool gParsedGameInfo = false;
51 bool bGameInit = false;
52 SourceHook::List<GameDllInfo *> gamedll_list;
53 SourceHook::CallClass<IServerGameDLL> *dllExec;
54 int g_GameDllVersion = 0;
56 void ClearGamedllList();
59 #define IFACE_MACRO(orig,nam) \
60 CPluginManager::CPlugin *pl; \
61 SourceHook::List<IMetamodListener *>::iterator event; \
62 IMetamodListener *api; \
65 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
67 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
69 mret = IFACE_FAILED; \
70 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
71 if (ret) *ret = mret; \
76 return (orig)(iface, ret);
78 #define ITER_EVENT(evn, args) \
79 CPluginManager::CPlugin *pl; \
80 SourceHook::List<IMetamodListener *>::iterator event; \
81 IMetamodListener *api; \
82 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
84 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
90 ///////////////////////////////////
91 // Main code for HL2 Interaction //
92 ///////////////////////////////////
94 //Initialize everything here
97 char full_path[260] = {0};
98 GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path)-1);
99 g_BinPath.assign(full_path);
101 //Like metamod, reload plugins at the end of the map.
102 //This is so plugins can hook everything on load, BUT, new plugins will be reloaded
103 // if the server is shut down (silly, but rare case).
104 bInFirstLevel = true;
106 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
107 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
108 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
109 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
110 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
111 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
113 if (g_GameDll.pGameClients)
115 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
117 // If IServerGameClients isn't found, this really isn't a fatal error so...
118 LogMessage("[META] Warning: Could not find IServerGameClients!");
119 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
123 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
125 g_Engine.engineFactory = engineFactory;
126 g_Engine.fileSystemFactory = filesystemFactory;
127 g_Engine.physicsFactory = physicsFactory;
128 g_Engine.pGlobals = pGlobals;
130 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
131 if (!g_Engine.engine)
133 Error("Could not find IVEngineServer! Metamod cannot load.");
136 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
139 Error("Could not find ICvar! Metamod cannot load.");
143 g_Engine.loaded = true;
145 //Initialize our console hooks
146 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
148 if (!g_SmmAPI.CacheCmds())
150 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
151 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
155 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
158 pluginFile = GetPluginsFile();
162 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
164 LoadPluginsFromFile(full_path);
166 bInFirstLevel = true;
168 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
170 RETURN_META_VALUE(MRES_IGNORED, true);
173 bool GameInit_handler()
180 if (g_SmmAPI.VSPEnabled())
182 g_SmmAPI.LoadAsVSP();
190 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
192 g_PluginMngr.SetAllLoaded();
193 RETURN_META_VALUE(MRES_IGNORED, true);
196 //This is where the magic happens
197 SMM_API void *CreateInterface(const char *iface, int *ret)
199 // Prevent loading of self as a SourceMM plugin or Valve server plugin :x
200 const char *vspIface = "ISERVERPLUGINCALLBACKS";
201 if (strcmp(iface, PLAPI_NAME) == 0)
203 Warning("Do not try loading Metamod:Source as a SourceMM or Valve server plugin.\n");
213 if (strncmp(iface, vspIface, 22) == 0)
220 return &g_VspListener;
223 if (!gParsedGameInfo)
225 gParsedGameInfo = true;
226 char curpath[260] = {0};
227 char dllpath[260] = {0};
228 getcwd(curpath, sizeof(curpath)-1);
229 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
231 Error("GetFileOfAddress() failed! Metamod cannot load.\n");
234 SourceHook::String s_dllpath(dllpath);
235 //begin the heuristics for searching for the mod path (these are quite ugly).
236 //for OS compatibility purposes, we're going to do case insensitivity on windows.
237 size_t path_len = strlen(curpath);
238 size_t dll_len = strlen(dllpath);
240 //strip the dll path off
241 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
242 for (size_t i=dll_len-1; i>0; i--)
244 if (dllpath[i] == '\\' || dllpath[i] == '/')
248 //save path by stripping off file name and ending terminator
255 //strip absolute path terminators if any!
256 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
257 curpath[--path_len] = '\0';
259 //if the base path doesn't fit into the module path, something is wrong!
260 // ex: c:\games\srcds
262 if (path_len > dll_len)
264 Error("Could not detect GameDLL path! Metamod cannot load[1].\n");
268 //we are now in such a position that the two dir names SHOULD MATCH!
269 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
277 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
279 //:TODO: In this case, we should read /proc/self/maps and find srcds!
280 Error("Could not detect GameDLL path! Metamod cannot load[2].\n");
283 //this will skip past the dir and its separator char
284 char *ptr = &(dllpath[path_len+1]);
285 path_len = strlen(ptr);
286 for (size_t i=0; i<path_len; i++)
288 if (ptr[i] == '/' || ptr[i] == '\\')
292 Error("Could not detect GameDLL path! Metamod cannot load[3].\n");
301 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
303 snprintf(temp_path, sizeof(temp_path)-1,
309 g_ModPath.assign(temp_path);
311 snprintf(temp_path, sizeof(temp_path)-1,
317 FILE *fp = fopen(temp_path, "rt");
320 /* Do not error out here! It's possible the mod exists in the root directory, i.e.
321 * Dark Messiah. Let's check that just in case!
323 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s", curpath);
324 g_ModPath.assign(temp_path);
325 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
327 fp = fopen(temp_path, "rt");
330 /* Okay, we have to concede here. */
331 Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
336 char key[128], val[128];
338 const char *gameinfo = "|gameinfo_path|";
339 size_t gameinfo_len = strlen(gameinfo);
341 bool gamebin = false;
346 fgets(buffer, sizeof(buffer)-1, fp);
347 len = strlen(buffer);
348 if (buffer[len-1] == '\n')
349 buffer[--len] = '\0';
350 UTIL_TrimComments(buffer);
351 UTIL_TrimLeft(buffer);
352 UTIL_TrimRight(buffer);
353 if (stricmp(buffer, "SearchPaths") == 0)
357 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
358 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
360 if (stricmp(key, "Game") == 0)
365 if (strncmp(val, gameinfo, gameinfo_len) == 0)
367 ptr = &(val[gameinfo_len]);
370 lptr = g_ModPath.c_str();
375 size_t ptr_len = strlen(ptr);
376 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
377 ptr[--ptr_len] = '\0';
379 //no need to append "bin"
382 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
383 } else if (!ptr[0]) {
384 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, "bin", SERVER_DLL);
386 g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
388 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
390 FILE *fp = fopen(temp_path, "rb");
393 //:TODO: Optimize this a bit!
394 SourceHook::List<GameDllInfo *>::iterator iter;
397 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
400 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)-1))
402 if (UTIL_PathCmp(temp_path, buffer))
412 HINSTANCE gamedll = dlmount(temp_path);
415 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
421 GameDllInfo *pInfo = new GameDllInfo;
423 pInfo->lib = gamedll;
424 pInfo->loaded = true;
425 pInfo->pGameDLL = NULL;
426 pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
427 gamedll_list.push_back(pInfo);
435 if (!g_GameDll.loaded)
437 const char *str = "ServerGameDLL";
438 size_t len = strlen(str);
440 if (strncmp(iface, str, len) == 0)
442 //This is the interface we want! Right now we support versions 3 through 5.
443 g_GameDllVersion = atoi(&(iface[len]));
444 int sizeTooBig = 0; //rename this to sizeWrong in the future!
445 if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
447 //maybe this will get used in the future
448 sizeTooBig = g_GameDllVersion;
454 SourceHook::List<GameDllInfo *>::iterator iter;
455 GameDllInfo *pInfo = NULL;
457 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
460 ptr = (pInfo->factory)(iface, ret);
463 //this is our gamedll. unload the others.
464 gamedll_list.erase(iter);
466 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
472 if (g_GameDll.loaded)
476 Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
493 //:TODO: .. something a bit more intelligent?
494 Error("Engine requested unknown interface before GameDLL was known!\n");
499 //if we got here, there's definitely a gamedll.
500 IFACE_MACRO(g_GameDll.factory, GameDLL);
503 void ClearGamedllList()
505 SourceHook::List<GameDllInfo *>::iterator iter;
508 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
515 gamedll_list.clear();
518 void DLLShutdown_handler()
521 g_PluginMngr.UnloadAll();
523 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
524 g_SMConVarAccessor.MarkCommandsAsGameDLL();
525 g_SMConVarAccessor.UnregisterGameDLLCommands();
527 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
529 SH_RELEASE_CALLCLASS(dllExec);
532 g_SourceHook.CompleteShutdown();
534 if (g_GameDll.lib && g_GameDll.loaded)
535 dlclose(g_GameDll.lib);
536 memset(&g_GameDll, 0, sizeof(GameDllInfo));
538 RETURN_META(MRES_SUPERCEDE);
541 int LoadPluginsFromFile(const char *_file)
544 int total = 0, skipped=0;
548 fp = fopen(_file, "rt");
551 LogMessage("[META] Could not open plugins file %s\n", _file);
555 char buffer[255], error[255], full_path[255];
556 const char *ptr, *ext, *file;
561 fgets(buffer, sizeof(buffer)-1, fp);
562 length = strlen(buffer);
565 if (buffer[length-1] == '\n')
566 buffer[--length] = '\0';
568 UTIL_TrimLeft(buffer);
569 UTIL_TrimRight(buffer);
571 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
574 if (buffer[0] == '"')
595 while (*cptr && isspace(*cptr))
598 UTIL_TrimRight(cptr);
599 if (*cptr && isalpha(*cptr))
601 g_PluginMngr.SetAlias(buffer, cptr);
613 //First find if it's an absolute path or not...
614 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
616 //If we're in an absolute path, ignore our normal heuristics
617 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error)-1);
618 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
620 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
628 //Attempt to find a file extension
629 ptr = UTIL_GetExtension(file);
630 //Add an extension if there's none there
633 #if defined WIN32 || defined _WIN32
641 //Format the new path
642 g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), file, ext);
643 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
644 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
646 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
659 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
661 LogMessage("[META] Loaded %d plugins from file.", total);
667 //Wrapper function. This is called when the GameDLL thinks it's using
668 // the engine's real engineFactory.
669 void *EngineFactory(const char *iface, int *ret)
671 IFACE_MACRO(g_Engine.engineFactory, Engine);
674 //Wrapper function. This is called when the GameDLL thinks it's using
675 // the engine's real physicsFactory.
676 void *PhysicsFactory(const char *iface, int *ret)
678 IFACE_MACRO(g_Engine.physicsFactory, Physics);
681 //Wrapper function. This is called when the GameDLL thinks it's using
682 // the engine's real fileSystemFactory.
683 void *FileSystemFactory(const char *iface, int *ret)
685 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
688 void LogMessage(const char *msg, ...)
691 static char buffer[2048];
696 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
697 strcat(buffer, "\n");
700 if (!g_Engine.engine)
702 fprintf(stdout, "%s", buffer);
704 g_Engine.engine->LogPrint(buffer);
708 void LevelShutdown_handler(void)
713 g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
715 LoadPluginsFromFile(full_path);
717 bInFirstLevel = false;
720 ITER_EVENT(OnLevelShutdown, ());
722 RETURN_META(MRES_IGNORED);
725 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
727 if (!g_SmmAPI.CacheSuccessful())
729 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
730 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
733 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
735 RETURN_META_VALUE(MRES_IGNORED, false);
738 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
739 void * operator new(size_t size) {
740 return(calloc(1, size));
743 void * operator new[](size_t size) {
744 return(calloc(1, size));
747 void operator delete(void * ptr) {
752 void operator delete[](void * ptr) {