core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Sat Feb 17 09:02:22 2007 +0000 (2007-02-17)
changeset 516 0807e52b4e02
parent 496 a16c05dcf584
child 520 7676d61cde2d
permissions -rw-r--r--
clientconnect now blocks properly when needed
removed cruft
     1 /**
     2  * ===============================================================
     3  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     4  * ===============================================================
     5  *
     6  * This file is not open source and may not be copied without explicit
     7  * written permission of AlliedModders LLC.  This file may not be redistributed 
     8  * in whole or significant part.
     9  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    10  *
    11  * Version: $Id$
    12  */
    13 
    14 #include <stdio.h>
    15 #include "sourcemod.h"
    16 #include "sourcemm_api.h"
    17 #include "systems/LibrarySys.h"
    18 #include "vm/sp_vm_engine.h"
    19 #include <sh_string.h>
    20 #include "PluginSys.h"
    21 #include "ShareSys.h"
    22 #include "CLogger.h"
    23 #include "ExtensionSys.h"
    24 #include "AdminCache.h"
    25 #include "sm_stringutil.h"
    26 #include "CPlayerManager.h"
    27 
    28 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    29 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    30 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    31 
    32 SourcePawnEngine g_SourcePawn;
    33 SourceModBase g_SourceMod;
    34 
    35 ILibrary *g_pJIT = NULL;
    36 SourceHook::String g_BaseDir;
    37 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
    38 IVirtualMachine *g_pVM;
    39 IdentityToken_t *g_pCoreIdent = NULL;
    40 float g_LastTime = 0.0f;
    41 float g_LastAuthCheck = 0.0f;
    42 
    43 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    44 typedef unsigned int (*GETEXPORTCOUNT)();
    45 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    46 typedef void (*NOTIFYSHUTDOWN)();
    47 
    48 void ShutdownJIT()
    49 {
    50 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    51 	if (notify)
    52 	{
    53 		notify();
    54 	}
    55 
    56 	g_pJIT->CloseLibrary();
    57 }
    58 
    59 SourceModBase::SourceModBase()
    60 {
    61 	m_IsMapLoading = false;
    62 	m_ExecPluginReload = false;
    63 }
    64 
    65 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
    66 {
    67 	g_BaseDir.assign(g_SMAPI->GetBaseDir());
    68 	g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
    69 	g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
    70 
    71 	/* Attempt to load the JIT! */
    72 	char file[PLATFORM_MAX_PATH];
    73 	char myerror[255];
    74 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
    75 		GetSourceModPath(),
    76 		PLATFORM_LIB_EXT
    77 		);
    78 
    79 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
    80 	if (!g_pJIT)
    81 	{
    82 		if (error && err_max)
    83 		{
    84 			snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
    85 				myerror,
    86 				PLATFORM_LIB_EXT);
    87 		}
    88 		return false;
    89 	}
    90 
    91 	int err;
    92 	GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
    93 	if (!jit_init)
    94 	{
    95 		ShutdownJIT();
    96 		if (error && err_max)
    97 		{
    98 			snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
    99 		}
   100 		return false;
   101 	}
   102 
   103 	if ((err=jit_init(g_pSourcePawn)) != 0)
   104 	{
   105 		ShutdownJIT();
   106 		if (error && err_max)
   107 		{
   108 			snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
   109 		}
   110 		return false;
   111 	}
   112 
   113 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   114 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   115 	if (!jit_get)
   116 	{
   117 		ShutdownJIT();
   118 		if (error && err_max)
   119 		{
   120 			snprintf(error, err_max, "JIT is missing a necessary export!");
   121 		}
   122 		return false;
   123 	}
   124 
   125 	unsigned int num = jit_getnum();
   126 	if (!num || ((g_pVM=jit_get(0)) == NULL))
   127 	{
   128 		ShutdownJIT();
   129 		if (error && err_max)
   130 		{
   131 			snprintf(error, err_max, "JIT did not export any virtual machines!");
   132 		}
   133 		return false;
   134 	}
   135 
   136 	unsigned int api = g_pVM->GetAPIVersion();
   137 	if (api != SOURCEPAWN_VM_API_VERSION)
   138 	{
   139 		ShutdownJIT();
   140 		if (error && err_max)
   141 		{
   142 			snprintf(error, err_max, "JIT is not a compatible version");
   143 		}
   144 		return false;
   145 	}
   146 
   147 	StartSourceMod(late);
   148 
   149 	return true;
   150 }
   151 
   152 void SourceModBase::StartSourceMod(bool late)
   153 {
   154 	/* First initialize the global hooks we need */
   155 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   156 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   157 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   158 
   159 	enginePatch = SH_GET_CALLCLASS(engine);
   160 
   161 	/* Notify! */
   162 	SMGlobalClass *pBase = SMGlobalClass::head;
   163 	while (pBase)
   164 	{
   165 		pBase->OnSourceModStartup(false);
   166 		pBase = pBase->m_pGlobalClassNext;
   167 	}
   168 
   169 	/* Make the global core identity */
   170 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   171 
   172 	/* Notify! */
   173 	pBase = SMGlobalClass::head;
   174 	while (pBase)
   175 	{
   176 		pBase->OnSourceModAllInitialized();
   177 		pBase = pBase->m_pGlobalClassNext;
   178 	}
   179 
   180 	/* Add us now... */
   181 	g_ShareSys.AddInterface(NULL, this);
   182 }
   183 
   184 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   185 {
   186 	m_IsMapLoading = true;
   187 	m_ExecPluginReload = true;
   188 	g_LastTime = 0.0f;
   189 	g_LastAuthCheck = 0.0f;
   190 
   191 	g_Logger.MapChange(pMapName);
   192 
   193 	DoGlobalPluginLoads();
   194 
   195 	m_IsMapLoading = false;
   196 
   197 	g_Admins.DumpAdminCache(AdminCache_Overrides, true);
   198 	g_Admins.DumpAdminCache(AdminCache_Groups, true);
   199 
   200 	RETURN_META_VALUE(MRES_IGNORED, true);
   201 }
   202 
   203 void SourceModBase::GameFrame(bool simulating)
   204 {
   205 	/**
   206 	 * Note: This is all hardcoded rather than delegated to save
   207 	 * precious CPU cycles.
   208 	 */
   209 	float curtime = gpGlobals->curtime;
   210 	if (curtime - g_LastTime > 0.1f)
   211 	{
   212 		if (m_CheckingAuth
   213 			&& (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
   214 		{
   215 			g_LastAuthCheck = gpGlobals->curtime;
   216 			g_Players.RunAuthChecks();
   217 		}
   218 		g_LastTime = curtime;
   219 	}
   220 }
   221 
   222 void SourceModBase::LevelShutdown()
   223 {
   224 	if (m_ExecPluginReload)
   225 	{
   226 		g_PluginSys.ReloadOrUnloadPlugins();
   227 		m_ExecPluginReload = false;
   228 	}
   229 }
   230 
   231 bool SourceModBase::IsMapLoading() const
   232 {
   233 	return m_IsMapLoading;
   234 }
   235 
   236 void SourceModBase::DoGlobalPluginLoads()
   237 {
   238 	char config_path[PLATFORM_MAX_PATH];
   239 	char plugins_path[PLATFORM_MAX_PATH];
   240 
   241 	BuildPath(Path_SM, config_path, 
   242 		sizeof(config_path),
   243 		"configs/plugin_settings.cfg");
   244 	BuildPath(Path_SM, plugins_path,
   245 		sizeof(plugins_path),
   246 		"plugins");
   247 
   248 	/* Load any auto extensions */
   249 	g_Extensions.TryAutoload();
   250 
   251 	/* Run the first pass */
   252 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   253 
   254 	/* Mark any extensions as loaded */
   255 	g_Extensions.MarkAllLoaded();
   256 
   257 	/* No modules yet, it's safe to call this from here */
   258 	g_PluginSys.LoadAll_SecondPass();
   259 
   260 	/* Re-mark any extensions as loaded */
   261 	g_Extensions.MarkAllLoaded();
   262 }
   263 
   264 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
   265 {
   266 	char _buffer[PLATFORM_MAX_PATH+1];
   267 	va_list ap;
   268 
   269 	va_start(ap, format);
   270 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   271 	va_end(ap);
   272 
   273 	const char *base = NULL;
   274 	if (type == Path_Game)
   275 	{
   276 		base = GetModPath();
   277 	} else if (type == Path_SM) {
   278 		base = GetSourceModPath();
   279 	} else if (type == Path_SM_Rel) {
   280 		base = m_SMRelDir;
   281 	}
   282 
   283 	if (base)
   284 	{
   285 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   286 	} else {
   287 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   288 	}
   289 }
   290 
   291 void SourceModBase::CloseSourceMod()
   292 {
   293 	/* Notify! */
   294 	SMGlobalClass *pBase = SMGlobalClass::head;
   295 	while (pBase)
   296 	{
   297 		pBase->OnSourceModShutdown();
   298 		pBase = pBase->m_pGlobalClassNext;
   299 	}
   300 
   301 	/* Delete all data packs */
   302 	CStack<CDataPack *>::iterator iter;
   303 	CDataPack *pd;
   304 	for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   305 	{
   306 		pd = (*iter);
   307 		delete pd;
   308 	}
   309 	m_freepacks.popall();
   310 
   311 	/* Notify! */
   312 	pBase = SMGlobalClass::head;
   313 	while (pBase)
   314 	{
   315 		pBase->OnSourceModAllShutdown();
   316 		pBase = pBase->m_pGlobalClassNext;
   317 	}
   318 
   319 	if (enginePatch)
   320 	{
   321 		SH_RELEASE_CALLCLASS(enginePatch);
   322 		enginePatch = NULL;
   323 	}
   324 
   325 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   326 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   327 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   328 
   329 	/* Rest In Peace */
   330 	ShutdownJIT();
   331 }
   332 
   333 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   334 {
   335 	IExtensionInterface *pAPI = pExt->GetAPI();
   336 	const char *tag = pAPI->GetExtensionTag();
   337 	char buffer[2048];
   338 	va_list ap;
   339 
   340 	va_start(ap, format);
   341 	vsnprintf(buffer, sizeof(buffer), format, ap);
   342 	va_end(ap);
   343 
   344 	if (tag)
   345 	{
   346 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   347 	} else {
   348 		g_Logger.LogMessage("%s", buffer);
   349 	}
   350 }
   351 
   352 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   353 {
   354 	IExtensionInterface *pAPI = pExt->GetAPI();
   355 	const char *tag = pAPI->GetExtensionTag();
   356 	char buffer[2048];
   357 	va_list ap;
   358 
   359 	va_start(ap, format);
   360 	vsnprintf(buffer, sizeof(buffer), format, ap);
   361 	va_end(ap);
   362 
   363 	if (tag)
   364 	{
   365 		g_Logger.LogError("[%s] %s", tag, buffer);
   366 	} else {
   367 		g_Logger.LogError("%s", buffer);
   368 	}
   369 }
   370 
   371 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   372 {
   373 	char *fmt;
   374 
   375 	pContext->LocalToString(params[param], &fmt);
   376 
   377 	int lparam = ++param;
   378 
   379 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   380 }
   381 
   382 const char *SourceModBase::GetSourceModPath() const
   383 {
   384 	return m_SMBaseDir;
   385 }
   386 
   387 const char *SourceModBase::GetModPath() const
   388 {
   389 	return g_BaseDir.c_str();
   390 }
   391 
   392 void SourceModBase::SetGlobalTarget(unsigned int index)
   393 {
   394 	m_target = index;
   395 }
   396 
   397 void SourceModBase::SetAuthChecking(bool set)
   398 {
   399 	m_CheckingAuth = set;
   400 }
   401 
   402 unsigned int SourceModBase::GetGlobalTarget() const
   403 {
   404 	return m_target;
   405 }
   406 
   407 IDataPack *SourceModBase::CreateDataPack()
   408 {
   409 	CDataPack *pack;
   410 	if (m_freepacks.empty())
   411 	{
   412 		pack = new CDataPack;
   413 	} else {
   414 		pack = m_freepacks.front();
   415 		m_freepacks.pop();
   416 		pack->Initialize();
   417 	}
   418 	return pack;
   419 }
   420 
   421 void SourceModBase::FreeDataPack(IDataPack *pack)
   422 {
   423 	m_freepacks.push(static_cast<CDataPack *>(pack));
   424 }
   425 
   426 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   427 {
   428 	//:TODO:
   429 	return 0;
   430 }
   431 
   432 SMGlobalClass *SMGlobalClass::head = NULL;
   433 
   434 SMGlobalClass::SMGlobalClass()
   435 {
   436 	m_pGlobalClassNext = SMGlobalClass::head;
   437 	SMGlobalClass::head = this;
   438 }