3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
34 #include "GameConfigs.h"
35 #include "sm_stringutil.h"
36 #include "sourcemod.h"
37 #include "sourcemm_api.h"
38 #include "HalfLife2.h"
41 #include "MemoryUtils.h"
42 #include "LibrarySys.h"
43 #include "HandleSys.h"
46 #if defined PLATFORM_LINUX
50 GameConfigManager g_GameConfigs;
51 IGameConfig *g_pGameConf = NULL;
52 static char g_Game[256];
53 static char g_GameDesc[256] = {'!', '\0'};
54 static char g_GameName[256] = {'$', '\0'};
57 #define PSTATE_GAMES 1
58 #define PSTATE_GAMEDEFS 2
59 #define PSTATE_GAMEDEFS_OFFSETS 3
60 #define PSTATE_GAMEDEFS_OFFSETS_OFFSET 4
61 #define PSTATE_GAMEDEFS_KEYS 5
62 #define PSTATE_GAMEDEFS_SUPPORTED 6
63 #define PSTATE_GAMEDEFS_SIGNATURES 7
64 #define PSTATE_GAMEDEFS_SIGNATURES_SIG 8
65 #define PSTATE_GAMEDEFS_CRC 9
66 #define PSTATE_GAMEDEFS_CRC_BINARY 10
67 #define PSTATE_GAMEDEFS_CUSTOM 11
69 #if defined PLATFORM_WINDOWS
70 #define PLATFORM_NAME "windows"
71 #define PLATFORM_SERVER_BINARY "server.dll"
72 #elif defined PLATFORM_LINUX
73 #define PLATFORM_NAME "linux"
74 #define PLATFORM_SERVER_BINARY "server_i486.so"
75 #elif defined PLATFORM_APPLE
76 #define PLATFORM_NAME "undef"
77 #define PLATFORM_SERVER_BINARY "undef.dylib"
90 unsigned int s_ServerBinCRC;
91 bool s_ServerBinCRC_Ok = false;
93 static bool DoesGameMatch(const char *value)
95 #if defined PLATFORM_WINDOWS
96 if (strcasecmp(value, g_Game) == 0 ||
98 if (strcmp(value, g_Game) == 0 ||
100 strcmp(value, g_GameDesc) == 0 ||
101 strcmp(value, g_GameName) == 0)
108 static bool DoesEngineMatch(const char *value)
110 #if SOURCE_ENGINE == SE_EPISODEONE
111 if (strcmp(value, "original") == 0)
112 #elif SOURCE_ENGINE == SE_DARKMESSIAH
113 if (strcmp(value, "darkmessiah") == 0)
114 #elif SOURCE_ENGINE == SE_ORANGEBOX
115 if (strcmp(value, "orangebox") == 0)
116 #elif SOURCE_ENGINE == SE_ORANGEBOXVALVE
117 if (strcmp(value, "orangebox_valve") == 0)
118 #elif SOURCE_ENGINE == SE_LEFT4DEAD
119 if (strcmp(value, "left4dead") == 0)
121 #error "Unknown engine type"
129 CGameConfig::CGameConfig(const char *file)
131 strncopy(m_File, file, sizeof(m_File));
132 m_pOffsets = sm_trie_create();
133 m_pProps = sm_trie_create();
134 m_pKeys = sm_trie_create();
135 m_pSigs = sm_trie_create();
136 m_pStrings = new BaseStringTable(512);
140 m_CustomHandler = NULL;
143 CGameConfig::~CGameConfig()
145 sm_trie_destroy(m_pOffsets);
146 sm_trie_destroy(m_pProps);
147 sm_trie_destroy(m_pKeys);
148 sm_trie_destroy(m_pSigs);
152 SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *name)
157 return SMCResult_Continue;
160 switch (m_ParseState)
164 if (strcmp(name, "Games") == 0)
166 m_ParseState = PSTATE_GAMES;
174 if (strcmp(name, "*") == 0 ||
175 strcmp(name, "#default") == 0 ||
178 bShouldBeReadingDefault = true;
179 m_ParseState = PSTATE_GAMEDEFS;
180 strncopy(m_Game, name, sizeof(m_Game));
186 case PSTATE_GAMEDEFS:
188 if (strcmp(name, "Offsets") == 0)
190 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
192 else if (strcmp(name, "Keys") == 0)
194 m_ParseState = PSTATE_GAMEDEFS_KEYS;
196 else if ((strcmp(name, "#supported") == 0) && (strcmp(m_Game, "#default") == 0))
198 m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
199 /* Ignore this section unless we get a game. */
200 bShouldBeReadingDefault = false;
202 matched_game = false;
204 matched_engine = false;
206 else if (strcmp(name, "Signatures") == 0)
208 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
210 else if (strcmp(name, "CRC") == 0)
212 m_ParseState = PSTATE_GAMEDEFS_CRC;
213 bShouldBeReadingDefault = false;
217 ITextListener_SMC **pListen = g_GameConfigs.m_customHandlers.retrieve(name);
222 m_ParseState = PSTATE_GAMEDEFS_CUSTOM;
223 m_CustomHandler = *pListen;
224 m_CustomHandler->ReadSMC_ParseStart();
232 case PSTATE_GAMEDEFS_OFFSETS:
236 strncopy(m_offset, name, sizeof(m_offset));
237 m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
240 case PSTATE_GAMEDEFS_SIGNATURES:
242 strncopy(m_offset, name, sizeof(m_offset));
244 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
247 case PSTATE_GAMEDEFS_CRC:
251 if (strcmp(name, "server") != 0)
253 UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
255 else if (!s_ServerBinCRC_Ok)
258 char path[PLATFORM_MAX_PATH];
260 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
261 if ((fp = fopen(path, "rb")) == NULL)
263 UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
268 fseek(fp, 0, SEEK_END);
270 fseek(fp, 0, SEEK_SET);
272 buffer = malloc(size);
273 fread(buffer, size, 1, fp);
274 s_ServerBinCRC = UTIL_CRC32(buffer, size);
276 s_ServerBinCRC_Ok = true;
280 if (error[0] != '\0')
283 g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_CurFile);
284 g_Logger.LogError("[SM] %s", error);
286 m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
290 case PSTATE_GAMEDEFS_CUSTOM:
293 return m_CustomHandler->ReadSMC_NewSection(states, name);
296 /* No sub-sections allowed:
297 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
298 case PSTATE_GAMEDEFS_KEYS:
299 case PSTATE_GAMEDEFS_SUPPORTED:
300 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
301 case PSTATE_GAMEDEFS_CRC_BINARY:
305 /* If we don't know what we got, start ignoring */
311 return SMCResult_Continue;
314 SMCResult CGameConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
318 return SMCResult_Continue;
321 if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
323 if (strcmp(key, "class") == 0)
325 strncopy(m_Class, value, sizeof(m_Class));
326 } else if (strcmp(key, "prop") == 0) {
327 strncopy(m_Prop, value, sizeof(m_Prop));
328 } else if (strcmp(key, PLATFORM_NAME) == 0) {
329 int val = atoi(value);
330 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
332 } else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
333 int id = m_pStrings->AddString(value);
334 sm_trie_replace(m_pKeys, key, (void *)id);
335 } else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
336 if (strcmp(key, "game") == 0)
339 if (DoesGameMatch(value))
343 if ((!had_engine && matched_game) || (matched_engine && matched_game))
345 bShouldBeReadingDefault = true;
348 else if (strcmp(key, "engine") == 0)
351 if (DoesEngineMatch(value))
353 matched_engine = true;
355 if ((!had_game && matched_engine) || (matched_game && matched_engine))
357 bShouldBeReadingDefault = true;
360 } else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
361 if (strcmp(key, PLATFORM_NAME) == 0)
363 strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
364 } else if (strcmp(key, "library") == 0) {
365 strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
367 } else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
368 if (strcmp(key, PLATFORM_NAME) == 0
370 && !bShouldBeReadingDefault)
372 unsigned int crc = 0;
373 sscanf(value, "%08X", &crc);
374 if (s_ServerBinCRC == crc)
376 bShouldBeReadingDefault = true;
379 } else if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM) {
380 return m_CustomHandler->ReadSMC_KeyValue(states, key, value);
383 return SMCResult_Continue;
386 SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states)
391 return SMCResult_Continue;
397 m_CustomHandler->ReadSMC_LeavingSection(states);
398 return SMCResult_Continue;
401 switch (m_ParseState)
405 m_ParseState = PSTATE_NONE;
408 case PSTATE_GAMEDEFS:
410 m_ParseState = PSTATE_GAMES;
413 case PSTATE_GAMEDEFS_CUSTOM:
415 m_ParseState = PSTATE_GAMEDEFS;
416 m_CustomHandler->ReadSMC_ParseEnd(false, false);
419 case PSTATE_GAMEDEFS_KEYS:
420 case PSTATE_GAMEDEFS_OFFSETS:
422 m_ParseState = PSTATE_GAMEDEFS;
425 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
427 /* Parse the offset... */
428 if (m_Class[0] != '\0'
429 && m_Prop[0] != '\0')
431 SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
434 int val = pProp->GetOffset();
435 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
436 sm_trie_replace(m_pProps, m_offset, pProp);
438 /* Check if it's a non-default game and no offsets exist */
439 if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
440 && (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
442 g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")",
450 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
453 case PSTATE_GAMEDEFS_CRC:
454 case PSTATE_GAMEDEFS_SUPPORTED:
456 if (!bShouldBeReadingDefault)
458 /* If we shouldn't read the rest of this section, set the ignore level. */
460 m_ParseState = PSTATE_GAMES;
462 m_ParseState = PSTATE_GAMEDEFS;
466 case PSTATE_GAMEDEFS_CRC_BINARY:
468 m_ParseState = PSTATE_GAMEDEFS_CRC;
471 case PSTATE_GAMEDEFS_SIGNATURES:
473 m_ParseState = PSTATE_GAMEDEFS;
476 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
478 if (s_TempSig.library[0] == '\0')
481 strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
483 void *addrInBase = NULL;
484 if (strcmp(s_TempSig.library, "server") == 0)
486 addrInBase = (void *)g_SMAPI->GetServerFactory(false);
487 } else if (strcmp(s_TempSig.library, "engine") == 0) {
488 addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
490 void *final_addr = NULL;
491 if (addrInBase == NULL)
493 g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")",
497 #if defined PLATFORM_LINUX
498 if (s_TempSig.sig[0] == '@')
501 /* GNU only: returns 0 on error, inconsistent! >:[ */
502 if (dladdr(addrInBase, &info) != 0)
504 void *handle = dlopen(info.dli_fname, RTLD_NOW);
507 final_addr = dlsym(handle, &s_TempSig.sig[1]);
510 g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
515 g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
525 /* First, preprocess the signature */
526 unsigned char real_sig[511];
531 length = strlen(s_TempSig.sig);
533 real_bytes = UTIL_DecodeHexString(real_sig, sizeof(real_sig), s_TempSig.sig);
537 final_addr = g_MemUtils.FindPattern(addrInBase, (char*)real_sig, real_bytes);
541 #if defined PLATFORM_LINUX
544 sm_trie_replace(m_pSigs, m_offset, final_addr);
545 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
551 return SMCResult_Continue;
554 #define MSTATE_NONE 0
555 #define MSTATE_MAIN 1
556 #define MSTATE_FILE 2
558 class MasterReader : public ITextListener_SMC
561 virtual void ReadSMC_ParseStart()
567 virtual SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
571 return SMCResult_Continue;
574 if (state == MSTATE_NONE)
576 if (strcmp(name, "Game Master") == 0)
585 else if (state == MSTATE_MAIN)
587 strncopy(cur_file, name, sizeof(cur_file));
589 matched_engine = false;
591 matched_game = false;
594 else if (state == MSTATE_FILE)
599 return SMCResult_Continue;
602 virtual SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
604 if (ignoreLevel || state != MSTATE_FILE)
606 return SMCResult_Continue;
609 if (strcmp(key, "engine") == 0)
612 if (DoesEngineMatch(value))
614 matched_engine = true;
617 else if (strcmp(key, "game") == 0)
620 if (DoesGameMatch(value))
626 return SMCResult_Continue;
629 virtual SMCResult ReadSMC_LeavingSection(const SMCStates *states)
634 return SMCResult_Continue;
637 if (state == MSTATE_FILE)
639 /* The four success conditions:
641 * 2. Needed game only.
642 * 3. Needed engine only.
643 * 4. Needed both engine and game.
644 * Final result is minimized via k-map.
647 if ((!had_engine && !had_game) ||
648 (!had_engine && (had_game && matched_game)) ||
649 (!had_game && (had_engine && matched_engine)) ||
650 ((had_game && had_engine) && (matched_game && matched_engine)))
652 if ((!had_engine && !had_game) ||
653 (!had_engine && matched_game) ||
654 (!had_game && matched_engine) ||
655 (matched_engine && matched_game))
657 fileList->push_back(cur_file);
661 else if (state == MSTATE_MAIN)
666 return SMCResult_Continue;
669 List<String> *fileList;
671 unsigned int ignoreLevel;
672 char cur_file[PLATFORM_MAX_PATH];
679 static MasterReader master_reader;
681 bool CGameConfig::Reparse(char *error, size_t maxlength)
683 /* Reset cached data */
685 sm_trie_clear(m_pOffsets);
686 sm_trie_clear(m_pProps);
687 sm_trie_clear(m_pKeys);
689 char path[PLATFORM_MAX_PATH];
691 /* See if we can use the extended gamedata format. */
692 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/master.games.txt", m_File);
693 if (!g_LibSys.PathExists(path))
695 /* Nope, use the old mechanism. */
696 UTIL_Format(path, sizeof(path), "%s.txt", m_File);
697 return EnterFile(path, error, maxlength);
700 /* Otherwise, it's time to parse the master. */
702 SMCStates state = {0, 0};
703 List<String> fileList;
704 master_reader.fileList = &fileList;
706 err = textparsers->ParseSMCFile(path, &master_reader, &state, error, maxlength);
707 if (err != SMCError_Okay)
709 const char *msg = textparsers->GetSMCErrorString(err);
711 g_Logger.LogError("[SM] Error parsing master gameconf file \"%s\":", path);
712 g_Logger.LogError("[SM] Error %d on line %d, col %d: %s",
716 msg ? msg : "Unknown error");
720 /* Go through each file we found and parse it. */
721 List<String>::iterator iter;
722 for (iter = fileList.begin(); iter != fileList.end(); iter++)
724 UTIL_Format(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
725 if (!EnterFile(path, error, maxlength))
731 /* Parse the contents of the 'custom' directory */
732 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/custom", m_File);
733 IDirectory *customDir = g_LibSys.OpenDirectory(path);
740 while (customDir->MoreFiles())
742 if (!customDir->IsEntryFile())
744 customDir->NextEntry();
748 const char *curFile = customDir->GetEntryName();
750 /* Only allow .txt files */
751 int len = strlen(curFile);
752 if (len > 4 && strcmp(&curFile[len-4], ".txt") != 0)
754 customDir->NextEntry();
758 UTIL_Format(path, sizeof(path), "%s/custom/%s", m_File, curFile);
759 if (!EnterFile(path, error, maxlength))
761 g_LibSys.CloseDirectory(customDir);
765 customDir->NextEntry();
768 g_LibSys.CloseDirectory(customDir);
772 bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength)
775 SMCStates state = {0, 0};
777 g_SourceMod.BuildPath(Path_SM, m_CurFile, sizeof(m_CurFile), "gamedata/%s", file);
779 /* Initialize parse states */
781 bShouldBeReadingDefault = true;
782 m_ParseState = PSTATE_NONE;
784 if ((err=textparsers->ParseSMCFile(m_CurFile, this, &state, error, maxlength))
789 msg = textparsers->GetSMCErrorString(err);
791 g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile);
792 g_Logger.LogError("[SM] Error %d on line %d, col %d: %s",
796 msg ? msg : "Unknown error");
798 if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
800 //error occurred while parsing a custom section
801 m_CustomHandler->ReadSMC_ParseEnd(true, true);
802 m_CustomHandler = NULL;
812 bool CGameConfig::GetOffset(const char *key, int *value)
816 if (!sm_trie_retrieve(m_pOffsets, key, &obj))
826 const char *CGameConfig::GetKeyValue(const char *key)
829 if (!sm_trie_retrieve(m_pKeys, key, &obj))
833 return m_pStrings->GetString((int)obj);
836 SendProp *CGameConfig::GetSendProp(const char *key)
840 if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
848 bool CGameConfig::GetMemSig(const char *key, void **addr)
850 return sm_trie_retrieve(m_pSigs, key, addr);
853 void CGameConfig::IncRefCount()
858 unsigned int CGameConfig::DecRefCount()
864 GameConfigManager::GameConfigManager()
866 m_pLookup = sm_trie_create();
869 GameConfigManager::~GameConfigManager()
871 sm_trie_destroy(m_pLookup);
874 void GameConfigManager::OnSourceModStartup(bool late)
876 LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
878 strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
879 strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
881 KeyValues *pGameInfo = new KeyValues("GameInfo");
882 if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
885 if ((str = pGameInfo->GetString("game", NULL)) != NULL)
887 strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
890 pGameInfo->deleteThis();
893 void GameConfigManager::OnSourceModAllInitialized()
895 /* NOW initialize the game file */
896 CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
899 if (!pGameConf->Reparse(error, sizeof(error)))
904 g_ShareSys.AddInterface(NULL, this);
907 void GameConfigManager::OnSourceModAllShutdown()
909 CloseGameConfigFile(g_pGameConf);
912 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
915 /* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
916 if (g_blockGameDataLoad)
918 UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
923 CGameConfig *pConfig;
925 if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
927 pConfig->IncRefCount();
932 pConfig = new CGameConfig(file);
934 /* :HACKHACK: Don't parse the main config file */
936 if (_pConfig != &g_pGameConf)
938 retval = pConfig->Reparse(error, maxlength);
941 m_cfgs.push_back(pConfig);
942 sm_trie_insert(m_pLookup, file, pConfig);
944 pConfig->IncRefCount();
951 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
953 CGameConfig *pConfig = (CGameConfig *)cfg;
955 if (pConfig->DecRefCount() == 0)
957 sm_trie_delete(m_pLookup, pConfig->m_File);
962 extern HandleType_t g_GameConfigsType;
964 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
966 HandleSecurity sec(ident, g_pCoreIdent);
967 IGameConfig *conf = NULL;
968 HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
978 void GameConfigManager::AddUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
980 m_customHandlers.insert(sectionname, listener);
983 void GameConfigManager::RemoveUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
985 ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
987 if (pListener == NULL)
992 if (*pListener != listener)
997 m_customHandlers.remove(sectionname);
1002 void GameConfigManager::AcquireLock()
1006 void GameConfigManager::ReleaseLock()