core/GameConfigs.cpp
author David Anderson <dvander@alliedmods.net>
Sat Sep 26 17:12:23 2009 -0400 (2009-09-26)
changeset 2806 686c283b08fc
parent 2768 939a96921719
child 2828 74059a80142c
permissions -rw-r--r--
Added generic command hooking mechanism, to replace Reg*Cmd which is intended for command creation (bug 4015, 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 				unsigned 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 				real_bytes = UTIL_DecodeHexString(real_sig, sizeof(real_sig), s_TempSig.sig);
   530 
   531 				if (real_bytes >= 1)
   532 				{
   533 					final_addr = g_MemUtils.FindPattern(addrInBase, (char*)real_sig, real_bytes);
   534 				}
   535 			}
   536 
   537 #if defined PLATFORM_LINUX
   538 skip_find:
   539 #endif
   540 			sm_trie_replace(m_pSigs, m_offset, final_addr);
   541 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   542 
   543 			break;
   544 		}
   545 	}
   546 
   547 	return SMCResult_Continue;
   548 }
   549 
   550 #define MSTATE_NONE		0
   551 #define MSTATE_MAIN		1
   552 #define MSTATE_FILE		2
   553 
   554 class MasterReader : public ITextListener_SMC
   555 {
   556 public:
   557 	virtual void ReadSMC_ParseStart()
   558 	{
   559 		state = MSTATE_NONE;
   560 		ignoreLevel = 0;
   561 	}
   562 
   563 	virtual SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
   564 	{
   565 		if (ignoreLevel)
   566 		{
   567 			return SMCResult_Continue;
   568 		}
   569 
   570 		if (state == MSTATE_NONE)
   571 		{
   572 			if (strcmp(name, "Game Master") == 0)
   573 			{
   574 				state = MSTATE_MAIN;
   575 			}
   576 			else
   577 			{
   578 				ignoreLevel++;
   579 			}
   580 		}
   581 		else if (state == MSTATE_MAIN)
   582 		{
   583 			strncopy(cur_file, name, sizeof(cur_file));
   584 			had_engine = false;
   585 			matched_engine = false;
   586 			had_game = false;
   587 			matched_game = false;
   588 			state = MSTATE_FILE;
   589 		}
   590 		else if (state == MSTATE_FILE)
   591 		{
   592 			ignoreLevel++;
   593 		}
   594 
   595 		return SMCResult_Continue;
   596 	}
   597 
   598 	virtual SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   599 	{
   600 		if (ignoreLevel || state != MSTATE_FILE)
   601 		{
   602 			return SMCResult_Continue;
   603 		}
   604 
   605 		if (strcmp(key, "engine") == 0)
   606 		{
   607 			had_engine = true;
   608 			if (DoesEngineMatch(value))
   609 			{
   610 				matched_engine = true;
   611 			}
   612 		}
   613 		else if (strcmp(key, "game") == 0)
   614 		{
   615 			had_game = true;
   616 			if (DoesGameMatch(value))
   617 			{
   618 				matched_game = true;
   619 			}
   620 		}
   621 
   622 		return SMCResult_Continue;
   623 	}
   624 
   625 	virtual SMCResult ReadSMC_LeavingSection(const SMCStates *states)
   626 	{
   627 		if (ignoreLevel)
   628 		{
   629 			ignoreLevel--;
   630 			return SMCResult_Continue;
   631 		}
   632 
   633 		if (state == MSTATE_FILE)
   634 		{
   635 			/* The four success conditions:
   636 			 * 1. Needed nothing.
   637 			 * 2. Needed game only.
   638 			 * 3. Needed engine only.
   639 			 * 4. Needed both engine and game.
   640 			 * Final result is minimized via k-map.
   641 			 */
   642 #if 0
   643 			if ((!had_engine && !had_game) ||
   644 				(!had_engine && (had_game && matched_game)) ||
   645 				(!had_game && (had_engine && matched_engine)) ||
   646 				((had_game && had_engine) && (matched_game && matched_engine)))
   647 #endif
   648 			if ((!had_engine && !had_game) ||
   649 				(!had_engine && matched_game) ||
   650 				(!had_game && matched_engine) ||
   651 				(matched_engine && matched_game))
   652 			{
   653 				fileList->push_back(cur_file);
   654 			}
   655 			state = MSTATE_MAIN;
   656 		}
   657 		else if (state == MSTATE_MAIN)
   658 		{
   659 			state = MSTATE_NONE;
   660 		}
   661 
   662 		return SMCResult_Continue;
   663 	}
   664 public:
   665 	List<String> *fileList;
   666 	unsigned int state;
   667 	unsigned int ignoreLevel;
   668 	char cur_file[PLATFORM_MAX_PATH];
   669 	bool had_engine;
   670 	bool matched_engine;
   671 	bool had_game;
   672 	bool matched_game;
   673 };
   674 
   675 static MasterReader master_reader;
   676 
   677 bool CGameConfig::Reparse(char *error, size_t maxlength)
   678 {
   679 	/* Reset cached data */
   680 	m_pStrings->Reset();
   681 	sm_trie_clear(m_pOffsets);
   682 	sm_trie_clear(m_pProps);
   683 	sm_trie_clear(m_pKeys);
   684 
   685 	char path[PLATFORM_MAX_PATH];
   686 
   687 	/* See if we can use the extended gamedata format. */
   688 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/master.games.txt", m_File);
   689 	if (!g_LibSys.PathExists(path))
   690 	{
   691 		/* Nope, use the old mechanism. */
   692 		UTIL_Format(path, sizeof(path), "%s.txt", m_File);
   693 		return EnterFile(path, error, maxlength);
   694 	}
   695 
   696 	/* Otherwise, it's time to parse the master. */
   697 	SMCError err;
   698 	SMCStates state = {0, 0};
   699 	List<String> fileList;
   700 	master_reader.fileList = &fileList;
   701 
   702 	err = textparsers->ParseSMCFile(path, &master_reader, &state, error, maxlength);
   703 	if (err != SMCError_Okay)
   704 	{
   705 		const char *msg = textparsers->GetSMCErrorString(err);
   706 
   707 		g_Logger.LogError("[SM] Error parsing master gameconf file \"%s\":", path);
   708 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   709 			err,
   710 			state.line,
   711 			state.col,
   712 			msg ? msg : "Unknown error");
   713 		return false;
   714 	}
   715 
   716 	/* Go through each file we found and parse it. */
   717 	List<String>::iterator iter;
   718 	for (iter = fileList.begin(); iter != fileList.end(); iter++)
   719 	{
   720 		UTIL_Format(path, sizeof(path), "%s/%s", m_File, (*iter).c_str());
   721 		if (!EnterFile(path, error, maxlength))
   722 		{
   723 			return false;
   724 		}
   725 	}
   726 
   727 	/* Parse the contents of the 'custom' directory */
   728 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s/custom", m_File);
   729 	IDirectory *customDir = g_LibSys.OpenDirectory(path);
   730 
   731 	if (!customDir)
   732 	{
   733 		return true;
   734 	}
   735 
   736 	while (customDir->MoreFiles())
   737 	{
   738 		if (!customDir->IsEntryFile())
   739 		{
   740 			customDir->NextEntry();
   741 			continue;
   742 		}
   743 		
   744 		const char *curFile = customDir->GetEntryName();
   745 
   746 		/* Only allow .txt files */
   747 		int len = strlen(curFile);
   748 		if (len > 4 && strcmp(&curFile[len-4], ".txt") != 0)
   749 		{
   750 			customDir->NextEntry();
   751 			continue;	
   752 		}
   753 
   754 		UTIL_Format(path, sizeof(path), "%s/custom/%s", m_File, curFile);
   755 		if (!EnterFile(path, error, maxlength))
   756 		{
   757 			g_LibSys.CloseDirectory(customDir);
   758 			return false;
   759 		}
   760 
   761 		customDir->NextEntry();
   762 	}
   763 
   764 	g_LibSys.CloseDirectory(customDir);
   765 	return true;
   766 }
   767 
   768 bool CGameConfig::EnterFile(const char *file, char *error, size_t maxlength)
   769 {
   770 	SMCError err;
   771 	SMCStates state = {0, 0};
   772 
   773 	g_SourceMod.BuildPath(Path_SM, m_CurFile, sizeof(m_CurFile), "gamedata/%s", file);
   774 
   775 	/* Initialize parse states */
   776 	m_IgnoreLevel = 0;
   777 	bShouldBeReadingDefault = true;
   778 	m_ParseState = PSTATE_NONE;
   779 
   780 	if ((err=textparsers->ParseSMCFile(m_CurFile, this, &state, error, maxlength))
   781 		!= SMCError_Okay)
   782 	{
   783 		const char *msg;
   784 
   785 		msg = textparsers->GetSMCErrorString(err);
   786 
   787 		g_Logger.LogError("[SM] Error parsing gameconfig file \"%s\":", m_CurFile);
   788 		g_Logger.LogError("[SM] Error %d on line %d, col %d: %s", 
   789 			err,
   790 			state.line,
   791 			state.col,
   792 			msg ? msg : "Unknown error");
   793 
   794 		if (m_ParseState == PSTATE_GAMEDEFS_CUSTOM)
   795 		{
   796 			//error occurred while parsing a custom section
   797 			m_CustomHandler->ReadSMC_ParseEnd(true, true);
   798 			m_CustomHandler = NULL;
   799 			m_CustomLevel = 0;
   800 		}
   801 
   802 		return false;
   803 	}
   804 
   805 	return true;
   806 }
   807 
   808 bool CGameConfig::GetOffset(const char *key, int *value)
   809 {
   810 	void *obj;
   811 
   812 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   813 	{
   814 		return false;
   815 	}
   816 
   817 	*value = (int)obj;
   818 	
   819 	return true;
   820 }
   821 
   822 const char *CGameConfig::GetKeyValue(const char *key)
   823 {
   824 	void *obj;
   825 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   826 	{
   827 		return NULL;
   828 	}
   829 	return m_pStrings->GetString((int)obj);
   830 }
   831 
   832 SendProp *CGameConfig::GetSendProp(const char *key)
   833 {
   834 	SendProp *pProp;
   835 
   836 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   837 	{
   838 		return NULL;
   839 	}
   840 
   841 	return pProp;
   842 }
   843 
   844 bool CGameConfig::GetMemSig(const char *key, void **addr)
   845 {
   846 	return sm_trie_retrieve(m_pSigs, key, addr);
   847 }
   848 
   849 void CGameConfig::IncRefCount()
   850 {
   851 	m_RefCount++;
   852 }
   853 
   854 unsigned int CGameConfig::DecRefCount()
   855 {
   856 	m_RefCount--;
   857 	return m_RefCount;
   858 }
   859 
   860 GameConfigManager::GameConfigManager()
   861 {
   862 	m_pLookup = sm_trie_create();
   863 }
   864 
   865 GameConfigManager::~GameConfigManager()
   866 {
   867 	sm_trie_destroy(m_pLookup);
   868 }
   869 
   870 void GameConfigManager::OnSourceModStartup(bool late)
   871 {
   872 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   873 
   874 	strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
   875 	strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
   876 
   877 	KeyValues *pGameInfo = new KeyValues("GameInfo");
   878 	if (g_HL2.KVLoadFromFile(pGameInfo, basefilesystem, "gameinfo.txt"))
   879 	{
   880 		const char *str;
   881 		if ((str = pGameInfo->GetString("game", NULL)) != NULL)
   882 		{
   883 			strncopy(g_GameName + 1, str, sizeof(g_GameName) - 1);
   884 		}
   885 	}
   886 	pGameInfo->deleteThis();
   887 }
   888 
   889 void GameConfigManager::OnSourceModAllInitialized()
   890 {
   891 	/* NOW initialize the game file */
   892 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
   893 	
   894 	char error[255];
   895 	if (!pGameConf->Reparse(error, sizeof(error)))
   896 	{
   897 		/* :TODO: log */
   898 	}
   899 
   900 	g_ShareSys.AddInterface(NULL, this);
   901 }
   902 
   903 void GameConfigManager::OnSourceModAllShutdown()
   904 {
   905 	CloseGameConfigFile(g_pGameConf);
   906 }
   907 
   908 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
   909 {
   910 #if 0
   911 	/* A crash was detected during last load - We block the gamedata loading so it hopefully won't happen again */
   912 	if (g_blockGameDataLoad)
   913 	{
   914 		UTIL_Format(error, maxlength, "GameData loaded blocked due to detected crash");
   915 		return false;
   916 	}
   917 #endif
   918 
   919 	CGameConfig *pConfig;
   920 
   921 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
   922 	{
   923 		pConfig->IncRefCount();
   924 		*_pConfig = pConfig;
   925 		return true;
   926 	}
   927 
   928 	pConfig = new CGameConfig(file);
   929 
   930 	/* :HACKHACK: Don't parse the main config file */
   931 	bool retval = true;
   932 	if (_pConfig != &g_pGameConf)
   933 	{
   934 		retval = pConfig->Reparse(error, maxlength);
   935 	}
   936 
   937 	m_cfgs.push_back(pConfig);
   938 	sm_trie_insert(m_pLookup, file, pConfig);
   939 
   940 	pConfig->IncRefCount();
   941 
   942 	*_pConfig = pConfig;
   943 
   944 	return retval;
   945 }
   946 
   947 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
   948 {
   949 	CGameConfig *pConfig = (CGameConfig *)cfg;
   950 
   951 	if (pConfig->DecRefCount() == 0)
   952 	{
   953 		sm_trie_delete(m_pLookup, pConfig->m_File);
   954 		delete pConfig;
   955 	}
   956 }
   957 
   958 extern HandleType_t g_GameConfigsType;
   959 
   960 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
   961 {
   962 	HandleSecurity sec(ident, g_pCoreIdent);
   963 	IGameConfig *conf = NULL;
   964 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
   965 
   966 	if (err)
   967 	{
   968 		*err = _err;
   969 	}
   970 
   971 	return conf;
   972 }
   973 
   974 void GameConfigManager::AddUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
   975 {
   976 	m_customHandlers.insert(sectionname, listener);
   977 }
   978 
   979 void GameConfigManager::RemoveUserConfigHook(const char *sectionname, ITextListener_SMC *listener)
   980 {
   981 	ITextListener_SMC **pListener = m_customHandlers.retrieve(sectionname);
   982 
   983 	if (pListener == NULL)
   984 	{
   985 		return;
   986 	}
   987 
   988 	if (*pListener != listener)
   989 	{
   990 		return;
   991 	}
   992 
   993 	m_customHandlers.remove(sectionname);
   994 	
   995 	return;
   996 }
   997 
   998 void GameConfigManager::AcquireLock()
   999 {
  1000 }
  1001 
  1002 void GameConfigManager::ReleaseLock()
  1003 {
  1004 }