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"
44 #ifdef PLATFORM_WINDOWS
45 ConVar sm_corecfgfile("sm_corecfgfile", "addons\\sourcemod\\configs\\core.cfg", 0, "SourceMod core configuration file");
46 #elif defined PLATFORM_LINUX
47 ConVar sm_corecfgfile("sm_corecfgfile", "addons/sourcemod/configs/core.cfg", 0, "SourceMod core configuration file");
50 IForward *g_pOnServerCfg = NULL;
51 IForward *g_pOnConfigsExecuted = NULL;
52 IForward *g_pOnAutoConfigsBuffered = NULL;
53 CoreConfig g_CoreConfig;
54 bool g_bConfigsExecd = false;
55 bool g_bServerExecd = false;
56 bool g_bGotServerStart = false;
57 bool g_bGotTrigger = false;
58 ConCommand *g_pExecPtr = NULL;
59 ConVar *g_ServerCfgFile = NULL;
61 void CheckAndFinalizeConfigs();
63 #if defined ORANGEBOX_BUILD
64 SH_DECL_EXTERN1_void(ConCommand, Dispatch, SH_NOATTRIB, false, const CCommand &);
65 void Hook_ExecDispatchPre(const CCommand &cmd)
67 extern bool __SourceHook_FHAddConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
68 extern bool __SourceHook_FHRemoveConCommandDispatch(void *,bool,class fastdelegate::FastDelegate0<void>);
69 void Hook_ExecDispatchPre()
72 #if !defined ORANGEBOX_BUILD
76 const char *arg = cmd.Arg(1);
80 && strcmp(arg, g_ServerCfgFile->GetString()) == 0)
86 #if defined ORANGEBOX_BUILD
87 void Hook_ExecDispatchPost(const CCommand &cmd)
89 void Hook_ExecDispatchPost()
94 g_bGotTrigger = false;
95 g_bServerExecd = true;
96 CheckAndFinalizeConfigs();
100 void CheckAndFinalizeConfigs()
102 if ((g_bServerExecd || g_ServerCfgFile == NULL)
103 && g_bGotServerStart)
105 /* Order is important here. We need to buffer things before we send the command out. */
106 g_pOnAutoConfigsBuffered->Execute(NULL);
107 engine->ServerCommand("sm internal 1\n");
111 void CoreConfig::OnSourceModAllInitialized()
113 g_RootMenu.AddRootConsoleCommand("config", "Set core configuration options", this);
114 g_pOnServerCfg = g_Forwards.CreateForward("OnServerCfg", ET_Ignore, 0, NULL);
115 g_pOnConfigsExecuted = g_Forwards.CreateForward("OnConfigsExecuted", ET_Ignore, 0, NULL);
116 g_pOnAutoConfigsBuffered = g_Forwards.CreateForward("OnAutoConfigsBuffered", ET_Ignore, 0, NULL);
119 void CoreConfig::OnSourceModShutdown()
121 g_RootMenu.RemoveRootConsoleCommand("config", this);
122 g_Forwards.ReleaseForward(g_pOnServerCfg);
123 g_Forwards.ReleaseForward(g_pOnConfigsExecuted);
124 g_Forwards.ReleaseForward(g_pOnAutoConfigsBuffered);
126 if (g_pExecPtr != NULL)
128 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
129 SH_REMOVE_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
134 void CoreConfig::OnSourceModLevelChange(const char *mapName)
136 static bool already_checked = false;
138 if (!already_checked)
140 g_ServerCfgFile = icvar->FindVar("servercfgfile");
141 if (g_ServerCfgFile != NULL)
143 ConCommandBase *pBase = icvar->GetCommands();
144 while (pBase != NULL)
146 if (pBase->IsCommand() && strcmp(pBase->GetName(), "exec") == 0)
150 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
153 g_pExecPtr = (ConCommand *)pBase;
154 if (g_pExecPtr != NULL)
156 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
157 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
161 g_ServerCfgFile = NULL;
164 already_checked = true;
167 g_bConfigsExecd = false;
168 g_bServerExecd = false;
169 g_bGotServerStart = false;
170 g_bGotTrigger = false;
173 void CoreConfig::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
175 int argcount = command.ArgC();
178 const char *option = command.Arg(2);
179 const char *value = command.Arg(3);
183 ConfigResult res = SetConfigOption(option, value, ConfigSource_Console, error, sizeof(error));
185 if (res == ConfigResult_Reject)
187 g_RootMenu.ConsolePrint("[SM] Could not set config option \"%s\" to \"%s\" (%s)", option, value, error);
188 } else if (res == ConfigResult_Ignore) {
189 g_RootMenu.ConsolePrint("[SM] No such config option \"%s\" exists.", option);
191 g_RootMenu.ConsolePrint("Config option \"%s\" successfully set to \"%s.\"", option, value);
197 g_RootMenu.ConsolePrint("[SM] Usage: sm config <option> <value>");
200 void CoreConfig::Initialize()
203 char filePath[PLATFORM_MAX_PATH];
205 /* Try to get command line value of core config convar */
206 const char *corecfg = icvar->GetCommandLineValue("sm_corecfgfile");
208 /* If sm_corecfgfile not specified on command line, use default value */
211 corecfg = sm_corecfgfile.GetDefault();
214 /* Format path to config file */
215 g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s", g_SourceMod.GetGamePath(), corecfg);
217 /* Parse config file */
218 if ((err=textparsers->ParseFile_SMC(filePath, this, NULL)) != SMCError_Okay)
220 /* :TODO: This won't actually log or print anything :( - So fix that somehow */
221 const char *error = textparsers->GetSMCErrorString(err);
222 g_Logger.LogFatal("[SM] Error encountered parsing core config file: %s", error ? error : "");
226 SMCResult CoreConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
229 ConfigResult err = SetConfigOption(key, value, ConfigSource_File, error, sizeof(error));
231 if (err == ConfigResult_Reject)
233 /* This is a fatal error */
234 g_Logger.LogFatal("Config error (key: %s) (value: %s) %s", key, value, error);
237 return SMCResult_Continue;
240 ConfigResult CoreConfig::SetConfigOption(const char *option, const char *value, ConfigSource source, char *error, size_t maxlength)
245 SMGlobalClass *pBase = SMGlobalClass::head;
248 if ((result = pBase->OnSourceModConfigChanged(option, value, source, error, maxlength)) != ConfigResult_Ignore)
252 pBase = pBase->m_pGlobalClassNext;
255 return ConfigResult_Ignore;
258 bool SM_AreConfigsExecuted()
260 return g_bConfigsExecd;
263 inline bool IsPathSepChar(char c)
265 #if defined PLATFORM_WINDOWS
266 return (c == '\\' || c == '/');
267 #elif defined PLATFORM_LINUX
272 bool SM_ExecuteConfig(CPlugin *pl, AutoConfig *cfg, bool can_create)
274 bool will_create = false;
276 /* See if we should be creating */
277 if (can_create && cfg->create)
281 /* If the folder does not exist, attempt to create it.
282 * We're awfully nice.
284 const char *folder = cfg->folder.c_str();
285 char path[PLATFORM_MAX_PATH];
286 char build[PLATFORM_MAX_PATH];
288 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "cfg/%s", folder);
290 if (!g_LibSys.IsPathDirectory(path))
292 char *cur_ptr = path;
295 g_LibSys.PathFormat(path, sizeof(path), "%s", folder);
296 len = g_SourceMod.BuildPath(Path_Game, build, sizeof(build), "cfg");
300 /* Find next suitable path */
301 char *next_ptr = cur_ptr;
302 while (*next_ptr != '\0')
304 if (IsPathSepChar(*next_ptr))
312 if (*next_ptr == '\0')
316 len += g_LibSys.PathFormat(&build[len],
320 if (!g_LibSys.CreateFolder(build))
329 /* Check if the file exists. */
330 char file[PLATFORM_MAX_PATH];
331 char local[PLATFORM_MAX_PATH];
333 if (cfg->folder.size())
335 g_LibSys.PathFormat(local,
339 cfg->autocfg.c_str());
341 g_LibSys.PathFormat(local,
344 cfg->autocfg.c_str());
347 g_SourceMod.BuildPath(Path_Game, file, sizeof(file), "cfg/%s", local);
349 bool file_exists = g_LibSys.IsPathFile(file);
350 if (!file_exists && will_create)
352 List<const ConVar *> *convars = NULL;
353 if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
355 /* Attempt to create it */
356 FILE *fp = fopen(file, "wt");
359 fprintf(fp, "// This file was auto-generated by SourceMod (v%s)\n", SVN_FULL_VERSION);
360 fprintf(fp, "// ConVars for plugin \"%s\"\n", pl->GetFilename());
363 List<const ConVar *>::iterator iter;
365 for (iter = convars->begin(); iter != convars->end(); iter++)
367 const ConVar *cvar = (*iter);
369 if ((cvar->GetFlags() & FCVAR_DONTRECORD) == FCVAR_DONTRECORD)
377 /* Print comments until there is no more */
378 strncopy(descr, cvar->GetHelpText(), sizeof(descr));
379 while (*dptr != '\0')
381 /* Find the next line */
382 char *next_ptr = dptr;
383 while (*next_ptr != '\0')
385 if (*next_ptr == '\n')
393 fprintf(fp, "// %s\n", dptr);
397 fprintf(fp, "// -\n");
398 fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
401 fprintf(fp, "// Minimum: \"%02f\"\n", x);
405 fprintf(fp, "// Maximum: \"%02f\"\n", x);
407 fprintf(fp, "%s \"%s\"\n", cvar->GetName(), cvar->GetDefault());
422 UTIL_Format(cmd, sizeof(cmd), "exec %s\n", local);
423 engine->ServerCommand(cmd);
429 void SM_DoSingleExecFwds(IPluginContext *ctx)
433 if ((pf = ctx->GetFunctionByName("OnServerCfg")) != NULL)
438 if ((pf = ctx->GetFunctionByName("OnConfigsExecuted")) != NULL)
444 void SM_ConfigsExecuted_Plugin(unsigned int serial)
446 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
447 while (iter->MorePlugins())
449 CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
450 if (plugin->GetSerial() == serial)
452 SM_DoSingleExecFwds(plugin->GetBaseContext());
460 void SM_ExecuteForPlugin(IPluginContext *ctx)
462 CPlugin *plugin = (CPlugin *)g_PluginSys.GetPluginByCtx(ctx->GetContext());
464 unsigned int num = plugin->GetConfigCount();
467 SM_DoSingleExecFwds(ctx);
471 bool can_create = true;
472 for (unsigned int i=0; i<num; i++)
474 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
477 UTIL_Format(cmd, sizeof(cmd), "sm internal 2 %d\n", plugin->GetSerial());
478 engine->ServerCommand(cmd);
482 void SM_ExecuteAllConfigs()
484 if (g_bGotServerStart)
489 engine->ServerCommand("exec sourcemod/sourcemod.cfg\n");
491 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
492 while (iter->MorePlugins())
494 CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
495 unsigned int num = plugin->GetConfigCount();
496 bool can_create = true;
497 for (unsigned int i=0; i<num; i++)
499 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
505 #if defined ORANGEBOX_BUILD
506 engine->ServerExecute();
509 g_bGotServerStart = true;
510 CheckAndFinalizeConfigs();
513 void SM_ConfigsExecuted_Global()
520 g_bConfigsExecd = true;
522 g_pOnServerCfg->Execute(NULL);
523 g_pOnConfigsExecuted->Execute(NULL);