3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
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"
41 #include "PluginSys.h"
42 #include "ForwardSys.h"
43 #include "frame_hooks.h"
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");
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;
62 void CheckAndFinalizeConfigs();
64 #if defined ORANGEBOX_BUILD
65 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
66 void Hook_ExecDispatchPre(const CCommand &cmd)
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()
73 #if !defined ORANGEBOX_BUILD
77 const char *arg = cmd.Arg(1);
81 && strcmp(arg, g_ServerCfgFile->GetString()) == 0)
87 #if defined ORANGEBOX_BUILD
88 void Hook_ExecDispatchPost(const CCommand &cmd)
90 void Hook_ExecDispatchPost()
95 g_bGotTrigger = false;
96 g_bServerExecd = true;
97 CheckAndFinalizeConfigs();
101 void CheckAndFinalizeConfigs()
103 if ((g_bServerExecd || g_ServerCfgFile == NULL)
104 && g_bGotServerStart)
106 #if defined ORANGEBOX_BUILD
107 g_PendingInternalPush = true;
109 SM_InternalCmdTrigger();
114 void CoreConfig::OnSourceModAllInitialized()
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);
122 void CoreConfig::OnSourceModShutdown()
124 g_RootMenu.RemoveRootConsoleCommand("config", this);
125 g_Forwards.ReleaseForward(g_pOnServerCfg);
126 g_Forwards.ReleaseForward(g_pOnConfigsExecuted);
127 g_Forwards.ReleaseForward(g_pOnAutoConfigsBuffered);
129 if (g_pExecPtr != NULL)
131 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
132 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
137 void CoreConfig::OnSourceModLevelChange(const char *mapName)
139 static bool already_checked = false;
141 if (!already_checked)
143 g_ServerCfgFile = icvar->FindVar("servercfgfile");
144 if (g_ServerCfgFile != NULL)
146 ConCommandBase *pBase = icvar->GetCommands();
147 while (pBase != NULL)
149 if (pBase->IsCommand() && strcmp(pBase->GetName(), "exec") == 0)
153 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
156 g_pExecPtr = (ConCommand *)pBase;
157 if (g_pExecPtr != NULL)
159 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
160 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
164 g_ServerCfgFile = NULL;
167 already_checked = true;
170 g_bConfigsExecd = false;
171 g_bServerExecd = false;
172 g_bGotServerStart = false;
173 g_bGotTrigger = false;
176 void CoreConfig::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
178 int argcount = command.ArgC();
181 const char *option = command.Arg(2);
182 const char *value = command.Arg(3);
186 ConfigResult res = SetConfigOption(option, value, ConfigSource_Console, error, sizeof(error));
188 if (res == ConfigResult_Reject)
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);
194 g_RootMenu.ConsolePrint("Config option \"%s\" successfully set to \"%s.\"", option, value);
200 g_RootMenu.ConsolePrint("[SM] Usage: sm config <option> <value>");
203 void CoreConfig::Initialize()
206 char filePath[PLATFORM_MAX_PATH];
208 /* Try to get command line value of core config convar */
209 const char *corecfg = icvar->GetCommandLineValue("sm_corecfgfile");
211 /* If sm_corecfgfile not specified on command line, use default value */
214 corecfg = sm_corecfgfile.GetDefault();
217 /* Format path to config file */
218 g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s", g_SourceMod.GetGamePath(), corecfg);
220 /* Parse config file */
221 if ((err=textparsers->ParseFile_SMC(filePath, this, NULL)) != SMCError_Okay)
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 : "");
229 SMCResult CoreConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
232 ConfigResult err = SetConfigOption(key, value, ConfigSource_File, error, sizeof(error));
234 if (err == ConfigResult_Reject)
236 /* This is a fatal error */
237 g_Logger.LogFatal("Config error (key: %s) (value: %s) %s", key, value, error);
240 return SMCResult_Continue;
243 ConfigResult CoreConfig::SetConfigOption(const char *option, const char *value, ConfigSource source, char *error, size_t maxlength)
248 SMGlobalClass *pBase = SMGlobalClass::head;
251 if ((result = pBase->OnSourceModConfigChanged(option, value, source, error, maxlength)) != ConfigResult_Ignore)
255 pBase = pBase->m_pGlobalClassNext;
258 return ConfigResult_Ignore;
261 bool SM_AreConfigsExecuted()
263 return g_bConfigsExecd;
266 inline bool IsPathSepChar(char c)
268 #if defined PLATFORM_WINDOWS
269 return (c == '\\' || c == '/');
270 #elif defined PLATFORM_LINUX
275 bool SM_ExecuteConfig(CPlugin *pl, AutoConfig *cfg, bool can_create)
277 bool will_create = false;
279 /* See if we should be creating */
280 if (can_create && cfg->create)
284 /* If the folder does not exist, attempt to create it.
285 * We're awfully nice.
287 const char *folder = cfg->folder.c_str();
288 char path[PLATFORM_MAX_PATH];
289 char build[PLATFORM_MAX_PATH];
291 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "cfg/%s", folder);
293 if (!g_LibSys.IsPathDirectory(path))
295 char *cur_ptr = path;
298 g_LibSys.PathFormat(path, sizeof(path), "%s", folder);
299 len = g_SourceMod.BuildPath(Path_Game, build, sizeof(build), "cfg");
303 /* Find next suitable path */
304 char *next_ptr = cur_ptr;
305 while (*next_ptr != '\0')
307 if (IsPathSepChar(*next_ptr))
315 if (*next_ptr == '\0')
319 len += g_LibSys.PathFormat(&build[len],
323 if (!g_LibSys.CreateFolder(build))
332 /* Check if the file exists. */
333 char file[PLATFORM_MAX_PATH];
334 char local[PLATFORM_MAX_PATH];
336 if (cfg->folder.size())
338 g_LibSys.PathFormat(local,
342 cfg->autocfg.c_str());
344 g_LibSys.PathFormat(local,
347 cfg->autocfg.c_str());
350 g_SourceMod.BuildPath(Path_Game, file, sizeof(file), "cfg/%s", local);
352 bool file_exists = g_LibSys.IsPathFile(file);
353 if (!file_exists && will_create)
355 List<const ConVar *> *convars = NULL;
356 if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
358 /* Attempt to create it */
359 FILE *fp = fopen(file, "wt");
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());
366 List<const ConVar *>::iterator iter;
368 for (iter = convars->begin(); iter != convars->end(); iter++)
370 const ConVar *cvar = (*iter);
372 if ((cvar->GetFlags() & FCVAR_DONTRECORD) == FCVAR_DONTRECORD)
380 /* Print comments until there is no more */
381 strncopy(descr, cvar->GetHelpText(), sizeof(descr));
382 while (*dptr != '\0')
384 /* Find the next line */
385 char *next_ptr = dptr;
386 while (*next_ptr != '\0')
388 if (*next_ptr == '\n')
396 fprintf(fp, "// %s\n", dptr);
400 fprintf(fp, "// -\n");
401 fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
404 fprintf(fp, "// Minimum: \"%02f\"\n", x);
408 fprintf(fp, "// Maximum: \"%02f\"\n", x);
410 fprintf(fp, "%s \"%s\"\n", cvar->GetName(), cvar->GetDefault());
425 UTIL_Format(cmd, sizeof(cmd), "exec %s\n", local);
426 engine->ServerCommand(cmd);
432 void SM_DoSingleExecFwds(IPluginContext *ctx)
436 if ((pf = ctx->GetFunctionByName("OnServerCfg")) != NULL)
441 if ((pf = ctx->GetFunctionByName("OnConfigsExecuted")) != NULL)
447 void SM_ConfigsExecuted_Plugin(unsigned int serial)
449 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
450 while (iter->MorePlugins())
452 CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
453 if (plugin->GetSerial() == serial)
455 SM_DoSingleExecFwds(plugin->GetBaseContext());
463 void SM_ExecuteForPlugin(IPluginContext *ctx)
465 CPlugin *plugin = (CPlugin *)g_PluginSys.GetPluginByCtx(ctx->GetContext());
467 unsigned int num = plugin->GetConfigCount();
470 SM_DoSingleExecFwds(ctx);
474 bool can_create = true;
475 for (unsigned int i=0; i<num; i++)
477 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
480 UTIL_Format(cmd, sizeof(cmd), "sm internal 2 %d\n", plugin->GetSerial());
481 engine->ServerCommand(cmd);
485 void SM_ExecuteAllConfigs()
487 if (g_bGotServerStart)
492 engine->ServerCommand("exec sourcemod/sourcemod.cfg\n");
494 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
495 while (iter->MorePlugins())
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++)
502 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
508 g_bGotServerStart = true;
509 CheckAndFinalizeConfigs();
512 void SM_ConfigsExecuted_Global()
519 g_bConfigsExecd = true;
521 g_pOnServerCfg->Execute(NULL);
522 g_pOnConfigsExecuted->Execute(NULL);
525 void SM_InternalCmdTrigger()
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;