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 * @brief Implementation of main SourceMM GameDLL functionality
25 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
26 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
27 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
28 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
29 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
30 void DLLShutdown_handler();
31 void LevelShutdown_handler();
32 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
34 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
36 SourceHook::CSourceHookImpl g_SourceHook;
37 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
38 SourceHook::String g_ModPath;
39 SourceHook::String g_BinPath;
40 PluginId g_PLID = Pl_Console; //Technically, SourceMM is the "Console" plugin... :p
41 bool bInFirstLevel = true;
42 bool gParsedGameInfo = false;
43 SourceHook::List<GameDllInfo *> gamedll_list;
44 SourceHook::CallClass<IServerGameDLL> *dllExec;
46 void ClearGamedllList();
48 ///////////////////////////////////
49 // Main code for HL2 Interaction //
50 ///////////////////////////////////
52 //Initialize everything here
55 char full_path[260] = {0};
56 GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
57 g_BinPath.assign(full_path);
59 UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
61 //Like metamod, reload plugins at the end of the map.
62 //This is so plugins can hook everything on load, BUT, new plugins will be reloaded
63 // if the server is shut down (silly, but rare case).
66 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
67 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
68 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
69 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
72 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
74 g_Engine.engineFactory = engineFactory;
75 g_Engine.fileSystemFactory = filesystemFactory;
76 g_Engine.physicsFactory = physicsFactory;
77 g_Engine.pGlobals = pGlobals;
79 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
82 Error("Could not find IVEngineServer! Metamod cannot load.");
85 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
88 Error("Could not find ICvar! Metamod cannot load.");
92 g_Engine.loaded = true;
94 //Initialize our console hooks
95 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
97 if (!g_SmmAPI.CacheCmds())
99 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
100 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
104 UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
106 LoadPluginsFromFile(full_path);
108 g_PluginMngr.SetAllLoaded();
110 bInFirstLevel = true;
112 dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
114 RETURN_META_VALUE(MRES_IGNORED, true);
117 //This is where the magic happens
118 SMM_API void *CreateInterface(const char *name, int *ret)
120 if (!gParsedGameInfo)
122 gParsedGameInfo = true;
123 char curpath[260] = {0};
124 char dllpath[260] = {0};
125 getcwd(curpath, sizeof(curpath)-1);
126 if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
128 Error("GetFileOfAddress() failed! Metamod cannot load.");
131 SourceHook::String s_dllpath(dllpath);
132 //begin the heuristics for searching for the mod path (these are quite ugly).
133 //for OS compatibility purposes, we're going to do case insensitivity on windows.
134 size_t path_len = strlen(curpath);
135 size_t dll_len = strlen(dllpath);
137 //strip the dll path off
138 //:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
139 for (size_t i=dll_len-1; i>0; i--)
141 if (dllpath[i] == '\\' || dllpath[i] == '/')
145 //save path by stripping off file name and ending terminator
152 //strip absolute path terminators if any!
153 if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
154 curpath[--path_len] = '\0';
156 //if the base path doesn't fit into the module path, something is wrong!
157 // ex: c:\games\srcds
159 if (path_len > dll_len)
161 Error("Could not detect GameDLL path! Metamod cannot load[1].");
165 //we are now in such a position that the two dir names SHOULD MATCH!
166 typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
174 if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
176 //:TODO: In this case, we should read /proc/self/maps and find srcds!
177 Error("Could not detect GameDLL path! Metamod cannot load[2].");
180 //this will skip past the dir and its separator char
181 char *ptr = &(dllpath[path_len+1]);
182 path_len = strlen(ptr);
183 for (size_t i=0; i<path_len; i++)
185 if (ptr[i] == '/' || ptr[i] == '\\')
189 Error("Could not detect GameDLL path! Metamod cannot load[3].");
198 //WE NOW HAVE A GUESS AT THE MOD DIR. OH MY GOD.
200 snprintf(temp_path, sizeof(temp_path)-1,
206 g_ModPath.assign(temp_path);
208 snprintf(temp_path, sizeof(temp_path)-1,
214 FILE *fp = fopen(temp_path, "rt");
217 Error("Unable to open gameinfo.txt! Metamod cannot load.");
221 char key[128], val[128];
223 const char *gameinfo = "|gameinfo_path|";
224 size_t gameinfo_len = strlen(gameinfo);
226 bool gamebin = false;
231 fgets(buffer, sizeof(buffer)-1, fp);
232 len = strlen(buffer);
233 if (buffer[len-1] == '\n')
234 buffer[--len] = '\0';
235 UTIL_TrimComments(buffer);
236 UTIL_TrimLeft(buffer);
237 UTIL_TrimRight(buffer);
238 if (stricmp(buffer, "SearchPaths") == 0)
242 UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
243 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
245 if (stricmp(key, "Game") == 0)
250 if (strncmp(val, gameinfo, gameinfo_len) == 0)
252 ptr = &(val[gameinfo_len]);
255 lptr = g_ModPath.c_str();
260 size_t ptr_len = strlen(ptr);
261 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
262 ptr[--ptr_len] = '\0';
263 //no need to append "bin"
266 UTIL_PathFmt(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
268 UTIL_PathFmt(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
270 if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
272 FILE *fp = fopen(temp_path, "rb");
275 //:TODO: Optimize this a bit!
276 SourceHook::List<GameDllInfo *>::iterator iter;
279 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
282 if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
284 if (UTIL_PathCmp(temp_path, buffer))
294 HINSTANCE gamedll = dlmount(temp_path);
297 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
303 GameDllInfo *pInfo = new GameDllInfo;
305 pInfo->lib = gamedll;
306 pInfo->loaded = true;
307 pInfo->pGameDLL = NULL;
308 gamedll_list.push_back(pInfo);
315 if (!g_GameDll.loaded)
317 const char *str = "ServerGameDLL";
318 size_t len = strlen(str);
320 if (strncmp(name, str, len) == 0)
322 //This is the interface we want! Right now we support versions 3 and 4.
323 int version = atoi(&(name[len]));
324 if (version < MIN_GAMEDLL_VERSION || version > MAX_GAMEDLL_VERSION)
326 Error("GameDLL version %d is not supported by Metamod!", version);
329 SourceHook::List<GameDllInfo *>::iterator iter;
330 GameDllInfo *pInfo = NULL;
332 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
335 ptr = (pInfo->factory)(name, ret);
338 //this is our gamedll. unload the others.
339 gamedll_list.erase(iter);
341 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
347 if (g_GameDll.loaded)
357 //:TODO: .. something a bit more intelligent?
358 Error("Engine requested unknown interface before GameDLL was known!");
363 //if we got here, there's definitely a gamedll.
364 //META_INTERFACE_MACRO(server, g_GameDll.factory);
365 return (g_GameDll.factory)(name, ret);
368 void ClearGamedllList()
370 SourceHook::List<GameDllInfo *>::iterator iter;
373 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
380 gamedll_list.clear();
383 void DLLShutdown_handler()
386 g_PluginMngr.UnloadAll();
388 // Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
389 g_SMConVarAccessor.MarkCommandsAsGameDLL();
390 g_SMConVarAccessor.UnregisterGameDLLCommands();
392 SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
394 SH_RELEASE_CALLCLASS(dllExec);
397 g_SourceHook.CompleteShutdown();
399 if (g_GameDll.lib && g_GameDll.loaded)
400 dlclose(g_GameDll.lib);
401 memset(&g_GameDll, 0, sizeof(GameDllInfo));
403 RETURN_META(MRES_SUPERCEDE);
406 int LoadPluginsFromFile(const char *file)
409 int total = 0, skipped=0;
413 fp = fopen(file, "rt");
416 LogMessage("[META] Could not open plugins file %s\n", file);
420 char buffer[255], error[255], full_path[128];
421 const char *ptr, *ext;
426 fgets(buffer, sizeof(buffer)-1, fp);
427 length = strlen(buffer);
430 if (buffer[length-1] == '\n')
431 buffer[length-1] = '\0';
433 UTIL_TrimLeft(buffer);
434 UTIL_TrimRight(buffer);
436 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
438 //First find if it's an absolute path or not...
439 if (buffer[0] == '/' || strncmp(&(buffer[1]), ":\\", 2) == 0)
441 //If we're in an absolute path, ignore our normal heuristics
442 id = g_PluginMngr.Load(buffer, Pl_File, already, error, sizeof(error)-1);
443 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
445 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
453 //Attempt to find a file extension
454 ptr = UTIL_GetExtension(buffer);
455 //Add an extension if there's none there
458 #if defined WIN32 || defined _WIN32
466 //Format the new path
467 UTIL_PathFmt(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), buffer, ext);
468 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
469 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
471 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
484 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
486 LogMessage("[META] Loaded %d plugins from file.", total);
492 //Wrapper function. This is called when the GameDLL thinks it's using
493 // the engine's real engineFactory.
494 void *EngineFactory(const char *name, int *ret)
496 META_INTERFACE_MACRO(engine, g_Engine.engineFactory);
499 //Wrapper function. This is called when the GameDLL thinks it's using
500 // the engine's real physicsFactory.
501 void *PhysicsFactory(const char *name, int *ret)
503 META_INTERFACE_MACRO(physics, g_Engine.physicsFactory);
506 //Wrapper function. This is called when the GameDLL thinks it's using
507 // the engine's real fileSystemFactory.
508 void *FileSystemFactory(const char *name, int *ret)
510 META_INTERFACE_MACRO(fileSystem, g_Engine.fileSystemFactory);
513 void LogMessage(const char *msg, ...)
516 static char buffer[2048];
521 vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
522 strcat(buffer, "\n");
525 if (!g_Engine.engine)
527 fprintf(stdout, "%s", buffer);
529 g_Engine.engine->LogPrint(buffer);
533 void LevelShutdown_handler(void)
538 #if defined WIN32 || defined _WIN32
539 snprintf(full_path, sizeof(full_path)-1, "%s\\addons\\metamod\\%s", g_ModPath.c_str(), "metaplugins.ini");
541 snprintf(full_path, sizeof(full_path)-1, "%s/addons/metamod/%s", g_ModPath.c_str(), "metaplugins.ini");
543 LoadPluginsFromFile(full_path);
545 bInFirstLevel = false;
549 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
551 if (!g_SmmAPI.CacheSuccessful())
553 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
554 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
557 RETURN_META_VALUE(MRES_IGNORED, false);
560 #if defined __GNUC__ && (__GNUC__ == 3)
561 void * ::operator new(size_t size) {
562 return(calloc(1, size));
565 void * ::operator new[](size_t size) {
566 return(calloc(1, size));
569 void ::operator delete(void * ptr) {
574 void ::operator delete[](void * ptr) {