core/GameConfigs.cpp
author Phong Dang <teame06@gmail.com>
Wed Aug 01 07:29:40 2007 +0000 (2007-08-01)
changeset 1241 2e8046793bc9
parent 1231 17badaf66ce4
child 1307 4f646bb1f89f
permissions -rw-r--r--
Added check to make sure player are alive to perform sm_slap, sm_burn, sm_slay.
     1 /**
     2  * vim: set ts=4 :
     3  * ================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 AlliedModders LLC.  All rights reserved.
     6  * ================================================================
     7  *
     8  * This program is free software; you can redistribute it and/or 
     9  * modify it under the terms of the GNU General Public License, 
    10  * version 3.0, as published by the Free Software Foundation.
    11  * 
    12  * This program is distributed in the hope that it will be useful,
    13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    15  * GNU General Public License for more details.
    16  *
    17  * You should have received a copy of the GNU General Public License
    18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    19  *
    20  * As a special exception, AlliedModders LLC gives you permission to 
    21  * link the code of this program (as well as its derivative works) to 
    22  * "Half-Life 2," the "Source Engine," the "SourcePawn JIT," and any 
    23  * Game MODs that run on software by the Valve Corporation.  You must 
    24  * obey the GNU General Public License in all respects for all other 
    25  * code used. Additionally, AlliedModders LLC grants this exception 
    26  * to all derivative works. AlliedModders LLC defines further 
    27  * exceptions, found in LICENSE.txt (as of this writing, version 
    28  * JULY-31-2007), or <http://www.sourcemod.net/license.php>.
    29  *
    30  * Version: $Id$
    31  */
    32 
    33 #include <string.h>
    34 #include <stdlib.h>
    35 #include "GameConfigs.h"
    36 #include "TextParsers.h"
    37 #include "sm_stringutil.h"
    38 #include "sourcemod.h"
    39 #include "sourcemm_api.h"
    40 #include "HalfLife2.h"
    41 #include "Logger.h"
    42 #include "ShareSys.h"
    43 #include "MemoryUtils.h"
    44 #include "LibrarySys.h"
    45 #include "HandleSys.h"
    46 
    47 #if defined PLATFORM_LINUX
    48 #include <dlfcn.h>
    49 #endif
    50 
    51 GameConfigManager g_GameConfigs;
    52 IGameConfig *g_pGameConf = NULL;
    53 char g_Game[256];
    54 char g_GameDesc[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 
    66 #if defined PLATFORM_WINDOWS
    67 #define PLATFORM_NAME	"windows"
    68 #elif defined PLATFORM_LINUX
    69 #define PLATFORM_NAME	"linux"
    70 #endif
    71 
    72 struct TempSigInfo
    73 {
    74 	void Reset()
    75 	{
    76 		library[0] = '\0';
    77 		sig[0] = '\0';
    78 	}
    79 	char sig[512];
    80 	char library[64];
    81 } s_TempSig;
    82 
    83 CGameConfig::CGameConfig(const char *file)
    84 {
    85 	m_pFile = sm_strdup(file);
    86 	m_pOffsets = sm_trie_create();
    87 	m_pProps = sm_trie_create();
    88 	m_pKeys = sm_trie_create();
    89 	m_pSigs = sm_trie_create();
    90 	m_pStrings = new BaseStringTable(512);
    91 	m_RefCount = 0;
    92 }
    93 
    94 CGameConfig::~CGameConfig()
    95 {
    96 	sm_trie_destroy(m_pOffsets);
    97 	sm_trie_destroy(m_pProps);
    98 	sm_trie_destroy(m_pKeys);
    99 	sm_trie_destroy(m_pSigs);
   100 	delete [] m_pFile;
   101 	delete m_pStrings;
   102 }
   103 
   104 SMCParseResult CGameConfig::ReadSMC_NewSection(const char *name, bool opt_quotes)
   105 {
   106 	if (m_IgnoreLevel)
   107 	{
   108 		m_IgnoreLevel++;
   109 		return SMCParse_Continue;
   110 	}
   111 
   112 	switch (m_ParseState)
   113 	{
   114 	case PSTATE_NONE:
   115 		{
   116 			if (strcmp(name, "Games") == 0)
   117 			{
   118 				m_ParseState = PSTATE_GAMES;
   119 			} else {
   120 				m_IgnoreLevel++;
   121 			}
   122 			break;
   123 		}
   124 	case PSTATE_GAMES:
   125 		{
   126 			if ((strcmp(name, "*") == 0)
   127 				|| (strcmp(name, "#default") == 0)
   128 				|| (strcasecmp(name, g_Game) == 0)
   129 				|| (strcasecmp(name, g_GameDesc) == 0))
   130 			{
   131 				m_ParseState = PSTATE_GAMEDEFS;
   132 				strncopy(m_Game, name, sizeof(m_Game));
   133 			} else {
   134 				m_IgnoreLevel++;
   135 			}
   136 			break;
   137 		}
   138 	case PSTATE_GAMEDEFS:
   139 		{
   140 			if (strcmp(name, "Offsets") == 0)
   141 			{
   142 				m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   143 			}
   144 			else if (strcmp(name, "Keys") == 0)
   145 			{
   146 				m_ParseState = PSTATE_GAMEDEFS_KEYS;
   147 			}
   148 			else if ((strcmp(name, "#supported") == 0)
   149 					 && (strcmp(m_Game, "#default") == 0))
   150 			{
   151 				m_ParseState = PSTATE_GAMEDEFS_SUPPORTED;
   152 				/* Ignore this section unless we get a game. */
   153 				bShouldBeReadingDefault = false;
   154 			}
   155 			else if (strcmp(name, "Signatures") == 0)
   156 			{
   157 				m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   158 			}
   159 			else
   160 			{
   161 				m_IgnoreLevel++;
   162 			}
   163 			break;
   164 		}
   165 	case PSTATE_GAMEDEFS_OFFSETS:
   166 		{
   167 			m_Prop[0] = '\0';
   168 			m_Class[0] = '\0';
   169 			strncopy(m_offset, name, sizeof(m_offset));
   170 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS_OFFSET;
   171 			break;
   172 		}
   173 	case PSTATE_GAMEDEFS_SIGNATURES:
   174 		{
   175 			strncopy(m_offset, name, sizeof(m_offset));
   176 			s_TempSig.Reset();
   177 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES_SIG;
   178 			break;
   179 		}
   180 	/* No sub-sections allowed:
   181 	 case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   182 	 case PSTATE_GAMEDEFS_KEYS:
   183 	 case PSTATE_GAMEDEFS_SUPPORTED:
   184 	 case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   185 	 */
   186 	default:
   187 		{
   188 			/* If we don't know what we got, start ignoring */
   189 			m_IgnoreLevel++;
   190 			break;
   191 		}
   192 	}
   193 
   194 	return SMCParse_Continue;
   195 }
   196 
   197 SMCParseResult CGameConfig::ReadSMC_KeyValue(const char *key, const char *value, bool key_quotes, bool value_quotes)
   198 {
   199 	if (m_IgnoreLevel)
   200 	{
   201 		return SMCParse_Continue;
   202 	}
   203 
   204 	if (m_ParseState == PSTATE_GAMEDEFS_OFFSETS_OFFSET)
   205 	{
   206 		if (strcmp(key, "class") == 0)
   207 		{
   208 			strncopy(m_Class, value, sizeof(m_Class));
   209 		} else if (strcmp(key, "prop") == 0) {
   210 			strncopy(m_Prop, value, sizeof(m_Prop));
   211 		} else if (strcmp(key, PLATFORM_NAME) == 0) {
   212 			int val = atoi(value);
   213 			sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   214 		}
   215 	} else if (m_ParseState == PSTATE_GAMEDEFS_KEYS) {
   216 		int id = m_pStrings->AddString(value);
   217 		sm_trie_replace(m_pKeys, key, (void *)id);
   218 	} else if (m_ParseState == PSTATE_GAMEDEFS_SUPPORTED) {
   219 		if (strcmp(key, "game") == 0
   220 			&& (strcasecmp(value, g_Game) == 0 || strcasecmp(value, g_GameDesc) == 0))
   221 		{
   222 			bShouldBeReadingDefault = true;
   223 		}
   224 	} else if (m_ParseState == PSTATE_GAMEDEFS_SIGNATURES_SIG) {
   225 		if (strcmp(key, PLATFORM_NAME) == 0)
   226 		{
   227 			strncopy(s_TempSig.sig, value, sizeof(s_TempSig.sig));
   228 		} else if (strcmp(key, "library") == 0) {
   229 			strncopy(s_TempSig.library, value, sizeof(s_TempSig.library));
   230 		}
   231 	}
   232 
   233 	return SMCParse_Continue;
   234 }
   235 
   236 SMCParseResult CGameConfig::ReadSMC_LeavingSection()
   237 {
   238 	if (m_IgnoreLevel)
   239 	{
   240 		m_IgnoreLevel--;
   241 		return SMCParse_Continue;
   242 	}
   243 
   244 	switch (m_ParseState)
   245 	{
   246 	case PSTATE_GAMES:
   247 		{
   248 			m_ParseState = PSTATE_NONE;
   249 			break;
   250 		}
   251 	case PSTATE_GAMEDEFS:
   252 		{
   253 			m_ParseState = PSTATE_GAMES;
   254 			break;
   255 		}
   256 	case PSTATE_GAMEDEFS_KEYS:
   257 	case PSTATE_GAMEDEFS_OFFSETS:
   258 		{
   259 			m_ParseState = PSTATE_GAMEDEFS;
   260 			break;
   261 		}
   262 	case PSTATE_GAMEDEFS_OFFSETS_OFFSET:
   263 		{
   264 			/* Parse the offset... */
   265 			if (m_Class[0] != '\0'
   266 				&& m_Prop[0] != '\0')
   267 			{
   268 				SendProp *pProp = g_HL2.FindInSendTable(m_Class, m_Prop);
   269 				if (pProp)
   270 				{
   271 					int val = pProp->GetOffset();
   272 					sm_trie_replace(m_pOffsets, m_offset, (void *)val);
   273 					sm_trie_replace(m_pProps, m_offset, pProp);
   274 				} else {
   275 					/* Check if it's a non-default game and no offsets exist */
   276 					if (((strcmp(m_Game, "*") != 0) && strcmp(m_Game, "#default") != 0)
   277 						&& (!sm_trie_retrieve(m_pOffsets, m_offset, NULL)))
   278 					{
   279 						g_Logger.LogError("[SM] Unable to find property %s.%s (file \"%s\") (mod \"%s\")", 
   280 							m_Class,
   281 							m_Prop,
   282 							m_pFile,
   283 							m_Game);
   284 					}
   285 				}
   286 			}
   287 			m_ParseState = PSTATE_GAMEDEFS_OFFSETS;
   288 			break;
   289 		}
   290 	case PSTATE_GAMEDEFS_SUPPORTED:
   291 		{
   292 			if (!bShouldBeReadingDefault)
   293 			{
   294 				/* If we shouldn't read the rest of this section, set the ignore level. */
   295 				m_IgnoreLevel = 1;
   296 				m_ParseState = PSTATE_GAMES;
   297 			} else {
   298 				m_ParseState = PSTATE_GAMEDEFS;
   299 			}
   300 			break;
   301 		}
   302 	case PSTATE_GAMEDEFS_SIGNATURES:
   303 		{
   304 			m_ParseState = PSTATE_GAMEDEFS;
   305 			break;
   306 		}
   307 	case PSTATE_GAMEDEFS_SIGNATURES_SIG:
   308 		{
   309 			if (s_TempSig.library[0] == '\0')
   310 			{
   311 				/* assume server */
   312 				strncopy(s_TempSig.library, "server", sizeof(s_TempSig.library));
   313 			}
   314 			void *addrInBase = NULL;
   315 			if (strcmp(s_TempSig.library, "server") == 0)
   316 			{
   317 				addrInBase = (void *)g_SMAPI->serverFactory(false);
   318 			} else if (strcmp(s_TempSig.library, "engine") == 0) {
   319 				addrInBase = (void *)g_SMAPI->engineFactory(false);
   320 			}
   321 			void *final_addr = NULL;
   322 			if (addrInBase == NULL)
   323 			{
   324 				g_Logger.LogError("[SM] Unrecognized library \"%s\" (gameconf \"%s\")", 
   325 					s_TempSig.library, 
   326 					m_pFile);
   327 			} else {
   328 #if defined PLATFORM_LINUX
   329 				if (s_TempSig.sig[0] == '@')
   330 				{
   331 					Dl_info info;
   332 					/* GNU only: returns 0 on error, inconsistent! >:[ */
   333 					if (dladdr(addrInBase, &info) != 0)
   334 					{
   335 						void *handle = dlopen(info.dli_fname, RTLD_NOW);
   336 						if (handle)
   337 						{
   338 							final_addr = dlsym(handle, &s_TempSig.sig[1]);
   339 							dlclose(handle);
   340 						} else {
   341 							g_Logger.LogError("[SM] Unable to load library \"%s\" (gameconf \"%s\")",
   342 								s_TempSig.library,
   343 								m_pFile);
   344 						}
   345 					} else {
   346 						g_Logger.LogError("[SM] Unable to find library \"%s\" in memory (gameconf \"%s\")",
   347 							s_TempSig.library,
   348 							m_pFile);
   349 					}
   350 				}
   351 				if (final_addr)
   352 				{
   353 					goto skip_find;
   354 				}
   355 #endif
   356 				/* First, preprocess the signature */
   357 				char real_sig[255];
   358 				size_t real_bytes;
   359 				size_t length;
   360 
   361 				real_bytes = 0;
   362 				length = strlen(s_TempSig.sig);
   363 
   364 				for (size_t i=0; i<length; i++)
   365 				{
   366 					if (real_bytes >= sizeof(real_sig))
   367 					{
   368 						break;
   369 					}
   370 					real_sig[real_bytes++] = s_TempSig.sig[i];
   371 					if (s_TempSig.sig[i] == '\\'
   372 						&& s_TempSig.sig[i+1] == 'x')
   373 					{
   374 						if (i + 3 >= length)
   375 						{
   376 							continue;
   377 						}
   378 						/* Get the hex part */
   379 						char s_byte[3];
   380 						int r_byte;
   381 						s_byte[0] = s_TempSig.sig[i+2];
   382 						s_byte[1] = s_TempSig.sig[i+3];
   383 						s_byte[2] = '\0';
   384 						/* Read it as an integer */
   385 						sscanf(s_byte, "%x", &r_byte);
   386 						/* Save the value */
   387 						real_sig[real_bytes-1] = r_byte;
   388 						/* Adjust index */
   389 						i += 3;
   390 					}
   391 				}
   392 
   393 				if (real_bytes >= 1)
   394 				{
   395 					final_addr = g_MemUtils.FindPattern(addrInBase, real_sig, real_bytes);
   396 				}
   397 			}
   398 
   399 #if defined PLATFORM_LINUX
   400 skip_find:
   401 #endif
   402 			sm_trie_replace(m_pSigs, m_offset, final_addr);
   403 			m_ParseState = PSTATE_GAMEDEFS_SIGNATURES;
   404 
   405 			break;
   406 		}
   407 	}
   408 
   409 	return SMCParse_Continue;
   410 }
   411 
   412 bool CGameConfig::Reparse(char *error, size_t maxlength)
   413 {
   414 	SMCParseError err;
   415 
   416 	char path[PLATFORM_MAX_PATH];
   417 	g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "gamedata/%s.txt", m_pFile);
   418 	/* Backwards compatibility */
   419 	if (!g_LibSys.PathExists(path))
   420 	{
   421 		g_SourceMod.BuildPath(Path_SM, path, sizeof(path), "configs/gamedata/%s.txt", m_pFile);
   422 	}
   423 
   424 	/* Initialize parse states */
   425 	m_IgnoreLevel = 0;
   426 	bShouldBeReadingDefault = true;
   427 	m_ParseState = PSTATE_NONE;
   428 	/* Reset cached data */
   429 	m_pStrings->Reset();
   430 	sm_trie_clear(m_pOffsets);
   431 	sm_trie_clear(m_pProps);
   432 	sm_trie_clear(m_pKeys);
   433 
   434 	if ((err=g_TextParser.ParseFile_SMC(path, this, NULL, NULL))
   435 		!= SMCParse_Okay)
   436 	{
   437 		if (error && (err != SMCParse_Custom))
   438 		{
   439 			const char *str = g_TextParser.GetSMCErrorString(err);
   440 			snprintf(error, maxlength, "%s", str);
   441 		}
   442 		return false;
   443 	}
   444 
   445 	return true;
   446 }
   447 
   448 bool CGameConfig::GetOffset(const char *key, int *value)
   449 {
   450 	void *obj;
   451 
   452 	if (!sm_trie_retrieve(m_pOffsets, key, &obj))
   453 	{
   454 		return false;
   455 	}
   456 
   457 	*value = (int)obj;
   458 	
   459 	return true;
   460 }
   461 
   462 const char *CGameConfig::GetKeyValue(const char *key)
   463 {
   464 	void *obj;
   465 	if (!sm_trie_retrieve(m_pKeys, key, &obj))
   466 	{
   467 		return NULL;
   468 	}
   469 	return m_pStrings->GetString((int)obj);
   470 }
   471 
   472 SendProp *CGameConfig::GetSendProp(const char *key)
   473 {
   474 	SendProp *pProp;
   475 
   476 	if (!sm_trie_retrieve(m_pProps, key, (void **)&pProp))
   477 	{
   478 		return NULL;
   479 	}
   480 
   481 	return pProp;
   482 }
   483 
   484 bool CGameConfig::GetMemSig(const char *key, void **addr)
   485 {
   486 	return sm_trie_retrieve(m_pSigs, key, addr);
   487 }
   488 
   489 void CGameConfig::IncRefCount()
   490 {
   491 	m_RefCount++;
   492 }
   493 
   494 unsigned int CGameConfig::DecRefCount()
   495 {
   496 	m_RefCount--;
   497 	return m_RefCount;
   498 }
   499 
   500 GameConfigManager::GameConfigManager()
   501 {
   502 	m_pLookup = sm_trie_create();
   503 }
   504 
   505 GameConfigManager::~GameConfigManager()
   506 {
   507 	sm_trie_destroy(m_pLookup);
   508 }
   509 
   510 void GameConfigManager::OnSourceModStartup(bool late)
   511 {
   512 	LoadGameConfigFile("core.games", &g_pGameConf, NULL, 0);
   513 
   514 	strncopy(g_Game, g_SourceMod.GetGameFolderName(), sizeof(g_Game));
   515 	strncopy(g_GameDesc + 1, SERVER_CALL(GetGameDescription)(), sizeof(g_GameDesc) - 1);
   516 }
   517 
   518 void GameConfigManager::OnSourceModAllInitialized()
   519 {
   520 	/* NOW initialize the game file */
   521 	CGameConfig *pGameConf = (CGameConfig *)g_pGameConf;
   522 	
   523 	char error[255];
   524 	if (!pGameConf->Reparse(error, sizeof(error)))
   525 	{
   526 		/* :TODO: log */
   527 	}
   528 
   529 	g_ShareSys.AddInterface(NULL, this);
   530 }
   531 
   532 void GameConfigManager::OnSourceModAllShutdown()
   533 {
   534 	CloseGameConfigFile(g_pGameConf);
   535 }
   536 
   537 bool GameConfigManager::LoadGameConfigFile(const char *file, IGameConfig **_pConfig, char *error, size_t maxlength)
   538 {
   539 	CGameConfig *pConfig;
   540 
   541 	if (sm_trie_retrieve(m_pLookup, file, (void **)&pConfig))
   542 	{
   543 		pConfig->IncRefCount();
   544 		*_pConfig = pConfig;
   545 		return true;
   546 	}
   547 
   548 	pConfig = new CGameConfig(file);
   549 
   550 	/* :HACKHACK: Don't parse the main config file */
   551 	bool retval = true;
   552 	if (_pConfig != &g_pGameConf)
   553 	{
   554 		retval = pConfig->Reparse(error, maxlength);
   555 	}
   556 
   557 	m_cfgs.push_back(pConfig);
   558 	sm_trie_insert(m_pLookup, file, pConfig);
   559 
   560 	pConfig->IncRefCount();
   561 
   562 	*_pConfig = pConfig;
   563 
   564 	return retval;
   565 }
   566 
   567 void GameConfigManager::CloseGameConfigFile(IGameConfig *cfg)
   568 {
   569 	CGameConfig *pConfig = (CGameConfig *)cfg;
   570 
   571 	if (pConfig->DecRefCount() == 0)
   572 	{
   573 		sm_trie_delete(m_pLookup, pConfig->m_pFile);
   574 		delete pConfig;
   575 	}
   576 }
   577 
   578 extern HandleType_t g_GameConfigsType;
   579 
   580 IGameConfig *GameConfigManager::ReadHandle(Handle_t hndl, IdentityToken_t *ident, HandleError *err)
   581 {
   582 	HandleSecurity sec(ident, g_pCoreIdent);
   583 	IGameConfig *conf = NULL;
   584 	HandleError _err = g_HandleSys.ReadHandle(hndl, g_GameConfigsType, &sec, (void **)&conf);
   585 
   586 	if (err)
   587 	{
   588 		*err = _err;
   589 	}
   590 
   591 	return conf;
   592 }