core/smn_core.cpp
author David Anderson <dvander@alliedmods.net>
Wed Feb 27 13:49:57 2008 +0000 (2008-02-27)
changeset 1900 457329ae65bd
parent 1833 3bb2c9cb63d2
child 1947 e73a1e51833b
permissions -rw-r--r--
fixed amb1483 - GetEntPropString() rejected FIELD_MODELNAME/FIELD_SOUNDNAME
     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 		cell_t result = 0;
    98 		g_OnLogAction->PushCell(hndl);
    99 		g_OnLogAction->PushCell(type);
   100 		g_OnLogAction->PushCell(client);
   101 		g_OnLogAction->PushCell(target);
   102 		g_OnLogAction->PushString(message);
   103 		g_OnLogAction->Execute(&result);
   104 
   105 		if (result >= (ResultType)Pl_Handled)
   106 		{
   107 			return;
   108 		}
   109 	}
   110 
   111 	const char *logtag = "SM";
   112 	if (type == 2)
   113 	{
   114 		HandleError err;
   115 		IPlugin *pPlugin = g_PluginSys.PluginFromHandle(hndl, &err);
   116 		if (pPlugin)
   117 		{
   118 			logtag = pPlugin->GetFilename();
   119 		}
   120 	}
   121 
   122 	g_Logger.LogMessage("[%s] %s", logtag, message);
   123 }
   124 
   125 static cell_t ThrowError(IPluginContext *pContext, const cell_t *params)
   126 {
   127 	char buffer[512];
   128 
   129 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   130 
   131 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   132 
   133 	if (pContext->GetContext()->n_err == SP_ERROR_NONE)
   134 	{
   135 		pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
   136 	}
   137 
   138 	return 0;
   139 }
   140 
   141 static cell_t GetTime(IPluginContext *pContext, const cell_t *params)
   142 {
   143 	time_t t = GetAdjustedTime();
   144 	cell_t *addr;
   145 	pContext->LocalToPhysAddr(params[1], &addr);
   146 
   147 	*(time_t *)addr = t;
   148 
   149 	return static_cast<cell_t>(t);
   150 }
   151 
   152 #if defined SUBPLATFORM_SECURECRT
   153 void _ignore_invalid_parameter(
   154 						const wchar_t * expression,
   155 						const wchar_t * function, 
   156 						const wchar_t * file, 
   157 						unsigned int line,
   158 						uintptr_t pReserved
   159 						)
   160 {
   161 	/* Wow we don't care, thanks Microsoft. */
   162 }
   163 #endif
   164 
   165 static cell_t FormatTime(IPluginContext *pContext, const cell_t *params)
   166 {
   167 	char *format, *buffer;
   168 	pContext->LocalToString(params[1], &buffer);
   169 	pContext->LocalToStringNULL(params[3], &format);
   170 
   171 	if (format == NULL)
   172 	{
   173 		format = const_cast<char *>(sm_datetime_format.GetString());
   174 	}
   175 
   176 #if defined SUBPLATFORM_SECURECRT
   177 	_invalid_parameter_handler handler = _set_invalid_parameter_handler(_ignore_invalid_parameter);
   178 #endif
   179 
   180 	time_t t = (params[4] == -1) ? GetAdjustedTime() : (time_t)params[4];
   181 	size_t written = strftime(buffer, params[2], format, localtime(&t));
   182 
   183 #if defined SUBPLATFORM_SECURECRT
   184 	_set_invalid_parameter_handler(handler);
   185 #endif
   186 
   187 	if (params[2] && format[0] != '\0' && !written)
   188 	{
   189 		pContext->ThrowNativeError("Invalid time format or buffer too small");
   190 		return 0;
   191 	}
   192 
   193 	return 1;
   194 }
   195 
   196 static cell_t GetPluginIterator(IPluginContext *pContext, const cell_t *params)
   197 {
   198 	IPluginIterator *iter = g_PluginSys.GetPluginIterator();
   199 
   200 	Handle_t hndl = g_HandleSys.CreateHandle(g_PlIter, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
   201 
   202 	if (hndl == BAD_HANDLE)
   203 	{
   204 		iter->Release();
   205 	}
   206 
   207 	return hndl;
   208 }
   209 
   210 static cell_t MorePlugins(IPluginContext *pContext, const cell_t *params)
   211 {
   212 	Handle_t hndl = (Handle_t)params[1];
   213 	HandleError err;
   214 	IPluginIterator *pIter;
   215 
   216 	HandleSecurity sec;
   217 	sec.pIdentity = g_pCoreIdent;
   218 	sec.pOwner = pContext->GetIdentity();
   219 
   220 	if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
   221 	{
   222 		return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   223 	}
   224 
   225 	return pIter->MorePlugins() ? 1 : 0;
   226 }
   227 
   228 static cell_t ReadPlugin(IPluginContext *pContext, const cell_t *params)
   229 {
   230 	Handle_t hndl = (Handle_t)params[1];
   231 	HandleError err;
   232 	IPluginIterator *pIter;
   233 
   234 	HandleSecurity sec;
   235 	sec.pIdentity = g_pCoreIdent;
   236 	sec.pOwner = pContext->GetIdentity();
   237 
   238 	if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
   239 	{
   240 		return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   241 	}
   242 
   243 	CPlugin *pPlugin = (CPlugin *)pIter->GetPlugin();
   244 	if (!pPlugin)
   245 	{
   246 		return BAD_HANDLE;
   247 	}
   248 
   249 	pIter->NextPlugin();
   250 
   251 	return pPlugin->GetMyHandle();
   252 }
   253 
   254 CPlugin *GetPluginFromHandle(IPluginContext *pContext, Handle_t hndl)
   255 {
   256 	if (hndl == BAD_HANDLE)
   257 	{
   258 		return g_PluginSys.GetPluginByCtx(pContext->GetContext());
   259 	} else {
   260 		HandleError err;
   261 		CPlugin *pPlugin = (CPlugin *)g_PluginSys.PluginFromHandle(hndl, &err);
   262 		if (!pPlugin)
   263 		{
   264 			pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
   265 		}
   266 		return pPlugin;
   267 	}
   268 }
   269 
   270 static cell_t GetPluginStatus(IPluginContext *pContext, const cell_t *params)
   271 {
   272 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   273 	if (!pPlugin)
   274 	{
   275 		return 0;
   276 	}
   277 
   278 	return pPlugin->GetStatus();
   279 }
   280 
   281 static cell_t GetPluginFilename(IPluginContext *pContext, const cell_t *params)
   282 {
   283 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   284 	if (!pPlugin)
   285 	{
   286 		return 0;
   287 	}
   288 
   289 	pContext->StringToLocalUTF8(params[2], params[3], pPlugin->GetFilename(), NULL);
   290 
   291 	return 1;
   292 }
   293 
   294 static cell_t IsPluginDebugging(IPluginContext *pContext, const cell_t *params)
   295 {
   296 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   297 	if (!pPlugin)
   298 	{
   299 		return 0;
   300 	}
   301 
   302 	return pPlugin->IsDebugging() ? 1 : 0;
   303 }
   304 
   305 /* Local to plugins only */
   306 enum PluginInfo
   307 {
   308 	PlInfo_Name,			/**< Plugin name */
   309 	PlInfo_Author,			/**< Plugin author */
   310 	PlInfo_Description,		/**< Plugin description */
   311 	PlInfo_Version,			/**< Plugin verison */
   312 	PlInfo_URL,				/**< Plugin URL */
   313 };
   314 
   315 static cell_t GetPluginInfo(IPluginContext *pContext, const cell_t *params)
   316 {
   317 	CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
   318 	if (!pPlugin)
   319 	{
   320 		return 0;
   321 	}
   322 
   323 	const sm_plugininfo_t *info = pPlugin->GetPublicInfo();
   324 
   325 	if (!info)
   326 	{
   327 		return 0;
   328 	}
   329 
   330 	const char *str = NULL;
   331 
   332 	switch ((PluginInfo)params[2])
   333 	{
   334 	case PlInfo_Name:
   335 		{
   336 			str = info->name;
   337 			break;
   338 		}
   339 	case PlInfo_Author:
   340 		{
   341 			str = info->author;
   342 			break;
   343 		}
   344 	case PlInfo_Description:
   345 		{
   346 			str = info->description;
   347 			break;
   348 		}
   349 	case PlInfo_Version:
   350 		{
   351 			str = info->version;
   352 			break;
   353 		}
   354 	case PlInfo_URL:
   355 		{
   356 			str = info->url;
   357 			break;
   358 		}
   359 	}
   360 
   361 	if (!str || str[0] == '\0')
   362 	{
   363 		return 0;
   364 	}
   365 
   366 	pContext->StringToLocalUTF8(params[3], params[4], str, NULL);
   367 
   368 	return 1;
   369 }
   370 
   371 static cell_t SetFailState(IPluginContext *pContext, const cell_t *params)
   372 {
   373 	char *str;
   374 	CPlugin *pPlugin;
   375 
   376 	pContext->LocalToString(params[1], &str);
   377 	pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   378 
   379 	if (params[0] == 1)
   380 	{
   381 		pPlugin->SetErrorState(Plugin_Error, "%s", str);
   382 
   383 		return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", str);
   384 	}
   385 	else
   386 	{
   387 		char buffer[2048];
   388 
   389 		g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
   390 		if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   391 		{
   392 			pPlugin->SetErrorState(Plugin_Error, "%s", str);
   393 			return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "Formatting error (%s)", str);
   394 		}
   395 		else
   396 		{
   397 			pPlugin->SetErrorState(Plugin_Error, "%s", buffer);
   398 			return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
   399 		}
   400 	}
   401 
   402 	return 0;
   403 }
   404 
   405 static cell_t GetSysTickCount(IPluginContext *pContext, const cell_t *params)
   406 {
   407 #if defined PLATFORM_WINDOWS
   408 	return (cell_t)GetTickCount();
   409 #elif defined PLATFORM_LINUX
   410 	tms tm;
   411 	clock_t ticks = times(&tm);
   412 	long ticks_per_sec = sysconf(_SC_CLK_TCK);
   413 	double fticks = (double)ticks / (double)ticks_per_sec;
   414 	fticks *= 1000.0f;
   415 	if (fticks > INT_MAX)
   416 	{
   417 		double r = (int)(fticks / INT_MAX) * (double)INT_MAX;
   418 		fticks -= r;
   419 	}
   420 	return (cell_t)fticks;
   421 #endif
   422 }
   423 
   424 static cell_t AutoExecConfig(IPluginContext *pContext, const cell_t *params)
   425 {
   426 	CPlugin *plugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   427 
   428 	char *cfg, *folder;
   429 	pContext->LocalToString(params[2], &cfg);
   430 	pContext->LocalToString(params[3], &folder);
   431 
   432 	if (cfg[0] == '\0')
   433 	{
   434 		static char temp_str[255];
   435 		static char temp_file[PLATFORM_MAX_PATH];
   436 		char *ptr;
   437 
   438 		g_LibSys.GetFileFromPath(temp_str, sizeof(temp_str), plugin->GetFilename());
   439 		if ((ptr = strstr(temp_str, ".smx")) != NULL)
   440 		{
   441 			*ptr = '\0';
   442 		}
   443 
   444 		/* We have the raw filename! */
   445 		UTIL_Format(temp_file, sizeof(temp_file), "plugin.%s", temp_str);
   446 		cfg = temp_file;
   447 	}
   448 
   449 	plugin->AddConfig(params[1] ? true : false, cfg, folder);
   450 
   451 	return 1;
   452 }
   453 
   454 static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *params)
   455 {
   456 	char *name;
   457 	uint32_t idx;
   458 	sp_context_t *ctx = pContext->GetContext();
   459 
   460 	pContext->LocalToString(params[1], &name);
   461 	if (pContext->FindNativeByName(name, &idx) != SP_ERROR_NONE)
   462 	{
   463 		/* Oops! This HAS to silently fail! */
   464 		return 0;
   465 	}
   466 
   467 	ctx->natives[idx].flags |= SP_NTVFLAG_OPTIONAL;
   468 
   469 	return 1;
   470 }
   471 
   472 static cell_t RegPluginLibrary(IPluginContext *pContext, const cell_t *params)
   473 {
   474 	char *name;
   475 	CPlugin *pl = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   476 
   477 	pContext->LocalToString(params[1], &name);
   478 
   479 	pl->AddLibrary(name);
   480 
   481 	return 1;
   482 }
   483 
   484 static cell_t LibraryExists(IPluginContext *pContext, const cell_t *params)
   485 {
   486 	char *str;
   487 	pContext->LocalToString(params[1], &str);
   488 
   489 	if (g_PluginSys.LibraryExists(str))
   490 	{
   491 		return 1;
   492 	}
   493 
   494 	if (g_Extensions.LibraryExists(str))
   495 	{
   496 		return 1;
   497 	}
   498 
   499 	return 0;
   500 }
   501 
   502 static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params)
   503 {
   504 	char buffer[2048];
   505 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   506 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
   507 
   508 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   509 	{
   510 		return 0;
   511 	}
   512 
   513 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   514 
   515 	LogAction(pPlugin->GetMyHandle(), 2, params[1], params[2], buffer);
   516 
   517 	return 1;
   518 }
   519 
   520 static cell_t LogToFile(IPluginContext *pContext, const cell_t *params)
   521 {
   522 	char *file;
   523 	pContext->LocalToString(params[1], &file);
   524 
   525 	char path[PLATFORM_MAX_PATH];
   526 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
   527 
   528 	FILE *fp = fopen(path, "at");
   529 	if (!fp)
   530 	{
   531 		return pContext->ThrowNativeError("Could not open file \"%s\"", path);
   532 	}
   533 
   534 	char buffer[2048];
   535 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   536 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   537 
   538 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   539 	{
   540 		fclose(fp);
   541 		return 0;
   542 	}
   543 
   544 	CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
   545 
   546 	g_Logger.LogToOpenFile(fp, "[%s] %s", pPlugin->GetFilename(), buffer);
   547 
   548 	fclose(fp);
   549 
   550 	return 1;
   551 }
   552 
   553 static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params)
   554 {
   555 	char *file;
   556 	pContext->LocalToString(params[1], &file);
   557 
   558 	char path[PLATFORM_MAX_PATH];
   559 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
   560 
   561 	FILE *fp = fopen(path, "at");
   562 	if (!fp)
   563 	{
   564 		return pContext->ThrowNativeError("Could not open file \"%s\"", path);
   565 	}
   566 
   567 	char buffer[2048];
   568 	g_SourceMod.SetGlobalTarget(LANG_SERVER);
   569 	g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
   570 
   571 	if (pContext->GetContext()->n_err != SP_ERROR_NONE)
   572 	{
   573 		fclose(fp);
   574 		return 0;
   575 	}
   576 
   577 	g_Logger.LogToOpenFile(fp, "%s", buffer);
   578 
   579 	fclose(fp);
   580 
   581 	return 1;
   582 }
   583 
   584 static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *params)
   585 {
   586 	char *str;
   587 	pContext->LocalToString(params[1], &str);
   588 
   589 	IExtension *pExtension = g_Extensions.FindExtensionByFile(str);
   590 	
   591 	if (!pExtension)
   592 	{
   593 		return -2;
   594 	}
   595 	
   596 	if (!pExtension->IsLoaded())
   597 	{
   598 		return -1;
   599 	}
   600 
   601 	char *error;
   602 	pContext->LocalToString(params[2], &error);
   603 	if (!pExtension->IsRunning(error, params[3]))
   604 	{
   605 		return 0;
   606 	}
   607 
   608 	return 1;
   609 }
   610 
   611 static cell_t FindPluginByNumber(IPluginContext *pContext, const cell_t *params)
   612 {
   613 	CPlugin *pPlugin = g_PluginSys.GetPluginByOrder(params[1]);
   614 	
   615 	if (pPlugin == NULL)
   616 	{
   617 		return BAD_HANDLE;
   618 	}
   619 
   620 	return pPlugin->GetMyHandle();
   621 }
   622 
   623 REGISTER_NATIVES(coreNatives)
   624 {
   625 	{"AutoExecConfig",			AutoExecConfig},
   626 	{"GetPluginFilename",		GetPluginFilename},
   627 	{"GetPluginInfo",			GetPluginInfo},
   628 	{"GetPluginIterator",		GetPluginIterator},
   629 	{"GetPluginStatus",			GetPluginStatus},
   630 	{"GetSysTickCount",			GetSysTickCount},
   631 	{"GetTime",					GetTime},
   632 	{"IsPluginDebugging",		IsPluginDebugging},
   633 	{"MorePlugins",				MorePlugins},
   634 	{"ReadPlugin",				ReadPlugin},
   635 	{"ThrowError",				ThrowError},
   636 	{"SetFailState",			SetFailState},
   637 	{"FormatTime",				FormatTime},
   638 	{"MarkNativeAsOptional",	MarkNativeAsOptional},
   639 	{"RegPluginLibrary",		RegPluginLibrary},
   640 	{"LibraryExists",			LibraryExists},
   641 	{"LogAction",				sm_LogAction},
   642 	{"LogToFile",				LogToFile},
   643 	{"LogToFileEx",				LogToFileEx},
   644 	{"GetExtensionFileStatus",	GetExtensionFileStatus},
   645 	{"FindPluginByNumber",		FindPluginByNumber},
   646 	{NULL,						NULL},
   647 };
   648