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>.
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"
42 #include "ForwardSys.h"
44 #include "ExtensionSys.h"
45 #include <sm_trie_tpl.h>
47 #if defined PLATFORM_WINDOWS
49 #elif defined PLATFORM_LINUX
52 #include <sys/times.h>
55 HandleType_t g_PlIter;
56 ConVar sm_datetime_format("sm_datetime_format", "%m/%d/%Y - %H:%M:%S", 0, "Default formatting time rules");
57 IForward *g_OnLogAction = NULL;
59 class CoreNativeHelpers :
61 public IHandleTypeDispatch
64 void OnSourceModAllInitialized()
67 g_HandleSys.InitAccessDefaults(NULL, &hacc);
68 hacc.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY|HANDLE_RESTRICT_OWNER;
70 g_PlIter = g_HandleSys.CreateType("PluginIterator", this, 0, NULL, NULL, g_pCoreIdent, NULL);
72 g_OnLogAction = g_Forwards.CreateForward("OnLogAction",
82 void OnHandleDestroy(HandleType_t type, void *object)
84 IPluginIterator *iter = (IPluginIterator *)object;
87 void OnSourceModShutdown()
89 g_Forwards.ReleaseForward(g_OnLogAction);
90 g_HandleSys.RemoveType(g_PlIter, g_pCoreIdent);
92 } g_CoreNativeHelpers;
94 void LogAction(Handle_t hndl, int type, int client, int target, const char *message)
96 if (g_OnLogAction->GetFunctionCount())
99 g_OnLogAction->PushCell(hndl);
100 g_OnLogAction->PushCell(type);
101 g_OnLogAction->PushCell(client);
102 g_OnLogAction->PushCell(target);
103 g_OnLogAction->PushString(message);
104 g_OnLogAction->Execute(&result);
106 if (result >= (ResultType)Pl_Handled)
112 const char *logtag = "SM";
116 IPlugin *pPlugin = g_PluginSys.PluginFromHandle(hndl, &err);
119 logtag = pPlugin->GetFilename();
123 g_Logger.LogMessage("[%s] %s", logtag, message);
126 static cell_t ThrowError(IPluginContext *pContext, const cell_t *params)
130 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
132 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
134 if (pContext->GetLastNativeError() == SP_ERROR_NONE)
136 pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
142 static cell_t GetTime(IPluginContext *pContext, const cell_t *params)
144 time_t t = GetAdjustedTime();
146 pContext->LocalToPhysAddr(params[1], &addr);
150 return static_cast<cell_t>(t);
153 #if defined SUBPLATFORM_SECURECRT
154 void _ignore_invalid_parameter(
155 const wchar_t * expression,
156 const wchar_t * function,
157 const wchar_t * file,
162 /* Wow we don't care, thanks Microsoft. */
166 static cell_t FormatTime(IPluginContext *pContext, const cell_t *params)
168 char *format, *buffer;
169 pContext->LocalToString(params[1], &buffer);
170 pContext->LocalToStringNULL(params[3], &format);
174 format = const_cast<char *>(sm_datetime_format.GetString());
177 #if defined SUBPLATFORM_SECURECRT
178 _invalid_parameter_handler handler = _set_invalid_parameter_handler(_ignore_invalid_parameter);
181 time_t t = (params[4] == -1) ? GetAdjustedTime() : (time_t)params[4];
182 size_t written = strftime(buffer, params[2], format, localtime(&t));
184 #if defined SUBPLATFORM_SECURECRT
185 _set_invalid_parameter_handler(handler);
188 if (params[2] && format[0] != '\0' && !written)
190 pContext->ThrowNativeError("Invalid time format or buffer too small");
197 static cell_t GetPluginIterator(IPluginContext *pContext, const cell_t *params)
199 IPluginIterator *iter = g_PluginSys.GetPluginIterator();
201 Handle_t hndl = g_HandleSys.CreateHandle(g_PlIter, iter, pContext->GetIdentity(), g_pCoreIdent, NULL);
203 if (hndl == BAD_HANDLE)
211 static cell_t MorePlugins(IPluginContext *pContext, const cell_t *params)
213 Handle_t hndl = (Handle_t)params[1];
215 IPluginIterator *pIter;
218 sec.pIdentity = g_pCoreIdent;
219 sec.pOwner = pContext->GetIdentity();
221 if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
223 return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
226 return pIter->MorePlugins() ? 1 : 0;
229 static cell_t ReadPlugin(IPluginContext *pContext, const cell_t *params)
231 Handle_t hndl = (Handle_t)params[1];
233 IPluginIterator *pIter;
236 sec.pIdentity = g_pCoreIdent;
237 sec.pOwner = pContext->GetIdentity();
239 if ((err=g_HandleSys.ReadHandle(hndl, g_PlIter, &sec, (void **)&pIter)) != HandleError_None)
241 return pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
244 CPlugin *pPlugin = (CPlugin *)pIter->GetPlugin();
252 return pPlugin->GetMyHandle();
255 CPlugin *GetPluginFromHandle(IPluginContext *pContext, Handle_t hndl)
257 if (hndl == BAD_HANDLE)
259 return g_PluginSys.GetPluginByCtx(pContext->GetContext());
262 CPlugin *pPlugin = (CPlugin *)g_PluginSys.PluginFromHandle(hndl, &err);
265 pContext->ThrowNativeError("Could not read Handle %x (error %d)", hndl, err);
271 static cell_t GetPluginStatus(IPluginContext *pContext, const cell_t *params)
273 CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
279 return pPlugin->GetStatus();
282 static cell_t GetPluginFilename(IPluginContext *pContext, const cell_t *params)
284 CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
290 pContext->StringToLocalUTF8(params[2], params[3], pPlugin->GetFilename(), NULL);
295 static cell_t IsPluginDebugging(IPluginContext *pContext, const cell_t *params)
297 CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
303 return pPlugin->IsDebugging() ? 1 : 0;
306 /* Local to plugins only */
309 PlInfo_Name, /**< Plugin name */
310 PlInfo_Author, /**< Plugin author */
311 PlInfo_Description, /**< Plugin description */
312 PlInfo_Version, /**< Plugin verison */
313 PlInfo_URL, /**< Plugin URL */
316 static cell_t GetPluginInfo(IPluginContext *pContext, const cell_t *params)
318 CPlugin *pPlugin = GetPluginFromHandle(pContext, params[1]);
324 const sm_plugininfo_t *info = pPlugin->GetPublicInfo();
331 const char *str = NULL;
333 switch ((PluginInfo)params[2])
345 case PlInfo_Description:
347 str = info->description;
362 if (!str || str[0] == '\0')
367 pContext->StringToLocalUTF8(params[3], params[4], str, NULL);
372 static cell_t SetFailState(IPluginContext *pContext, const cell_t *params)
377 pContext->LocalToString(params[1], &str);
378 pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
382 pPlugin->SetErrorState(Plugin_Error, "%s", str);
384 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", str);
390 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 1);
391 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
393 pPlugin->SetErrorState(Plugin_Error, "%s", str);
394 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "Formatting error (%s)", str);
398 pPlugin->SetErrorState(Plugin_Error, "%s", buffer);
399 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", buffer);
406 static cell_t GetSysTickCount(IPluginContext *pContext, const cell_t *params)
408 #if defined PLATFORM_WINDOWS
409 return (cell_t)GetTickCount();
410 #elif defined PLATFORM_LINUX
412 clock_t ticks = times(&tm);
413 long ticks_per_sec = sysconf(_SC_CLK_TCK);
414 double fticks = (double)ticks / (double)ticks_per_sec;
416 if (fticks > INT_MAX)
418 double r = (int)(fticks / INT_MAX) * (double)INT_MAX;
421 return (cell_t)fticks;
422 #elif defined PLATFORM_APPLE
428 static cell_t AutoExecConfig(IPluginContext *pContext, const cell_t *params)
430 CPlugin *plugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
433 pContext->LocalToString(params[2], &cfg);
434 pContext->LocalToString(params[3], &folder);
438 static char temp_str[255];
439 static char temp_file[PLATFORM_MAX_PATH];
442 g_LibSys.GetFileFromPath(temp_str, sizeof(temp_str), plugin->GetFilename());
443 if ((ptr = strstr(temp_str, ".smx")) != NULL)
448 /* We have the raw filename! */
449 UTIL_Format(temp_file, sizeof(temp_file), "plugin.%s", temp_str);
453 plugin->AddConfig(params[1] ? true : false, cfg, folder);
458 static cell_t MarkNativeAsOptional(IPluginContext *pContext, const cell_t *params)
464 pContext->LocalToString(params[1], &name);
465 if (pContext->FindNativeByName(name, &idx) != SP_ERROR_NONE)
467 /* Oops! This HAS to silently fail! */
471 pContext->GetNativeByIndex(idx, &native);
473 native->flags |= SP_NTVFLAG_OPTIONAL;
478 static cell_t RegPluginLibrary(IPluginContext *pContext, const cell_t *params)
481 CPlugin *pl = g_PluginSys.GetPluginByCtx(pContext->GetContext());
483 pContext->LocalToString(params[1], &name);
485 pl->AddLibrary(name);
490 static cell_t LibraryExists(IPluginContext *pContext, const cell_t *params)
493 pContext->LocalToString(params[1], &str);
495 if (strcmp(str, "__CanTestFeatures__") == 0)
500 if (g_PluginSys.LibraryExists(str))
505 if (g_Extensions.LibraryExists(str))
513 static cell_t sm_LogAction(IPluginContext *pContext, const cell_t *params)
516 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
517 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
519 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
524 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
526 LogAction(pPlugin->GetMyHandle(), 2, params[1], params[2], buffer);
531 static cell_t LogToFile(IPluginContext *pContext, const cell_t *params)
534 pContext->LocalToString(params[1], &file);
536 char path[PLATFORM_MAX_PATH];
537 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
539 FILE *fp = fopen(path, "at");
542 return pContext->ThrowNativeError("Could not open file \"%s\"", path);
546 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
547 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
549 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
555 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
557 g_Logger.LogToOpenFile(fp, "[%s] %s", pPlugin->GetFilename(), buffer);
564 static cell_t LogToFileEx(IPluginContext *pContext, const cell_t *params)
567 pContext->LocalToString(params[1], &file);
569 char path[PLATFORM_MAX_PATH];
570 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "%s", file);
572 FILE *fp = fopen(path, "at");
575 return pContext->ThrowNativeError("Could not open file \"%s\"", path);
579 g_SourceMod.SetGlobalTarget(SOURCEMOD_SERVER_LANGUAGE);
580 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 2);
582 if (pContext->GetLastNativeError() != SP_ERROR_NONE)
588 g_Logger.LogToOpenFile(fp, "%s", buffer);
595 static cell_t GetExtensionFileStatus(IPluginContext *pContext, const cell_t *params)
598 pContext->LocalToString(params[1], &str);
600 IExtension *pExtension = g_Extensions.FindExtensionByFile(str);
607 if (!pExtension->IsLoaded())
613 pContext->LocalToString(params[2], &error);
614 if (!pExtension->IsRunning(error, params[3]))
622 static cell_t FindPluginByNumber(IPluginContext *pContext, const cell_t *params)
624 CPlugin *pPlugin = g_PluginSys.GetPluginByOrder(params[1]);
631 return pPlugin->GetMyHandle();
634 static cell_t VerifyCoreVersion(IPluginContext *pContext, const cell_t *params)
639 static cell_t GetFeatureStatus(IPluginContext *pContext, const cell_t *params)
641 FeatureType type = (FeatureType)params[1];
644 pContext->LocalToString(params[2], &name);
646 return g_ShareSys.TestFeature(pContext->GetRuntime(),type, name);
649 static cell_t RequireFeature(IPluginContext *pContext, const cell_t *params)
651 FeatureType type = (FeatureType)params[1];
654 pContext->LocalToString(params[2], &name);
656 if (g_ShareSys.TestFeature(pContext->GetRuntime(),type, name) != FeatureStatus_Available)
660 char default_message[255];
661 CPlugin *pPlugin = g_PluginSys.GetPluginByCtx(pContext->GetContext());
663 g_SourceMod.FormatString(buffer, sizeof(buffer), pContext, params, 3);
664 if (pContext->GetLastNativeError() != SP_ERROR_NONE || buffer[0] == '\0')
666 UTIL_Format(default_message, sizeof(default_message), "Feature \"%s\" not available", name);
667 msg = default_message;
669 pPlugin->SetErrorState(Plugin_Error, "%s", msg);
670 return pContext->ThrowNativeErrorEx(SP_ERROR_ABORTED, "%s", msg);
676 REGISTER_NATIVES(coreNatives)
678 {"AutoExecConfig", AutoExecConfig},
679 {"GetPluginFilename", GetPluginFilename},
680 {"GetPluginInfo", GetPluginInfo},
681 {"GetPluginIterator", GetPluginIterator},
682 {"GetPluginStatus", GetPluginStatus},
683 {"GetSysTickCount", GetSysTickCount},
684 {"GetTime", GetTime},
685 {"IsPluginDebugging", IsPluginDebugging},
686 {"MorePlugins", MorePlugins},
687 {"ReadPlugin", ReadPlugin},
688 {"ThrowError", ThrowError},
689 {"SetFailState", SetFailState},
690 {"FormatTime", FormatTime},
691 {"MarkNativeAsOptional", MarkNativeAsOptional},
692 {"RegPluginLibrary", RegPluginLibrary},
693 {"LibraryExists", LibraryExists},
694 {"LogAction", sm_LogAction},
695 {"LogToFile", LogToFile},
696 {"LogToFileEx", LogToFileEx},
697 {"GetExtensionFileStatus", GetExtensionFileStatus},
698 {"FindPluginByNumber", FindPluginByNumber},
699 {"VerifyCoreVersion", VerifyCoreVersion},
700 {"GetFeatureStatus", GetFeatureStatus},
701 {"RequireFeature", RequireFeature},