3 * =============================================================================
5 * Copyright (C) 2004-2007 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 "TextParsers.h"
36 #include "sm_stringutil.h"
37 #include "sourcemod.h"
38 #include "sourcemm_api.h"
39 #include "HalfLife2.h"
42 #include "MemoryUtils.h"
43 #include "LibrarySys.h"
44 #include "HandleSys.h"
47 #if defined PLATFORM_LINUX
51 GameConfigManager g_GameConfigs;
52 IGameConfig *g_pGameConf = NULL;
54 char g_GameDesc[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
68 #if defined PLATFORM_WINDOWS
69 #define PLATFORM_NAME "windows"
70 #define PLATFORM_SERVER_BINARY "server.dll"
71 #elif defined PLATFORM_LINUX
72 #define PLATFORM_NAME "linux"
73 #define PLATFORM_SERVER_BINARY "server_i486.so"
86 unsigned int s_ServerBinCRC;
87 bool s_ServerBinCRC_Ok = false;
89 CGameConfig::CGameConfig(const char *file)
91 m_pFile = sm_strdup(file);
92 m_pOffsets = sm_trie_create();
93 m_pProps = sm_trie_create();
94 m_pKeys = sm_trie_create();
95 m_pSigs = sm_trie_create();
96 m_pStrings = new BaseStringTable(512);
100 CGameConfig::~CGameConfig()
102 sm_trie_destroy(m_pOffsets);
103 sm_trie_destroy(m_pProps);
104 sm_trie_destroy(m_pKeys);
105 sm_trie_destroy(m_pSigs);
110 SMCParseResult CGameConfig::ReadSMC_NewSection(const char *name, bool opt_quotes)
115 return SMCParse_Continue;
118 switch (m_ParseState)
122 if (strcmp(name, "Games") == 0)
124 m_ParseState = PSTATE_GAMES;
132 if ((strcmp(name, "*") == 0)
133 || (strcmp(name, "#default") == 0)
134 || (strcasecmp(name, g_Game) == 0)
135 || (strcasecmp(name, g_GameDesc) == 0))
137 bShouldBeReadingDefault = true;
138 m_ParseState = PSTATE_GAMEDEFS;
139 strncopy(m_Game, name, sizeof(m_Game));
145 case PSTATE_GAMEDEFS:
147 if (strcmp(name, "Offsets") == 0)
149 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
151 else if (strcmp(name, "Keys") == 0)
153 m_ParseState = PSTATE_GAMEDEFS_KEYS;
155 else if ((strcmp(name, "#supported") == 0)
156 && (strcmp(m_Game, "#default") == 0))
158 m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
159 /* Ignore this section unless we get a game. */
160 bShouldBeReadingDefault = false;
162 else if (strcmp(name, "Signatures") == 0)
164 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
166 else if (strcmp(name, "CRC") == 0)
168 m_ParseState = PSTATE_GAMEDEFS_CRC;
169 bShouldBeReadingDefault = false;
177 case PSTATE_GAMEDEFS_OFFSETS:
181 strncopy(m_offset, name, sizeof(m_offset));
182 m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
185 case PSTATE_GAMEDEFS_SIGNATURES:
187 strncopy(m_offset, name, sizeof(m_offset));
189 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
192 case PSTATE_GAMEDEFS_CRC:
196 if (strcmp(name, "server") != 0)
198 UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
200 else if (!s_ServerBinCRC_Ok)
203 char path[PLATFORM_MAX_PATH];
205 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
206 if ((fp = fopen(path, "rb")) == NULL)
208 UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
213 fseek(fp, 0, SEEK_END);
215 fseek(fp, 0, SEEK_SET);
217 buffer = malloc(size);
218 fread(buffer, size, 1, fp);
219 s_ServerBinCRC = UTIL_CRC32(buffer, size);
221 s_ServerBinCRC_Ok = true;
224 if (error[0] != '\0')
227 g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_pFile);
228 g_Logger.LogError("[SM] %s", error);
230 m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
234 /* No sub-sections allowed:
235 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
236 case PSTATE_GAMEDEFS_KEYS:
237 case PSTATE_GAMEDEFS_SUPPORTED:
238 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
239 case PSTATE_GAMEDEFS_CRC_BINARY:
243 /* If we don't know what we got, start ignoring */
249 return SMCParse_Continue;
252 SMCParseResult CGameConfig::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
256 return SMCParse_Continue;
259 if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
261 if (strcmp(key, "class") == 0)
263 strncopy(m_Class, value, sizeof(m_Class));
264 } else if (strcmp(key, "prop") == 0) {
265 strncopy(m_Prop, value, sizeof(m_Prop));
266 } else if (strcmp(key, PLATFORM_NAME) == 0) {
267 int val = atoi(value);
268 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
270 } else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
271 int id = m_pStrings->AddString(value);
272 sm_trie_replace(m_pKeys, key, (void *)id);
273 } else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
274 if (strcmp(key, "game") == 0
275 && (strcasecmp(value, g_Game) == 0 || strcasecmp(value, g_GameDesc) == 0))
277 bShouldBeReadingDefault = true;
279 } else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
280 if (strcmp(key, PLATFORM_NAME) == 0)
282 strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
283 } else if (strcmp(key, "library") == 0) {
284 strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
286 } else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
287 if (strcmp(key, PLATFORM_NAME) == 0
289 && !bShouldBeReadingDefault)
291 unsigned int crc = 0;
292 sscanf(value, "%08X", &crc);
293 if (s_ServerBinCRC == crc)
295 bShouldBeReadingDefault = true;
300 return SMCParse_Continue;
303 SMCParseResult CGameConfig::ReadSMC_LeavingSection()
308 return SMCParse_Continue;
311 switch (m_ParseState)
315 m_ParseState = PSTATE_NONE;
318 case PSTATE_GAMEDEFS:
320 m_ParseState = PSTATE_GAMES;
323 case PSTATE_GAMEDEFS_KEYS:
324 case PSTATE_GAMEDEFS_OFFSETS:
326 m_ParseState = PSTATE_GAMEDEFS;
329 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
331 /* Parse the offset... */
332 if (m_Class[0] != '\0'
333 && m_Prop[0] != '\0')
335 SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
338 int val = pProp->GetOffset();
339 sm_trie_replace(m_pOffsets, m_offset, (void *)val);
340 sm_trie_replace(m_pProps, m_offset, pProp);
342 /* Check if it's a non-default game and no offsets exist */
343 if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
344 && (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
346 g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")",
354 m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
357 case PSTATE_GAMEDEFS_CRC:
358 case PSTATE_GAMEDEFS_SUPPORTED:
360 if (!bShouldBeReadingDefault)
362 /* If we shouldn't read the rest of this section, set the ignore level. */
364 m_ParseState = PSTATE_GAMES;
366 m_ParseState = PSTATE_GAMEDEFS;
370 case PSTATE_GAMEDEFS_CRC_BINARY:
372 m_ParseState = PSTATE_GAMEDEFS_CRC;
375 case PSTATE_GAMEDEFS_SIGNATURES:
377 m_ParseState = PSTATE_GAMEDEFS;
380 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
382 if (s_TempSig.library[0] == '\0')
385 strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
387 void *addrInBase = NULL;
388 if (strcmp(s_TempSig.library, "server") == 0)
390 addrInBase = (void *)g_SMAPI->serverFactory(false);
391 } else if (strcmp(s_TempSig.library, "engine") == 0) {
392 addrInBase = (void *)g_SMAPI->engineFactory(false);
394 void *final_addr = NULL;
395 if (addrInBase == NULL)
397 g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")",
401 #if defined PLATFORM_LINUX
402 if (s_TempSig.sig[0] == '@')
405 /* GNU only: returns 0 on error, inconsistent! >:[ */
406 if (dladdr(addrInBase, &info) != 0)
408 void *handle = dlopen(info.dli_fname, RTLD_NOW);
411 final_addr = dlsym(handle, &s_TempSig.sig[1]);
414 g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
419 g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
429 /* First, preprocess the signature */
435 length = strlen(s_TempSig.sig);
437 for (size_t i=0; i<length; i++)
439 if (real_bytes >= sizeof(real_sig))
443 real_sig[real_bytes++] = s_TempSig.sig[i];
444 if (s_TempSig.sig[i] == '\\'
445 && s_TempSig.sig[i+1] == 'x')
451 /* Get the hex part */
454 s_byte[0] = s_TempSig.sig[i+2];
455 s_byte[1] = s_TempSig.sig[i+3];
457 /* Read it as an integer */
458 sscanf(s_byte, "%x", &r_byte);
460 real_sig[real_bytes-1] = r_byte;
468 final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
472 #if defined PLATFORM_LINUX
475 sm_trie_replace(m_pSigs, m_offset, final_addr);
476 m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
482 return SMCParse_Continue;
485 bool CGameConfig::Reparse(char *error, size_t maxlength)
489 char path[PLATFORM_MAX_PATH];
490 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s.txt", m_pFile);
491 /* Backwards compatibility */
492 if (!g_LibSys.PathExists(path))
494 g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/gamedata/%s.txt", m_pFile);
497 /* Initialize parse states */
499 bShouldBeReadingDefault = true;
500 m_ParseState = PSTATE_NONE;
501 /* Reset cached data */
503 sm_trie_clear(m_pOffsets);
504 sm_trie_clear(m_pProps);
505 sm_trie_clear(m_pKeys);
507 if ((err=g_TextParser.ParseFile_SMC(path, this, NULL, NULL))
510 if (error && (err != SMCParse_Custom))
512 const char *str = g_TextParser.GetSMCErrorString(err);
513 snprintf(error, maxlength, "%s", str);
521 bool CGameConfig::GetOffset(const char *key, int *value)
525 if (!sm_trie_retrieve(m_pOffsets, key, &obj))
535 const char *CGameConfig::GetKeyValue(const char *key)
538 if (!sm_trie_retrieve(m_pKeys, key, &obj))
542 return m_pStrings->GetString((int)obj);
545 SendProp *CGameConfig::GetSendProp(const char *key)
549 if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
557 bool CGameConfig::GetMemSig(const char *key, void **addr)
559 return sm_trie_retrieve(m_pSigs, key, addr);
562 void CGameConfig::IncRefCount()
567 unsigned int CGameConfig::DecRefCount()
573 GameConfigManager::GameConfigManager()
575 m_pLookup = sm_trie_create();
578 GameConfigManager::~GameConfigManager()
580 sm_trie_destroy(m_pLookup);
583 void GameConfigManager::OnSourceModStartup(bool late)
585 LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
587 strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
588 strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
591 void GameConfigManager::OnSourceModAllInitialized()
593 /* NOW initialize the game file */
594 CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
597 if (!pGameConf->Reparse(error, sizeof(error)))
602 g_ShareSys.AddInterface(NULL, this);
605 void GameConfigManager::OnSourceModAllShutdown()
607 CloseGameConfigFile(g_pGameConf);
610 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
612 CGameConfig *pConfig;
614 if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
616 pConfig->IncRefCount();
621 pConfig = new CGameConfig(file);
623 /* :HACKHACK: Don't parse the main config file */
625 if (_pConfig != &g_pGameConf)
627 retval = pConfig->Reparse(error, maxlength);
630 m_cfgs.push_back(pConfig);
631 sm_trie_insert(m_pLookup, file, pConfig);
633 pConfig->IncRefCount();
640 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
642 CGameConfig *pConfig = (CGameConfig *)cfg;
644 if (pConfig->DecRefCount() == 0)
646 sm_trie_delete(m_pLookup, pConfig->m_pFile);
651 extern HandleType_t g_GameConfigsType;
653 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
655 HandleSecurity sec(ident, g_pCoreIdent);
656 IGameConfig *conf = NULL;
657 HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);