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