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 <sourcemod_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 || defined PLATFORM_APPLE
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 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()
71 # if SH_IMPL_VERSION >= 4
72 extern int __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
74 extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
76 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
77 void Hook_ExecDispatchPre()
80 #if SOURCE_ENGINE <= SE_DARKMESSIAH
84 const char *arg = cmd.Arg(1);
86 if (!g_bServerExecd && arg != NULL && strcmp(arg, g_ServerCfgFile->GetString()) == 0)
92 #if SOURCE_ENGINE >= SE_ORANGEBOX
93 void Hook_ExecDispatchPost(const CCommand &cmd)
95 void Hook_ExecDispatchPost()
100 g_bGotTrigger = false;
101 g_bServerExecd = true;
102 CheckAndFinalizeConfigs();
106 void CheckAndFinalizeConfigs()
108 if ((g_bServerExecd || g_ServerCfgFile == NULL) && g_bGotServerStart)
110 g_PendingInternalPush = true;
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 CoreConfig::CoreConfig() : m_Strings(512)
126 CoreConfig::~CoreConfig()
130 void CoreConfig::OnSourceModShutdown()
132 g_RootMenu.RemoveRootConsoleCommand("config", this);
133 g_Forwards.ReleaseForward(g_pOnServerCfg);
134 g_Forwards.ReleaseForward(g_pOnConfigsExecuted);
135 g_Forwards.ReleaseForward(g_pOnAutoConfigsBuffered);
137 if (g_pExecPtr != NULL)
139 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
140 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
145 void CoreConfig::OnSourceModLevelChange(const char *mapName)
147 static bool already_checked = false;
149 if (!already_checked)
151 if (engine->IsDedicatedServer())
153 g_ServerCfgFile = icvar->FindVar("servercfgfile");
157 g_ServerCfgFile = icvar->FindVar("lservercfgfile");
160 if (g_ServerCfgFile != NULL)
162 g_pExecPtr = FindCommand("exec");
163 if (g_pExecPtr != NULL)
165 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
166 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
170 g_ServerCfgFile = NULL;
173 already_checked = true;
176 g_bConfigsExecd = false;
177 g_bServerExecd = false;
178 g_bGotServerStart = false;
179 g_bGotTrigger = false;
182 void CoreConfig::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
184 int argcount = command.ArgC();
187 const char *option = command.Arg(2);
188 const char *value = command.Arg(3);
192 ConfigResult res = SetConfigOption(option, value, ConfigSource_Console, error, sizeof(error));
194 if (res == ConfigResult_Reject)
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);
200 g_RootMenu.ConsolePrint("[SM] Config option \"%s\" successfully set to \"%s\".", option, value);
204 } else if (argcount >= 3) {
205 const char *option = command.Arg(2);
207 const char *value = GetCoreConfigValue(option);
211 g_RootMenu.ConsolePrint("[SM] No such config option \"%s\" exists.", option);
213 g_RootMenu.ConsolePrint("[SM] Config option \"%s\" is set to \"%s\".", option, value);
219 g_RootMenu.ConsolePrint("[SM] Usage: sm config <option> [value]");
222 void CoreConfig::Initialize()
225 char filePath[PLATFORM_MAX_PATH];
227 /* Try to get command line value of core config convar */
228 const char *corecfg = icvar->GetCommandLineValue("sm_corecfgfile");
230 /* If sm_corecfgfile is on the command line, use that
231 * If sm_corecfgfile isn't there, check sm_basepath on the command line and build the path off that
232 * If sm_basepath isn't there, just use the default path for the cfg
236 g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s", g_SourceMod.GetGamePath(), corecfg);
240 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
242 /* Format path to config file */
245 g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s/%s", g_SourceMod.GetGamePath(), basepath, "configs/core.cfg");
249 g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s", g_SourceMod.GetGamePath(), sm_corecfgfile.GetDefault());
253 /* Reset cached key values */
257 /* Parse config file */
258 if ((err=textparsers->ParseFile_SMC(filePath, this, NULL)) != SMCError_Okay)
260 /* :TODO: This won't actually log or print anything :( - So fix that somehow */
261 const char *error = textparsers->GetSMCErrorString(err);
262 g_Logger.LogFatal("[SM] Error encountered parsing core config file: %s", error ? error : "");
266 SMCResult CoreConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
269 ConfigResult err = SetConfigOption(key, value, ConfigSource_File, error, sizeof(error));
271 if (err == ConfigResult_Reject)
273 /* This is a fatal error */
274 g_Logger.LogFatal("Config error (key: %s) (value: %s) %s", key, value, error);
277 return SMCResult_Continue;
280 ConfigResult CoreConfig::SetConfigOption(const char *option, const char *value, ConfigSource source, char *error, size_t maxlength)
285 SMGlobalClass *pBase = SMGlobalClass::head;
288 if ((result = pBase->OnSourceModConfigChanged(option, value, source, error, maxlength)) != ConfigResult_Ignore)
292 pBase = pBase->m_pGlobalClassNext;
295 m_KeyValues.replace(option, m_Strings.AddString(value));
297 return ConfigResult_Ignore;
300 const char *CoreConfig::GetCoreConfigValue(const char *key)
302 int *pKey = m_KeyValues.retrieve(key);
307 return m_Strings.GetString(*pKey);
310 bool SM_AreConfigsExecuted()
312 return g_bConfigsExecd;
315 inline bool IsPathSepChar(char c)
317 #if defined PLATFORM_WINDOWS
318 return (c == '\\' || c == '/');
319 #elif defined PLATFORM_LINUX || defined PLATFORM_POSIX
324 bool SM_ExecuteConfig(CPlugin *pl, AutoConfig *cfg, bool can_create)
326 bool will_create = false;
328 /* See if we should be creating */
329 if (can_create && cfg->create)
333 /* If the folder does not exist, attempt to create it.
334 * We're awfully nice.
336 const char *folder = cfg->folder.c_str();
337 char path[PLATFORM_MAX_PATH];
338 char build[PLATFORM_MAX_PATH];
340 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "cfg/%s", folder);
342 if (!g_LibSys.IsPathDirectory(path))
344 char *cur_ptr = path;
347 g_LibSys.PathFormat(path, sizeof(path), "%s", folder);
348 len = g_SourceMod.BuildPath(Path_Game, build, sizeof(build), "cfg");
352 /* Find next suitable path */
353 char *next_ptr = cur_ptr;
354 while (*next_ptr != '\0')
356 if (IsPathSepChar(*next_ptr))
364 if (*next_ptr == '\0')
368 len += g_LibSys.PathFormat(&build[len],
372 if (!g_LibSys.CreateFolder(build))
381 /* Check if the file exists. */
382 char file[PLATFORM_MAX_PATH];
383 char local[PLATFORM_MAX_PATH];
385 if (cfg->folder.size())
387 g_LibSys.PathFormat(local,
391 cfg->autocfg.c_str());
393 g_LibSys.PathFormat(local,
396 cfg->autocfg.c_str());
399 g_SourceMod.BuildPath(Path_Game, file, sizeof(file), "cfg/%s", local);
401 bool file_exists = g_LibSys.IsPathFile(file);
402 if (!file_exists && will_create)
404 List<const ConVar *> *convars = NULL;
405 if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
407 /* Attempt to create it */
408 FILE *fp = fopen(file, "wt");
411 fprintf(fp, "// This file was auto-generated by SourceMod (v%s)\n", SM_VERSION_STRING);
412 fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename());
415 List<const ConVar *>::iterator iter;
417 for (iter = convars->begin(); iter != convars->end(); iter++)
419 const ConVar *cvar = (*iter);
421 if ((cvar->GetFlags() & FCVAR_DONTRECORD) == FCVAR_DONTRECORD)
429 /* Print comments until there is no more */
430 strncopy(descr, cvar->GetHelpText(), sizeof(descr));
431 while (*dptr != '\0')
433 /* Find the next line */
434 char *next_ptr = dptr;
435 while (*next_ptr != '\0')
437 if (*next_ptr == '\n')
445 fprintf(fp, "// %s\n", dptr);
449 fprintf(fp, "// -\n");
450 fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
453 fprintf(fp, "// Minimum: \"%02f\"\n", x);
457 fprintf(fp, "// Maximum: \"%02f\"\n", x);
459 fprintf(fp, "%s \"%s\"\n", cvar->GetName(), cvar->GetDefault());
474 UTIL_Format(cmd, sizeof(cmd), "exec %s\n", local);
475 engine->ServerCommand(cmd);
481 void SM_DoSingleExecFwds(IPluginContext *ctx)
485 if ((pf = ctx->GetFunctionByName("OnServerCfg")) != NULL)
490 if ((pf = ctx->GetFunctionByName("OnConfigsExecuted")) != NULL)
496 void SM_ConfigsExecuted_Plugin(unsigned int serial)
498 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
499 while (iter->MorePlugins())
501 CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
502 if (plugin->GetSerial() == serial)
504 SM_DoSingleExecFwds(plugin->GetBaseContext());
512 void SM_ExecuteForPlugin(IPluginContext *ctx)
514 CPlugin *plugin = (CPlugin *)g_PluginSys.GetPluginByCtx(ctx->GetContext());
516 unsigned int num = plugin->GetConfigCount();
519 SM_DoSingleExecFwds(ctx);
523 bool can_create = true;
524 for (unsigned int i=0; i<num; i++)
526 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
529 UTIL_Format(cmd, sizeof(cmd), "sm internal 2 %d\n", plugin->GetSerial());
530 engine->ServerCommand(cmd);
534 void SM_ExecuteAllConfigs()
536 if (g_bGotServerStart)
541 engine->ServerCommand("exec sourcemod/sourcemod.cfg\n");
543 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
544 while (iter->MorePlugins())
546 CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
547 unsigned int num = plugin->GetConfigCount();
548 bool can_create = true;
549 for (unsigned int i=0; i<num; i++)
551 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
557 g_bGotServerStart = true;
558 CheckAndFinalizeConfigs();
561 void SM_ConfigsExecuted_Global()
568 g_bConfigsExecd = true;
570 g_pOnServerCfg->Execute(NULL);
571 g_pOnConfigsExecuted->Execute(NULL);
574 void SM_InternalCmdTrigger()
576 /* Order is important here. We need to buffer things before we send the command out. */
577 g_pOnAutoConfigsBuffered->Execute(NULL);
578 engine->ServerCommand("sm internal 1\n");
579 g_PendingInternalPush = false;