core/PluginSys.h
author Asher Baker <asherkin@gmail.com>
Thu Aug 09 01:54:43 2012 +0100 (2012-08-09)
changeset 3601 d3a2fb7b3a1e
parent 3515 c14c14e06cc1
child 3613 b0740093756d
permissions -rw-r--r--
Added system to block malware or illegal plugins (bug 5289, r=dvander).
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2010 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 #ifndef _INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
    33 #define _INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
    34 
    35 #include <time.h>
    36 #include <errno.h>
    37 #include <sys/stat.h>
    38 #include <IPluginSys.h>
    39 #include <IHandleSys.h>
    40 #include <IForwardSys.h>
    41 #include <sh_list.h>
    42 #include <sh_stack.h>
    43 #include <sh_vector.h>
    44 #include <sh_string.h>
    45 #include "sm_globals.h"
    46 #include "PluginInfoDatabase.h"
    47 #include "sm_trie.h"
    48 #include "sourcemod.h"
    49 #include <IRootConsoleMenu.h>
    50 #if SOURCE_ENGINE >= SE_ALIENSWARM
    51 #include "convar_sm_swarm.h"
    52 #elif (SOURCE_ENGINE == SE_LEFT4DEAD) || (SOURCE_ENGINE == SE_LEFT4DEAD2)
    53 #include "convar_sm_l4d.h"
    54 #elif (SOURCE_ENGINE == SE_ORANGEBOX) || (SOURCE_ENGINE == SE_BLOODYGOODTIME) || (SOURCE_ENGINE == SE_EYE) || (SOURCE_ENGINE == SE_ORANGEBOXVALVE)
    55 #include "convar_sm_ob.h"
    56 #else
    57 #include "convar_sm.h"
    58 #endif
    59 #include "ITranslator.h"
    60 #include "IGameConfigs.h"
    61 #include "NativeOwner.h"
    62 #include "ShareSys.h"
    63 
    64 class CPlayer;
    65 
    66 using namespace SourceHook;
    67 
    68 /**
    69  * NOTES:
    70  *
    71  * UPDATE 2008-03-11: These comments are horribly out of date.  They paint a good overall 
    72  * picture of how PluginSys works, but things like dependencies and fake natives have 
    73  * complicated things quite a bit.
    74  *
    75  *  Currently this system needs a lot of work but it's good skeletally.  Plugin creation 
    76  * is done without actually compiling anything.  This is done by Load functions in the 
    77  * manager.  This will need a rewrite when we add context switching.
    78  *
    79  *  The plugin object itself has a few things to note.  The most important is that it stores
    80  * a table of function objects.  The manager marshals allocation and freeing of these objects.
    81  * The plugin object can be in erroneous states, they are:
    82  *   Plugin_Error   --> Some error occurred any time during or after compilation.
    83  *						This error can be cleared since the plugin itself is valid.
    84  *						However, the state itself being set prevents any runtime action.
    85  *   Plugin_BadLoad	--> The plugin failed to load entirely and nothing can be done to save it.
    86  *
    87  *  If a plugin fails to load externally, it is never added to the internal tracker.  However, 
    88  * plugins that failed to load from the internal loading mechanism are always tracked.  This 
    89  * allows users to see which automatically loaded plugins failed, and makes the interface a bit
    90  * more flexible.
    91  *
    92  *  Once a plugin is compiled, it sets its own state to Plugin_Created.  This state is still invalid
    93  * for execution.  SourceMod is a two pass system, and even though the second pass is not implemented
    94  * yet, it is structured so Plugin_Created must be switched to Plugin_Running in the second pass.  When
    95  * implemented, a Created plugin will be switched to Error in the second pass if it not loadable.
    96  *
    97  *  The two pass loading mechanism is described below.  Modules/natives are not implemented yet.
    98  * PASS ONE: All loadable plugins are found and have the following steps performed:
    99  *			 1.  Loading and compilation is attempted.
   100  *			 2.  If successful, all natives from Core are added.
   101  *			 3.  OnPluginLoad() is called.
   102  *			 4.  If failed, any user natives are scrapped and the process halts here.
   103  *			 5.  If successful, the plugin is ready for Pass 2.
   104  * INTERMEDIATE:
   105  *			 1.  All forced modules are loaded.
   106  * PASS TWO: All loaded plugins are found and have these steps performed:
   107  *			 1. Any modules referenced in the plugin that are not already loaded, are loaded.
   108  *			 2. If any module fails to load and the plugin requires it, load fails and jump to step 6.
   109  *			 3. If any natives are unresolved, check if they are found in the user-natives pool.
   110  *			 4. If yes, load succeeds.  If not, natives are passed through a native acceptance filter.
   111  *			 5. If the filter fails, the plugin is marked as failed.
   112  *			 6. If the plugin has failed to load at this point, any dynamic natives it has added are scrapped.
   113  *			    Furthermore, any plugin that referenced these natives must now have pass 2 re-ran.
   114  * PASS THREE (not a real pass):
   115  *			 7. Once all plugins are deemed to be loaded, OnPluginStart() is called
   116  */
   117 
   118 enum LoadRes
   119 {
   120 	LoadRes_Successful,
   121 	LoadRes_AlreadyLoaded,
   122 	LoadRes_Failure,
   123 	LoadRes_SilentFailure,
   124 	LoadRes_NeverLoad
   125 };
   126 
   127 enum APLRes
   128 {
   129 	APLRes_Success,
   130 	APLRes_Failure,
   131 	APLRes_SilentFailure
   132 };
   133 
   134 struct AutoConfig
   135 {
   136 	String autocfg;
   137 	String folder;
   138 	bool create;
   139 };
   140 
   141 class CPlugin;
   142 
   143 class CPlugin : 
   144 	public IPlugin,
   145 	public CNativeOwner
   146 {
   147 	friend class CPluginManager;
   148 	friend class CFunction;
   149 public:
   150 	CPlugin(const char *file);
   151 	~CPlugin();
   152 public:
   153 	PluginType GetType();
   154 	SourcePawn::IPluginContext *GetBaseContext();
   155 	sp_context_t *GetContext();
   156 	void *GetPluginStructure();
   157 	const char *GetFilename();
   158 	bool IsDebugging();
   159 	PluginStatus GetStatus();
   160 	bool IsSilentlyFailed();
   161 	void SetSilentlyFailed(bool sf);
   162 	const sm_plugininfo_t *GetPublicInfo();
   163 	bool SetPauseState(bool paused);
   164 	unsigned int GetSerial();
   165 	IdentityToken_t *GetIdentity();
   166 	unsigned int CalcMemUsage();
   167 	bool SetProperty(const char *prop, void *ptr);
   168 	bool GetProperty(const char *prop, void **ptr, bool remove=false);
   169 	void DropEverything();
   170 	SourcePawn::IPluginRuntime *GetRuntime();
   171 public:
   172 	/**
   173 	 * Creates a plugin object with default values.
   174 	 *   If an error buffer is specified, and an error occurs, the error will be copied to the buffer
   175 	 * and NULL will be returned.
   176 	 *   If an error buffer is not specified, the error will be copied to an internal buffer and 
   177 	 * a valid (but error-stated) CPlugin will be returned.
   178 	 */
   179 	static CPlugin *CreatePlugin(const char *file, char *error, size_t maxlength);
   180 public:
   181 
   182 	/**
   183 	 * Sets an error state on the plugin
   184 	 */
   185 	void SetErrorState(PluginStatus status, const char *error_fmt, ...);
   186 
   187 	/**
   188 	 * Initializes the plugin's identity information
   189 	 */
   190 	void InitIdentity();
   191 
   192 	/**
   193 	 * Calls the OnPluginLoad function, and sets any failed states if necessary.
   194 	 * NOTE: Valid pre-states are: Plugin_Created
   195 	 * NOTE: If validated, plugin state is changed to Plugin_Loaded
   196 	 *
   197 	 * If the error buffer is NULL, the error message is cached locally.
   198 	 */
   199 	APLRes Call_AskPluginLoad(char *error, size_t maxlength);
   200 
   201 	/**
   202 	 * Calls the OnPluginStart function.
   203 	 * NOTE: Valid pre-states are: Plugin_Created
   204 	 * NOTE: Post-state will be Plugin_Running
   205 	 */
   206 	void Call_OnPluginStart();
   207 
   208 	/**
   209 	 * Calls the OnPluginEnd function.
   210 	 */
   211 	void Call_OnPluginEnd();
   212 
   213 	/**
   214 	 * Calls the OnAllPluginsLoaded function.
   215 	 */
   216 	void Call_OnAllPluginsLoaded();
   217 
   218 	/**
   219 	 * Returns true if a plugin is usable.
   220 	 */
   221 	bool IsRunnable();
   222 
   223 	/**
   224 	 * Get languages info.
   225 	 */
   226 	IPhraseCollection *GetPhrases();
   227 public:
   228 	/**
   229 	 * Returns the modification time during last plugin load.
   230 	 */
   231 	time_t GetTimeStamp();
   232 
   233 	/**
   234 	 * Returns the current modification time of the plugin file.
   235 	 */
   236 	time_t GetFileTimeStamp();
   237 
   238 	/** 
   239 	 * Returns true if the plugin was running, but is now invalid.
   240 	 */
   241 	bool WasRunning();
   242 
   243 	Handle_t GetMyHandle();
   244 
   245 	bool AddFakeNative(IPluginFunction *pFunc, const char *name, SPVM_FAKENATIVE_FUNC func);
   246 	void AddConfig(bool autoCreate, const char *cfg, const char *folder);
   247 	unsigned int GetConfigCount();
   248 	AutoConfig *GetConfig(unsigned int i);
   249 	inline void AddLibrary(const char *name)
   250 	{
   251 		m_Libraries.push_back(name);
   252 	}
   253 	void LibraryActions(bool dropping);
   254 	void SyncMaxClients(int max_clients);
   255 protected:
   256 	bool UpdateInfo();
   257 	void SetTimeStamp(time_t t);
   258 	void DependencyDropped(CPlugin *pOwner);
   259 private:
   260 	PluginType m_type;
   261 	char m_filename[PLATFORM_MAX_PATH];
   262 	PluginStatus m_status;
   263 	bool m_bSilentlyFailed;
   264 	unsigned int m_serial;
   265 	sm_plugininfo_t m_info;
   266 	char m_errormsg[256];
   267 	time_t m_LastAccess;
   268 	IdentityToken_t *m_ident;
   269 	Handle_t m_handle;
   270 	bool m_WasRunning;
   271 	IPhraseCollection *m_pPhrases;
   272 	List<String> m_RequiredLibs;
   273 	List<String> m_Libraries;
   274 	Trie *m_pProps;
   275 	bool m_FakeNativesMissing;
   276 	bool m_LibraryMissing;
   277 	CVector<AutoConfig *> m_configs;
   278 	bool m_bGotAllLoaded;
   279 	int m_FileVersion;
   280 	char m_DateTime[256];
   281 	IPluginRuntime *m_pRuntime;
   282 	IPluginContext *m_pContext;
   283 	sp_pubvar_t *m_MaxClientsVar;
   284 };
   285 
   286 class CPluginManager : 
   287 	public IPluginManager,
   288 	public SMGlobalClass,
   289 	public IHandleTypeDispatch,
   290 	public IRootConsoleCommand
   291 {
   292 	friend class CPlugin;
   293 public:
   294 	CPluginManager();
   295 	~CPluginManager();
   296 public:
   297 	/* Implements iterator class */
   298 	class CPluginIterator : public IPluginIterator
   299 	{
   300 	public:
   301 		CPluginIterator(List<CPlugin *> *mylist);
   302 		virtual ~CPluginIterator();
   303 		virtual bool MorePlugins();
   304 		virtual IPlugin *GetPlugin();
   305 		virtual void NextPlugin();
   306 		void Release();
   307 	public:
   308 		void Reset();
   309 	private:
   310 		List<CPlugin *> *mylist;
   311 		List<CPlugin *>::iterator current;
   312 	};
   313 	friend class CPluginManager::CPluginIterator;
   314 public: //IPluginManager
   315 	IPlugin *LoadPlugin(const char *path, 
   316 								bool debug,
   317 								PluginType type,
   318 								char error[],
   319 								size_t maxlength,
   320 								bool *wasloaded);
   321 	bool UnloadPlugin(IPlugin *plugin);
   322 	IPlugin *FindPluginByContext(const sp_context_t *ctx);
   323 	unsigned int GetPluginCount();
   324 	IPluginIterator *GetPluginIterator();
   325 	void AddPluginsListener(IPluginsListener *listener);
   326 	void RemovePluginsListener(IPluginsListener *listener);
   327 public: //SMGlobalClass
   328 	void OnSourceModAllInitialized();
   329 	void OnSourceModShutdown();
   330 	ConfigResult OnSourceModConfigChanged(const char *key, const char *value, ConfigSource source, char *error, size_t maxlength);
   331 	void OnSourceModMaxPlayersChanged(int newvalue);
   332 public: //IHandleTypeDispatch
   333 	void OnHandleDestroy(HandleType_t type, void *object);
   334 	bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize);
   335 public: //IRootConsoleCommand
   336 	void OnRootConsoleCommand(const char *cmdname, const CCommand &command);
   337 public:
   338 	/**
   339 	 * Loads all plugins not yet loaded
   340 	 */
   341 	void LoadAll_FirstPass(const char *config, const char *basedir);
   342 
   343 	/**
   344 	 * Runs the second loading pass for all plugins
   345 	 */
   346 	void LoadAll_SecondPass();
   347 
   348 	/**
   349 	 * Tests a plugin file mask against a local folder.
   350 	 * The alias is searched backwards from localdir - i.e., given this input:
   351 	 *   csdm/ban        csdm/ban
   352 	 *   ban             csdm/ban
   353 	 *   csdm/ban        optional/csdm/ban
   354 	 * All of these will return true for an alias match.  
   355 	 * Wildcards are allowed in the filename.
   356 	 */
   357 	bool TestAliasMatch(const char *alias, const char *localdir);
   358 
   359 	/** 
   360 	 * Returns whether anything loaded will be a late load.
   361 	 */
   362 	bool IsLateLoadTime() const;
   363 
   364 	/**
   365 	 * Converts a Handle to an IPlugin if possible.
   366 	 */
   367 	IPlugin *PluginFromHandle(Handle_t handle, HandleError *err);
   368 
   369 	/**
   370 	 * Finds a plugin based on its index. (starts on index 1)
   371 	 */
   372 	CPlugin *GetPluginByOrder(int num);
   373 
   374 	int GetOrderOfPlugin(IPlugin *pl);
   375 
   376 	/** 
   377 	 * Internal version of FindPluginByContext()
   378 	 */
   379 	CPlugin *GetPluginByCtx(const sp_context_t *ctx);
   380 
   381 	/**
   382 	 * Gets status text for a status code 
   383 	 */
   384 	const char *GetStatusText(PluginStatus status);
   385 
   386 	/**
   387 	* Reload or update plugins on level shutdown.
   388 	*/
   389 	void ReloadOrUnloadPlugins();
   390 
   391 	/**
   392 	 * Add public functions from all running or paused
   393 	 * plugins to the specified forward if the names match.
   394 	 */
   395 	void AddFunctionsToForward(const char *name, IChangeableForward *pForward);
   396 
   397 	/**
   398 	 * Iterates through plugins to call OnAllPluginsLoaded.
   399 	 */
   400 	void AllPluginsLoaded();
   401 
   402 	CPlugin *GetPluginFromIdentity(IdentityToken_t *pToken);
   403 
   404 	void Shutdown();
   405 
   406 	void OnLibraryAction(const char *lib, bool is_a_plugin, bool drop);
   407 
   408 	bool LibraryExists(const char *lib);
   409 
   410 	bool ReloadPlugin(CPlugin *pl);
   411 
   412 	void UnloadAll();
   413 
   414 	CPlugin *FindPluginByConsoleArg(const char *arg);
   415 
   416 	void SyncMaxClients(int max_clients);
   417 
   418 	void ListPluginsToClient(CPlayer *player, const CCommand &args);
   419 private:
   420 	LoadRes _LoadPlugin(CPlugin **pPlugin, const char *path, bool debug, PluginType type, char error[], size_t maxlength);
   421 
   422 	void LoadAutoPlugin(const char *plugin);
   423 
   424 	/**
   425 	 * Recursively loads all plugins in the given directory.
   426 	 */
   427 	void LoadPluginsFromDir(const char *basedir, const char *localdir);
   428 
   429 	/**
   430 	 * Adds a plugin object.  This is wrapped by LoadPlugin functions.
   431 	 */
   432 	void AddPlugin(CPlugin *pPlugin);
   433 
   434 	/**
   435 	 * Runs the second loading pass on a plugin.
   436 	 */
   437 	bool RunSecondPass(CPlugin *pPlugin, char *error, size_t maxlength);
   438 
   439 	/**
   440 	 * Runs an extension pass on a plugin.
   441 	 */
   442 	bool LoadOrRequireExtensions(CPlugin *pPlugin, unsigned int pass, char *error, size_t maxlength);
   443 
   444 	/**
   445 	* Manages required natives.
   446 	*/
   447 	bool FindOrRequirePluginDeps(CPlugin *pPlugin, char *error, size_t maxlength);
   448 
   449 	void _SetPauseState(CPlugin *pPlugin, bool pause);
   450 protected:
   451 	/**
   452 	 * Caching internal objects
   453 	 */
   454 	void ReleaseIterator(CPluginIterator *iter);
   455 public:
   456 	inline IdentityToken_t *GetIdentity()
   457 	{
   458 		return m_MyIdent;
   459 	}
   460 private:
   461 	void TryRefreshDependencies(CPlugin *pOther);
   462 private:
   463 	List<IPluginsListener *> m_listeners;
   464 	List<CPlugin *> m_plugins;
   465 	CStack<CPluginManager::CPluginIterator *> m_iters;
   466 	CPluginInfoDatabase m_PluginInfo;
   467 	Trie *m_LoadLookup;
   468 	bool m_AllPluginsLoaded;
   469 	IdentityToken_t *m_MyIdent;
   470 
   471 	/* Dynamic native stuff */
   472 	List<FakeNative *> m_Natives;
   473 
   474 	bool m_LoadingLocked;
   475 	
   476 	// Config
   477 	bool m_bBlockBadPlugins;
   478 };
   479 
   480 extern CPluginManager g_PluginSys;
   481 
   482 #endif //_INCLUDE_SOURCEMOD_PLUGINSYSTEM_H_
   483