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