core/smn_core.cpp
author David Anderson <dvander@alliedmods.net>
Fri Sep 14 02:11:10 2007 +0000 (2007-09-14)
changeset 1423 e73b3563f254
parent 1419 67fdba7710ba
child 1458 be64f55b7ac5
permissions -rw-r--r--
- added 3 new natives for banning/unbanning and interception
- moved banning commands into new plugin, basebans
- improved quality and input methods of ban commands
- corrected svn props on a few files
- added an IsLANServer() to IGameHelpers API
- completely deprecated and removed old banning forwards
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2007 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <time.h>
    33 #include <string.h>
    34 #include <stdlib.h>
    35 #include "sm_stringutil.h"
    36 #include "sm_globals.h"
    37 #include "sourcemod.h"
    38 #include "PluginSys.h"
    39 #include "HandleSys.h"
    40 #include "LibrarySys.h"
    41 #include "TimerSys.h"
    42 #include "ForwardSys.h"
    43 #include "Logger.h"
    44 #include "ExtensionSys.h"
    45 
    46 #if defined PLATFORM_WINDOWS
    47 #include <windows.h>
    48 #elif defined PLATFORM_LINUX
    49 #include <limits.h>
    50 #include <unistd.h>
    51 #include <sys/times.h>
    52 #endif
    53 
    54 HandleType_t g_PlIter;
    55 ConVar sm_datetime_format("sm_datetime_format", "%m/%d/%Y - %H:%M:%S", 0, "Default formatting time rules");
    56 IForward *g_OnLogAction = NULL;
    57 
    58 class CoreNativeHelpers : 
    59 	public SMGlobalClass,
    60 	public IHandleTypeDispatch
    61 {
    62 public:
    63 	void OnSourceModAllInitialized()
    64 	{
    65 		HandleAccess hacc;
    66 		g_HandleSys.InitAccessDefaults(NULL,  &hacc);
    67 		hacc.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
    68 
    69 		g_PlIter = g_HandleSys.CreateType("PluginIterator", this, 0, NULL, NULL, g_pCoreIdent, NULL);
    70 
    71 		g_OnLogAction = g_Forwards.CreateForward("OnLogAction", 
    72 			ET_Hook, 
    73 			5, 
    74 			NULL,
    75 			Param_Cell,
    76 			Param_Cell,
    77 			Param_Cell,
    78 			Param_Cell,
    79 			Param_String);
    80 	}
    81 	void OnHandleDestroy(HandleType_t type, void *object)
    82 	{
    83 		IPluginIterator *iter = (IPluginIterator *)object;
    84 		iter->Release();
    85 	}
    86 	void OnSourceModShutdown()
    87 	{
    88 		g_Forwards.ReleaseForward(g_OnLogAction);
    89 		g_HandleSys.RemoveType(g_PlIter, g_pCoreIdent);
    90 	}
    91 } g_CoreNativeHelpers;
    92 
    93 void LogAction(Handle_t hndl, int type, int client, int target, const char *message)
    94 {
    95 	if (!g_OnLogAction->GetFunctionCount())
    96 	{
    97 		return;
    98 	}
    99 
   100 	cell_t result = 0;
   101 	g_OnLogAction->PushCell(hndl);
   102 	g_OnLogAction->PushCell(type);
   103 	g_OnLogAction->PushCell(client);
   104 	g_OnLogAction->PushCell(target);
   105 	g_OnLogAction->PushString(message);
   106 	g_OnLogAction->Execute(&result);
   107 
   108 	if (result >= (ResultType)Pl_Handled)
   109 	{
   110 		return;
   111 	}
   112 
   113 	const char *logtag = "SM";
   114 	if (type == 2)
   115 	{
   116 		HandleError err;
   117 		IPlugin *pPlugin = g_PluginSys.PluginFromHandle(hndl, &err);
   118 		if (pPlugin)
   119 		{
   120 			logtag = pPlugin->GetFilename();
   121 		}
   122 	}
   123 
   124 	g_Logger.LogMessage("[%s] %s", logtag, message);
   125 }
   126 
   127 static cell_t ThrowError(IPluginContext *pContext, const cell_t *params)
   128 {
   129 	char buffer[512];
   130 
   131 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   132 
   133 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   134 
   135 	if (pContext->GetContext()->n_err == SP_ERROR_NONE)
   136 	{
   137 		pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
   138 	}
   139 
   140 	return 0;
   141 }
   142 
   143 static cell_t GetTime(IPluginContext *pContext, const cell_t *params)
   144 {
   145 	time_t t = GetAdjustedTime();
   146 	cell_t *addr;
   147 	pContext->LocalToPhysAddr(params[1], &addr);
   148 
   149 	*(time_t *)addr = t;
   150 
   151 	return static_cast<cell_t>(t);
   152 }
   153 
   154 #if defined SUBPLATFORM_SECURECRT
   155 void _ignore_invalid_parameter(
   156 						const wchar_t * expression,
   157 						const wchar_t * function, 
   158 						const wchar_t * file, 
   159 						unsigned int line,
   160 						uintptr_t pReserved
   161 						)
   162 {
   163 	/* Wow we don't care, thanks Microsoft. */
   164 }
   165 #endif
   166 
   167 static cell_t FormatTime(IPluginContext *pContext, const cell_t *params)
   168 {
   169 	char *format, *buffer;
   170 	pContext->LocalToString(params[1], &buffer);
   171 	pContext->LocalToStringNULL(params[3], &format);
   172 
   173 	if (format == NULL)
   174 	{
   175 		format = const_cast<char *>(sm_datetime_format.GetString());
   176 	}
   177 
   178 #if defined SUBPLATFORM_SECURECRT
   179 	_invalid_parameter_handler handler = _set_invalid_parameter_handler(_ignore_invalid_parameter);
   180 #endif
   181 
   182 	time_t t = (params[4] == -1) ? GetAdjustedTime() : (time_t)params[4];
   183 	size_t written = strftime(buffer, params[2], format, localtime(&t));
   184 
   185 #if defined SUBPLATFORM_SECURECRT
   186 	_set_invalid_parameter_handler(handler);
   187 #endif
   188 
   189 	if (params[2] && format[0] != '\0' && !written)
   190 	{
   191 		pContext->ThrowNativeError("Invalid time format or buffer too small");
   192 		return 0;
   193 	}
   194 
   195 	return 1;
   196 }
   197 
   198 static cell_t GetPluginIterator(IPluginContext *pContext, const cell_t *params)
   199 {
   200 	IPluginIterator *iter = g_PluginSys.GetPluginIterator();
   201 
   202 	Handle_t hndl = g_HandleSys.CreateHandle(g_PlIter, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
   203 
   204 	if (hndl == BAD_HANDLE)
   205 	{
   206 		iter->Release();
   207 	}
   208 
   209 	return hndl;
   210 }
   211 
   212 static cell_t MorePlugins(IPluginContext *pContext, const cell_t *params)
   213 {
   214 	Handle_t hndl = (Handle_t)params[1];
   215 	HandleError err;
   216 	IPluginIterator *pIter;
   217 
   218 	HandleSecurity sec;
   219 	sec.pIdentity = g_pCoreIdent;
   220 	sec.pOwner = pContext->GetIdentity();
   221 
   222 	if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
   223 	{
   224 		return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   225 	}
   226 
   227 	return pIter->MorePlugins() ? 1 : 0;
   228 }
   229 
   230 static cell_t ReadPlugin(IPluginContext *pContext, const cell_t *params)
   231 {
   232 	Handle_t hndl = (Handle_t)params[1];
   233 	HandleError err;
   234 	IPluginIterator *pIter;
   235 
   236 	HandleSecurity sec;
   237 	sec.pIdentity = g_pCoreIdent;
   238 	sec.pOwner = pContext->GetIdentity();
   239 
   240 	if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
   241 	{
   242 		return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   243 	}
   244 
   245 	CPlugin *pPlugin = (CPlugin *)pIter->GetPlugin();
   246 	if (!pPlugin)
   247 	{
   248 		return BAD_HANDLE;
   249 	}
   250 
   251 	pIter->NextPlugin();
   252 
   253 	return pPlugin->GetMyHandle();
   254 }
   255 
   256 CPlugin *GetPluginFromHandle(IPluginContext *pContext, Handle_t hndl)
   257 {
   258 	if (hndl == BAD_HANDLE)
   259 	{
   260 		return g_PluginSys.GetPluginByCtx(pContext->GetContext());
   261 	} else {
   262 		HandleError err;
   263 		CPlugin *pPlugin = (CPlugin *)g_PluginSys.PluginFromHandle(hndl, &err);
   264 		if (!pPlugin)
   265 		{
   266 			pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   267 		}
   268 		return pPlugin;
   269 	}
   270 }
   271 
   272 static cell_t GetPluginStatus(IPluginContext *pContext, const cell_t *params)
   273 {
   274 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   275 	if (!pPlugin)
   276 	{
   277 		return 0;
   278 	}
   279 
   280 	return pPlugin->GetStatus();
   281 }
   282 
   283 static cell_t GetPluginFilename(IPluginContext *pContext, const cell_t *params)
   284 {
   285 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   286 	if (!pPlugin)
   287 	{
   288 		return 0;
   289 	}
   290 
   291 	pContext->StringToLocalUTF8(params[2], params[3], pPlugin->GetFilename(), NULL);
   292 
   293 	return 1;
   294 }
   295 
   296 static cell_t IsPluginDebugging(IPluginContext *pContext, const cell_t *params)
   297 {
   298 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   299 	if (!pPlugin)
   300 	{
   301 		return 0;
   302 	}
   303 
   304 	return pPlugin->IsDebugging() ? 1 : 0;
   305 }
   306 
   307 /* Local to plugins only */
   308 enum PluginInfo
   309 {
   310 	PlInfo_Name,			/**< Plugin name */
   311 	PlInfo_Author,			/**< Plugin author */
   312 	PlInfo_Description,		/**< Plugin description */
   313 	PlInfo_Version,			/**< Plugin verison */
   314 	PlInfo_URL,				/**< Plugin URL */
   315 };
   316 
   317 static cell_t GetPluginInfo(IPluginContext *pContext, const cell_t *params)
   318 {
   319 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   320 	if (!pPlugin)
   321 	{
   322 		return 0;
   323 	}
   324 
   325 	const sm_plugininfo_t *info = pPlugin->GetPublicInfo();
   326 
   327 	if (!info)
   328 	{
   329 		return 0;
   330 	}
   331 
   332 	const char *str = NULL;
   333 
   334 	switch ((PluginInfo)params[2])
   335 	{
   336 	case PlInfo_Name:
   337 		{
   338 			str = info->name;
   339 			break;
   340 		}
   341 	case PlInfo_Author:
   342 		{
   343 			str = info->author;
   344 			break;
   345 		}
   346 	case PlInfo_Description:
   347 		{
   348 			str = info->description;
   349 			break;
   350 		}
   351 	case PlInfo_Version:
   352 		{
   353 			str = info->version;
   354 			break;
   355 		}
   356 	case PlInfo_URL:
   357 		{
   358 			str = info->url;
   359 			break;
   360 		}
   361 	}
   362 
   363 	if (!str || str[0] == '\0')
   364 	{
   365 		return 0;
   366 	}
   367 
   368 	pContext->StringToLocalUTF8(params[3], params[4], str, NULL);
   369 
   370 	return 1;
   371 }
   372 
   373 static cell_t SetFailState(IPluginContext *pContext, const cell_t *params)
   374 {
   375 	char *str;
   376 	pContext->LocalToString(params[1], &str);
   377 
   378 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   379 	pPlugin->SetErrorState(Plugin_Error, "%s", str);
   380 
   381 	return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", str);
   382 }
   383 
   384 static cell_t GetSysTickCount(IPluginContext *pContext, const cell_t *params)
   385 {
   386 #if defined PLATFORM_WINDOWS
   387 	return (cell_t)GetTickCount();
   388 #elif defined PLATFORM_LINUX
   389 	tms tm;
   390 	clock_t ticks = times(&tm);
   391 	long ticks_per_sec = sysconf(_SC_CLK_TCK);
   392 	double fticks = (double)ticks / (double)ticks_per_sec;
   393 	fticks *= 1000.0f;
   394 	if (fticks > INT_MAX)
   395 	{
   396 		double r = (int)(fticks / INT_MAX) * (double)INT_MAX;
   397 		fticks -= r;
   398 	}
   399 	return (cell_t)fticks;
   400 #endif
   401 }
   402 
   403 static cell_t AutoExecConfig(IPluginContext *pContext, const cell_t *params)
   404 {
   405 	CPlugin *plugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   406 
   407 	char *cfg, *folder;
   408 	pContext->LocalToString(params[2], &cfg);
   409 	pContext->LocalToString(params[3], &folder);
   410 
   411 	if (cfg[0] == '\0')
   412 	{
   413 		static char temp_str[255];
   414 		static char temp_file[PLATFORM_MAX_PATH];
   415 		char *ptr;
   416 
   417 		g_LibSys.GetFileFromPath(temp_str, sizeof(temp_str), plugin->GetFilename());
   418 		if ((ptr = strstr(temp_str, ".smx")) != NULL)
   419 		{
   420 			*ptr = '\0';
   421 		}
   422 
   423 		/* We have the raw filename! */
   424 		UTIL_Format(temp_file, sizeof(temp_file), "plugin.%s", temp_str);
   425 		cfg = temp_file;
   426 	}
   427 
   428 	plugin->AddConfig(params[1] ? true : false, cfg, folder);
   429 
   430 	return 1;
   431 }
   432 
   433 static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *params)
   434 {
   435 	char *name;
   436 	uint32_t idx;
   437 	sp_context_t *ctx = pContext->GetContext();
   438 
   439 	pContext->LocalToString(params[1], &name);
   440 	if (pContext->FindNativeByName(name, &idx) != SP_ERROR_NONE)
   441 	{
   442 		/* Oops! This HAS to silently fail! */
   443 		return 0;
   444 	}
   445 
   446 	ctx->natives[idx].flags |= SP_NTVFLAG_OPTIONAL;
   447 
   448 	return 1;
   449 }
   450 
   451 static cell_t RegPluginLibrary(IPluginContext *pContext, const cell_t *params)
   452 {
   453 	char *name;
   454 	CPlugin *pl = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   455 
   456 	pContext->LocalToString(params[1], &name);
   457 
   458 	pl->AddLibrary(name);
   459 
   460 	return 1;
   461 }
   462 
   463 static cell_t LibraryExists(IPluginContext *pContext, const cell_t *params)
   464 {
   465 	char *str;
   466 	pContext->LocalToString(params[1], &str);
   467 
   468 	return g_PluginSys.LibraryExists(str) ? 1 : 0;
   469 }
   470 
   471 static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params)
   472 {
   473 	char buffer[2048];
   474 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   475 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
   476 
   477 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   478 	{
   479 		return 0;
   480 	}
   481 
   482 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   483 
   484 	LogAction(pPlugin->GetMyHandle(), 2, params[1], params[2], buffer);
   485 
   486 	return 1;
   487 }
   488 
   489 static cell_t LogToFile(IPluginContext *pContext, const cell_t *params)
   490 {
   491 	char *file;
   492 	pContext->LocalToString(params[1], &file);
   493 
   494 	char path[PLATFORM_MAX_PATH];
   495 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
   496 
   497 	FILE *fp = fopen(path, "at");
   498 	if (!fp)
   499 	{
   500 		return pContext->ThrowNativeError("Could not open file \"%s\"", path);
   501 	}
   502 
   503 	char buffer[2048];
   504 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   505 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   506 
   507 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   508 	{
   509 		fclose(fp);
   510 		return 0;
   511 	}
   512 
   513 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   514 
   515 	g_Logger.LogToOpenFile(fp, "[%s] %s", pPlugin->GetFilename(), buffer);
   516 
   517 	fclose(fp);
   518 
   519 	return 1;
   520 }
   521 
   522 static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params)
   523 {
   524 	char *file;
   525 	pContext->LocalToString(params[1], &file);
   526 
   527 	char path[PLATFORM_MAX_PATH];
   528 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
   529 
   530 	FILE *fp = fopen(path, "at");
   531 	if (!fp)
   532 	{
   533 		return pContext->ThrowNativeError("Could not open file \"%s\"", path);
   534 	}
   535 
   536 	char buffer[2048];
   537 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   538 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   539 
   540 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   541 	{
   542 		fclose(fp);
   543 		return 0;
   544 	}
   545 
   546 	g_Logger.LogToOpenFile(fp, "%s", buffer);
   547 
   548 	fclose(fp);
   549 
   550 	return 1;
   551 }
   552 
   553 static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *params)
   554 {
   555 	char *str;
   556 	pContext->LocalToString(params[1], &str);
   557 
   558 	IExtension *pExtension = g_Extensions.FindExtensionByFile(str);
   559 	
   560 	if (!pExtension)
   561 	{
   562 		return -2;
   563 	}
   564 	
   565 	if (!pExtension->IsLoaded())
   566 	{
   567 		return -1;
   568 	}
   569 
   570 	char *error;
   571 	pContext->LocalToString(params[2], &error);
   572 	if (!pExtension->IsRunning(error, params[3]))
   573 	{
   574 		return 0;
   575 	}
   576 
   577 	return 1;
   578 }
   579 
   580 REGISTER_NATIVES(coreNatives)
   581 {
   582 	{"AutoExecConfig",			AutoExecConfig},
   583 	{"GetPluginFilename",		GetPluginFilename},
   584 	{"GetPluginInfo",			GetPluginInfo},
   585 	{"GetPluginIterator",		GetPluginIterator},
   586 	{"GetPluginStatus",			GetPluginStatus},
   587 	{"GetSysTickCount",			GetSysTickCount},
   588 	{"GetTime",					GetTime},
   589 	{"IsPluginDebugging",		IsPluginDebugging},
   590 	{"MorePlugins",				MorePlugins},
   591 	{"ReadPlugin",				ReadPlugin},
   592 	{"ThrowError",				ThrowError},
   593 	{"SetFailState",			SetFailState},
   594 	{"FormatTime",				FormatTime},
   595 	{"MarkNativeAsOptional",	MarkNativeAsOptional},
   596 	{"RegPluginLibrary",		RegPluginLibrary},
   597 	{"LibraryExists",			LibraryExists},
   598 	{"LogAction",				sm_LogAction},
   599 	{"LogToFile",				LogToFile},
   600 	{"LogToFileEx",				LogToFileEx},
   601 	{"GetExtensionFileStatus",	GetExtensionFileStatus},
   602 	{NULL,						NULL},
   603 };
   604