core/CoreConfig.cpp
author Scott Ehlert <ds@alliedmods.net>
Wed Feb 18 02:30:21 2009 -0600 (2009-02-18)
changeset 2584 6972eb067f48
parent 2583 d3b2571c378b
parent 2574 d05c7ee81134
child 2752 e19de59cb8e5
permissions -rw-r--r--
Merge.
     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 <ITextParsers.h>
    33 #include "CoreConfig.h"
    34 #include "sourcemod.h"
    35 #include "sourcemm_api.h"
    36 #include "sm_srvcmds.h"
    37 #include "sm_version.h"
    38 #include "sm_stringutil.h"
    39 #include "LibrarySys.h"
    40 #include "Logger.h"
    41 #include "PluginSys.h"
    42 #include "ForwardSys.h"
    43 #include "frame_hooks.h"
    44 
    45 #ifdef PLATFORM_WINDOWS
    46 ConVar sm_corecfgfile("sm_corecfgfile", "addons\\sourcemod\\configs\\core.cfg", 0, "SourceMod core configuration file");
    47 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
    48 ConVar sm_corecfgfile("sm_corecfgfile", "addons/sourcemod/configs/core.cfg", 0, "SourceMod core configuration file");
    49 #endif
    50 
    51 IForward *g_pOnServerCfg = NULL;
    52 IForward *g_pOnConfigsExecuted = NULL;
    53 IForward *g_pOnAutoConfigsBuffered = NULL;
    54 CoreConfig g_CoreConfig;
    55 bool g_bConfigsExecd = false;
    56 bool g_bServerExecd = false;
    57 bool g_bGotServerStart = false;
    58 bool g_bGotTrigger = false;
    59 ConCommand *g_pExecPtr = NULL;
    60 ConVar *g_ServerCfgFile = NULL;
    61 
    62 void CheckAndFinalizeConfigs();
    63 
    64 #if SOURCE_ENGINE >= SE_ORANGEBOX
    65 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
    66 void Hook_ExecDispatchPre(const CCommand &cmd)
    67 #elif SOURCE_ENGINE == SE_DARKMESSIAH
    68 SH_DECL_EXTERN0_void(ConCommand, Dispatch, SH_NOATTRIB, false);
    69 void Hook_ExecDispatchPre()
    70 #else
    71 extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    72 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
    73 void Hook_ExecDispatchPre()
    74 #endif
    75 {
    76 #if SOURCE_ENGINE <= SE_DARKMESSIAH
    77 	CCommand cmd;
    78 #endif
    79 
    80 	const char *arg = cmd.Arg(1);
    81 
    82 	if (!g_bServerExecd && arg != NULL && strcmp(arg, g_ServerCfgFile->GetString()) == 0)
    83 	{
    84 		g_bGotTrigger = true;
    85 	}
    86 }
    87 
    88 #if SOURCE_ENGINE >= SE_ORANGEBOX
    89 void Hook_ExecDispatchPost(const CCommand &cmd)
    90 #else
    91 void Hook_ExecDispatchPost()
    92 #endif
    93 {
    94 	if (g_bGotTrigger)
    95 	{
    96 		g_bGotTrigger = false;
    97 		g_bServerExecd = true;
    98 		CheckAndFinalizeConfigs();
    99 	}
   100 }
   101 
   102 void CheckAndFinalizeConfigs()
   103 {
   104 	if ((g_bServerExecd || g_ServerCfgFile == NULL) && g_bGotServerStart)
   105 	{
   106 #if SOURCE_ENGINE >= SE_ORANGEBOX
   107         g_PendingInternalPush = true;
   108 #else
   109         SM_InternalCmdTrigger();
   110 #endif
   111 	}
   112 }
   113 
   114 void CoreConfig::OnSourceModAllInitialized()
   115 {
   116 	g_RootMenu.AddRootConsoleCommand("config", "Set core configuration options", this);
   117 	g_pOnServerCfg = g_Forwards.CreateForward("OnServerCfg", ET_Ignore, 0, NULL);
   118 	g_pOnConfigsExecuted = g_Forwards.CreateForward("OnConfigsExecuted", ET_Ignore, 0, NULL);
   119 	g_pOnAutoConfigsBuffered = g_Forwards.CreateForward("OnAutoConfigsBuffered", ET_Ignore, 0, NULL);
   120 }
   121 
   122 CoreConfig::CoreConfig() : m_Strings(512)
   123 {
   124 }
   125 
   126 CoreConfig::~CoreConfig()
   127 {
   128 }
   129 
   130 void CoreConfig::OnSourceModShutdown()
   131 {
   132 	g_RootMenu.RemoveRootConsoleCommand("config", this);
   133 	g_Forwards.ReleaseForward(g_pOnServerCfg);
   134 	g_Forwards.ReleaseForward(g_pOnConfigsExecuted);
   135 	g_Forwards.ReleaseForward(g_pOnAutoConfigsBuffered);
   136 
   137 	if (g_pExecPtr != NULL)
   138 	{
   139 		SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
   140 		SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
   141 		g_pExecPtr = NULL;
   142 	}
   143 }
   144 
   145 void CoreConfig::OnSourceModLevelChange(const char *mapName)
   146 {
   147 	static bool already_checked = false;
   148 
   149 	if (!already_checked)
   150 	{
   151 		if (engine->IsDedicatedServer())
   152 		{
   153 			g_ServerCfgFile = icvar->FindVar("servercfgfile");
   154 		}
   155 		else
   156 		{
   157 			g_ServerCfgFile = icvar->FindVar("lservercfgfile");
   158 		}
   159 
   160 		if (g_ServerCfgFile != NULL)
   161 		{
   162 			g_pExecPtr = FindCommand("exec");
   163 			if (g_pExecPtr != NULL)
   164 			{
   165 				SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
   166 				SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
   167 			}
   168 			else
   169 			{
   170 				g_ServerCfgFile = NULL;
   171 			}
   172 		}
   173 		already_checked = true;
   174 	}
   175 
   176 	g_bConfigsExecd = false;
   177 	g_bServerExecd = false;
   178 	g_bGotServerStart = false;
   179 	g_bGotTrigger = false;
   180 }
   181 
   182 void CoreConfig::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
   183 {
   184 	int argcount = command.ArgC();
   185 	if (argcount >= 4)
   186 	{
   187 		const char *option = command.Arg(2);
   188 		const char *value = command.Arg(3);
   189 
   190 		char error[255];
   191 
   192 		ConfigResult res = SetConfigOption(option, value, ConfigSource_Console, error, sizeof(error));
   193 
   194 		if (res == ConfigResult_Reject)
   195 		{
   196 			g_RootMenu.ConsolePrint("[SM] Could not set config option \"%s\" to \"%s\" (%s)", option, value, error);
   197 		} else if (res == ConfigResult_Ignore) {
   198 			g_RootMenu.ConsolePrint("[SM] No such config option \"%s\" exists.", option);
   199 		} else {
   200 			g_RootMenu.ConsolePrint("Config option \"%s\" successfully set to \"%s.\"", option, value);
   201 		}
   202 
   203 		return;
   204 	}
   205 
   206 	g_RootMenu.ConsolePrint("[SM] Usage: sm config <option> <value>");
   207 }
   208 
   209 void CoreConfig::Initialize()
   210 {
   211 	SMCError err;
   212 	char filePath[PLATFORM_MAX_PATH];
   213 
   214 	/* Try to get command line value of core config convar */
   215 	const char *corecfg = icvar->GetCommandLineValue("sm_corecfgfile");
   216 
   217 	/* If sm_corecfgfile not specified on command line, use default value */
   218 	if (!corecfg)
   219 	{
   220 		corecfg = sm_corecfgfile.GetDefault();
   221 	}
   222 
   223 	/* Format path to config file */
   224 	g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s", g_SourceMod.GetGamePath(), corecfg);
   225 
   226 	/* Reset cached key values */
   227 	m_KeyValues.clear();
   228 	m_Strings.Reset();
   229 
   230 	/* Parse config file */
   231 	if ((err=textparsers->ParseFile_SMC(filePath, this, NULL)) != SMCError_Okay)
   232 	{
   233  		/* :TODO: This won't actually log or print anything :( - So fix that somehow */
   234 		const char *error = textparsers->GetSMCErrorString(err);
   235 		g_Logger.LogFatal("[SM] Error encountered parsing core config file: %s", error ? error : "");
   236 	}
   237 }
   238 
   239 SMCResult CoreConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   240 {
   241 	char error[255];
   242 	ConfigResult err = SetConfigOption(key, value, ConfigSource_File, error, sizeof(error));
   243 
   244 	if (err == ConfigResult_Reject)
   245 	{
   246 		/* This is a fatal error */
   247 		g_Logger.LogFatal("Config error (key: %s) (value: %s) %s", key, value, error);
   248 	}
   249 
   250 	return SMCResult_Continue;
   251 }
   252 
   253 ConfigResult CoreConfig::SetConfigOption(const char *option, const char *value, ConfigSource source, char *error, size_t maxlength)
   254 {
   255 	ConfigResult result;
   256 
   257 	/* Notify! */
   258 	SMGlobalClass *pBase = SMGlobalClass::head;
   259 	while (pBase)
   260 	{
   261 		if ((result = pBase->OnSourceModConfigChanged(option, value, source, error, maxlength)) != ConfigResult_Ignore)
   262 		{
   263 			return result;
   264 		}
   265 		pBase = pBase->m_pGlobalClassNext;
   266 	}
   267 
   268 	m_KeyValues.replace(option, m_Strings.AddString(value));
   269 
   270 	return ConfigResult_Ignore;
   271 }
   272 
   273 const char *CoreConfig::GetCoreConfigValue(const char *key)
   274 {
   275 	int *pKey = m_KeyValues.retrieve(key);
   276 	if (pKey == NULL)
   277 	{
   278 		return NULL;
   279 	}
   280 	return m_Strings.GetString(*pKey);
   281 }
   282 
   283 bool SM_AreConfigsExecuted()
   284 {
   285 	return g_bConfigsExecd;
   286 }
   287 
   288 inline bool IsPathSepChar(char c)
   289 {
   290 #if defined PLATFORM_WINDOWS
   291 	return (c == '\\' || c == '/');
   292 #elif defined PLATFORM_LINUX || defined PLATFORM_POSIX
   293 	return (c == '/');
   294 #endif
   295 }
   296 
   297 bool SM_ExecuteConfig(CPlugin *pl, AutoConfig *cfg, bool can_create)
   298 {
   299 	bool will_create = false;
   300 	
   301 	/* See if we should be creating */
   302 	if (can_create && cfg->create)
   303 	{
   304 		will_create = true;
   305 		
   306 		/* If the folder does not exist, attempt to create it.  
   307 		 * We're awfully nice.
   308 		 */
   309 		const char *folder = cfg->folder.c_str();
   310 		char path[PLATFORM_MAX_PATH];
   311 		char build[PLATFORM_MAX_PATH];
   312 
   313 		g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "cfg/%s", folder);
   314 
   315 		if (!g_LibSys.IsPathDirectory(path))
   316 		{
   317 			char *cur_ptr = path;
   318 			size_t len;
   319 			
   320 			g_LibSys.PathFormat(path, sizeof(path), "%s", folder);
   321 			len = g_SourceMod.BuildPath(Path_Game, build, sizeof(build), "cfg");
   322 
   323 			do
   324 			{
   325 				/* Find next suitable path */
   326 				char *next_ptr = cur_ptr;
   327 				while (*next_ptr != '\0')
   328 				{
   329 					if (IsPathSepChar(*next_ptr))
   330 					{
   331 						*next_ptr = '\0';
   332 						next_ptr++;
   333 						break;
   334 					}
   335 					next_ptr++;
   336 				}
   337 				if (*next_ptr == '\0')
   338 				{
   339 					next_ptr = NULL;
   340 				}
   341 				len += g_LibSys.PathFormat(&build[len], 
   342 					sizeof(build)-len,
   343 					"/%s",
   344 					cur_ptr);
   345 				if (!g_LibSys.CreateFolder(build))
   346 				{
   347 					break;
   348 				}
   349 				cur_ptr = next_ptr;
   350 			} while (cur_ptr);
   351 		}
   352 	}
   353 
   354 	/* Check if the file exists. */
   355 	char file[PLATFORM_MAX_PATH];
   356 	char local[PLATFORM_MAX_PATH];
   357 
   358 	if (cfg->folder.size())
   359 	{
   360 		g_LibSys.PathFormat(local, 
   361 			sizeof(local), 
   362 			"%s/%s.cfg",
   363 			cfg->folder.c_str(),
   364 			cfg->autocfg.c_str());
   365 	} else {
   366 		g_LibSys.PathFormat(local,
   367 			sizeof(local),
   368 			"%s.cfg",
   369 			cfg->autocfg.c_str());
   370 	}
   371 	
   372 	g_SourceMod.BuildPath(Path_Game, file, sizeof(file), "cfg/%s", local);
   373 
   374 	bool file_exists = g_LibSys.IsPathFile(file);
   375 	if (!file_exists && will_create)
   376 	{
   377 		List<const ConVar *> *convars = NULL;
   378 		if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
   379 		{
   380 			/* Attempt to create it */
   381 			FILE *fp = fopen(file, "wt");
   382 			if (fp)
   383 			{
   384 				fprintf(fp, "// This file was auto-generated by SourceMod (v%s)\n", SVN_FULL_VERSION);
   385 				fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename());
   386 				fprintf(fp, "\n\n");
   387 
   388 				List<const ConVar *>::iterator iter;
   389 				float x;
   390 				for (iter = convars->begin(); iter != convars->end(); iter++)
   391 				{
   392 					const ConVar *cvar = (*iter);
   393 
   394 					if ((cvar->GetFlags() & FCVAR_DONTRECORD) == FCVAR_DONTRECORD)
   395 					{
   396 						continue;
   397 					}
   398 
   399 					char descr[255];
   400 					char *dptr = descr;
   401 
   402 					/* Print comments until there is no more */
   403 					strncopy(descr, cvar->GetHelpText(), sizeof(descr));
   404 					while (*dptr != '\0')
   405 					{
   406 						/* Find the next line */
   407 						char *next_ptr = dptr;
   408 						while (*next_ptr != '\0')
   409 						{
   410 							if (*next_ptr == '\n')
   411 							{
   412 								*next_ptr = '\0';
   413 								next_ptr++;
   414 								break;
   415 							}
   416 							next_ptr++;
   417 						}
   418 						fprintf(fp, "// %s\n", dptr);
   419 						dptr = next_ptr;
   420 					}
   421 
   422 					fprintf(fp, "// -\n");
   423 					fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
   424 					if (cvar->GetMin(x))
   425 					{
   426 						fprintf(fp, "// Minimum: \"%02f\"\n", x);
   427 					}
   428 					if (cvar->GetMax(x))
   429 					{
   430 						fprintf(fp, "// Maximum: \"%02f\"\n", x);
   431 					}
   432 					fprintf(fp, "%s \"%s\"\n", cvar->GetName(), cvar->GetDefault());
   433 					fprintf(fp, "\n");
   434 				}
   435 				fprintf(fp, "\n");
   436 
   437 				file_exists = true;
   438 				can_create = false;
   439 				fclose(fp);
   440 			}
   441 		}
   442 	}
   443 
   444 	if (file_exists)
   445 	{
   446 		char cmd[255];
   447 		UTIL_Format(cmd, sizeof(cmd), "exec %s\n", local);
   448 		engine->ServerCommand(cmd);
   449 	}
   450 
   451 	return can_create;
   452 }
   453 
   454 void SM_DoSingleExecFwds(IPluginContext *ctx)
   455 {
   456 	IPluginFunction *pf;
   457 
   458 	if ((pf = ctx->GetFunctionByName("OnServerCfg")) != NULL)
   459 	{
   460 		pf->Execute(NULL);
   461 	}
   462 
   463 	if ((pf = ctx->GetFunctionByName("OnConfigsExecuted")) != NULL)
   464 	{
   465 		pf->Execute(NULL);
   466 	}
   467 }
   468 
   469 void SM_ConfigsExecuted_Plugin(unsigned int serial)
   470 {
   471 	IPluginIterator *iter = g_PluginSys.GetPluginIterator();
   472 	while (iter->MorePlugins())
   473 	{
   474 		CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
   475 		if (plugin->GetSerial() == serial)
   476 		{
   477 			SM_DoSingleExecFwds(plugin->GetBaseContext());
   478 			break;
   479 		}
   480 		iter->NextPlugin();
   481 	}
   482 	iter->Release();
   483 }
   484 
   485 void SM_ExecuteForPlugin(IPluginContext *ctx)
   486 {
   487 	CPlugin *plugin = (CPlugin *)g_PluginSys.GetPluginByCtx(ctx->GetContext());
   488 
   489 	unsigned int num = plugin->GetConfigCount();
   490 	if (!num)
   491 	{
   492 		SM_DoSingleExecFwds(ctx);
   493 	}
   494 	else
   495 	{
   496 		bool can_create = true;
   497 		for (unsigned int i=0; i<num; i++)
   498 		{
   499 			can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
   500 		}
   501 		char cmd[255];
   502 		UTIL_Format(cmd, sizeof(cmd), "sm internal 2 %d\n", plugin->GetSerial());
   503 		engine->ServerCommand(cmd);
   504 	}
   505 }
   506 
   507 void SM_ExecuteAllConfigs()
   508 {
   509 	if (g_bGotServerStart)
   510 	{
   511 		return;
   512 	}
   513 
   514 	engine->ServerCommand("exec sourcemod/sourcemod.cfg\n");
   515 
   516 	IPluginIterator *iter = g_PluginSys.GetPluginIterator();
   517 	while (iter->MorePlugins())
   518 	{
   519 		CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
   520 		unsigned int num = plugin->GetConfigCount();
   521 		bool can_create = true;
   522 		for (unsigned int i=0; i<num; i++)
   523 		{
   524 			can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
   525 		}
   526 		iter->NextPlugin();
   527 	}
   528 	iter->Release();
   529 
   530 	g_bGotServerStart = true;
   531 	CheckAndFinalizeConfigs();
   532 }
   533 
   534 void SM_ConfigsExecuted_Global()
   535 {
   536 	if (g_bConfigsExecd)
   537 	{
   538 		return;
   539 	}
   540 
   541 	g_bConfigsExecd = true;
   542 
   543 	g_pOnServerCfg->Execute(NULL);
   544 	g_pOnConfigsExecuted->Execute(NULL);
   545 }
   546 
   547 void SM_InternalCmdTrigger()
   548 {
   549 	/* Order is important here.  We need to buffer things before we send the command out. */
   550 	g_pOnAutoConfigsBuffered->Execute(NULL);
   551 	engine->ServerCommand("sm internal 1\n");
   552     g_PendingInternalPush = false;
   553 }
   554