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