core/GameConfigs.cpp
author David Anderson <dvander@alliedmods.net>
Tue May 12 19:06:57 2009 -0400 (2009-05-12)
changeset 2723 d8cde305bb14
parent 2628 541e48653064
child 2768 939a96921719
permissions -rw-r--r--
Central place to mark releases so buildbot symbols aren't scrapped by purge script (bug 3809, r=me, a12=NPOTB).
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <string.h>
    33 #include <stdlib.h>
    34 #include "GameConfigs.h"
    35 #include "sm_stringutil.h"
    36 #include "sourcemod.h"
    37 #include "sourcemm_api.h"
    38 #include "HalfLife2.h"
    39 #include "Logger.h"
    40 #include "ShareSys.h"
    41 #include "MemoryUtils.h"
    42 #include "LibrarySys.h"
    43 #include "HandleSys.h"
    44 #include "sm_crc32.h"
    45 
    46 #if defined PLATFORM_LINUX
    47 #include <dlfcn.h>
    48 #endif
    49 
    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'};
    55 
    56 #define PSTATE_NONE						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
    68 
    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"
    78 #endif
    79 
    80 struct TempSigInfo
    81 {
    82 	void Reset()
    83 	{
    84 		library[0] = '\0';
    85 		sig[0] = '\0';
    86 	}
    87 	char sig[512];
    88 	char library[64];
    89 } s_TempSig;
    90 unsigned int s_ServerBinCRC;
    91 bool s_ServerBinCRC_Ok = false;
    92 
    93 static bool DoesGameMatch(const char *value)
    94 {
    95 	if (strcmp(value, g_Game) == 0 ||
    96 		strcmp(value, g_GameDesc) == 0 ||
    97 		strcmp(value, g_GameName) == 0)
    98 	{
    99 		return true;
   100 	}
   101 	return false;
   102 }
   103 
   104 static bool DoesEngineMatch(const char *value)
   105 {
   106 #if SOURCE_ENGINE == SE_EPISODEONE
   107 	if (strcmp(value, "original") == 0)
   108 #elif SOURCE_ENGINE == SE_DARKMESSIAH
   109 	if (strcmp(value, "darkmessiah") == 0)
   110 #elif SOURCE_ENGINE == SE_ORANGEBOX
   111 	if (strcmp(value, "orangebox") == 0)
   112 #elif SOURCE_ENGINE == SE_LEFT4DEAD
   113 	if (strcmp(value, "left4dead") == 0)
   114 #else
   115 #error "Unknown engine type"
   116 #endif
   117 	{
   118 		return true;
   119 	}
   120 	return false;
   121 }
   122 
   123 CGameConfig::CGameConfig(const char *file)
   124 {
   125 	strncopy(m_File, file, sizeof(m_File));
   126 	m_pOffsets = sm_trie_create();
   127 	m_pProps = sm_trie_create();
   128 	m_pKeys = sm_trie_create();
   129 	m_pSigs = sm_trie_create();
   130 	m_pStrings = new BaseStringTable(512);
   131 	m_RefCount = 0;
   132 
   133 	m_CustomLevel = 0;
   134 	m_CustomHandler = NULL;
   135 }
   136 
   137 CGameConfig::~CGameConfig()
   138 {
   139 	sm_trie_destroy(m_pOffsets);
   140 	sm_trie_destroy(m_pProps);
   141 	sm_trie_destroy(m_pKeys);
   142 	sm_trie_destroy(m_pSigs);
   143 	delete m_pStrings;
   144 }
   145 
   146 SMCResult CGameConfig::ReadSMC_NewSection(const SMCStates *states, const char *name)
   147 {
   148 	if (m_IgnoreLevel)
   149 	{
   150 		m_IgnoreLevel++;
   151 		return SMCResult_Continue;
   152 	}
   153 
   154 	switch (m_ParseState)
   155 	{
   156 	case PSTATE_NONE:
   157 		{
   158 			if (strcmp(name, "Games") == 0)
   159 			{
   160 				m_ParseState = PSTATE_GAMES;
   161 			} else {
   162 				m_IgnoreLevel++;
   163 			}
   164 			break;
   165 		}
   166 	case PSTATE_GAMES:
   167 		{
   168 			if (strcmp(name, "*") == 0 ||
   169 				strcmp(name, "#default") == 0 ||
   170 				DoesGameMatch(name))
   171 			{
   172 				bShouldBeReadingDefault = true;
   173 				m_ParseState = PSTATE_GAMEDEFS;
   174 				strncopy(m_Game, name, sizeof(m_Game));
   175 			} else {
   176 				m_IgnoreLevel++;
   177 			}
   178 			break;
   179 		}
   180 	case PSTATE_GAMEDEFS:
   181 		{
   182 			if (strcmp(name, "Offsets") == 0)
   183 			{
   184 				m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   185 			}
   186 			else if (strcmp(name, "Keys") == 0)
   187 			{
   188 				m_ParseState = PSTATE_GAMEDEFS_KEYS;
   189 			}
   190 			else if ((strcmp(name, "#supported") == 0) && (strcmp(m_Game, "#default") == 0))
   191 			{
   192 				m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
   193 				/* Ignore this section unless we get a game. */
   194 				bShouldBeReadingDefault = false;
   195 				had_game = false;
   196 				matched_game = false;
   197 				had_engine = false;
   198 				matched_engine = false;
   199 			}
   200 			else if (strcmp(name, "Signatures") == 0)
   201 			{
   202 				m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   203 			}
   204 			else if (strcmp(name, "CRC") == 0)
   205 			{
   206 				m_ParseState = PSTATE_GAMEDEFS_CRC;
   207 				bShouldBeReadingDefault = false;
   208 			}
   209 			else
   210 			{
   211 				ITextListener_SMC **pListen = g_GameConfigs.m_customHandlers.retrieve(name);
   212 
   213 				if (pListen != NULL)
   214 				{
   215 					m_CustomLevel = 0;
   216 					m_ParseState = PSTATE_GAMEDEFS_CUSTOM;
   217 					m_CustomHandler = *pListen;
   218 					m_CustomHandler->ReadSMC_ParseStart();
   219 					break;
   220 				}
   221 
   222 				m_IgnoreLevel++;
   223 			}
   224 			break;
   225 		}
   226 	case PSTATE_GAMEDEFS_OFFSETS:
   227 		{
   228 			m_Prop[0] = '\0';
   229 			m_Class[0] = '\0';
   230 			strncopy(m_offset, name, sizeof(m_offset));
   231 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
   232 			break;
   233 		}
   234 	case PSTATE_GAMEDEFS_SIGNATURES:
   235 		{
   236 			strncopy(m_offset, name, sizeof(m_offset));
   237 			s_TempSig.Reset();
   238 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
   239 			break;
   240 		}
   241 	case PSTATE_GAMEDEFS_CRC:
   242 		{
   243 			char error[255];
   244 			error[0] = '\0';
   245 			if (strcmp(name, "server") != 0)
   246 			{
   247 				UTIL_Format(error, sizeof(error), "Unrecognized library \"%s\"", name);
   248 			} 
   249 			else if (!s_ServerBinCRC_Ok)
   250 			{
   251 				FILE *fp;
   252 				char path[PLATFORM_MAX_PATH];
   253 
   254 				g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "bin/" PLATFORM_SERVER_BINARY);
   255 				if ((fp = fopen(path, "rb")) == NULL)
   256 				{
   257 					UTIL_Format(error, sizeof(error), "Could not open binary: %s", path);
   258 				} else {
   259 					size_t size;
   260 					void *buffer;
   261 
   262 					fseek(fp, 0, SEEK_END);
   263 					size = ftell(fp);
   264 					fseek(fp, 0, SEEK_SET);
   265 
   266 					buffer = malloc(size);
   267 					fread(buffer, size, 1, fp);
   268 					s_ServerBinCRC = UTIL_CRC32(buffer, size);
   269 					free(buffer);
   270 					s_ServerBinCRC_Ok = true;
   271 					fclose(fp);
   272 				}
   273 			}
   274 			if (error[0] != '\0')
   275 			{
   276 				m_IgnoreLevel = 1;
   277 				g_Logger.LogError("[SM] Error while parsing CRC section for \"%s\" (%s):", m_Game, m_CurFile);
   278 				g_Logger.LogError("[SM] %s", error);
   279 			} else {
   280 				m_ParseState = PSTATE_GAMEDEFS_CRC_BINARY;
   281 			}
   282 			break;
   283 		}
   284 	case PSTATE_GAMEDEFS_CUSTOM:
   285 		{
   286 			m_CustomLevel++;
   287 			return m_CustomHandler->ReadSMC_NewSection(states, name);
   288 			break;
   289 		}
   290 	/* No sub-sections allowed:
   291 	 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   292 	 case PSTATE_GAMEDEFS_KEYS:
   293 	 case PSTATE_GAMEDEFS_SUPPORTED:
   294 	 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   295 	 case PSTATE_GAMEDEFS_CRC_BINARY:
   296 	 */
   297 	default:
   298 		{
   299 			/* If we don't know what we got, start ignoring */
   300 			m_IgnoreLevel++;
   301 			break;
   302 		}
   303 	}
   304 
   305 	return SMCResult_Continue;
   306 }
   307 
   308 SMCResult CGameConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   309 {
   310 	if (m_IgnoreLevel)
   311 	{
   312 		return SMCResult_Continue;
   313 	}
   314 
   315 	if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
   316 	{
   317 		if (strcmp(key, "class") == 0)
   318 		{
   319 			strncopy(m_Class, value, sizeof(m_Class));
   320 		} else if (strcmp(key, "prop") == 0) {
   321 			strncopy(m_Prop, value, sizeof(m_Prop));
   322 		} else if (strcmp(key, PLATFORM_NAME) == 0) {
   323 			int val = atoi(value);
   324 			sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   325 		}
   326 	} else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
   327 		int id = m_pStrings->AddString(value);
   328 		sm_trie_replace(m_pKeys, key, (void *)id);
   329 	} else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
   330 		if (strcmp(key, "game") == 0)
   331 		{
   332 			had_game = true;
   333 			if (DoesGameMatch(value))
   334 			{
   335 				matched_game = true;
   336 			}
   337 			if ((!had_engine && matched_game) || (matched_engine && matched_game))
   338 			{
   339 				bShouldBeReadingDefault = true;
   340 			}
   341 		}
   342 		else if (strcmp(key, "engine") == 0)
   343 		{
   344 			had_engine = true;
   345 			if (DoesEngineMatch(value))
   346 			{
   347 				matched_engine = true;
   348 			}
   349 			if ((!had_game && matched_engine) || (matched_game && matched_engine))
   350 			{
   351 				bShouldBeReadingDefault = true;
   352 			}
   353 		}
   354 	} else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
   355 		if (strcmp(key, PLATFORM_NAME) == 0)
   356 		{
   357 			strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
   358 		} else if (strcmp(key, "library") == 0) {
   359 			strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
   360 		}
   361 	} else if (m_ParseState == PSTATE_GAMEDEFS_CRC_BINARY) {
   362 		if (strcmp(key, PLATFORM_NAME) == 0 
   363 			&& s_ServerBinCRC_Ok
   364 			&& !bShouldBeReadingDefault)
   365 		{
   366 			unsigned int crc = 0;
   367 			sscanf(value, "%08X", &crc);
   368 			if (s_ServerBinCRC == crc)
   369 			{
   370 				bShouldBeReadingDefault = true;
   371 			}
   372 		}
   373 	} else if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM) {
   374 		return m_CustomHandler->ReadSMC_KeyValue(states, key, value);
   375 	}
   376 
   377 	return SMCResult_Continue;
   378 }
   379 
   380 SMCResult CGameConfig::ReadSMC_LeavingSection(const SMCStates *states)
   381 {
   382 	if (m_IgnoreLevel)
   383 	{
   384 		m_IgnoreLevel--;
   385 		return SMCResult_Continue;
   386 	}
   387 
   388 	if (m_CustomLevel)
   389 	{
   390 		m_CustomLevel--;
   391 		m_CustomHandler->ReadSMC_LeavingSection(states);
   392 		return SMCResult_Continue;
   393 	}
   394 
   395 	switch (m_ParseState)
   396 	{
   397 	case PSTATE_GAMES:
   398 		{
   399 			m_ParseState = PSTATE_NONE;
   400 			break;
   401 		}
   402 	case PSTATE_GAMEDEFS:
   403 		{
   404 			m_ParseState = PSTATE_GAMES;
   405 			break;
   406 		}
   407 	case PSTATE_GAMEDEFS_CUSTOM:
   408 		{
   409 			m_ParseState = PSTATE_GAMEDEFS;
   410 			m_CustomHandler->ReadSMC_ParseEnd(false, false);
   411 			break;
   412 		}
   413 	case PSTATE_GAMEDEFS_KEYS:
   414 	case PSTATE_GAMEDEFS_OFFSETS:
   415 		{
   416 			m_ParseState = PSTATE_GAMEDEFS;
   417 			break;
   418 		}
   419 	case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   420 		{
   421 			/* Parse the offset... */
   422 			if (m_Class[0] != '\0'
   423 				&& m_Prop[0] != '\0')
   424 			{
   425 				SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
   426 				if (pProp)
   427 				{
   428 					int val = pProp->GetOffset();
   429 					sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   430 					sm_trie_replace(m_pProps, m_offset, pProp);
   431 				} else {
   432 					/* Check if it's a non-default game and no offsets exist */
   433 					if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
   434 						&& (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
   435 					{
   436 						g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", 
   437 							m_Class,
   438 							m_Prop,
   439 							m_CurFile,
   440 							m_Game);
   441 					}
   442 				}
   443 			}
   444 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   445 			break;
   446 		}
   447 	case PSTATE_GAMEDEFS_CRC:
   448 	case PSTATE_GAMEDEFS_SUPPORTED:
   449 		{
   450 			if (!bShouldBeReadingDefault)
   451 			{
   452 				/* If we shouldn't read the rest of this section, set the ignore level. */
   453 				m_IgnoreLevel = 1;
   454 				m_ParseState = PSTATE_GAMES;
   455 			} else {
   456 				m_ParseState = PSTATE_GAMEDEFS;
   457 			}
   458 			break;
   459 		}
   460 	case PSTATE_GAMEDEFS_CRC_BINARY:
   461 		{
   462 			m_ParseState = PSTATE_GAMEDEFS_CRC;
   463 			break;
   464 		}
   465 	case PSTATE_GAMEDEFS_SIGNATURES:
   466 		{
   467 			m_ParseState = PSTATE_GAMEDEFS;
   468 			break;
   469 		}
   470 	case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   471 		{
   472 			if (s_TempSig.library[0] == '\0')
   473 			{
   474 				/* assume server */
   475 				strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
   476 			}
   477 			void *addrInBase = NULL;
   478 			if (strcmp(s_TempSig.library, "server") == 0)
   479 			{
   480 				addrInBase = (void *)g_SMAPI->GetServerFactory(false);
   481 			} else if (strcmp(s_TempSig.library, "engine") == 0) {
   482 				addrInBase = (void *)g_SMAPI->GetEngineFactory(false);
   483 			}
   484 			void *final_addr = NULL;
   485 			if (addrInBase == NULL)
   486 			{
   487 				g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   488 					s_TempSig.library, 
   489 					m_CurFile);
   490 			} else {
   491 #if defined PLATFORM_LINUX
   492 				if (s_TempSig.sig[0] == '@')
   493 				{
   494 					Dl_info info;
   495 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   496 					if (dladdr(addrInBase, &info) != 0)
   497 					{
   498 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   499 						if (handle)
   500 						{
   501 							final_addr = dlsym(handle, &s_TempSig.sig[1]);
   502 							dlclose(handle);
   503 						} else {
   504 							g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   505 								s_TempSig.library,
   506 								m_File);
   507 						}
   508 					} else {
   509 						g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   510 							s_TempSig.library,
   511 							m_File);
   512 					}
   513 				}
   514 				if (final_addr)
   515 				{
   516 					goto skip_find;
   517 				}
   518 #endif
   519 				/* First, preprocess the signature */
   520 				char real_sig[511];
   521 				size_t real_bytes;
   522 				size_t length;
   523 
   524 				real_bytes = 0;
   525 				length = strlen(s_TempSig.sig);
   526 
   527 				for (size_t i=0; i<length; i++)
   528 				{
   529 					if (real_bytes >= sizeof(real_sig))
   530 					{
   531 						break;
   532 					}
   533 					real_sig[real_bytes++] = s_TempSig.sig[i];
   534 					if (s_TempSig.sig[i] == '\\'
   535 						&& s_TempSig.sig[i+1] == 'x')
   536 					{
   537 						if (i + 3 >= length)
   538 						{
   539 							continue;
   540 						}
   541 						/* Get the hex part */
   542 						char s_byte[3];
   543 						int r_byte;
   544 						s_byte[0] = s_TempSig.sig[i+2];
   545 						s_byte[1] = s_TempSig.sig[i+3];
   546 						s_byte[2] = '\0';
   547 						/* Read it as an integer */
   548 						sscanf(s_byte, "%x", &r_byte);
   549 						/* Save the value */
   550 						real_sig[real_bytes-1] = r_byte;
   551 						/* Adjust index */
   552 						i += 3;
   553 					}
   554 				}
   555 
   556 				if (real_bytes >= 1)
   557 				{
   558 					final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
   559 				}
   560 			}
   561 
   562 #if defined PLATFORM_LINUX
   563 skip_find:
   564 #endif
   565 			sm_trie_replace(m_pSigs, m_offset, final_addr);
   566 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   567 
   568 			break;
   569 		}
   570 	}
   571 
   572 	return SMCResult_Continue;
   573 }
   574 
   575 #define MSTATE_NONE		0
   576 #define MSTATE_MAIN		1
   577 #define MSTATE_FILE		2
   578 
   579 class MasterReader : public ITextListener_SMC
   580 {
   581 public:
   582 	virtual void ReadSMC_ParseStart()
   583 	{
   584 		state = MSTATE_NONE;
   585 		ignoreLevel = 0;
   586 	}
   587 
   588 	virtual SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
   589 	{
   590 		if (ignoreLevel)
   591 		{
   592 			return SMCResult_Continue;
   593 		}
   594 
   595 		if (state == MSTATE_NONE)
   596 		{
   597 			if (strcmp(name, "Game Master") == 0)
   598 			{
   599 				state = MSTATE_MAIN;
   600 			}
   601 			else
   602 			{
   603 				ignoreLevel++;
   604 			}
   605 		}
   606 		else if (state == MSTATE_MAIN)
   607 		{
   608 			strncopy(cur_file, name, sizeof(cur_file));
   609 			had_engine = false;
   610 			matched_engine = false;
   611 			had_game = false;
   612 			matched_game = false;
   613 			state = MSTATE_FILE;
   614 		}
   615 		else if (state == MSTATE_FILE)
   616 		{
   617 			ignoreLevel++;
   618 		}
   619 
   620 		return SMCResult_Continue;
   621 	}
   622 
   623 	virtual SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   624 	{
   625 		if (ignoreLevel || state != MSTATE_FILE)
   626 		{
   627 			return SMCResult_Continue;
   628 		}
   629 
   630 		if (strcmp(key, "engine") == 0)
   631 		{
   632 			had_engine = true;
   633 			if (DoesEngineMatch(value))
   634 			{
   635 				matched_engine = true;
   636 			}
   637 		}
   638 		else if (strcmp(key, "game") == 0)
   639 		{
   640 			had_game = true;
   641 			if (DoesGameMatch(value))
   642 			{
   643 				matched_game = true;
   644 			}
   645 		}
   646 
   647 		return SMCResult_Continue;
   648 	}
   649 
   650 	virtual SMCResult ReadSMC_LeavingSection(const SMCStates *states)
   651 	{
   652 		if (ignoreLevel)
   653 		{
   654 			ignoreLevel--;
   655 			return SMCResult_Continue;
   656 		}
   657 
   658 		if (state == MSTATE_FILE)
   659 		{
   660 			/* The four success conditions:
   661 			 * 1. Needed nothing.
   662 			 * 2. Needed game only.
   663 			 * 3. Needed engine only.
   664 			 * 4. Needed both engine and game.
   665 			 * Final result is minimized via k-map.
   666 			 */
   667 #if 0
   668 			if ((!had_engine && !had_game) ||
   669 				(!had_engine && (had_game && matched_game)) ||
   670 				(!had_game && (had_engine && matched_engine)) ||
   671 				((had_game && had_engine) && (matched_game && matched_engine)))
   672 #endif
   673 			if ((!had_engine && !had_game) ||
   674 				(!had_engine && matched_game) ||
   675 				(!had_game && matched_engine) ||
   676 				(matched_engine && matched_game))
   677 			{
   678 				fileList->push_back(cur_file);
   679 			}
   680 			state = MSTATE_MAIN;
   681 		}
   682 		else if (state == MSTATE_MAIN)
   683 		{
   684 			state = MSTATE_NONE;
   685 		}
   686 
   687 		return SMCResult_Continue;
   688 	}
   689 public:
   690 	List<String> *fileList;
   691 	unsigned int state;
   692 	unsigned int ignoreLevel;
   693 	char cur_file[PLATFORM_MAX_PATH];
   694 	bool had_engine;
   695 	bool matched_engine;
   696 	bool had_game;
   697 	bool matched_game;
   698 };
   699 
   700 static MasterReader master_reader;
   701 
   702 bool CGameConfig::Reparse(char *error, size_t maxlength)
   703 {
   704 	/* Reset cached data */
   705 	m_pStrings->Reset();
   706 	sm_trie_clear(m_pOffsets);
   707 	sm_trie_clear(m_pProps);
   708 	sm_trie_clear(m_pKeys);
   709 
   710 	char path[PLATFORM_MAX_PATH];
   711 
   712 	/* See if we can use the extended gamedata format. */
   713 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/master.games.txt", m_File);
   714 	if (!g_LibSys.PathExists(path))
   715 	{
   716 		/* Nope, use the old mechanism. */
   717 		UTIL_Format(path, sizeof(path), "%s.txt", m_File);
   718 		return EnterFile(path, error, maxlength);
   719 	}
   720 
   721 	/* Otherwise, it's time to parse the master. */
   722 	SMCError err;
   723 	SMCStates state = {0, 0};
   724 	List<String> fileList;
   725 	master_reader.fileList = &fileList;
   726 
   727 	err = textparsers->ParseSMCFile(path, &master_reader, &state, error, maxlength);
   728 	if (err != SMCError_Okay)
   729 	{
   730 		const char *msg = textparsers->GetSMCErrorString(err);
   731 
   732 		g_Logger.LogError("[SM] Error parsing master gameconf file \"%s\":", path);
   733 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   734 			err,
   735 			state.line,
   736 			state.col,
   737 			msg ? msg : "Unknown error");
   738 		return false;
   739 	}
   740 
   741 	/* Go through each file we found and parse it. */
   742 	List<String>::iterator iter;
   743 	for (iter = fileList.begin(); iter != fileList.end(); iter++)
   744 	{
   745 		UTIL_Format(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
   746 		if (!EnterFile(path, error, maxlength))
   747 		{
   748 			return false;
   749 		}
   750 	}
   751 
   752 	/* Parse the contents of the 'custom' directory */
   753 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/custom", m_File);
   754 	IDirectory *customDir = g_LibSys.OpenDirectory(path);
   755 
   756 	if (!customDir)
   757 	{
   758 		return true;
   759 	}
   760 
   761 	while (customDir->MoreFiles())
   762 	{
   763 		if (!customDir->IsEntryFile())
   764 		{
   765 			customDir->NextEntry();
   766 			continue;
   767 		}
   768 		
   769 		const char *curFile = customDir->GetEntryName();
   770 
   771 		/* Only allow .txt files */
   772 		int len = strlen(curFile);
   773 		if (len > 4 && strcmp(&curFile[len-4], ".txt") != 0)
   774 		{
   775 			customDir->NextEntry();
   776 			continue;	
   777 		}
   778 
   779 		UTIL_Format(path, sizeof(path), "%s/custom/%s", m_File, curFile);
   780 		if (!EnterFile(path, error, maxlength))
   781 		{
   782 			g_LibSys.CloseDirectory(customDir);
   783 			return false;
   784 		}
   785 
   786 		customDir->NextEntry();
   787 	}
   788 
   789 	g_LibSys.CloseDirectory(customDir);
   790 	return true;
   791 }
   792 
   793 bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength)
   794 {
   795 	SMCError err;
   796 	SMCStates state = {0, 0};
   797 
   798 	g_SourceMod.BuildPath(Path_SM, m_CurFile, sizeof(m_CurFile), "gamedata/%s", file);
   799 
   800 	/* Initialize parse states */
   801 	m_IgnoreLevel = 0;
   802 	bShouldBeReadingDefault = true;
   803 	m_ParseState = PSTATE_NONE;
   804 
   805 	if ((err=textparsers->ParseSMCFile(m_CurFile, this, &state, error, maxlength))
   806 		!= SMCError_Okay)
   807 	{
   808 		const char *msg;
   809 
   810 		msg = textparsers->GetSMCErrorString(err);
   811 
   812 		g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile);
   813 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   814 			err,
   815 			state.line,
   816 			state.col,
   817 			msg ? msg : "Unknown error");
   818 
   819 		if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
   820 		{
   821 			//error occurred while parsing a custom section
   822 			m_CustomHandler->ReadSMC_ParseEnd(true, true);
   823 			m_CustomHandler = NULL;
   824 			m_CustomLevel = 0;
   825 		}
   826 
   827 		return false;
   828 	}
   829 
   830 	return true;
   831 }
   832 
   833 bool CGameConfig::GetOffset(const char *key, int *value)
   834 {
   835 	void *obj;
   836 
   837 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   838 	{
   839 		return false;
   840 	}
   841 
   842 	*value = (int)obj;
   843 	
   844 	return true;
   845 }
   846 
   847 const char *CGameConfig::GetKeyValue(const char *key)
   848 {
   849 	void *obj;
   850 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   851 	{
   852 		return NULL;
   853 	}
   854 	return m_pStrings->GetString((int)obj);
   855 }
   856 
   857 SendProp *CGameConfig::GetSendProp(const char *key)
   858 {
   859 	SendProp *pProp;
   860 
   861 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   862 	{
   863 		return NULL;
   864 	}
   865 
   866 	return pProp;
   867 }
   868 
   869 bool CGameConfig::GetMemSig(const char *key, void **addr)
   870 {
   871 	return sm_trie_retrieve(m_pSigs, key, addr);
   872 }
   873 
   874 void CGameConfig::IncRefCount()
   875 {
   876 	m_RefCount++;
   877 }
   878 
   879 unsigned int CGameConfig::DecRefCount()
   880 {
   881 	m_RefCount--;
   882 	return m_RefCount;
   883 }
   884 
   885 GameConfigManager::GameConfigManager()
   886 {
   887 	m_pLookup = sm_trie_create();
   888 }
   889 
   890 GameConfigManager::~GameConfigManager()
   891 {
   892 	sm_trie_destroy(m_pLookup);
   893 }
   894 
   895 void GameConfigManager::OnSourceModStartup(bool late)
   896 {
   897 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   898 
   899 	strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
   900 	strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
   901 
   902 	KeyValues *pGameInfo = new KeyValues("GameInfo");
   903 	if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
   904 	{
   905 		const char *str;
   906 		if ((str = pGameInfo->GetString("game", NULL)) != NULL)
   907 		{
   908 			strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
   909 		}
   910 	}
   911 	pGameInfo->deleteThis();
   912 }
   913 
   914 void GameConfigManager::OnSourceModAllInitialized()
   915 {
   916 	/* NOW initialize the game file */
   917 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
   918 	
   919 	char error[255];
   920 	if (!pGameConf->Reparse(error, sizeof(error)))
   921 	{
   922 		/* :TODO: log */
   923 	}
   924 
   925 	g_ShareSys.AddInterface(NULL, this);
   926 }
   927 
   928 void GameConfigManager::OnSourceModAllShutdown()
   929 {
   930 	CloseGameConfigFile(g_pGameConf);
   931 }
   932 
   933 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
   934 {
   935 #if 0
   936 	/* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
   937 	if (g_blockGameDataLoad)
   938 	{
   939 		UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
   940 		return false;
   941 	}
   942 #endif
   943 
   944 	CGameConfig *pConfig;
   945 
   946 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
   947 	{
   948 		pConfig->IncRefCount();
   949 		*_pConfig = pConfig;
   950 		return true;
   951 	}
   952 
   953 	pConfig = new CGameConfig(file);
   954 
   955 	/* :HACKHACK: Don't parse the main config file */
   956 	bool retval = true;
   957 	if (_pConfig != &g_pGameConf)
   958 	{
   959 		retval = pConfig->Reparse(error, maxlength);
   960 	}
   961 
   962 	m_cfgs.push_back(pConfig);
   963 	sm_trie_insert(m_pLookup, file, pConfig);
   964 
   965 	pConfig->IncRefCount();
   966 
   967 	*_pConfig = pConfig;
   968 
   969 	return retval;
   970 }
   971 
   972 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
   973 {
   974 	CGameConfig *pConfig = (CGameConfig *)cfg;
   975 
   976 	if (pConfig->DecRefCount() == 0)
   977 	{
   978 		sm_trie_delete(m_pLookup, pConfig->m_File);
   979 		delete pConfig;
   980 	}
   981 }
   982 
   983 extern HandleType_t g_GameConfigsType;
   984 
   985 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
   986 {
   987 	HandleSecurity sec(ident, g_pCoreIdent);
   988 	IGameConfig *conf = NULL;
   989 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
   990 
   991 	if (err)
   992 	{
   993 		*err = _err;
   994 	}
   995 
   996 	return conf;
   997 }
   998 
   999 void GameConfigManager::AddUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
  1000 {
  1001 	m_customHandlers.insert(sectionname, listener);
  1002 }
  1003 
  1004 void GameConfigManager::RemoveUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
  1005 {
  1006 	ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
  1007 
  1008 	if (pListener == NULL)
  1009 	{
  1010 		return;
  1011 	}
  1012 
  1013 	if (*pListener != listener)
  1014 	{
  1015 		return;
  1016 	}
  1017 
  1018 	m_customHandlers.remove(sectionname);
  1019 	
  1020 	return;
  1021 }
  1022 
  1023 void GameConfigManager::AcquireLock()
  1024 {
  1025 }
  1026 
  1027 void GameConfigManager::ReleaseLock()
  1028 {
  1029 }