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