Merge.
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 SOURCE_ENGINE >= SE_ORANGEBOX
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 SOURCE_ENGINE == SE_EPISODEONE
77 const char *arg = cmd.Arg(1);
81 && strcmp(arg, g_ServerCfgFile->GetString()) == 0)
87 #if SOURCE_ENGINE >= SE_ORANGEBOX
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 SOURCE_ENGINE >= SE_ORANGEBOX
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 if (engine->IsDedicatedServer())
145 g_ServerCfgFile = icvar->FindVar("servercfgfile");
149 g_ServerCfgFile = icvar->FindVar("lservercfgfile");
152 if (g_ServerCfgFile != NULL)
154 g_pExecPtr = FindCommand("exec");
155 if (g_pExecPtr != NULL)
157 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPre, false);
158 SH_ADD_HOOK_STATICFUNC(ConCommand, Dispatch, g_pExecPtr, Hook_ExecDispatchPost, true);
162 g_ServerCfgFile = NULL;
165 already_checked = true;
168 g_bConfigsExecd = false;
169 g_bServerExecd = false;
170 g_bGotServerStart = false;
171 g_bGotTrigger = false;
174 void CoreConfig::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
176 int argcount = command.ArgC();
179 const char *option = command.Arg(2);
180 const char *value = command.Arg(3);
184 ConfigResult res = SetConfigOption(option, value, ConfigSource_Console, error, sizeof(error));
186 if (res == ConfigResult_Reject)
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);
192 g_RootMenu.ConsolePrint("Config option \"%s\" successfully set to \"%s.\"", option, value);
198 g_RootMenu.ConsolePrint("[SM] Usage: sm config <option> <value>");
201 void CoreConfig::Initialize()
204 char filePath[PLATFORM_MAX_PATH];
206 /* Try to get command line value of core config convar */
207 const char *corecfg = icvar->GetCommandLineValue("sm_corecfgfile");
209 /* If sm_corecfgfile not specified on command line, use default value */
212 corecfg = sm_corecfgfile.GetDefault();
215 /* Format path to config file */
216 g_LibSys.PathFormat(filePath, sizeof(filePath), "%s/%s", g_SourceMod.GetGamePath(), corecfg);
218 /* Parse config file */
219 if ((err=textparsers->ParseFile_SMC(filePath, this, NULL)) != SMCError_Okay)
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 : "");
227 SMCResult CoreConfig::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
230 ConfigResult err = SetConfigOption(key, value, ConfigSource_File, error, sizeof(error));
232 if (err == ConfigResult_Reject)
234 /* This is a fatal error */
235 g_Logger.LogFatal("Config error (key: %s) (value: %s) %s", key, value, error);
238 return SMCResult_Continue;
241 ConfigResult CoreConfig::SetConfigOption(const char *option, const char *value, ConfigSource source, char *error, size_t maxlength)
246 SMGlobalClass *pBase = SMGlobalClass::head;
249 if ((result = pBase->OnSourceModConfigChanged(option, value, source, error, maxlength)) != ConfigResult_Ignore)
253 pBase = pBase->m_pGlobalClassNext;
256 return ConfigResult_Ignore;
259 bool SM_AreConfigsExecuted()
261 return g_bConfigsExecd;
264 inline bool IsPathSepChar(char c)
266 #if defined PLATFORM_WINDOWS
267 return (c == '\\' || c == '/');
268 #elif defined PLATFORM_LINUX
273 bool SM_ExecuteConfig(CPlugin *pl, AutoConfig *cfg, bool can_create)
275 bool will_create = false;
277 /* See if we should be creating */
278 if (can_create && cfg->create)
282 /* If the folder does not exist, attempt to create it.
283 * We're awfully nice.
285 const char *folder = cfg->folder.c_str();
286 char path[PLATFORM_MAX_PATH];
287 char build[PLATFORM_MAX_PATH];
289 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "cfg/%s", folder);
291 if (!g_LibSys.IsPathDirectory(path))
293 char *cur_ptr = path;
296 g_LibSys.PathFormat(path, sizeof(path), "%s", folder);
297 len = g_SourceMod.BuildPath(Path_Game, build, sizeof(build), "cfg");
301 /* Find next suitable path */
302 char *next_ptr = cur_ptr;
303 while (*next_ptr != '\0')
305 if (IsPathSepChar(*next_ptr))
313 if (*next_ptr == '\0')
317 len += g_LibSys.PathFormat(&build[len],
321 if (!g_LibSys.CreateFolder(build))
330 /* Check if the file exists. */
331 char file[PLATFORM_MAX_PATH];
332 char local[PLATFORM_MAX_PATH];
334 if (cfg->folder.size())
336 g_LibSys.PathFormat(local,
340 cfg->autocfg.c_str());
342 g_LibSys.PathFormat(local,
345 cfg->autocfg.c_str());
348 g_SourceMod.BuildPath(Path_Game, file, sizeof(file), "cfg/%s", local);
350 bool file_exists = g_LibSys.IsPathFile(file);
351 if (!file_exists && will_create)
353 List<const ConVar *> *convars = NULL;
354 if (pl->GetProperty("ConVarList", (void **)&convars, false) && convars)
356 /* Attempt to create it */
357 FILE *fp = fopen(file, "wt");
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());
364 List<const ConVar *>::iterator iter;
366 for (iter = convars->begin(); iter != convars->end(); iter++)
368 const ConVar *cvar = (*iter);
370 if ((cvar->GetFlags() & FCVAR_DONTRECORD) == FCVAR_DONTRECORD)
378 /* Print comments until there is no more */
379 strncopy(descr, cvar->GetHelpText(), sizeof(descr));
380 while (*dptr != '\0')
382 /* Find the next line */
383 char *next_ptr = dptr;
384 while (*next_ptr != '\0')
386 if (*next_ptr == '\n')
394 fprintf(fp, "// %s\n", dptr);
398 fprintf(fp, "// -\n");
399 fprintf(fp, "// Default: \"%s\"\n", cvar->GetDefault());
402 fprintf(fp, "// Minimum: \"%02f\"\n", x);
406 fprintf(fp, "// Maximum: \"%02f\"\n", x);
408 fprintf(fp, "%s \"%s\"\n", cvar->GetName(), cvar->GetDefault());
423 UTIL_Format(cmd, sizeof(cmd), "exec %s\n", local);
424 engine->ServerCommand(cmd);
430 void SM_DoSingleExecFwds(IPluginContext *ctx)
434 if ((pf = ctx->GetFunctionByName("OnServerCfg")) != NULL)
439 if ((pf = ctx->GetFunctionByName("OnConfigsExecuted")) != NULL)
445 void SM_ConfigsExecuted_Plugin(unsigned int serial)
447 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
448 while (iter->MorePlugins())
450 CPlugin *plugin = (CPlugin *)(iter->GetPlugin());
451 if (plugin->GetSerial() == serial)
453 SM_DoSingleExecFwds(plugin->GetBaseContext());
461 void SM_ExecuteForPlugin(IPluginContext *ctx)
463 CPlugin *plugin = (CPlugin *)g_PluginSys.GetPluginByCtx(ctx->GetContext());
465 unsigned int num = plugin->GetConfigCount();
468 SM_DoSingleExecFwds(ctx);
472 bool can_create = true;
473 for (unsigned int i=0; i<num; i++)
475 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
478 UTIL_Format(cmd, sizeof(cmd), "sm internal 2 %d\n", plugin->GetSerial());
479 engine->ServerCommand(cmd);
483 void SM_ExecuteAllConfigs()
485 if (g_bGotServerStart)
490 engine->ServerCommand("exec sourcemod/sourcemod.cfg\n");
492 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
493 while (iter->MorePlugins())
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++)
500 can_create = SM_ExecuteConfig(plugin, plugin->GetConfig(i), can_create);
506 g_bGotServerStart = true;
507 CheckAndFinalizeConfigs();
510 void SM_ConfigsExecuted_Global()
517 g_bConfigsExecd = true;
519 g_pOnServerCfg->Execute(NULL);
520 g_pOnConfigsExecuted->Execute(NULL);
523 void SM_InternalCmdTrigger()
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;